Programs & Examples On #Smack

Smack is an XMPP (Jabber) client library written in Java for Android and Java SE. It provides a simple API allowing developers to write clients for XMPP services.

Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

I faced the similar problem in no reason, i think it was caused by IDE(android studio). I have tried all of above solutions but not worked. Finally, in my own situation, i solved this problem by the following actions: - Close the current project and remove it from the list of projects in android studio ,and reopen it by Open an existing Android Studio project, then it may be worked. I hope that my experience will be useful for you.

Gradle DSL method not found: 'runProguard'

enter image description hereIf you are using version 0.14.0 or higher of the gradle plugin, you should replace "runProguard" with "minifyEnabled" in your build.gradle files.

runProguard was renamed to minifyEnabled in version 0.14.0. For more info, See Android Build System

Delayed function calls

There is no standard way to delay a call to a function other than to use a timer and events.

This sounds like the GUI anti pattern of delaying a call to a method so that you can be sure the form has finished laying out. Not a good idea.

Default string initialization: NULL or Empty?

Is it possible that this is an error avoidance technique (advisable or not..)? Since "" is still a string, you would be able to call string functions on it that would result in an exception if it was NULL?

What is the "N+1 selects problem" in ORM (Object-Relational Mapping)?

N+1 SELECT problem is really hard to spot, especially in projects with large domain, to the moment when it starts degrading the performance. Even if the problem is fixed i.e. by adding eager loading, a further development may break the solution and/or introduce N+1 SELECT problem again in other places.

I've created open source library jplusone to address those problems in JPA based Spring Boot Java applications. The library provides two major features:

  1. Generates reports correlating SQL statements with executions of JPA operations which triggered them and places in source code of your application which were involved in it
2020-10-22 18:41:43.236 DEBUG 14913 --- [           main] c.a.j.core.report.ReportGenerator        :
    ROOT
        com.adgadev.jplusone.test.domain.bookshop.BookshopControllerTest.shouldGetBookDetailsLazily(BookshopControllerTest.java:65)
        com.adgadev.jplusone.test.domain.bookshop.BookshopController.getSampleBookUsingLazyLoading(BookshopController.java:31)
        com.adgadev.jplusone.test.domain.bookshop.BookshopService.getSampleBookDetailsUsingLazyLoading [PROXY]
            SESSION BOUNDARY
                OPERATION [IMPLICIT]
                    com.adgadev.jplusone.test.domain.bookshop.BookshopService.getSampleBookDetailsUsingLazyLoading(BookshopService.java:35)
                    com.adgadev.jplusone.test.domain.bookshop.Author.getName [PROXY]
                    com.adgadev.jplusone.test.domain.bookshop.Author [FETCHING ENTITY]
                        STATEMENT [READ]
                            select [...] from
                                author author0_
                                left outer join genre genre1_ on author0_.genre_id=genre1_.id
                            where
                                author0_.id=1
                OPERATION [IMPLICIT]
                    com.adgadev.jplusone.test.domain.bookshop.BookshopService.getSampleBookDetailsUsingLazyLoading(BookshopService.java:36)
                    com.adgadev.jplusone.test.domain.bookshop.Author.countWrittenBooks(Author.java:53)
                    com.adgadev.jplusone.test.domain.bookshop.Author.books [FETCHING COLLECTION]
                        STATEMENT [READ]
                            select [...] from
                                book books0_
                            where
                                books0_.author_id=1
  1. Provides API which allows to write tests checking how effectively your application is using JPA (i.e. assert amount of lazy loading operations )
@SpringBootTest
class LazyLoadingTest {

    @Autowired
    private JPlusOneAssertionContext assertionContext;

    @Autowired
    private SampleService sampleService;

    @Test
    public void shouldBusinessCheckOperationAgainstJPlusOneAssertionRule() {
        JPlusOneAssertionRule rule = JPlusOneAssertionRule
                .within().lastSession()
                .shouldBe().noImplicitOperations().exceptAnyOf(exclusions -> exclusions
                        .loadingEntity(Author.class).times(atMost(2))
                        .loadingCollection(Author.class, "books")
                );

        // trigger business operation which you wish to be asserted against the rule,
        // i.e. calling a service or sending request to your API controller
        sampleService.executeBusinessOperation();

        rule.check(assertionContext);
    }
}

xxxxxx.exe is not a valid Win32 application

It's Feb 2013, and I can now target XP in VS2012 by setting:

Project Properties -> General -> Platform Toolset to:

Visual Studio 2012 - Windows XP (v110_xp)

You will have to redistribute the msvcp110.dll libraries et al with your application, which are found here: "<Program Files>\Microsoft Visual Studio 11.0\VC\redist\x86\Microsoft.VC110.CRT\"


Update Aug 2015 with Visual Studio 2015

There seems to be quite a selection now. I was able to compile application in VS2015 using Visual Studio 2015 - Windows XP (v140_xp) setting. To make it actually run on Win XP I had to deploy (copy alongside application) msvcr100.dll for Release build and msvcr110.dll and msvcr100d.dll for Debug build (note there is a difference in numbers 100 and 110, also debug lib msvcr100d.dll may not be redistributable) Targeting Windows XP with Visual Studio 2015

env: node: No such file or directory in mac

NOTE: Only mac users!

  1. uninstall node completely with the commands
curl -ksO https://gist.githubusercontent.com/nicerobot/2697848/raw/uninstall-node.sh
chmod +x ./uninstall-node.sh
./uninstall-node.sh
rm uninstall-node.sh

Or you could check out this website: How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X)

if this doesn't work, you need to remove node via control panel or any other method. As long as it gets removed.

  1. Install node via this website: https://nodejs.org/en/download/

If you use nvm, you can use:

nvm install node

You can already check if it works, then you don't need to take the following steps with: npm -v and then node -v

if you have nvm installed: command -v nvm

  1. Uninstall npm using the following command:

sudo npm uninstall npm -g

Or, if that fails, get the npm source code, and do:

sudo make uninstall

If you have nvm installed, then use: nvm uninstall npm

  1. Install npm using the following command: npm install -g grunt

Background service with location listener in android

First you need to create a Service. In that Service, create a class extending LocationListener. For this, use the following code snippet of Service:

public class LocationService extends Service {
public static final String BROADCAST_ACTION = "Hello World";
private static final int TWO_MINUTES = 1000 * 60 * 2;
public LocationManager locationManager;
public MyLocationListener listener;
public Location previousBestLocation = null;

Intent intent;
int counter = 0;

@Override
public void onCreate() {
    super.onCreate();
    intent = new Intent(BROADCAST_ACTION);
}

@Override
public void onStart(Intent intent, int startId) {
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    listener = new MyLocationListener();
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 4000, 0, (LocationListener) listener);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 4000, 0, listener);
}

@Override
public IBinder onBind(Intent intent)
{
    return null;
}

protected boolean isBetterLocation(Location location, Location currentBestLocation) {
    if (currentBestLocation == null) {
        // A new location is always better than no location
        return true;
    }

    // Check whether the new location fix is newer or older
    long timeDelta = location.getTime() - currentBestLocation.getTime();
    boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
    boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
    boolean isNewer = timeDelta > 0;

    // If it's been more than two minutes since the current location, use the new location
    // because the user has likely moved
    if (isSignificantlyNewer) {
        return true;
        // If the new location is more than two minutes older, it must be worse
    } else if (isSignificantlyOlder) {
        return false;
    }

    // Check whether the new location fix is more or less accurate
    int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
    boolean isLessAccurate = accuracyDelta > 0;
    boolean isMoreAccurate = accuracyDelta < 0;
    boolean isSignificantlyLessAccurate = accuracyDelta > 200;

    // Check if the old and new location are from the same provider
    boolean isFromSameProvider = isSameProvider(location.getProvider(),
            currentBestLocation.getProvider());

    // Determine location quality using a combination of timeliness and accuracy
    if (isMoreAccurate) {
        return true;
    } else if (isNewer && !isLessAccurate) {
        return true;
    } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
        return true;
    }
    return false;
}



/** Checks whether two providers are the same */
private boolean isSameProvider(String provider1, String provider2) {
    if (provider1 == null) {
        return provider2 == null;
    }
    return provider1.equals(provider2);
}



@Override
public void onDestroy() {
    // handler.removeCallbacks(sendUpdatesToUI);     
    super.onDestroy();
    Log.v("STOP_SERVICE", "DONE");
    locationManager.removeUpdates(listener);
}

public static Thread performOnBackgroundThread(final Runnable runnable) {
    final Thread t = new Thread() {
        @Override
        public void run() {
            try {
                runnable.run();
            } finally {

            }
        }
    };
    t.start();
    return t;
}
public class MyLocationListener implements LocationListener
{

    public void onLocationChanged(final Location loc)
    {
        Log.i("*****", "Location changed");
        if(isBetterLocation(loc, previousBestLocation)) {
            loc.getLatitude();
            loc.getLongitude();
            intent.putExtra("Latitude", loc.getLatitude());
            intent.putExtra("Longitude", loc.getLongitude());
            intent.putExtra("Provider", loc.getProvider());
            sendBroadcast(intent);

        }
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    public void onProviderDisabled(String provider)
    {
        Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
    }


    public void onProviderEnabled(String provider)
    {
        Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
    }
}

Add this Service any where in your project, the way you want! :)

Push items into mongo array via mongoose

Another way to push items into array using Mongoose is- $addToSet, if you want only unique items to be pushed into array. $push operator simply adds the object to array whether or not the object is already present, while $addToSet does that only if the object is not present in the array so as not to incorporate duplicacy.

PersonModel.update(
  { _id: person._id }, 
  { $addToSet: { friends: friend } }
);

This will look for the object you are adding to array. If found, does nothing. If not, adds it to the array.

References:

Submitting a form on 'Enter' with jQuery?

Don't know if it will help, but you can try simulating a submit button click, instead of directly submitting the form. I have the following code in production, and it works fine:

    $('.input').keypress(function(e) {
        if(e.which == 13) {
            jQuery(this).blur();
            jQuery('#submit').focus().click();
        }
    });

Note: jQuery('#submit').focus() makes the button animate when enter is pressed.

Android runOnUiThread explanation

This should work for you

 public class MyActivity extends Activity {

    protected ProgressDialog mProgressDialog;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        populateTable();
    }

    private void populateTable() {
        mProgressDialog = ProgressDialog.show(this, "Please wait","Long operation starts...", true);
        new Thread() {
            @Override
            public void run() {

                doLongOperation();
                try {

                    // code runs in a thread
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mProgressDialog.dismiss();
                        }
                    });
                } catch (final Exception ex) {
                    Log.i("---","Exception in thread");
                }
            }
        }.start();

    }

    /** fake operation for testing purpose */
    protected void doLongOperation() {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
        }

    }
}

Converting ISO 8601-compliant String to java.util.Date

java.time

The java.time API (built into Java 8 and later), makes this a little easier.

If you know the input is in UTC, such as the Z (for Zulu) on the end, the Instant class can parse.

java.util.Date date = Date.from( Instant.parse( "2014-12-12T10:39:40Z" ));

If your input may be another offset-from-UTC values rather than UTC indicated by the Z (Zulu) on the end, use the OffsetDateTime class to parse.

OffsetDateTime odt = OffsetDateTime.parse( "2010-01-01T12:00:00+01:00" );

Then extract an Instant, and convert to a java.util.Date by calling from.

Instant instant = odt.toInstant();  // Instant is always in UTC.
java.util.Date date = java.util.Date.from( instant );

How do I format a String in an email so Outlook will print the line breaks?

Try \r\c instead of \n.

EDIT: I think @Robert Wilkinson had it right. \r\n. Memory just isn't what it used to be.

Less aggressive compilation with CSS3 calc

There's a tidier way to include variables inside the escaped calc, as explained in this post: CSS3 calc() function doesn't work with Less #974

@variable: 2em;

body{ width: calc(~"100% - @{variable} * 2");}

By using the curly brackets you don't need to close and reopen the escaping quotes.

How to launch jQuery Fancybox on page load?

$(document).ready(function() {
    $.fancybox(
      '<p>Yes. It works <p>',
       {
        'autoDimensions'    : false,
        'width'             : 400,
        'height'            : 200,
        'transitionIn'      : 'none',
        'transitionOut'     : 'none'
       }
    );
});

This will help..

Is there an XSL "contains" directive?

<xsl:if test="not contains(hhref,'1234')">

$("#form1").validate is not a function

I had this same issue. It turned out that I was loading the jQuery JavaScript file more than once on the page. This was due to included pages (or JSPs, in my case). Once I removed the duplicate reference to the jQuery js file, this error went away.

How to add lines to end of file on Linux

The easiest way is to redirect the output of the echo by >>:

echo 'VNCSERVERS="1:root"' >> /etc/sysconfig/configfile
echo 'VNCSERVERARGS[1]="-geometry 1600x1200"' >> /etc/sysconfig/configfile

git visual diff between branches

You can also do this easily with gitk.

> gitk branch1 branch2

First click on the tip of branch1. Now right-click on the tip of branch2 and select Diff this->selected.

sql use statement with variable

I have the same problem, I overcame it with an ugly -- but useful -- set of GOTOs.

The reason I call the "script runner" before everything is that I want to hide the complexity and ugly approach from any developer that just wants to work with the actual script. At the same time, I can make sure that the script is run in the two (extensible to three and more) databases in the exact same way.

GOTO ScriptRunner

ScriptExecutes:

--------------------ACTUAL SCRIPT--------------------
-------- Will be executed in DB1 and in DB2 ---------
--TODO: Your script right here

------------------ACTUAL SCRIPT ENDS-----------------

GOTO ScriptReturns

ScriptRunner:
    USE DB1
    GOTO ScriptExecutes

ScriptReturns:
    IF (db_name() = 'DB1')
    BEGIN
        USE DB2
        GOTO ScriptExecutes
    END

With this approach you get to keep your variables and SQL Server does not freak out if you happen to go over a DECLARE statement twice.

Convert integer to binary in C#

http://zamirsblog.blogspot.com/2011/10/convert-decimal-to-binary-in-c.html

    public string DecimalToBinary(string data)
    {
        string result = string.Empty;
        int rem = 0;
        try
        {
            if (!IsNumeric(data))
                error = "Invalid Value - This is not a numeric value";
            else
            {
                int num = int.Parse(data);
                while (num > 0)
                {
                    rem = num % 2;
                    num = num / 2;
                    result = rem.ToString() + result;
                }
            }
        }
        catch (Exception ex)
        {
            error = ex.Message;
        }
        return result;
    }

GUI-based or Web-based JSON editor that works like property explorer

Update: In an effort to answer my own question, here is what I've been able to uncover so far. If anyone else out there has something, I'd still be interested to find out more.

Based on JSON Schema

Commercial (No endorsement intended or implied, may or may not meet requirement)

jQuery

YAML

See Also

Forward X11 failed: Network error: Connection refused

you should install a x server such as XMing. and keep the x server is running. config your putty like this :Connection-Data-SSH-X11-Enable X11 forwarding should be checked. and X display location : localhost:0

error: No resource identifier found for attribute 'adSize' in package 'com.google.example' main.xml

I had a similar issue on MonoDroid when building a class library with Drawables and Layouts files that have "android:" attribute in the xml. I get a similar error as the one in the question.

No resource identifier found for attribute 'textCursorDrawable' in package 'android'

I found from that "android: " attribute is only available in Android API Level 12+ and I was trying to build for an older version. Updating my project to build against Android 4.0 fixed the issue for me. Here is where I found the answer. https://groups.google.com/forum/?fromgroups#!topic/android-developers/ocxKphM5MWM Just make sure that you are building against the right API level if you get a similar issue, and ensure that the missing identifier exists in that API level that you are build against.

Using "label for" on radio buttons

You almost got it. It should be this:

_x000D_
_x000D_
<input type="radio" name="group1" id="r1" value="1" />_x000D_
<label for="r1"> button one</label>
_x000D_
_x000D_
_x000D_

The value in for should be the id of the element you are labeling.

Android EditText Max Length

I had the same problem.

Here is a workaround

android:inputType="textNoSuggestions|textVisiblePassword"
android:maxLength="6"

Thx to How can I turnoff suggestions in EditText?

The simplest way to resize an UIImage?

Swift 5:

func imageWithImage(_ image: UIImage?, scaledToSize newSize: CGSize) -> UIImage? {
    UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0);
    image?.draw(in: CGRect(x: 0.0, y: 0.0, width: newSize.width, height: newSize.height))
    let newImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage
}

Usage:

let img: UIImage? = imageWithImage(UIImage(named: "DefaultAvatar"), scaledToSize:CGSize(width: 20.0, height: 20.0))

No module named 'pymysql'

I also got this error recently when using Anaconda on a Mac machine.

Here is what I found:

  1. After running python3 -m pip install PyMySql, pymysql module is under /Library/Python/3.7/site-packages
  2. Anaconda wants this module to be under /opt/anaconda3/lib/python3.8/site-packages

Therefore, after copying pymysql module to the designated path, it runs correctly.

@font-face not working

try to put below html in head tag.It worked for me.

 <title>ABC</title>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> 
 <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

Django DateField default options

I think a better way to solve this would be to use the datetime callable:

from datetime import datetime

date = models.DateField(default=datetime.now)

Note that no parenthesis were used. If you used parenthesis you would invoke the now() function just once (when the model is created). Instead, you pass the callable as an argument, thus being invoked everytime an instance of the model is created.

Credit to Django Musings. I've used it and works fine.

How to convert a column of DataTable to a List

Is this what you need?

DataTable myDataTable = new DataTable();
List<int> myList = new List<int>();
foreach (DataRow row in myDataTable.Rows)
{
    myList.Add((int)row[0]);
}

Easy way to turn JavaScript array into comma-separated list?

Do you want to end it with an "and"?

For this situation, I created an npm module.

Try arrford:


Usage

const arrford = require('arrford');

arrford(['run', 'climb', 'jump!']);
//=> 'run, climb, and jump!'

arrford(['run', 'climb', 'jump!'], false);
//=> 'run, climb and jump!'

arrford(['run', 'climb!']);
//=> 'run and climb!'

arrford(['run!']);
//=> 'run!'


Install

npm install --save arrford


Read More

https://github.com/dawsonbotsford/arrford


Try it yourself

Tonic link

Checking on a thread / remove from list

As TokenMacGuy says, you should use thread.is_alive() to check if a thread is still running. To remove no longer running threads from your list you can use a list comprehension:

for t in my_threads:
    if not t.is_alive():
        # get results from thread
        t.handled = True
my_threads = [t for t in my_threads if not t.handled]

This avoids the problem of removing items from a list while iterating over it.

Always pass weak reference of self into block in ARC?

It helps not to focus on the strong or weak part of the discussion. Instead focus on the cycle part.

A retain cycle is a loop that happens when Object A retains Object B, and Object B retains Object A. In that situation, if either object is released:

  • Object A won't be deallocated because Object B holds a reference to it.
  • But Object B won't ever be deallocated as long as Object A has a reference to it.
  • But Object A will never be deallocated because Object B holds a reference to it.
  • ad infinitum

Thus, those two objects will just hang around in memory for the life of the program even though they should, if everything were working properly, be deallocated.

So, what we're worried about is retain cycles, and there's nothing about blocks in and of themselves that create these cycles. This isn't a problem, for example:

[myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){
   [self doSomethingWithObject:obj];
}];

The block retains self, but self doesn't retain the block. If one or the other is released, no cycle is created and everything gets deallocated as it should.

Where you get into trouble is something like:

//In the interface:
@property (strong) void(^myBlock)(id obj, NSUInteger idx, BOOL *stop);

//In the implementation:
[self setMyBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  [self doSomethingWithObj:obj];     
}];

Now, your object (self) has an explicit strong reference to the block. And the block has an implicit strong reference to self. That's a cycle, and now neither object will be deallocated properly.

Because, in a situation like this, self by definition already has a strong reference to the block, it's usually easiest to resolve by making an explicitly weak reference to self for the block to use:

__weak MyObject *weakSelf = self;
[self setMyBlock:^(id obj, NSUInteger idx, BOOL *stop) {
  [weakSelf doSomethingWithObj:obj];     
}];

But this should not be the default pattern you follow when dealing with blocks that call self! This should only be used to break what would otherwise be a retain cycle between self and the block. If you were to adopt this pattern everywhere, you'd run the risk of passing a block to something that got executed after self was deallocated.

//SUSPICIOUS EXAMPLE:
__weak MyObject *weakSelf = self;
[[SomeOtherObject alloc] initWithCompletion:^{
  //By the time this gets called, "weakSelf" might be nil because it's not retained!
  [weakSelf doSomething];
}];

How do I update Homebrew?

Alternatively you could update brew by installing it again. (Think I did this as El Capitan changed something)

Note: this is a heavy handed approach that will remove all applications installed via brew!

Try to install brew a fresh and it will tell how to uninstall.

At original time of writing to uninstall:

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"

Edit: As of 2020 to uninstall:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall.sh)"

How to run crontab job every week on Sunday

10 * * * Sun

Position 1 for minutes, allowed values are 1-60
position 2 for hours, allowed values are 1-24
position 3 for day of month ,allowed values are 1-31
position 4 for month ,allowed values are 1-12 
position 5 for day of week ,allowed values are 1-7 or and the day starts at Monday. 

Imported a csv-dataset to R but the values becomes factors

By default, read.csv checks the first few rows of your data to see whether to treat each variable as numeric. If it finds non-numeric values, it assumes the variable is character data, and character variables are converted to factors.

It looks like the PTS and MP variables in your dataset contain non-numerics, which is why you're getting unexpected results. You can force these variables to numeric with

point <- as.numeric(as.character(point))
time <- as.numeric(as.character(time))

But any values that can't be converted will become missing. (The R FAQ gives a slightly different method for factor -> numeric conversion but I can never remember what it is.)

Displaying output of a remote command with Ansible

If you pass the -v flag to the ansible-playbook command, then ansible will show the output on your terminal.

For your use case, you may want to try using the fetch module to copy the public key from the server to your local machine. That way, it will only show a "changed" status when the file changes.

Cloudfront custom-origin distribution returns 502 "ERROR The request could not be satisfied." for some URLs

The problem, in my case, was that I was using Amazon's Cloudflare and Cloudfront's Cloudfront in tandem, and Cloudfront did not like the settings that I had provided Cloudflare.

More specifically, in the Crypto settings on Cloudflare, I had set the "Minimum TLS Settings" to 1.2, without enabling the TLS 1.2 communication setting for the distribution in Cloudfront. This was enough to make Cloudfront declare a 502 Bad Gateway error when it tried to connect to the Cloudflare-protected server.

To fix this, I had to disable SSLv3 support in the Origin Settings for that Cloudfront distribution, and enable TLS 1.2 as a supported protocol for that origin server.

To debug this problem, I used command-line versions of curl, to see what Cloudfront was actually returning when you asked for an image from its CDN, and I also used the command-line version of openssl, to determine exactly which protocols Cloudflare was offering (it wasn't offering TLS 1.0).

tl:dr; make sure everything accepts and asks for TLS 1.2, or whatever latest and greatest TLS everyone is using by the time you read this.

one line if statement in php

Something like this?

($var > 2 ? echo "greater" : echo "smaller")

HTML5 iFrame Seamless Attribute

Updated: October 2016

The seamless attribute no longer exists. It was originally pitched to be included in the first HTML5 spec, but subsequently dropped. An unrelated attribute of the same name made a brief cameo in the HTML5.1 draft, but that too was ditched mid-2016:

So I think the gist of it all both from the implementor side and the web-dev side is that seamless as-specced doesn’t seem to be what anybody wanted to begin with. Or at least it’s more than anybody actually wanted. And anyway like @annevk says, it’s seems a lot of it’s since been “overcome by events” in light of Shadow DOM.

In other words: purge the seamless attribute from your memory, and pretend it never existed.

For posterity's sake, here's my original answer from five years ago:

Original answer: April 2011

The attribute is in draft mode at the moment. For that reason, none of the current browsers are supporting it yet (as the implementation is subject to change). In the meantime, it's best just to use CSS to strip the borders/scrollbars from the iframe:

iframe[seamless]{
    background-color: transparent;
    border: 0px none transparent;
    padding: 0px;
    overflow: hidden;
}

There's more to the seamless attribute than what can be added with CSS: part of the reasoning behind the attribute was to allow nested content to inherit the same styles applied to the iframe (acting as though the embedded document was one big nested inside the element, for example).

Lastly, versions of Internet Explorer (8 and earlier) require additional attributes in order to remove the borders, scrollbars and background colour:

<iframe frameborder="0" allowtransparency="true" scrolling="no" src="..."></iframe>

Naturally, this doesn't validate. So it's up to you how to handle it. My (picky) approach would be to sniff the agent string and add the attributes for IE versions earlier than 9.

Hope that helps. :)

Can't use WAMP , port 80 is used by IIS 7.5

By default WampServer is installed to port 80 which is already used by IIS. To set WampServer to use an open port, left click on the WampServer icon in the system tray and go to Apache > httpd.conf

Open the httpd.conf in Notepad. press ctrl+f and search for "Listen 80", change this line to "Listen 8080" (u can change this port as what you want), and then close and save the httpd.conf file.

Open a web browser and enter "[];, this will open the WampServer configuration page where you can configure Apache, MySQL, and PHP.

and some times this problem may occur because of skype also use 80 as default port hope this will help

input type=file show only button

So here's the best way to do this FOR ALL BROWSERS:

Forget CSS!

<p>Append Image:</p> 
<input type="button" id="clickImage" value="Add Image" />
<input type="file" name="images[]" id="images" multiple />

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" charset="utf-8"></script>

<script>
$('#images').hide();        
$('#clickImage').click( function() {    
    $('#images').trigger('click');  
});
</script>

ASP.NET MVC 3 Razor: Include JavaScript file in the head tag

You can use Named Sections.

_Layout.cshtml

<head>
    <script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
    @RenderSection("JavaScript", required: false)
</head>

_SomeView.cshtml

@section JavaScript
{
   <script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
   <script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}

JSON string to JS object

You can use eval(jsonString) if you trust the data in the string, otherwise you'll need to parse it properly - check json.org for some code samples.

The operation cannot be completed because the DbContext has been disposed error

You need to remember that IQueryable queries are not actually executed against the data store until you enumerate them.

using (var dataContext = new dataContext())
{

This line of code doesn't actually do anything other than build the SQL statement

    users = dataContext.Users.Where(x => x.AccountID == accountId && x.IsAdmin == false);

.Any() is an operation that enumerates the IQueryable, so the SQL is sent to the data source (through dataContext), and then the .Any() operations is executed against it

    if(users.Any() == false)
    {
        return null;
    }
}

Your "problem" line is reusing the sql built above, and then doing an additional operation (.Select()), which just adds to the query. If you left it here, no exception, except your problem line

return users.Select(x => x.ToInfo()).ToList(); // this line is the problem

calls .ToList(), which enumerates the IQueryable, which causes the SQL to be sent to the datasource through the dataContext that was used in the original LINQ query. Since this dataContext has been disposed, it is no longer valid, and .ToList() throws an exception.

That is the "why it doesn't work". The fix is to move this line of code inside the scope of your dataContext.

How to use it properly is another question with a few arguably correct answers that depend on your application (Forms vs. ASP.net vs. MVC, etc.). The pattern that this implements is the Unit of Work pattern. There is almost no cost to creating a new context object, so the general rule is to create one, do your work, and then dispose of it. In web apps, some people will create a Context per request.

Converting double to string

Complete Info

You can use String.valueOf() for float, double, int, boolean etc.

double d = 0;
float f = 0;
int i = 0;
short i1 = 0;
char c = 0;
boolean bool = false;
char[] chars = {};
Object obj = new Object();


String.valueOf(d);
String.valueOf(i);
String.valueOf(i1);
String.valueOf(f);
String.valueOf(c);
String.valueOf(chars);
String.valueOf(bool);
String.valueOf(obj);

Subversion ignoring "--password" and "--username" options

Look to your local svn repo and look into directory .svn . there is file: entries look into them and you'll see lines begins with: svn+ssh://

this is your first configuration maked by svn checkout 'repo_source' or svn co 'repo_source'

if you want to change this, te best way is completly refresh this repository. update/commit what you should for save work. then remove completly directory and last step is create this by svn co/checkout 'URI-for-main-repo' [optionally local directory for store]

you should select connection method to repo file:// svn+ssh:// http:// https:// or other described in documentation.

after that you use svn update/commit as usual.

this topic looks like out of topic. better you go to superuser pages.

Style the first <td> column of a table differently

To select the first column of a table you can use this syntax

tr td:nth-child(1n + 2){
  padding-left: 10px;
}

Identifying country by IP address

Here is my solution in Python 3.x to return geo-location info given a dataframe containing IP Address(s); efficient parallelized application of function on vectorized pd.series/dataframe is the way to go.

Will contrast performance of two popular libraries to return location.

TLDR: use geolite2 method.

1. geolite2 package from geolite2 library

Input

# !pip install maxminddb-geolite2
import time
from geolite2 import geolite2
geo = geolite2.reader()
df_1 = train_data.loc[:50,['IP_Address']]

def IP_info_1(ip):
    try:
        x = geo.get(ip)
    except ValueError:   #Faulty IP value
        return np.nan
    try:
        return x['country']['names']['en'] if x is not None else np.nan
    except KeyError:   #Faulty Key value
        return np.nan

s_time = time.time()
# map IP --> country
#apply(fn) applies fn. on all pd.series elements
df_1['country'] = df_1.loc[:,'IP_Address'].apply(IP_info_1)
print(df_1.head(), '\n')
print('Time:',str(time.time()-s_time)+'s \n')

print(type(geo.get('48.151.136.76')))

Output

       IP_Address         country
0   48.151.136.76   United States
1    94.9.145.169  United Kingdom
2   58.94.157.121           Japan
3  193.187.41.186         Austria
4   125.96.20.172           China 

Time: 0.09906983375549316s 

<class 'dict'>

2. DbIpCity package from ip2geotools library

Input

# !pip install ip2geotools
import time
s_time = time.time()
from ip2geotools.databases.noncommercial import DbIpCity
df_2 = train_data.loc[:50,['IP_Address']]
def IP_info_2(ip):
    try:
        return DbIpCity.get(ip, api_key = 'free').country
    except:
        return np.nan
df_2['country'] = df_2.loc[:, 'IP_Address'].apply(IP_info_2)
print(df_2.head())
print('Time:',str(time.time()-s_time)+'s')

print(type(DbIpCity.get('48.151.136.76',api_key = 'free')))

Output

       IP_Address country
0   48.151.136.76      US
1    94.9.145.169      GB
2   58.94.157.121      JP
3  193.187.41.186      AT
4   125.96.20.172      CN

Time: 80.53318452835083s 

<class 'ip2geotools.models.IpLocation'>

A reason why the huge time difference could be due to the Data structure of the output, i.e direct subsetting from dictionaries seems way more efficient than indexing from the specicialized ip2geotools.models.IpLocation object.

Also, the output of the 1st method is dictionary containing geo-location data, subset respecitively to obtain needed info:

x = geolite2.reader().get('48.151.136.76')
print(x)

>>>
    {'city': {'geoname_id': 5101798, 'names': {'de': 'Newark', 'en': 'Newark', 'es': 'Newark', 'fr': 'Newark', 'ja': '??????', 'pt-BR': 'Newark', 'ru': '??????'}},

 'continent': {'code': 'NA', 'geoname_id': 6255149, 'names': {'de': 'Nordamerika', 'en': 'North America', 'es': 'Norteamérica', 'fr': 'Amérique du Nord', 'ja': '?????', 'pt-BR': 'América do Norte', 'ru': '???????? ???????', 'zh-CN': '???'}}, 

'country': {'geoname_id': 6252001, 'iso_code': 'US', 'names': {'de': 'USA', 'en': 'United States', 'es': 'Estados Unidos', 'fr': 'États-Unis', 'ja': '???????', 'pt-BR': 'Estados Unidos', 'ru': '???', 'zh-CN': '??'}}, 

'location': {'accuracy_radius': 1000, 'latitude': 40.7355, 'longitude': -74.1741, 'metro_code': 501, 'time_zone': 'America/New_York'}, 

'postal': {'code': '07102'}, 

'registered_country': {'geoname_id': 6252001, 'iso_code': 'US', 'names': {'de': 'USA', 'en': 'United States', 'es': 'Estados Unidos', 'fr': 'États-Unis', 'ja': '???????', 'pt-BR': 'Estados Unidos', 'ru': '???', 'zh-CN': '??'}}, 

'subdivisions': [{'geoname_id': 5101760, 'iso_code': 'NJ', 'names': {'en': 'New Jersey', 'es': 'Nueva Jersey', 'fr': 'New Jersey', 'ja': '?????????', 'pt-BR': 'Nova Jérsia', 'ru': '???-??????', 'zh-CN': '????'}}]}

Rails where condition using NOT NIL

The canonical way to do this with Rails 3:

Foo.includes(:bar).where("bars.id IS NOT NULL")

ActiveRecord 4.0 and above adds where.not so you can do this:

Foo.includes(:bar).where.not('bars.id' => nil)
Foo.includes(:bar).where.not(bars: { id: nil })

When working with scopes between tables, I prefer to leverage merge so that I can use existing scopes more easily.

Foo.includes(:bar).merge(Bar.where.not(id: nil))

Also, since includes does not always choose a join strategy, you should use references here as well, otherwise you may end up with invalid SQL.

Foo.includes(:bar)
   .references(:bar)
   .merge(Bar.where.not(id: nil))

How do I put text on ProgressBar?

Just want to point out something on @codingbadger answer. When using "ProgressBarRenderer" you should always check for "ProgressBarRenderer.IsSupported" before using the class. For me, this has been a nightmare with Visual Styles errors in Win7 that I couldn't fix. So, a better approach and workaround for the solution would be:

Rectangle clip = new Rectangle(rect.X, rect.Y, (int)Math.Round(((float)Value / Maximum) * rect.Width), rect.Height);
if (ProgressBarRenderer.IsSupported)
  ProgressBarRenderer.DrawHorizontalChunks(g, clip);
else
  g.FillRectangle(new SolidBrush(this.ForeColor), clip);

Notice that the fill will be a simple rectangle and not chunks. Chunks will be used only if ProgressBarRenderer is supported

How do I calculate the percentage of a number?

$percentage = 50;
$totalWidth = 350;

$new_width = ($percentage / 100) * $totalWidth;

Leaflet changing Marker color

Since you are working with svg elements you could feed your leaflet marker's icon with L.divIcon's html property instead of using iconUrl from L.icon to link your image.

L.marker(latlng, {
    icon: L.divIcon({
        className: 'ship-div-icon',
        html: '<svg>...</svg>'
    })
}).addTo(map);

Then use CSS fill property to color your svg shape. It could be useful to add a class\es to svg's path\s to have precise control

<svg ... >
    <g>
        <path class="ship-icon" ... />
    </g>
    ...
</svg>

At the end, as I also needed to randomly change the marker color I changed directly the path's fill property at the time of creating the marker

var pathFillColor = '#'+(Math.random()*0xFFFFFF<<0).toString(16);

L.marker(latlng, {
    icon: L.divIcon({
        className: 'ship-div-icon',
        html: '<svg ... ><g><path fill="'+pathFillColor+'" ... /> </g></svg>'
    })
}).addTo(map);

How do I get the value of a textbox using jQuery?

Use the .val() method to get the actual value of the element you need.

How to fill in proxy information in cntlm config file?

Without any configuration, you can simply issue the following command (modifying myusername and mydomain with your own information):

cntlm -u myusername -d mydomain -H

or

cntlm -u myusername@mydomain -H

It will ask you the password of myusername and will give you the following output:

PassLM          1AD35398BE6565DDB5C4EF70C0593492
PassNT          77B9081511704EE852F94227CF48A793
PassNTLMv2      A8FC9092D566461E6BEA971931EF1AEC    # Only for user 'myusername', domain 'mydomain'

Then create the file cntlm.ini (or cntlm.conf on Linux using default path) with the following content (replacing your myusername, mydomain and A8FC9092D566461E6BEA971931EF1AEC with your information and the result of the previous command):

Username    myusername
Domain      mydomain

Proxy       my_proxy_server.com:80
NoProxy     127.0.0.*, 192.168.*

Listen      127.0.0.1:5865
Gateway     yes

SOCKS5Proxy 5866

Auth        NTLMv2
PassNTLMv2  A8FC9092D566461E6BEA971931EF1AEC

Then you will have a local open proxy on local port 5865 and another one understanding SOCKS5 protocol at local port 5866.

@Autowired - No qualifying bean of type found for dependency

Can you try annotating only your concrete implementation with @Component? Maybe the following answer could help. It is kind of a similar problem. I usually put Spring annotations in the implementation classes.

https://stackoverflow.com/a/10322456/2619091

How to hide .php extension in .htaccess

I've used this:

RewriteEngine On

# Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ http://example.com/folder/$1 [R=301,L]

# Redirect external .php requests to extensionless URL
RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(.+)\.php$ http://example.com/folder/$1 [R=301,L]

# Resolve .php file for extensionless PHP URLs
RewriteRule ^([^/.]+)$ $1.php [L]

See also: this question

How do you synchronise projects to GitHub with Android Studio?

For existing project end existing repository with files:

git init
git remote add origin <.git>
git checkout -b master
git branch --set-upstream-to=origin/master master
git pull --allow-unrelated-histories

How to jump to top of browser page

If you're using jQuery UI dialog, you could just style the modal to appear with the position fixed in the window so it doesn't pop-up out of view, negating the need to scroll. Otherwise,

var scrollTop = function() {
    window.scrollTo(0, 0);
};

should do the trick.

Executing a batch script on Windows shutdown

I found this topic while searching for run script for startup and shutdown Windows 10. Those answers above didn't working. For me on windows 10 worked when I put scripts to task scheduler. How to do this: press window key and write Task scheduler, open it, then on the right is Add task... button. Here you can add scripts. PS: I found action for startup and logout user, there is not for shutdown.

An App ID with Identifier '' is not available. Please enter a different string

You may have no app with that same ID, but someone else may. The IDs must be unique globally, and not only within your own apps.

How to preserve insertion order in HashMap?

HashMap is unordered per the second line of the documentation:

This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

Perhaps you can do as aix suggests and use a LinkedHashMap, or another ordered collection. This link can help you find the most appropriate collection to use.

Running CMake on Windows

The default generator for Windows seems to be set to NMAKE. Try to use:

cmake -G "MinGW Makefiles"

Or use the GUI, and select MinGW Makefiles when prompted for a generator. Don't forget to cleanup the directory where you tried to run CMake, or delete the cache in the GUI. Otherwise, it will try again with NMAKE.

Showing empty view when ListView is empty

First check the list contains some values:

if (list.isEmpty()) {
    listview.setVisibility(View.GONE);
}

If it is then OK, otherwise use:

else {
     listview.setVisibility(View.VISIBLE);
}

How would you make two <div>s overlap?

Just use negative margins, in the second div say:

<div style="margin-top: -25px;">

And make sure to set the z-index property to get the layering you want.

Bootstrap 3 : Vertically Center Navigation Links when Logo Increasing The Height of Navbar

add this to your stylesheet. line-height should match the height of your logo

.navbar-nav li a {
 line-height: 50px;
}

Check out the fiddle at: http://jsfiddle.net/nD4tW/

Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies

I am using Visual Studio 2013 Update 2. In my case, I have a web project and a Web Api project and unit test project and other class libraries in a single solution.

I've spent couple of days to solve the problem. Below is the step-by-step solution that I have found.

  1. Right click on Web Api project. Select "Set as StartUp Project"
  2. Right click on Web Api project. Go to Properties ( Alt + Enter ).
  3. On the Application tab on left hand side menu, select Application
  4. Find Target framework. Change it to 4.5.1 and save. However, it is showing error in "Error List" window. After Rebuild, there is no error.
  5. Remove all Newtonsoft.Json packs from solution by using below query from Package Manager Console ( to get it View > Other Window > Package Manager Console ).

uninstall-package newtonsoft.json -force

  1. Reinstall Newtonsoft.Json from Package Manager Console

install-package newtonsoft.json

  1. If you have latest update for Visual Studio 2013, you might not encounter with this problem. As I am using Update 2, so, while trying to install Newtonsoft.Json, I have encountered with the following error.

The 'Newtonsoft.Json 10.0.3' package requires NuGet client version '2.12' or above, but the current NuGet version i s '2.8.50313.46'

  1. To solve this problem, we need to update the Package Manager Console. Got to

Tools > Extensions and Updates... > In left pane.. select Updates > Visual Studio Gallery.

  1. Update the NuGet Package Manager Extension. Follow the steps that are coming afterwards.

  2. Visual Studio will take a restart after that.

  3. Execute step 6 again.

After Installation packages.config will be added with this below line

  <package id="Newtonsoft.Json" version="10.0.3" targetFramework="net451" />

After installation web.config will be added with this below lines

<dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />
</dependentAssembly>

It will execute successfully, if there is no other error.

How to Replace dot (.) in a string in Java

return sentence.replaceAll("\s",".");

Fatal error: Call to undefined function sqlsrv_connect()

This helped me get to my answer. There are two php.ini files located, in my case, for wamp. One is under the php folder and the other one is in the C:\wamp\bin\apache\Apachex.x.x\bin folder. When connecting to SQL through sqlsrv_connect function, we are referring to the php.ini file in the apache folder. Add the following (as per your version) to this file:

extension=c:/wamp/bin/php/php5.4.16/ext/php_sqlsrv_53_ts.dll

Populate nested array in mongoose

You can do this using $lookup aggregation as well and probably the best way as now populate is becoming extinct from the mongo

Project.aggregate([
  { "$match": { "_id": mongoose.Types.ObjectId(id) } },
  { "$lookup": {
    "from": Pages.collection.name,
    "let": { "pages": "$pages" },
    "pipeline": [
      { "$match": { "$expr": { "$in": [ "$_id", "$$pages" ] } } },
      { "$lookup": {
        "from": Component.collection.name,
        "let": { "components": "$components" },
        "pipeline": [
          { "$match": { "$expr": { "$in": [ "$_id", "$$components" ] } } },
        ],
        "as": "components"
      }},
    ],
    "as": "pages"
  }}
])

Override back button to act like home button

if it helps someone else, I had an activity with 2 layouts that I toggled on and off for visibilty, trying to emulate a kind of page1 > page2 structure. if they were on page 2 and pressed the back button I wanted them to go back to page 1, if they pressed the back button on page 1 it should still work as normal. Its pretty basic but it works

@Override
public void onBackPressed() {
// check if page 2 is open
    RelativeLayout page2layout = (RelativeLayout)findViewById(R.id.page2layout);
    if(page2layout.getVisibility() == View.VISIBLE){
        togglePageLayout(); // my method to toggle the views
        return;
    }else{
        super.onBackPressed(); // allows standard use of backbutton for page 1
    }

}

hope it helps someone, cheers

How to execute Ant build in command line

is it still actual?

As I can see you wrote <target depends="build-subprojects,build-project" name="build"/>, then you wrote <target name="build-subprojects"/> (it does nothing). Could it be a reason? Does this <echo message="${ant.project.name}: ${ant.file}"/> print appropriate message? If no then target is not running. Take a look at the next link http://www.sqaforums.com/showflat.php?Number=623277

How do I select between the 1st day of the current month and current day in MySQL?

I was looking for a similar query where I needed to use the first day of a month in my query. The last_day function didn't work for me but DAYOFMONTH came in handy.

So if anyone is looking for the same issue, the following code returns the date for first day of the current month.

SELECT DATE_SUB(CURRENT_DATE, INTERVAL DAYOFMONTH(CURRENT_DATE)-1 DAY);

Comparing a date column with the first day of the month :

select * from table_name where date between 
DATE_SUB(CURRENT_DATE, INTERVAL DAYOFMONTH(CURRENT_DATE)-1 DAY) and CURRENT_DATE

C Programming: How to read the whole file contents into a buffer

Here is what I would recommend.

It should conform to C89, and be completely portable. In particular, it works also on pipes and sockets on POSIXy systems.

The idea is that we read the input in large-ish chunks (READALL_CHUNK), dynamically reallocating the buffer as we need it. We only use realloc(), fread(), ferror(), and free():

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>

/* Size of each input chunk to be
   read and allocate for. */
#ifndef  READALL_CHUNK
#define  READALL_CHUNK  262144
#endif

#define  READALL_OK          0  /* Success */
#define  READALL_INVALID    -1  /* Invalid parameters */
#define  READALL_ERROR      -2  /* Stream error */
#define  READALL_TOOMUCH    -3  /* Too much input */
#define  READALL_NOMEM      -4  /* Out of memory */

/* This function returns one of the READALL_ constants above.
   If the return value is zero == READALL_OK, then:
     (*dataptr) points to a dynamically allocated buffer, with
     (*sizeptr) chars read from the file.
     The buffer is allocated for one extra char, which is NUL,
     and automatically appended after the data.
   Initial values of (*dataptr) and (*sizeptr) are ignored.
*/
int readall(FILE *in, char **dataptr, size_t *sizeptr)
{
    char  *data = NULL, *temp;
    size_t size = 0;
    size_t used = 0;
    size_t n;

    /* None of the parameters can be NULL. */
    if (in == NULL || dataptr == NULL || sizeptr == NULL)
        return READALL_INVALID;

    /* A read error already occurred? */
    if (ferror(in))
        return READALL_ERROR;

    while (1) {

        if (used + READALL_CHUNK + 1 > size) {
            size = used + READALL_CHUNK + 1;

            /* Overflow check. Some ANSI C compilers
               may optimize this away, though. */
            if (size <= used) {
                free(data);
                return READALL_TOOMUCH;
            }

            temp = realloc(data, size);
            if (temp == NULL) {
                free(data);
                return READALL_NOMEM;
            }
            data = temp;
        }

        n = fread(data + used, 1, READALL_CHUNK, in);
        if (n == 0)
            break;

        used += n;
    }

    if (ferror(in)) {
        free(data);
        return READALL_ERROR;
    }

    temp = realloc(data, used + 1);
    if (temp == NULL) {
        free(data);
        return READALL_NOMEM;
    }
    data = temp;
    data[used] = '\0';

    *dataptr = data;
    *sizeptr = used;

    return READALL_OK;
}

Above, I've used a constant chunk size, READALL_CHUNK == 262144 (256*1024). This means that in the worst case, up to 262145 chars are wasted (allocated but not used), but only temporarily. At the end, the function reallocates the buffer to the optimal size. Also, this means that we do four reallocations per megabyte of data read.

The 262144-byte default in the code above is a conservative value; it works well for even old minilaptops and Raspberry Pis and most embedded devices with at least a few megabytes of RAM available for the process. Yet, it is not so small that it slows down the operation (due to many read calls, and many buffer reallocations) on most systems.

For desktop machines at this time (2017), I recommend a much larger READALL_CHUNK, perhaps #define READALL_CHUNK 2097152 (2 MiB).

Because the definition of READALL_CHUNK is guarded (i.e., it is defined only if it is at that point in the code still undefined), you can override the default value at compile time, by using (in most C compilers) -DREADALL_CHUNK=2097152 command-line option -- but do check your compiler options for defining a preprocessor macro using command-line options.

Changing Locale within the app itself

After a good night of sleep, I found the answer on the Web (a simple Google search on the following line "getBaseContext().getResources().updateConfiguration(mConfig, getBaseContext().getResources().getDisplayMetrics());"), here it is :

link text => this link also shows screenshots of what is happening !

Density was the issue here, I needed to have this in the AndroidManifest.xml

<supports-screens
android:smallScreens="true"
android:normalScreens="true"
android:largeScreens="true"
android:anyDensity="true"
/>

The most important is the android:anyDensity =" true ".

Don't forget to add the following in the AndroidManifest.xml for every activity (for Android 4.1 and below):

android:configChanges="locale"

This version is needed when you build for Android 4.2 (API level 17) explanation here:

android:configChanges="locale|layoutDirection"

Spark - load CSV file as DataFrame?

Default file format is Parquet with spark.read.. and file reading csv that why you are getting the exception. Specify csv format with api you are trying to use

Resize to fit image in div, and center horizontally and vertically

Only tested in Chrome 44.

Example: http://codepen.io/hugovk/pen/OVqBoq

HTML:

<div>
<img src="http://lorempixel.com/1600/900/">
</div>

CSS:

<style type="text/css">
img {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
    max-width: 100%;
    max-height: 100%;
}
</style>

Simple search MySQL database using php

I think its works for everyone

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Search</title>
</head>

<body>
    <form action="" method="post">
        <input type="text" placeholder="Search" name="search">
        <button type="submit" name="submit">Search</button>
    </form>
</body>

</html>
<?php


if (isset($_POST['submit'])) {
    $searchValue = $_POST['search'];
    $con = new mysqli("localhost", "root", "", "testing");
    if ($con->connect_error) {
        echo "connection Failed: " . $con->connect_error;
    } else {
        $sql = "SELECT * FROM customer_info WHERE name OR email LIKE '%$searchValue%'";

        $result = $con->query($sql);
        while ($row = $result->fetch_assoc()) {
            echo $row['name'] . "<br>";
            echo $row['email'] . "<br>";
        }

      
    }   
}



?>

ObjectiveC Parse Integer from String

NSArray *_returnedArguments = [serverOutput componentsSeparatedByString:@":"];

_returnedArguments is an array of NSStrings which the UITextField text property is expecting. No need to convert.

Syntax error:

[_appDelegate loggedIn:usernameField.text:passwordField.text:(int)[[_returnedArguments objectAtIndex:2] intValue]];

If your _appDelegate has a passwordField property, then you can set the text using the following

[[_appDelegate passwordField] setText:[_returnedArguments objectAtIndex:2]];

How do I check what version of Python is running my script?

Check Python version: python -V or python --version or apt-cache policy python

you can also run whereis python to see how many versions are installed.

http://localhost/phpMyAdmin/ unable to connect

Your web server isn't running! You need to find the XAMPP control panel and start the web server up.

Of course, you might find other problems after that, but this is the first step.

How to send a GET request from PHP?

In the other hand, using REST API of other servers are very popular in PHP. Suppose you are looking for a way to redirect some HTTP requests into the other server (for example getting an xml file). Here is a PHP package to help you:

https://github.com/romanpitak/PHP-REST-Client

So, getting the xml file:

$client = new Client('http://example.com');
$request = $client->newRequest('/filename.xml');
$response = $request->getResponse();
echo $response->getParsedResponse();

How to rename a single column in a data.frame?

I would simply change a column name to the dataset with the new name I want with the following code: names(dataset)[index_value] <- "new_col_name"

Set cursor position on contentEditable <div>

You can leverage selectNodeContents which is supported by modern browsers.

var el = document.getElementById('idOfYoursContentEditable');
var selection = window.getSelection();
var range = document.createRange();
selection.removeAllRanges();
range.selectNodeContents(el);
range.collapse(false);
selection.addRange(range);
el.focus();

How to use LINQ Distinct() with multiple fields

Employee emp1 = new Employee() { ID = 1, Name = "Narendra1", Salary = 11111, Experience = 3, Age = 30 };Employee emp2 = new Employee() { ID = 2, Name = "Narendra2", Salary = 21111, Experience = 10, Age = 38 };
Employee emp3 = new Employee() { ID = 3, Name = "Narendra3", Salary = 31111, Experience = 4, Age = 33 };
Employee emp4 = new Employee() { ID = 3, Name = "Narendra4", Salary = 41111, Experience = 7, Age = 33 };

List<Employee> lstEmployee = new List<Employee>();

lstEmployee.Add(emp1);
lstEmployee.Add(emp2);
lstEmployee.Add(emp3);
lstEmployee.Add(emp4);

var eemmppss=lstEmployee.Select(cc=>new {cc.ID,cc.Age}).Distinct();

getFilesDir() vs Environment.getDataDirectory()

Environment returns user data directory. And getFilesDir returns application data directory.

WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server

So all of these answers are basically the same one. They only address one idea: it has to be DNS related. Well, that is not the only part of this it turns out. After many changes, I was getting nowhere reading the next "same answer" hoping that it would just go my way.

What did the trick for me was to adjust my versions of Apache. I think what the deal was, is that the one of the configuration files get a path off or that the install due to IIS may have been messed up / or / or /etc. And so forcing a version change readdresses everything from your firewall to bad configurations.

In fact, when I switched back to Apache 2.4.2 it goes back to being a forbidden. And as soon as I go back to Apache 2.4.4 it comes back up. That rules out local network issues. I just wanted to point out that all of the answers here are the same and that I have been able to kill the forbidden by changing the Apache version.

PHP XML Extension: Not installed

You're close

sudo apt-get install php-xml

Then you need to restart apache so it takes effect

sudo service apache2 restart

How to create a connection string in asp.net c#

It occurs when IIS is not being connected to SQL SERVER. For a solution, see this screenshot: Solution

How to get all possible combinations of a list’s elements?

flag = 0
requiredCals =12
from itertools import chain, combinations

def powerset(iterable):
    s = list(iterable)  # allows duplicate elements
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

stuff = [2,9,5,1,6]
for i, combo in enumerate(powerset(stuff), 1):
    if(len(combo)>0):
        #print(combo , sum(combo))
        if(sum(combo)== requiredCals):
            flag = 1
            break
if(flag==1):
    print('True')
else:
    print('else')

SQL - Select first 10 rows only?

Depends on your RDBMS

MS SQL Server

SELECT TOP 10 ...

MySQL

SELECT ... LIMIT 10

Sybase

SET ROWCOUNT 10
SELECT ...

Etc.

Moment.js - two dates difference in number of days

const FindDate = (date, allDate) => {
        
    // moment().diff only works on moment(). Make sure both date and elements in allDate array are in moment format
    let nearestDate = -1; 
    
    allDate.some(d => {
        const currentDate = moment(d)
        const difference = currentDate.diff(d); // Or d.diff(date) depending on what you're trying to find
        if(difference >= 0){
            nearestDate = d
        }
    });
    
    console.log(nearestDate)
}

Swift - Remove " character from string

Replacing for Removing is not quite logical. String.filter allows to iterate a string char by char and keep only true assertion.

Swift 4 & 5

var aString = "Optional(\"5\")"

aString = aString.filter { $0 != "\"" }

> Optional(5)

Or to extend

var aString = "Optional(\"5\")"

let filteredChars = "\"\n\t"

aString = aString.filter { filteredChars.range(of: String($0)) == nil }

> Optional(5)

Loading state button in Bootstrap 3

You need to detect the click from js side, your HTML remaining same. Note: this method is deprecated since v3.5.5 and removed in v4.

$("button").click(function() {
    var $btn = $(this);
    $btn.button('loading');
    // simulating a timeout
    setTimeout(function () {
        $btn.button('reset');
    }, 1000);
});

Also, don't forget to load jQuery and Bootstrap js (based on jQuery) file in your page.

JSFIDDLE

Official Documentation

How to format JSON in notepad++

Here are the steps to install JSToolNPP plugin on your Notepad++.

  1. Download 64bit version from Sourceforge or the 32bit version if you are on a 32-bit OS.

    64bit - JSToolNPP.1.21.0.uni.64.zip: Download from SourceForget.net
    
  2. Notepad++ before installation

does not show JSTool in the Plugins menu.

  1. Unzip the downloaded JSToolNPP.1.21.0.uni.64 and copy the JSMinNPP.dll and place it under C:\Program Files\Notepad++\plugins.

  2. Close Notepad++ and reopen it. If you have downloaded an incompatible dll, then it will complain, else it will open successfully. If it complains about incompatibility, go back to STEP 1 and download the correct bit version as per your OS. Check Plugins in Notepad++.

JSTool is now located in the Plugins menu.

  1. Paste a sample unformatted but valid JSON data in Notepad++.

  2. Select all text in Notepad++ (CTRL+A) and format using Plugins -> JSTool -> JSFormat.

NOTE: On side note, if you do not want to install any plugins like this, I would recommend using the following 2 best online formatters.

Convert between UIImage and Base64 string

Decoding using convenience initialiser - Swift 5

extension UIImage {
    convenience init?(base64String: String) {
        guard let data = Data(base64Encoded: base64String) else { return nil }
        self.init(data: data)
    }
} 

How to set background color of a View

and what is the correct way to change the background color on any View?

On any View? What you have is correct, though you should drop the invalidate() call.

However, some Views already have backgrounds. A Button, for example, already has a background: the face of the button itself. This background is a StateListDrawable, which you can find in android-2.1/data/res/drawable/btn_default.xml in your Android SDK installation. That, in turn, refers to a bunch of nine-patch bitmap images, available in multiple densities. You would need to clone and modify all of that to accomplish your green goals.

In short, you will be better served finding another UI pattern rather than attempting to change the background of a Button.

Concatenate in jQuery Selector

There is nothing wrong with syntax of

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

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

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

$(<a string>)

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

To test do:

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

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

SQL Data Reader - handling Null column values

in c# 7.0 we can do :

var a = reader["ERateCode"] as string;
var b = reader["ERateLift"] as int?;
var c = reader["Id"] as int?;

so it will keep null value if it is.

Why can't I use Docker CMD multiple times to run multiple services?

While I respect the answer from qkrijger explaining how you can work around this issue I think there is a lot more we can learn about what's going on here ...

To actually answer your question of "why" ... I think it would for helpful for you to understand how the docker stop command works and that all processes should be shutdown cleanly to prevent problems when you try to restart them (file corruption etc).

Problem: What if docker did start SSH from it's command and started RabbitMQ from your Docker file? "The docker stop command attempts to stop a running container first by sending a SIGTERM signal to the root process (PID 1) in the container." Which process is docker tracking as PID 1 that will get the SIGTERM? Will it be SSH or Rabbit?? "According to the Unix process model, the init process -- PID 1 -- inherits all orphaned child processes and must reap them. Most Docker containers do not have an init process that does this correctly, and as a result their containers become filled with zombie processes over time."

Answer: Docker simply takes that last CMD as the one that will get launched as the root process with PID 1 and get the SIGTERM from docker stop.

Suggested solution: You should use (or create) a base image specifically made for running more than one service, such as phusion/baseimage

It should be important to note that tini exists exactly for this reason, and as of Docker 1.13 and up, tini is officially part of Docker, which tells us that running more than one process in Docker IS VALID .. so even if someone claims to be more skilled regarding Docker, and insists that you absurd for thinking of doing this, know that you are not. There are perfectly valid situations for doing so.

Good to know:

How do I check if a PowerShell module is installed?

Coming from Linux background. I would prefer using something similar to grep, therefore I use Select-String. So even if someone is not sure of the complete module name. They can provide the initials and determine whether the module exists or not.

Get-Module -ListAvailable -All | Select-String Module_Name(can be a part of the module name)

How to run a command in the background on Windows?

You should also take a look at the at command in Windows. It will launch a program at a certain time in the background which works in this case.

Another option is to use the nssm service manager software. This will wrap whatever command you are running as a windows service.

UPDATE:

nssm isn't very good. You should instead look at WinSW project. https://github.com/kohsuke/winsw

How do I parse JSON into an int?

Its very simple.

Example JSON:

{
   "value":1
}


int z = jsonObject.getInt("value");

Removing duplicates from a list of lists

Strangely, the answers above removes the 'duplicates' but what if I want to remove the duplicated value also?? The following should be useful and does not create a new object in memory!

def dictRemoveDuplicates(self):
    a=[[1,'somevalue1'],[1,'somevalue2'],[2,'somevalue1'],[3,'somevalue4'],[5,'somevalue5'],[5,'somevalue1'],[5,'somevalue1'],[5,'somevalue8'],[6,'somevalue9'],[6,'somevalue0'],[6,'somevalue1'],[7,'somevalue7']]


print(a)
temp = 0
position = -1
for pageNo, item in a:
    position+=1
    if pageNo != temp:
        temp = pageNo
        continue
    else:
        a[position] = 0
        a[position - 1] = 0
a = [x for x in a if x != 0]         
print(a)

and the o/p is:

[[1, 'somevalue1'], [1, 'somevalue2'], [2, 'somevalue1'], [3, 'somevalue4'], [5, 'somevalue5'], [5, 'somevalue1'], [5, 'somevalue1'], [5, 'somevalue8'], [6, 'somevalue9'], [6, 'somevalue0'], [6, 'somevalue1'], [7, 'somevalue7']]
[[2, 'somevalue1'], [3, 'somevalue4'], [7, 'somevalue7']]

What's the proper way to "go get" a private repository?

You have one thing to configure. The example is based on GitHub but this shouldn't change the process:

$ git config --global [email protected]:.insteadOf https://github.com/
$ cat ~/.gitconfig
[url "[email protected]:"]
    insteadOf = https://github.com/
$ go get github.com/private/repo

For Go modules to work (with Go 1.11 or newer), you'll also need to set the GOPRIVATE variable, to avoid using the public servers to fetch the code:

export GOPRIVATE=github.com/private/repo

Detect rotation of Android phone in the browser with JavaScript

A little contribution to the two-bit-fool's answer:

As described on the table on droid phones "orientationchange" event gets fired earlier than "resize" event thus blocking the next resize call (because of the if statement). Width property is still not set.

A workaround though maybe not a perfect one could be to not fire the "orientationchange" event. That can be archived by wrapping "orientationchange" event binding in "if" statement:

if (!navigator.userAgent.match(/android/i))
{
    window.addEventListener("orientationchange", checkOrientation, false);
}

Hope it helps

(tests were done on Nexus S)

jQuery: get data attribute

You could use the .attr() function:

$(this).attr('data-fullText')

or if you lowercase the attribute name:

data-fulltext="This is a span element"

then you could use the .data() function:

$(this).data('fulltext')

The .data() function expects and works only with lowercase attribute names.

What's the common practice for enums in Python?

You could probably use an inheritance structure although the more I played with this the dirtier I felt.

class AnimalEnum:
  @classmethod
  def verify(cls, other):
    return issubclass(other.__class__, cls)


class Dog(AnimalEnum):
  pass

def do_something(thing_that_should_be_an_enum):
  if not AnimalEnum.verify(thing_that_should_be_an_enum):
    raise OhGodWhy

How to force a script reload and re-execute?

I know that is to late, but I want to share my answer. What I did it's save de script's tags in a HTML file, locking up the scripts on my Index file in a div with an id, something like this.

<div id="ScriptsReload"><script src="js/script.js"></script></div>

and when I wanted to refresh I just used.

$("#ScriptsReload").load("html_with_scripts_tags.html", "", function(
    response,
    status,
    request
  ) {

  });

Swap DIV position with CSS only

This question already has a great answer but in the spirit of exploring all possibilities here is another technique to reorder dom elements whilst still allowing them to take up their space, unlike the absolute positioning method.

This method works in all modern browsers and IE9+ (basically any browser that supports display:table) it has a drawback that it can only be used on a max of 3 siblings though.

//the html    
<div class='container'>
    <div class='div1'>1</div>
    <div class='div2'>2</div>
    <div class='div3'>3</div>
</div>

//the css
.container {
   display:table;    
}
.div1 {
    display:table-footer-group;
}
.div2 {
    display:table-header-group;
}
.div3 {
    display:table-row-group;
}

This will reorder the elements from 1,2,3 to 2,3,1. Basically anything with the display set to table-header-group will be positioned at the top and table-footer-group at the bottom. Naturally table-row-group puts an element in the middle.

This method is quick with good support and requires much less css than the flexbox approach so if you are only looking to swap a few items around for a mobile layout for example then dont rule out this technique.

You can check out a live demo on codepen: http://codepen.io/thepixelninja/pen/eZVgLx

Reading a registry key in C#

string InstallPath = (string)Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\MyApplication\AppPath", "Installed", null);    
if (InstallPath != null)
{
    // Do stuff
}

That code should get your value. You'll need to be

using Microsoft.Win32;

for that to work though.

Having both a Created and Last Updated timestamp columns in MySQL 4.0

For mysql 5.7.21 I use the following and works fine:

CREATE TABLE Posts ( modified_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP )

kill -3 to get java thread dump

When using kill -3 one should see the thread dump in the standard output. Most of the application servers write the standard output to a separate file. You should find it there when using kill -3. There are multiple ways of getting thread dumps:

  • kill -3 <PID>: Gives output to standard output.
  • If one has access to the console window where server is running, one can use Ctrl+Break combination of keys to generate the stack trace on STDOUT.
  • For hotspot VM's we can also use jstack command to generate a thread dump. It’s a part of the JDK. Syntax is as follows:

    Usage:
    
    jstack [-l] <pid> (to connect to running process)
    jstack -F [-m] [-l] <pid>(to connect to a hung process)
    
     - For JRockit JVM we can use JRCMD command which comes with JDK Syntax: 
       jrcmd <jrockit pid> [<command> [<arguments>]] [-l] [-f file] [-p] -h]
    

Log to the base 2 in python

Try this ,

import math
print(math.log(8,2))  # math.log(number,base) 

MySQL INNER JOIN Alias

Use a seperate column to indicate the join condition

SELECT  t.importid, 
        case 
            when t.importid = g.home 
            then 'home' 
            else 'away' 
        end as join_condition, 
        g.network, 
        g.date_start 
FROM    game g
INNER JOIN team t ON (t.importid = g.home OR t.importid = g.away)
ORDER BY date_start DESC 
LIMIT 7

I got error "The DELETE statement conflicted with the REFERENCE constraint"

The error means that you have data in other tables that references the data you are trying to delete.

You would need to either drop and recreate the constraints or delete the data that the Foreign Key references.

Suppose you have the following tables

dbo.Students
(
StudentId
StudentName
StudentTypeId
)


dbo.StudentTypes
(
StudentTypeId
StudentType
)

Suppose a Foreign Key constraint exists between the StudentTypeId column in StudentTypes and the StudentTypeId column in Students

If you try to delete all the data in StudentTypes an error will occur as the StudentTypeId column in Students reference the data in the StudentTypes table.

EDIT:

DELETE and TRUNCATE essentially do the same thing. The only difference is that TRUNCATE does not save the changes in to the Log file. Also you can't use a WHERE clause with TRUNCATE

AS to why you can run this in SSMS but not via your Application. I really can't see this happening. The FK constraint would still throw an error regardless of where the transaction originated from.

How do I use Bash on Windows from the Visual Studio Code integrated terminal?

This, at least for me, will make Visual Studio Code open a new Bash window as an external terminal.

If you want the integrated environment you need to point to the sh.exe file inside the bin folder of your Git installation.

So the configuration should say C:\\<my-git-install>\\bin\\sh.exe.

How can I change image tintColor in iOS and WatchKit

Try this

http://robots.thoughtbot.com/designing-for-ios-blending-modes

or

- (void)viewDidLoad
{
[super viewDidLoad];

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10, 30, 300, 50)];
label.numberOfLines = 0;
label.font = [UIFont systemFontOfSize:13];
label.text = @"These checkmarks use the same gray checkmark image with a tintColor applied to the image view";
[self.view addSubview:label];

[self _createImageViewAtY:100 color:[UIColor purpleColor]];
}

- (void)_createImageViewAtY:(int)y color:(UIColor *)color {
UIImage *image = [[UIImage imageNamed:@"gray checkmark.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
CGRect frame = imageView.frame;
frame.origin.x = 100;
frame.origin.y = y;
imageView.frame = frame;

if (color)
    imageView.tintColor = color;

[self.view addSubview:imageView];
}

C# Sort and OrderBy comparison

I just want to add that orderby is way more useful.

Why? Because I can do this:

Dim thisAccountBalances = account.DictOfBalances.Values.ToList
thisAccountBalances.ForEach(Sub(x) x.computeBalanceOtherFactors())
thisAccountBalances=thisAccountBalances.OrderBy(Function(x) x.TotalBalance).tolist
listOfBalances.AddRange(thisAccountBalances)

Why complicated comparer? Just sort based on a field. Here I am sorting based on TotalBalance.

Very easy.

I can't do that with sort. I wonder why. Do fine with orderBy.

As for speed it's always O(n).

#define in Java

Comment space too small, so here is some more information for you on the use of static final. As I said in my comment to the Andrzej's answer, only primitive and String are compiled directly into the code as literals. To demonstrate this, try the following:

You can see this in action by creating three classes (in separate files):

public class DisplayValue {
    private String value;

    public DisplayValue(String value) {
        this.value = value;
    }

    public String toString() {
        return value;
    }
}

public class Constants {
    public static final int INT_VALUE = 0;
    public static final DisplayValue VALUE = new DisplayValue("A");
}

public class Test {
    public static void main(String[] args) {
        System.out.println("Int   = " + Constants.INT_VALUE);
        System.out.println("Value = " + Constants.VALUE);
    }
}

Compile these and run Test, which prints:

Int    = 0
Value  = A

Now, change Constants to have a different value for each and just compile class Constants. When you execute Test again (without recompiling the class file) it still prints the old value for INT_VALUE but not VALUE. For example:

public class Constants {
    public static final int INT_VALUE = 2;
    public static final DisplayValue VALUE = new DisplayValue("X");
}

Run Test without recompiling Test.java:

Int    = 0
Value  = X

Note that any other type used with static final is kept as a reference.

Similar to C/C++ #if/#endif, a constant literal or one defined through static final with primitives, used in a regular Java if condition and evaluates to false will cause the compiler to strip the byte code for the statements within the if block (they will not be generated).

private static final boolean DEBUG = false;

if (DEBUG) {
    ...code here...
}

The code at "...code here..." would not be compiled into the byte code. But if you changed DEBUG to true then it would be.

Issue with background color in JavaFX 8

panel.setStyle("-fx-background-color: #FFFFFF;");

How to change button color with tkinter

When you do self.button = Button(...).grid(...), what gets assigned to self.button is the result of the grid() command, not a reference to the Button object created.

You need to assign your self.button variable before packing/griding it. It should look something like this:

self.button = Button(self,text="Click Me",command=self.color_change,bg="blue")
self.button.grid(row = 2, column = 2, sticky = W)

How to detect the OS from a Bash script?

Try using "uname". For example, in Linux: "uname -a".

According to the manual page, uname conforms to SVr4 and POSIX, so it should be available on Mac OS X and Cygwin too, but I can't confirm that.

BTW: $OSTYPE is also set to linux-gnu here :)

Ruby max integer

There is no maximum since Ruby 2.4, as Bignum and Fixnum got unified into Integer. see Feature #12005

> (2 << 1000).is_a? Fixnum
(irb):322: warning: constant ::Fixnum is deprecated
=> true

> 1.is_a? Bignum
(irb):314: warning: constant ::Bignum is deprecated
=> true

> (2 << 1000).class
=> Integer

There won't be any overflow, what would happen is an out of memory.

java collections - keyset() vs entrySet() in map

Every time you call itr2.next() you are getting a distinct value. Not the same value. You should only call this once in the loop.

Iterator<String> itr2 = keys.iterator();
    while(itr2.hasNext()){
        String v = itr2.next();
        System.out.println("Key: "+v+" ,value: "+m.get(v));
    }

How to automatically generate unique id in SQL like UID12345678?

The only viable solution in my opinion is to use

  • an ID INT IDENTITY(1,1) column to get SQL Server to handle the automatic increment of your numeric value
  • a computed, persisted column to convert that numeric value to the value you need

So try this:

CREATE TABLE dbo.tblUsers
  (ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
   UserID AS 'UID' + RIGHT('00000000' + CAST(ID AS VARCHAR(8)), 8) PERSISTED,
   .... your other columns here....
  )

Now, every time you insert a row into tblUsers without specifying values for ID or UserID:

INSERT INTO dbo.tblUsersCol1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)

then SQL Server will automatically and safely increase your ID value, and UserID will contain values like UID00000001, UID00000002,...... and so on - automatically, safely, reliably, no duplicates.

Update: the column UserID is computed - but it still OF COURSE has a data type, as a quick peek into the Object Explorer reveals:

enter image description here

How can I print the contents of an array horizontally?

namespace ReverseString
{
    class Program
    {
        static void Main(string[] args)
        {
            string stat = "This is an example of code" +
                          "This code has written in C#\n\n";

            Console.Write(stat);

            char[] myArrayofChar = stat.ToCharArray();

            Array.Reverse(myArrayofChar);

            foreach (char myNewChar in myArrayofChar)
                Console.Write(myNewChar); // You just need to write the function
                                          // Write instead of WriteLine
            Console.ReadKey();
        }
    }
}

This is the output:

#C ni nettirw sah edoc sihTedoc fo elpmaxe na si sihT

UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory'

Well, you're getting a java.lang.NoClassDefFoundError. In your pom.xml, hibernate-core version is 3.3.2.GA and declared after hibernate-entitymanager, so it prevails. You can remove that dependency, since will be inherited version 3.6.7.Final from hibernate-entitymanager.

You're using spring-boot as parent, so no need to declare version of some dependencies, since they are managed by spring-boot.

Also, hibernate-commons-annotations is inherited from hibernate-entitymanager and hibernate-annotations is an old version of hibernate-commons-annotations, you can remove both.

Finally, your pom.xml can look like this:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.elsys.internetprogramming.trafficspy.server</groupId>
    <artifactId>TrafficSpyService</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.3.RELEASE</version>
    </parent>

    <dependencies>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cloud-connectors</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>javax.persistence</artifactId>
            <version>2.0.0</version>
        </dependency>

        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
        </dependency>

        <!-- MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

    <properties>
        <java.version>1.7</java.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </repository>

        <repository>
            <id>codehaus</id>
            <url>http://repository.codehaus.org/org/codehaus</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>

</project>

Let me know if you have a problem.

How to select only 1 row from oracle sql?

select name, price
  from (
    select name, price, 
    row_number() over (order by price) r
      from items
  )
where r between 1 and 5; 

What's the difference between an argument and a parameter?

Logically speaking,we're actually talking about the same thing. But I think a simple metaphor would be helpful to solve this dilemma.

If the metaphors can be called various connection point we can equate them to plug points on a wall. In this case we can consider parameters and arguments as follows;

Parameters are the sockets of the plug-point which may take various different shapes. But only certain types of plugs fit them.
Arguments will be the actual plugs that would be plugged into the plug points/sockets to activate certain equipments.

Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex)

The answer is not efficiency. Non-reentrant mutexes lead to better code.

Example: A::foo() acquires the lock. It then calls B::bar(). This worked fine when you wrote it. But sometime later someone changes B::bar() to call A::baz(), which also acquires the lock.

Well, if you don't have recursive mutexes, this deadlocks. If you do have them, it runs, but it may break. A::foo() may have left the object in an inconsistent state before calling bar(), on the assumption that baz() couldn't get run because it also acquires the mutex. But it probably shouldn't run! The person who wrote A::foo() assumed that nobody could call A::baz() at the same time - that's the entire reason that both of those methods acquired the lock.

The right mental model for using mutexes: The mutex protects an invariant. When the mutex is held, the invariant may change, but before releasing the mutex, the invariant is re-established. Reentrant locks are dangerous because the second time you acquire the lock you can't be sure the invariant is true any more.

If you are happy with reentrant locks, it is only because you have not had to debug a problem like this before. Java has non-reentrant locks these days in java.util.concurrent.locks, by the way.

Passing just a type as a parameter in C#

foo.GetColumnValues(dm.mainColumn, typeof(int));
foo.GetColumnValues(dm.mainColumn, typeof(string));

Or using generics:

foo.GetColumnValues<int>(dm.mainColumn);
foo.GetColumnValues<string>(dm.mainColumn);

Copy files from one directory into an existing directory

cp -R t1/ t2

The trailing slash on the source directory changes the semantics slightly, so it copies the contents but not the directory itself. It also avoids the problems with globbing and invisible files that Bertrand's answer has (copying t1/* misses invisible files, copying `t1/* t1/.*' copies t1/. and t1/.., which you don't want).

Getting the .Text value from a TextBox

Did you try using t.Text?

Grep for beginning and end of line?

The tricky part is a regex that includes a dash as one of the valid characters in a character class. The dash has to come immediately after the start for a (normal) character class and immediately after the caret for a negated character class. If you need a close square bracket too, then you need the close square bracket followed by the dash. Mercifully, you only need dash, hence the notation chosen.

grep '^[-d]rwx.*[0-9]$' "$@"

See: Regular Expressions and grep for POSIX-standard details.

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in

maybe you forget to add parameter dataType:'json' in your $.ajax

$.ajax({
   type: "POST",
   dataType: "json",
   url: url,
   data: { get_member: id },
   success: function( response ) 
   { 
     //some action here
   },
   error: function( error )
   {
     alert( error );
   }
});

Pandas split column of lists into multiple columns

Here's another solution using df.transform and df.set_index:

>>> (df['teams']
       .transform([lambda x:x[0], lambda x:x[1]])
       .set_axis(['team1','team2'],
                  axis=1,
                  inplace=False)
    )

  team1 team2
0    SF   NYG
1    SF   NYG
2    SF   NYG
3    SF   NYG
4    SF   NYG
5    SF   NYG
6    SF   NYG

matplotlib does not show my drawings although I call pyplot.show()

For Ubuntu 12.04:

sudo apt-get install python-qt4
virtualenv .env --no-site-packages
source .env/bin/activate
easy_install -U distribute
ln -s /usr/lib/python2.7/dist-packages/PyQt4 .
ln -s /usr/lib/python2.7/dist-packages/sip.so .
pip install matplotlib

String in function parameter

function("MyString");

is similar to

char *s = "MyString";
function(s);

"MyString" is in both cases a string literal and in both cases the string is unmodifiable.

function("MyString");

passes the address of a string literal to function as an argument.

LINQ Orderby Descending Query

You need to choose a Property to sort by and pass it as a lambda expression to OrderByDescending

like:

.OrderByDescending(x => x.Delivery.SubmissionDate);

Really, though the first version of your LINQ statement should work. Is t.Delivery.SubmissionDate actually populated with valid dates?

Tensorflow 2.0 - AttributeError: module 'tensorflow' has no attribute 'Session'

Same problem occurred for me

import tensorflow as tf
hello = tf.constant('Hello World ') 
sess = tf.compat.v1.Session()    *//I got the error on this step when I used 
                                   tf.Session()*
sess.run(hello)

Try replacing it with tf.compact.v1.Session()

How to increase Heap size of JVM

Java command line parameters

-Xms: initial heap size
-Xmx: Maximum heap size

if you are using Tomcat. Update CATALINA_OPTS environment variable

export CATALINA_OPTS=-Xms16m -Xmx256m;

How do I read the contents of a Node.js stream into a string variable?

(This answer is from years ago, when it was the best answer. There is now a better answer below this. I haven't kept up with node.js, and I cannot delete this answer because it is marked "correct on this question". If you are thinking of down clicking, what do you want me to do?)

The key is to use the data and end events of a Readable Stream. Listen to these events:

stream.on('data', (chunk) => { ... });
stream.on('end', () => { ... });

When you receive the data event, add the new chunk of data to a Buffer created to collect the data.

When you receive the end event, convert the completed Buffer into a string, if necessary. Then do what you need to do with it.

Generating a UUID in Postgres for Insert statement?

ALTER TABLE table_name ALTER COLUMN id SET DEFAULT uuid_in((md5((random())::text))::cstring);

After reading @ZuzEL's answer, i used the above code as the default value of the column id and it's working fine.

How do I use $scope.$watch and $scope.$apply in AngularJS?

I found very in-depth videos which cover $watch, $apply, $digest and digest cycles in:

Following are a couple of slides used in those videos to explain the concepts (just in case, if the above links are removed/not working).

Enter image description here

In the above image, "$scope.c" is not being watched as it is not used in any of the data bindings (in markup). The other two ($scope.a and $scope.b) will be watched.

Enter image description here

From the above image: Based on the respective browser event, AngularJS captures the event, performs digest cycle (goes through all the watches for changes), execute watch functions and update the DOM. If not browser events, the digest cycle can be manually triggered using $apply or $digest.

More about $apply and $digest:

Enter image description here

Classes vs. Functions

Classes (or rather their instances) are for representing things. Classes are used to define the operations supported by a particular class of objects (its instances). If your application needs to keep track of people, then Person is probably a class; the instances of this class represent particular people you are tracking.

Functions are for calculating things. They receive inputs and produce an output and/or have effects.

Classes and functions aren't really alternatives, as they're not for the same things. It doesn't really make sense to consider making a class to "calculate the age of a person given his/her birthday year and the current year". You may or may not have classes to represent any of the concepts of Person, Age, Year, and/or Birthday. But even if Age is a class, it shouldn't be thought of as calculating a person's age; rather the calculation of a person's age results in an instance of the Age class.

If you are modelling people in your application and you have a Person class, it may make sense to make the age calculation be a method of the Person class. A method is basically a function which is defined as part of a class; this is how you "define the operations supported by a particular class of objects" as I mentioned earlier.

So you could create a method on your person class for calculating the age of the person (it would probably retrieve the birthday year from the person object and receive the current year as a parameter). But the calculation is still done by a function (just a function that happens to be a method on a class).

Or you could simply create a stand-alone function that receives arguments (either a person object from which to retrieve a birth year, or simply the birth year itself). As you note, this is much simpler if you don't already have a class where this method naturally belongs! You should never create a class simply to hold an operation; if that's all there is to the class then the operation should just be a stand-alone function.

Efficiency of Java "Double Brace Initialization"?

Efficiency aside, I rarely find myself wishing for declarative collection creation outside of unit tests. I do believe that the double brace syntax is very readable.

Another way to achieve the declarative construction of lists specifically is to use Arrays.asList(T ...) like so:

List<String> aList = Arrays.asList("vanilla", "strawberry", "chocolate");

The limitation of this approach is of course that you cannot control the specific type of list to be generated.

How to use comparison operators like >, =, < on BigDecimal

Use the compareTo method of BigDecimal :

public int compareTo(BigDecimal val) Compares this BigDecimal with the specified BigDecimal.

Returns:
-1, 0, or 1 as this BigDecimal is numerically less than, equal to, or greater than val.

Indent List in HTML and CSS

I solved the same problem by adding text-indent to the nested list.

<h4>A nested List:</h4>
<ul>
  <li>Coffee</li>
  <li>Tea
    <ul id="list2">
    <li>Black tea</li>
    <li>Green tea</li>
    </ul>
  </li>
  <li>Milk</li>
</ul>

#list2
{
 text-indent:50px;
}

Git log to get commits only for a specific branch

The following shell command should do what you want:

git log --all --not $(git rev-list --no-walk --exclude=refs/heads/mybranch --all)

Caveats

If you have mybranch checked out, the above command won't work. That's because the commits on mybranch are also reachable by HEAD, so Git doesn't consider the commits to be unique to mybranch. To get it to work when mybranch is checked out, you must also add an exclude for HEAD:

git log --all --not $(git rev-list --no-walk \
    --exclude=refs/heads/mybranch \
    --exclude=HEAD \
    --all)

However, you should not exclude HEAD unless the mybranch is checked out, otherwise you risk showing commits that are not exclusive to mybranch.

Similarly, if you have a remote branch named origin/mybranch that corresponds to the local mybranch branch, you'll have to exclude it:

git log --all --not $(git rev-list --no-walk \
    --exclude=refs/heads/mybranch \
    --exclude=refs/remotes/origin/mybranch \
    --all)

And if the remote branch is the default branch for the remote repository (usually only true for origin/master), you'll have to exclude origin/HEAD as well:

git log --all --not $(git rev-list --no-walk \
    --exclude=refs/heads/mybranch \
    --exclude=refs/remotes/origin/mybranch \
    --exclude=refs/remotes/origin/HEAD \
    --all)

If you have the branch checked out, and there's a remote branch, and the remote branch is the default for the remote repository, then you end up excluding a lot:

git log --all --not $(git rev-list --no-walk \
    --exclude=refs/heads/mybranch \
    --exclude=HEAD
    --exclude=refs/remotes/origin/mybranch \
    --exclude=refs/remotes/origin/HEAD \
    --all)

Explanation

The git rev-list command is a low-level (plumbing) command that walks the given revisions and dumps the SHA1 identifiers encountered. Think of it as equivalent to git log except it only shows the SHA1—no log message, no author name, no timestamp, none of that "fancy" stuff.

The --no-walk option, as the name implies, prevents git rev-list from walking the ancestry chain. So if you type git rev-list --no-walk mybranch it will only print one SHA1 identifier: the identifier of the tip commit of the mybranch branch.

The --exclude=refs/heads/mybranch --all arguments tell git rev-list to start from each reference except for refs/heads/mybranch.

So, when you run git rev-list --no-walk --exclude=refs/heads/mybranch --all, Git prints the SHA1 identifier of the tip commit of each ref except for refs/heads/mybranch. These commits and their ancestors are the commits you are not interested in—these are the commits you do not want to see.

The other commits are the ones you want to see, so we collect the output of git rev-list --no-walk --exclude=refs/heads/mybranch --all and tell Git to show everything but those commits and their ancestors.

The --no-walk argument is necessary for large repositories (and is an optimization for small repositories): Without it, Git would have to print, and the shell would have to collect (and store in memory) many more commit identifiers than necessary. With a large repository, the number of collected commits could easily exceed the shell's command-line argument limit.

Git bug?

I would have expected the following to work:

git log --all --not --exclude=refs/heads/mybranch --all

but it does not. I'm guessing this is a bug in Git, but maybe it's intentional.

How to update values using pymongo?

You can use the $set syntax if you want to set the value of a document to an arbitrary value. This will either update the value if the attribute already exists on the document or create it if it doesn't. If you need to set a single value in a dictionary like you describe, you can use the dot notation to access child values.

If p is the object retrieved:

existing = p['d']['a']

For pymongo versions < 3.0

db.ProductData.update({
  '_id': p['_id']
},{
  '$set': {
    'd.a': existing + 1
  }
}, upsert=False, multi=False)

For pymongo versions >= 3.0

db.ProductData.update_one({
  '_id': p['_id']
},{
  '$set': {
    'd.a': existing + 1
  }
}, upsert=False)

However if you just need to increment the value, this approach could introduce issues when multiple requests could be running concurrently. Instead you should use the $inc syntax:

For pymongo versions < 3.0:

db.ProductData.update({
  '_id': p['_id']
},{
  '$inc': {
    'd.a': 1
  }
}, upsert=False, multi=False)

For pymongo versions >= 3.0:

db.ProductData.update_one({
  '_id': p['_id']
},{
  '$inc': {
    'd.a': 1
  }
}, upsert=False)

This ensures your increments will always happen.

How to change color of Android ListView separator line?

For a single color line use:

list.setDivider(new ColorDrawable(0x99F10529));   //0xAARRGGBB
list.setDividerHeight(1);

It's important that DividerHeight is set after the divider, else you won't get anything.

Vertical Alignment of text in a table cell

td.description {vertical-align: top;}

where description is the class name of the td with that text in it

_x000D_
_x000D_
td.description {_x000D_
  vertical-align: top;_x000D_
}
_x000D_
<td class="description">Description</td>
_x000D_
_x000D_
_x000D_

OR inline (yuk!)

_x000D_
_x000D_
<td style="vertical-align: top;">Description</td>
_x000D_
_x000D_
_x000D_

How to iterate through property names of Javascript object?

In JavaScript 1.8.5, Object.getOwnPropertyNames returns an array of all properties found directly upon a given object.

Object.getOwnPropertyNames ( obj )

and another method Object.keys, which returns an array containing the names of all of the given object's own enumerable properties.

Object.keys( obj )

I used forEach to list values and keys in obj, same as for (var key in obj) ..

Object.keys(obj).forEach(function (key) {
      console.log( key , obj[key] );
});

This all are new features in ECMAScript , the mothods getOwnPropertyNames, keys won't supports old browser's.

Set markers for individual points on a line in Matplotlib

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

How can I get the status code from an http error in Axios?

I am using this interceptors to get the error response.

const HttpClient = axios.create({
  baseURL: env.baseUrl,
});

HttpClient.interceptors.response.use((response) => {
  return response;
}, (error) => {
  return Promise.resolve({ error });
});

Debugging iframes with Chrome developer tools

In my fairly complex scenario the accepted answer for how to do this in Chrome doesn't work for me. You may want to try the Firefox debugger instead (part of the Firefox developer tools), which shows all of the 'Sources', including those that are part of an iFrame

How to shuffle an ArrayList

Try Collections.shuffle(list).If usage of this method is barred for solving the problem, then one can look at the actual implementation.

Search and replace a particular string in a file using Perl

A one liner:

perl -pi.back -e 's/<PREF>/ABCD/g;' inputfile

Is try-catch like error handling possible in ASP Classic?

Been a while since I was in ASP land, but iirc there's a couple of ways:

try catch finally can be reasonably simulated in VBS (good article here here) and there's an event called class_terminate you can watch and catch exceptions globally in. Then there's the possibility of changing your scripting language...

Removing "NUL" characters

Click Search --> Replace --> Find What: \0 Replace with: "empty" Search mode: Extended --> Replace all

How to use querySelectorAll only for elements that have a specific attribute set?

With your example:

<input type="checkbox" id="c2" name="c2" value="DE039230952"/>

Replace $$ with document.querySelectorAll in the examples:

$$('input') //Every input
$$('[id]') //Every element with id
$$('[id="c2"]') //Every element with id="c2"
$$('input,[id]') //Every input + every element with id
$$('input[id]') //Every input including id
$$('input[id="c2"]') //Every input including id="c2"
$$('input#c2') //Every input including id="c2" (same as above)
$$('input#c2[value="DE039230952"]') //Every input including id="c2" and value="DE039230952"
$$('input#c2[value^="DE039"]') //Every input including id="c2" and value has content starting with DE039
$$('input#c2[value$="0952"]') //Every input including id="c2" and value has content ending with 0952
$$('input#c2[value*="39230"]') //Every input including id="c2" and value has content including 39230

Use the examples directly with:

const $$ = document.querySelectorAll.bind(document);

Some additions:

$$(.) //The same as $([class])
$$(div > input) //div is parent tag to input
document.querySelector() //equals to $$()[0] or $()

curl : (1) Protocol https not supported or disabled in libcurl

My problem was coused by not displayed UTF symbol. I copy the link from the browser (in my case it was an nginx track) and got the following in clipboard:

$ echo -n "?https://sk.ee/upload/files/ESTEID-SK_2015.pem.crt" | hexdump -C
00000000  e2 80 8b 68 74 74 70 73  3a 2f 2f 73 6b 2e 65 65  |...https://sk.ee|
00000010  2f 75 70 6c 6f 61 64 2f  66 69 6c 65 73 2f 45 53  |/upload/files/ES|
00000020  54 45 49 44 2d 53 4b 5f  32 30 31 35 2e 70 65 6d  |TEID-SK_2015.pem|
00000030  2e 63 72 74                                       |.crt|

The problem is in the sequence 0xe2 0x80 0x8b, which precedes https. This sequence is a ZERO WIDTH JOINER encoded in UTF-8.

angularjs to output plain text instead of html

var app = angular.module('myapp', []);

app.filter('htmlToPlaintext', function()
{
    return function(text)
    {
        return  text ? String(text).replace(/<[^>]+>/gm, '') : '';
    };
});

<p>{{DetailblogList.description | htmlToPlaintext}}</p>

A generic error occurred in GDI+, JPEG Image to MemoryStream

SOLVED - I had this exact problem. The fix, for me, was to up the disk quota for IUSR on the IIS server. In this instance, we have a catalog app with images of items and such. The upload quota for the "Anonymous Web User" was set to 100MB, which is the default for this particular hosting company's IIS servers. I upped it to 400MB and was able to upload images without error.

This might not be your issue, but if it is, it's an easy fix.

Why do people write #!/usr/bin/env python on the first line of a Python script?

This is a shell convention that tells the shell which program can execute the script.

#!/usr/bin/env python

resolves to a path to the Python binary.

Random Number Between 2 Double Numbers

What if one of the values is negative? Wouldn't a better idea be:

double NextDouble(double min, double max)
{
       if (min >= max)
            throw new ArgumentOutOfRangeException();    
       return random.NextDouble() * (Math.Abs(max-min)) + min;
}

What key in windows registry disables IE connection parameter "Automatically Detect Settings"?

Indeed, the 9th byte indicates the check state of the button, but the answers above don't take into account the checkbox which enables manual configuration. This check state value is also present in this ninth byte. The real answer should thus be:

Byte value

00001001 = Manual proxy is checked

00000101 = Use automatic configuration script is checked

00000011 = Automatically detect settings is checked

When multiple checkboxes are checked, the value of the 9th byte is the result of the bitwise OR operation on the values for which the checkbox is checked.

Pass a password to ssh in pure bash

Since there were no exact answers to my question, I made some investigation why my code doesn't work when there are other solutions that works, and decided to post what I found to complete the subject.
As it turns out:

"ssh uses direct TTY access to make sure that the password is indeed issued by an interactive keyboard user." sshpass manpage

which answers the question, why the pipes don't work in this case. The obvious solution was to create conditions so that ssh "thought" that it is run in the regular terminal and since it may be accomplished by simple posix functions, it is beyond what simple bash offers.

Explanation of 'String args[]' and static in 'public static void main(String[] args)'

I would point a beginner to the Wiki article on the Main function, then supplement it with this.

  • Java only starts running a program with the specific public static void main(String[] args) signature, and one can think of a signature like their own name - it's how Java can tell the difference between someone else's main() and the one true main().

  • String[] args is a collection of Strings, separated by a space, which can be typed into the program on the terminal. More times than not, the beginner isn't going to use this variable, but it's always there just in case.

How to write LaTeX in IPython Notebook?

Using LaTeX syntax directly in a Markdown cell works for me. I'm using Jypiter 4.4.0.

I don't have to use %%latex magic command, I insist, simply a markdown cell:

\begin{align}
\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0
\end{align}

Renders to:

enter image description here

Could not extract response: no suitable HttpMessageConverter found for response type

Since you return to the client just String and its content type == 'text/plain', there is no any chance for default converters to determine how to convert String response to the FFSampleResponseHttp object.

The simple way to fix it:

  • remove expected-response-type from <int-http:outbound-gateway>
  • add to the replyChannel1 <json-to-object-transformer>

Otherwise you should write your own HttpMessageConverter to convert the String to the appropriate object.

To make it work with MappingJackson2HttpMessageConverter (one of default converters) and your expected-response-type, you should send your reply with content type = 'application/json'.

If there is a need, just add <header-enricher> after your <service-activator> and before sending a reply to the <int-http:inbound-gateway>.

So, it's up to you which solution to select, but your current state doesn't work, because of inconsistency with default configuration.

UPDATE

OK. Since you changed your server to return FfSampleResponseHttp object as HTTP response, not String, just add contentType = 'application/json' header before sending the response for the HTTP and MappingJackson2HttpMessageConverter will do the stuff for you - your object will be converted to JSON and with correct contentType header.

From client side you should come back to the expected-response-type="com.mycompany.MyChannel.model.FFSampleResponseHttp" and MappingJackson2HttpMessageConverter should do the stuff for you again.

Of course you should remove <json-to-object-transformer> from you message flow after <int-http:outbound-gateway>.

How do I multiply each element in a list by a number?

from functools import partial as p
from operator import mul
map(p(mul,5),my_list)

is one way you could do it ... your teacher probably knows a much less complicated way that was probably covered in class

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

Not sure it works in tsql, but some platforms have to_char():

test=#select to_char(131213211653.78, '9,999,999,999,999.99');
        to_char        
-----------------------
    131,213,211,653.78
test=# select to_char(131213211653.78, '9G999G999G999G999D99');
        to_char        
-----------------------
    131,213,211,653.78
test=# select to_char(485, 'RN');
     to_char     
-----------------
         CDLXXXV

As the example suggests, the format's length needs to match that of the number for best results, so you might want to wrap it in a function (e.g. number_format()) if needed.


Converting to money works too, as point out by the other repliers.

test=# select substring(cast(cast(131213211653.78 as money) as varchar) from 2);
     substring      
--------------------
 131,213,211,653.78

jQuery - setting the selected value of a select control via its text description

$("#myselect option:contains('YourTextHere')").val();

will return the value of the first option containing your text description. Tested this and works.

What's the u prefix in a Python string?

All strings meant for humans should use u"".

I found that the following mindset helps a lot when dealing with Python strings: All Python manifest strings should use the u"" syntax. The "" syntax is for byte arrays, only.

Before the bashing begins, let me explain. Most Python programs start out with using "" for strings. But then they need to support documentation off the Internet, so they start using "".decode and all of a sudden they are getting exceptions everywhere about decoding this and that - all because of the use of "" for strings. In this case, Unicode does act like a virus and will wreak havoc.

But, if you follow my rule, you won't have this infection (because you will already be infected).

MySQL Orderby a number, Nulls last

You can swap out instances of NULL with a different value to sort them first (like 0 or -1) or last (a large number or a letter)...

SELECT field1, IF(field2 IS NULL, 9999, field2) as ordered_field2
  FROM tablename
 WHERE visible = 1
 ORDER BY ordered_field2 ASC, id DESC

Force DOM redraw/refresh on Chrome/Mac

Most answers require the use of an asynchroneous timeout, which causes an annoying blink.

But I came up with this one, which works smoothly because it is synchroneous:

var p = el.parentNode,
    s = el.nextSibling;
p.removeChild(el);
p.insertBefore(el, s);

How to clone all remote branches in Git?

Cloning from a local repo will not work with git clone & git fetch: a lot of branches/tags will remain unfetched.

To get a clone with all branches and tags.

git clone --mirror git://example.com/myproject myproject-local-bare-repo.git

To get a clone with all branches and tags but also with a working copy:

git clone --mirror git://example.com/myproject myproject/.git
cd myproject
git config --unset core.bare
git config receive.denyCurrentBranch updateInstead
git checkout master

ApiNotActivatedMapError for simple html page using google-places-api

I had the same error. To fix the error:

  1. Open the console menu Gallery Menu and select API Manager.
  2. On the left, click Credentials and then click New Credentials.
  3. Click Create Credentials.
  4. Click API KEY.
  5. Click Navigator Key (there are more options; It depends on when consumed).

You must use this new API Navigator Key, generated by the system.

Convert file to byte array and vice versa

You can't do this. A File is just an abstract way to refer to a file in the file system. It doesn't contain any of the file contents itself.

If you're trying to create an in-memory file that can be referred to using a File object, you aren't going to be able to do that, either, as explained in this thread, this thread, and many other places..

Cross domain POST request is not sending cookie Ajax Jquery

Please note this doesn't solve the cookie sharing process, as in general this is bad practice.

You need to be using JSONP as your type:

From $.ajax documentation: Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.

$.ajax(
    { 
      type: "POST",
      url: "http://example.com/api/getlist.json",
      dataType: 'jsonp',
      xhrFields: {
           withCredentials: true
      },
      crossDomain: true,
      beforeSend: function(xhr) {
            xhr.setRequestHeader("Cookie", "session=xxxyyyzzz");
      },
      success: function(){
           alert('success');
      },
      error: function (xhr) {
             alert(xhr.responseText);
      }
    }
);

Vertical rulers in Visual Studio Code

Visual Studio Code: Version 1.14.2 (1.14.2)

  1. Press Shift + Command + P to open panel
    • For non-macOS users, press Ctrl+P
  2. Enter "settings.json" to open setting files.
  3. At default setting, you can see this:

    // Columns at which to show vertical rulers
    "editor.rulers": [],
    

    This means the empty array won't show the vertical rulers.

  4. At right window "user setting", add the following:

    "editor.rulers": [140]

Save the file, and you will see the rulers.

What does href expression <a href="javascript:;"></a> do?

Old thread but thought I'd just add that the reason developers use this construct is not to create a dead link, but because javascript URLs for some reason do not pass references to the active html element correctly.

e.g. handler_function(this.id) works as onClick but not as a javascript URL.

Thus it's a choice between writing pedantically standards-compliant code that involves you in having to manually adjust the call for each hyperlink, or slightly non-standard code which can be written once and used everywhere.

How to convert a string of numbers to an array of numbers?

There's no need to use lambdas and/or give radix parameter to parseInt, just use parseFloat or Number instead.

Reasons:

  1. It's working:

    var src = "1,2,5,4,3";
    var ids = src.split(',').map(parseFloat); // [1, 2, 5, 4, 3]
    
    var obj = {1: ..., 3: ..., 4: ..., 7: ...};
    var keys= Object.keys(obj); // ["1", "3", "4", "7"]
    var ids = keys.map(parseFloat); // [1, 3, 4, 7]
    
    var arr = ["1", 5, "7", 11];
    var ints= arr.map(parseFloat); // [1, 5, 7, 11]
    ints[1] === "5" // false
    ints[1] === 5   // true
    ints[2] === "7" // false
    ints[2] === 7   // true
    
  2. It's shorter.

  3. It's a tiny bit quickier and takes advantage of cache, when parseInt-approach - doesn't:

      // execution time measure function
      // keep it simple, yeah?
    > var f = (function (arr, c, n, m) {
          var i,t,m,s=n();
          for(i=0;i++<c;)t=arr.map(m);
          return n()-s
      }).bind(null, "2,4,6,8,0,9,7,5,3,1".split(','), 1000000, Date.now);
    
    > f(Number) // first launch, just warming-up cache
    > 3971 // nice =)
    
    > f(Number)
    > 3964 // still the same
    
    > f(function(e){return+e})
    > 5132 // yup, just little bit slower
    
    > f(function(e){return+e})
    > 5112 // second run... and ok.
    
    > f(parseFloat)
    > 3727 // little bit quicker than .map(Number)
    
    > f(parseFloat)
    > 3737 // all ok
    
    > f(function(e){return parseInt(e,10)})
    > 21852 // awww, how adorable...
    
    > f(function(e){return parseInt(e)})
    > 22928 // maybe, without '10'?.. nope.
    
    > f(function(e){return parseInt(e)})
    > 22769 // second run... and nothing changes.
    
    > f(Number)
    > 3873 // and again
    > f(parseFloat)
    > 3583 // and again
    > f(function(e){return+e})
    > 4967 // and again
    
    > f(function(e){return parseInt(e,10)})
    > 21649 // dammit 'parseInt'! >_<
    

Notice: In Firefox parseInt works about 4 times faster, but still slower than others. In total: +e < Number < parseFloat < parseInt

What's the difference between getRequestURI and getPathInfo methods in HttpServletRequest?

Consider the following servlet conf:

   <servlet>
        <servlet-name>NewServlet</servlet-name>
        <servlet-class>NewServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>NewServlet</servlet-name>
        <url-pattern>/NewServlet/*</url-pattern>
    </servlet-mapping>

Now, when I hit the URL http://localhost:8084/JSPTemp1/NewServlet/jhi, it will invoke NewServlet as it is mapped with the pattern described above.

Here:

getRequestURI() =  /JSPTemp1/NewServlet/jhi
getPathInfo() = /jhi

We have those ones:

  • getPathInfo()

    returns
    a String, decoded by the web container, specifying extra path information that comes after the servlet path but before the query string in the request URL; or null if the URL does not have any extra path information

  • getRequestURI()

    returns
    a String containing the part of the URL from the protocol name up to the query string

How to match hyphens with Regular Expression?

The hyphen is usually a normal character in regular expressions. Only if it’s in a character class and between two other characters does it take a special meaning.

Thus:

  • [-] matches a hyphen.
  • [abc-] matches a, b, c or a hyphen.
  • [-abc] matches a, b, c or a hyphen.
  • [ab-d] matches a, b, c or d (only here the hyphen denotes a character range).

ClientAbortException: java.net.SocketException: Connection reset by peer: socket write error

Windows Firewall could cause this exception, try to disable it or add a rule for port or even program (java)

Matplotlib scatter plot legend

2D scatter plot

Using the scatter method of the matplotlib.pyplot module should work (at least with matplotlib 1.2.1 with Python 2.7.5), as in the example code below. Also, if you are using scatter plots, use scatterpoints=1 rather than numpoints=1 in the legend call to have only one point for each legend entry.

In the code below I've used random values rather than plotting the same range over and over, making all the plots visible (i.e. not overlapping each other).

import matplotlib.pyplot as plt
from numpy.random import random

colors = ['b', 'c', 'y', 'm', 'r']

lo = plt.scatter(random(10), random(10), marker='x', color=colors[0])
ll = plt.scatter(random(10), random(10), marker='o', color=colors[0])
l  = plt.scatter(random(10), random(10), marker='o', color=colors[1])
a  = plt.scatter(random(10), random(10), marker='o', color=colors[2])
h  = plt.scatter(random(10), random(10), marker='o', color=colors[3])
hh = plt.scatter(random(10), random(10), marker='o', color=colors[4])
ho = plt.scatter(random(10), random(10), marker='x', color=colors[4])

plt.legend((lo, ll, l, a, h, hh, ho),
           ('Low Outlier', 'LoLo', 'Lo', 'Average', 'Hi', 'HiHi', 'High Outlier'),
           scatterpoints=1,
           loc='lower left',
           ncol=3,
           fontsize=8)

plt.show()

enter image description here

3D scatter plot

To plot a scatter in 3D, use the plot method, as the legend does not support Patch3DCollection as is returned by the scatter method of an Axes3D instance. To specify the markerstyle you can include this as a positional argument in the method call, as seen in the example below. Optionally one can include argument to both the linestyle and marker parameters.

import matplotlib.pyplot as plt
from numpy.random import random
from mpl_toolkits.mplot3d import Axes3D

colors=['b', 'c', 'y', 'm', 'r']

ax = plt.subplot(111, projection='3d')

ax.plot(random(10), random(10), random(10), 'x', color=colors[0], label='Low Outlier')
ax.plot(random(10), random(10), random(10), 'o', color=colors[0], label='LoLo')
ax.plot(random(10), random(10), random(10), 'o', color=colors[1], label='Lo')
ax.plot(random(10), random(10), random(10), 'o', color=colors[2], label='Average')
ax.plot(random(10), random(10), random(10), 'o', color=colors[3], label='Hi')
ax.plot(random(10), random(10), random(10), 'o', color=colors[4], label='HiHi')
ax.plot(random(10), random(10), random(10), 'x', color=colors[4], label='High Outlier')

plt.legend(loc='upper left', numpoints=1, ncol=3, fontsize=8, bbox_to_anchor=(0, 0))

plt.show()

enter image description here

What MySQL data type should be used for Latitude/Longitude with 8 decimal places?

in laravel used decimal column type for migration

$table->decimal('latitude', 10, 8);
$table->decimal('longitude', 11, 8);

for more information see available column type

How do I add a newline to command output in PowerShell?

The option that I tend to use, mostly because it's simple and I don't have to think, is using Write-Output as below. Write-Output will put an EOL marker in the string for you and you can simply output the finished string.

Write-Output $stringThatNeedsEOLMarker | Out-File -FilePath PathToFile -Append

Alternatively, you could also just build the entire string using Write-Output and then push the finished string into Out-File.

Error: Argument is not a function, got undefined

Could it be as simple as enclosing your asset in " " and whatever needs quotes on the inside with ' '?

<link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/main.css")">

becomes

<link rel="stylesheet" media="screen" href="@routes.Assets.at('stylesheets/main.css')">

That could be causing some problems with parsing

Failed to connect to mailserver at "localhost" port 25

If you are running your application just on localhost and it is not yet live, I believe it is very difficult to send mail using this.

Once you put your application online, I believe that this problem should be automatically solved. But i think ini_set() helps you to change the values in php.ini during run time.

How to get first and last day of week in Oracle?

First day of week (Monday):

SELECT TO_DATE(to_char(sysdate,'YYYY')||'0101','YYYYMMDD') + 7 * to_number(to_char(sysdate,'WW')-1)-1 first_day_week FROM dual;

Last day of week (Sunday):

SELECT TO_DATE(to_char(sysdate,'YYYY')||'0101','YYYYMMDD') + 7 * to_number(to_char(sysdate,'WW')-1)+5 last_day_week FROM dual;

Substituting your date or date field in these formulas will work for you!

What is meant with "const" at end of function declaration?

Bar is guaranteed not to change the object it is being invoked on. See the section about const correctness in the C++ FAQ, for example.

Swift 3 - Comparing Date objects

Date is Comparable & Equatable (as of Swift 3)

This answer complements @Ankit Thakur's answer.

Since Swift 3 the Date struct (based on the underlying NSDate class) adopts the Comparable and Equatable protocols.

  • Comparable requires that Date implement the operators: <, <=, >, >=.
  • Equatable requires that Date implement the == operator.
  • Equatable allows Date to use the default implementation of the != operator (which is the inverse of the Equatable == operator implementation).

The following sample code exercises these comparison operators and confirms which comparisons are true with print statements.

Comparison function

import Foundation

func describeComparison(date1: Date, date2: Date) -> String {

    var descriptionArray: [String] = []

    if date1 < date2 {
        descriptionArray.append("date1 < date2")
    }

    if date1 <= date2 {
        descriptionArray.append("date1 <= date2")
    }

    if date1 > date2 {
        descriptionArray.append("date1 > date2")
    }

    if date1 >= date2 {
        descriptionArray.append("date1 >= date2")
    }

    if date1 == date2 {
        descriptionArray.append("date1 == date2")
    }

    if date1 != date2 {
        descriptionArray.append("date1 != date2")
    }

    return descriptionArray.joined(separator: ",  ")
}

Sample Use

let now = Date()

describeComparison(date1: now, date2: now.addingTimeInterval(1))
// date1 < date2,  date1 <= date2,  date1 != date2

describeComparison(date1: now, date2: now.addingTimeInterval(-1))
// date1 > date2,  date1 >= date2,  date1 != date2

describeComparison(date1: now, date2: now)
// date1 <= date2,  date1 >= date2,  date1 == date2

HTML Form Redirect After Submit

Try this Javascript (jquery) code. Its an ajax request to an external URL. Use the callback function to fire any code:

<script type="text/javascript">
$(function() {
  $('form').submit(function(){
    $.post('http://example.com/upload', function() {
      window.location = 'http://google.com';
    });
    return false;
  });
});
</script>

How to use MySQLdb with Python and Django in OSX 10.6?

Running Ubuntu, I had to do:

sudo apt-get install python-mysqldb

Looping through a hash, or using an array in PowerShell

About looping through a hash:

$Q = @{"ONE"="1";"TWO"="2";"THREE"="3"}
$Q.GETENUMERATOR() | % { $_.VALUE }
1
3
2

$Q.GETENUMERATOR() | % { $_.key }
ONE
THREE
TWO

How to detect if a browser is Chrome using jQuery?

Although it is not Jquery , I use jquery myself but for browser detection I have used the script on this page a few times. It detects all major browsers, and then some. The work is pretty much all done for you.

How to convert char to int?

What everyone is forgeting is explaining WHY this happens.

A Char, is basically an integer, but with a pointer in the ASCII table. All characters have a corresponding integer value as you can clearly see when trying to parse it.

Pranay has clearly a different character set, thats why HIS code doesnt work. the only way is

int val = '1' - '0';

because this looks up the integer value in the table of '0' which is then the 'base value' subtracting your number in char format from this will give you the original number.

How to run a class from Jar which is not the Main-Class in its Manifest file

This answer is for Spring-boot users:

If your JAR was from a Spring-boot project and created using the command mvn package spring-boot:repackage, the above "-cp" method won't work. You will get:

Error: Could not find or load main class your.alternative.class.path

even if you can see the class in the JAR by jar tvf yours.jar.

In this case, run your alternative class by the following command:

java -cp yours.jar -Dloader.main=your.alternative.class.path org.springframework.boot.loader.PropertiesLauncher

As I understood, the Spring-boot's org.springframework.boot.loader.PropertiesLauncher class serves as a dispatching entrance class, and the -Dloader.main parameter tells it what to run.

Reference: https://github.com/spring-projects/spring-boot/issues/20404