text:
Q: Crop multiple images one at a time with JCrop and session in php I have an image crop script that crops one image at a time using the Jquery Jcrop plugin.
now I want to upload more images and crop them one by one using a for loop.
What is the best way to do this?
I set my input field to multiple so it could upload more than one.
EDIT:
I've editted my code below with a $max and count. and I think I'm doing it wrong. how can I fix it so when I click crop, it crops them after each-other.
This is my uploaded.php:
    <?php
         session_start();
         $max = count($_FILES['userfile']['name']);
         for($i = 0; $i < $max; $i++){
            $target = $_FILES['file'][$i];
         }

         $target = "data/uploads/";
         $target = $target . basename( $_FILES['filename']['name']) ;
         $_SESSION['target_path'] = $target;

         $ok=1;
         if(move_uploaded_file($_FILES['filename']['tmp_name'], $target))
         {
             echo "De afbeelding *". basename( $_FILES['filename']['name']). "* is geupload naar de map 'uploads'";
         }
         else
         {
             echo "Sorry, er is een probleem met het uploaden van de afbeelding.";
         }
    ?>

Thanks!

A: I think you want something more like this:
<?php
session_start();

$upload_dir = "data/uploads/";
for($i = 0; $i < 5; $i++){
     $target = $upload_dir . basename( $_FILES['file']['name'][$i]);
     if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target)) {
         echo "De afbeelding *". basename( $_FILES['file']['name'][$i]). "* is geupload naar de map 'uploads'";
     } else {
         echo "Sorry, er is een probleem met het uploaden van de afbeelding.";
     }
}

A: You need to check a few things
1) To upload files, read: http://php.net/manual/en/features.file-upload.multiple.php - specifically input name="userfile[]" in HTML and files on server show up as $_FILES['userfile']['name'][0],...,$_FILES['userfile']['name'][N]
2) move_uploaded_file() is a security check to ensure files are valid, dont leave home without it :-)
3) I'd recommend imagemagick library (http://php.net/manual/en/imagick.cropimage.php), I know, Jcrop demo uses GD library but worth your time looking at imagemagick.
4) Lastly if all fails, use print_r($variable) to ensure the files are getting into your server.
5) Sometimes it could be system admin issue like unwritable /tmp folder, disk full, upload size limit in php.ini and web server built-in timeout. Checking phpinfo() helps too


text:
Q: Trying to detect monitor I'm trying to get the monitor in order to check if is off or not.
Before checking with GetDevicePowerState, I'm trying to retrieve monitor in this way:
#include <cstdlib>
#include <iostream>
#include <windows.h>
#include <winuser.h>
using namespace std;

int main(int argc, char *argv[])
{
    POINT* p = new POINT;
    p->x=0;
    p->y=0;
    HMONITOR* monitor = MonitorFromPoint(p,DWORD.MONITOR_DEFAULTTOPRIMARY);
    system("PAUSE");
    return EXIT_SUCCESS;
}

But it continually gives me:
main.cpp `MonitorFromPoint' undeclared (first use this function)

Where have I gone wrong?

A: Your code has a number of problems, but none of them should cause the error message you're seeing. Here's code with some corrections, and a little more added to show at least some kind of result from the test:
#include <iostream>
#include <windows.h>

int main(int argc, char *argv[])
{
    POINT p{ 0, 0 };
    HMONITOR monitor = MonitorFromPoint(p, MONITOR_DEFAULTTONULL);

    if (monitor == NULL)
        std::cout << "No monitor found for point (0, 0)\n";
    else {
        MONITORINFOEX info;
        info.cbSize = sizeof(info);

        GetMonitorInfo(monitor, &info);
        std::cout << "Monitor: " << info.szDevice << "\n";
    }
}

I've tested this with both VC++ 2013 and MinGW 4.8.1, and in both cases it's compiled and run without any problems, producing:
Monitor: \\.\DISPLAY1

...as its output in both cases.

redpajama_set_name: RedPajamaStackExchange


text:
Q: AngularJS $http post fails I am new to AngularJS, I am from SAP background and as part of my PoC I built my REST services using SAP NW Gateway,I am facing an issue to POST data from Angularjs to my REST services.Please find the below detailed error log

    ***1.      Remote Address:
    10.xxx.xx.xx:8000
    2.      Request URL:
    //host:port/sap/opu/odata/sap/USERS/Users
    3.  Request Method:
    POST
    4.      Status Code:
    400 Bad Request
    5.      Request Headersview source
    1.      Accept:
    application/json, text/plain, */*
    2.      Accept-Encoding:
    gzip,deflate
    3.      Accept-Language:
    en,te;q=0.8
    4.      Authorization:
    Basic a2VsYW1yOmoyZDEwMA==
    5.      Connection:
    keep-alive
    6.      Content-Length:
    146
    7.      Content-Type:
    application/json;charset=UTF-8
    8.      Cookie:
    sap-usercontext=sap-client=100; SAP_SESSIONID_J2D_100=R_60WyUyNG2nV1MbhC9QAcKPzyBwwxHkmwsAUFaDBqQ%3d
    9.      Host:
    abcdefgh:8000
    10.  Origin:
    file://
    11.  User-Agent:
    Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36
    12.  X-CSRF-Token:
    _jXDnt2Cdpplpj5zvK3iPA==
    6.      Request Payloadview source
    {UserID:555, FirstName:rajesh555, LastName:kelam555, Email:rajesh555@gmail.com, Phone:9876554433,…}
    1.  Country: "UK"
    2.  Email: "rajesh555@gmail.com"
    3.  FirstName: "rajesh555"
    4.  LastName: "kelam555"
    5.  Phone: 9876554433
    6.  Postcode: "TW18 4BL"
    7.  UserID: 555
    7.      Response Headersview source
    1.      content-length:
    535
    2.      content-type:
    application/json
    3.      dataserviceversion:
    1.0****

Angular Code for Post :
 $scope.addRow = function () {

                           var config = {};

                           var pushdata = {'UserID':$scope.UserID, 'FirstName':$scope.FirstName, 'LastName':$scope.LastName, 'Email':$scope.Email, 'Phone':$scope.Phone, 'Country':$scope.Country, 'Postcode':$scope.Postcode};

                           // Sending Notification to User
                           growl.addSuccessMessage("User Created", config);
/*                         $http.post(url,pushdata, {'Content-Type':'application/json'}).success(function(pushdata) {
                                  $scope.resultSet = pushdata.d.results;
                                  alret("Data Posted");

                           }) */

                           $http.post(url,pushdata, {headers:{'Content-Type':'application/json'}}).success(function(data){alert(data);});
                           $scope.resultSet.push(pushdata);
                           $scope.createMessage();
                           $scope.UserID='';
                           $scope.FirstName='';
                           $scope.LastName='';
                           $scope.Email='';
                           $scope.Phone='';
                            $scope.Country='';

                     };

it would be great if some one help me to sort.

*Note: I am a kid in AngularJS...please ignore me and feel free to thought me.

I request to suggest the best URl/Site to learn Angularjs in a better and consistent way.

I thought, if I share the format(XML/JSON) of payload expecting for the POST to perform by my SAP Gateway service  which will helps me to quickly resolve this.Below are the formats of XML/JSON  works for POST.

XML Format:

    host:port/sap/opu/odata/sap/USERS/Users('123')

    Users('123')

    2014-11-21T15:21:52Z

    123

    RAJESH

    KELAM

    RAJESHKUMAR.KELAM@ABG.CO.UK

    123456789

    UK

    RG4 6SA

JSON Format:
    {
    d:
    {
    __metadata:
    {
    id: "host:port/sap/opu/odata/sap/USERS/Users('123')"
    uri: "host:port/sap/opu/odata/sap/USERS/Users('123')"
    type: "USERS.User"
    }
    -
    UserID: "123"
    FirstName: "RAJESH"
    LastName: "KELAM"
    Email: "RAJESHKUMAR.KELAM@ABG.CO.UK"
    Phone: "123456789"
    Country: "UK"
    Postcode: "RG4 6SA"
    }
    -
    }

A: You sure that the url you posting is expecting this data you want to post? You can use POSTMAN extension (in google chrome) and test if you service are ready to receive any data from http.post

A: Finally I could able to sort out my problem, it is all about formatting the data passing to REST service..
below is the peice of code which works is my case
$scope.addRow = function () {
                       var StrUId =  ($scope.UserID).toString();
                       var StrPh =  ($scope.Phone).toString();
                       var pushdata = {"UserID":StrUId, "FirstName":$scope.FirstName, "LastName":$scope.LastName, "Email":$scope.Email, "Phone":StrPh, "Country":$scope.Country, "Postcode":$scope.Postcode};

                       // Posting data
                       $http({
                              method: "post",
                              url:url,
                              data:pushdata,
                              headers: {
                                "X-CSRF-Token": "0XGo8HzpzrhaZxxX83QH9g==",
                                         },
                              dataType : "json",
                              async: false,
                         contentType: 'application/json',
                         success: function(data){
                               alert(data);
                         }
                       });

Thanks for the support given
Rajesh


text:
Q: Could not rewrite the get variable url I could rewrite the url localhost/web1/index.php?page=home to localhost/web1/home
But I couldn't rewrite the url localhost/web1/index.php?page=property_details&pid=1008&aid=283 to localhost/web1/property_details/1008/283
Below is the code that I have used:
Options +FollowSymLinks -MultiViews

RewriteEngine On

RewriteBase /web1/
RewriteCond %{THE_REQUEST} \s/+web1/?(?:index\.php)?\?page=([^\s&]+) [NC]
RewriteRule ^ %1? [R=302,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/.]+)/?$ index.php?page=$1 [L,QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]


text:
Q: determine padding for inner ranges on a number line I have a range, which is .1 to .75.  Within that range is a subrange of .13 to .74.
Within the range, the subrange takes up ~93.8% of the space.
The left side 'padding' of the subrange within the range takes up ~4.6% and the right side 'padding' ~1.5%.
I need to ensure there is at least 5% 'padding' on both sides of the subrange by expanding the range (not reducing the size of the inner range).  How to go about quickly determining what the enlarged extents of the range should be?
What if the inner range was [.5, .74] so that only the right side of the outer range needs to be enlarged to achieve minimum 5% padding of the inner range?
not homework :-)

A: Simple logic (edited after question correction):
 Given:  RangeLeft, RangeRight, SubLeft, SubRight
 MinPadding = (SubRight - SubLeft) * 5 / 90
 NewLeft = Min(RangeLeft, SubLeft - MinPadding)
 NewRight = Max(RangeRight, SubRight + MinPadding)]


text:
Q: How to create a Base Dialog? I am trying to create a BaseDialog and re use it all over application. But I am facing a issue on this. My BaseDialog class is
public class BaseDialog extends Dialog {

    private Context mContext;

    public BaseDialog(@NonNull Context context) {
        super(context);
        mContext = context;
    }

    public BaseDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
        mContext = context;
    }

    protected BaseDialog(@NonNull Context context, boolean cancelable, @Nullable DialogInterface.OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
        mContext = context;
    }

    @Override
    public void show() {
        /**
         * My Common code here for all alert
         */
        super.show();
    }
}

And I am using this class as following is working fine.
public class ConfirmCancelDialog extends BaseDialog{
    public ConfirmCancelDialog(Context context, boolean cancelable,
                               OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
    }

    public ConfirmCancelDialog(Context context, int theme) {
        super(context, theme);
    }

    public ConfirmCancelDialog(Context context) {
        super(context);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.confirm_cancel_dialog);

        //My remaining code
    }
}

But If if I try like following code I am getting error.
private void showDialog(){
        BaseDialog passwordDialog = new BaseDialog(context);
        passwordDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        passwordDialog.setContentView(R.layout.password);
        //Rest of my code
    }

I am getting error in setContentView();
But If I use  Dialog passwordDialog = new Dialog(context);my code is working fine. I want to use my BaseDialog in my entire application. Can any one help on me this Please?
I am getting the following error:
 at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
        at android.view.LayoutInflater.createView(LayoutInflater.java:613)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:812)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:752)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:883)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:846)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:522)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:430)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:377)
        at com.android.internal.policy.PhoneWindow.setContentView(PhoneWindow.java:412)
        at android.app.Dialog.setContentView(Dialog.java:519)
        at sonosite.com.dialogwithsound.BaseDialog.<init>(BaseDialog.java:50)
        at sonosite.com.dialogwithsound.MainActivity.showPasswordPromptDialog(MainActivity.java:219)
        at sonosite.com.dialogwithsound.MainActivity$2.onClick(MainActivity.java:61)
        at android.view.View.performClick(View.java:5647)
        at android.view.View$PerformClick.run(View.java:22465)
        at android.os.Handler.handleCallback(Handler.java:754)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:163)
        at android.app.ActivityThread.main(ActivityThread.java:6238)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
        Suppressed: java.io.IOException: No original dex files found for dex location /data/app/sonosite.com.dialogwithsound-1/split_lib_slice_7_apk.apk
        at dalvik.system.DexFile.openDexFileNative(Native Method)
        at dalvik.system.DexFile.openDexFile(DexFile.java:367)
        at dalvik.system.DexFile.<init>(DexFile.java:112)
        at dalvik.system.DexFile.<init>(DexFile.java:77)
        at dalvik.system.DexPathList.loadDexFile(DexPathList.java:359)
        at dalvik.system.DexPathList.makeElements(DexPathList.java:323)
        at dalvik.system.DexPathList.makeDexElements(DexPathList.java:263)
        at dalvik.system.DexPathList.<init>(DexPathList.java:126)
        at dalvik.system.BaseDexClassLoader.<init>(BaseDexClassLoader.java:48)
        at dalvik.system.PathClassLoader.<init>(PathClassLoader.java:64)
2019-02-14 16:14:11.795 30451-30451/sonosite.com.dialogwithsound E/AndroidRuntime:     at com.android.internal.os.PathClassLoaderFactory.createClassLoader(PathClassLoaderFactory.java:43)
        at android.app.ApplicationLoaders.getClassLoader(ApplicationLoaders.java:58)
        at android.app.LoadedApk.createOrUpdateClassLoaderLocked(LoadedApk.java:522)
        at android.app.LoadedApk.getClassLoader(LoadedApk.java:555)
        at android.app.ActivityThread.getTopLevelResources(ActivityThread.java:1924)
        at android.app.LoadedApk.getResources(LoadedApk.java:768)
        at android.app.ContextImpl.<init>(ContextImpl.java:2077)
        at android.app.ContextImpl.createAppContext(ContextImpl.java:2022)
        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5394)
        at android.app.ActivityThread.-wrap2(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
        at android.os.Handler.dispatchMessage(Handler.java:102)


text:
Q: Android : One Signal Push notification did not receive while the app is in use I am using One Signal Push notification in my app. When my app is in closed that mean when I am not using of my app, I get push notification from one signal that is sent from my testing team. But when I am using an app, I did not get it.
Your answer is more appreciated.

A: In latest version (3.+@aar) you should use inFocusDisplaying:
OneSignal.startInit(this)
  .inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification)
  .init();

And you can set None and InAppAlert instead of Notification.

A: By using this line,I can get the push notification though my app is in opened.
Link to refer
OneSignal.enableNotificationsWhenActive(true);

A: try this
window.plugins.OneSignal.enableInAppAlertNotification(true);


text:
Q: InjectionUtils - Parameter Class has no constructor I am trying to send a post request with cxf implementation. But I am getting InjectionUtils - Parameter Class SizeQuantityBean has no constructor with single String parameter, static valueOf(String) or fromString(String) methods error while binding a class.
My code to send request:
sellerService.register(sellerBean);

Implementation:
@Path(BASE_PATH + "/register")
@POST
@Produces({MediaType.APPLICATION_JSON})
BaseBean register(@QueryParam("") SellerBean sellerBean){
   ...
   ...
}

SellerBean class has List of SizeQuantityBean. How to reslove this conflict?

A: Have you tried removing @QueryParam annotation because your request is POST, you should use no tag body.


text:
Q: How to put in a profile picture in django im following Add image/avatar to users in django tip to have users upload their profile pictures, and to display the user's profile picture when a user log in.
Adding profile picture to django user
But for some reason, it comes with an error saying "Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited; form UserProfileForm needs updating."
Is there anyway i can directly modify the django.contrib.auth.models's User model so that i can add only the profile picture and have it displayed on index.html?
there is not a whole lot of information regarding this profile picture system.
and it's only been days since i started learning about django and python.
could anyone explain with examples, how i can achieve this?
Thanks.
(this is the forms.py that's implementing the tip above)
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, get_user_model, login, logout

class UserSignupForm(forms.ModelForm):
    email = forms.EmailField(label='Confirm Email')
    password = forms.CharField(widget=forms.PasswordInput)
    class Meta:
        model = User
        fields = [
            'username',
            'email',
            'password'
        ]
    def clean_email(self):
        email = self.cleaned_data.get('email')
        email_qs = User.objects.filter(email=email)
        if email_qs.exists():
            raise forms.ValidationError("This email has already been registered")
        return email

from django.core.files.images import get_image_dimensions
from .models import UserProfile

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile

    def clean_avatar(self):
        avatar = self.cleaned_data['avatar']

        try:
            w, h = get_image_dimensions(avatar)

            #validate dimensions
            max_width = max_height = 100
            if w > max_width or h > max_height:
                raise forms.ValidationError(
                    u'Please use an image that is '
                     '%s x %s pixels or smaller.' % (max_width, max_height))

            #validate content type
            main, sub = avatar.content_type.split('/')
            if not (main == 'image' and sub in ['jpeg', 'pjpeg', 'gif', 'png']):
                raise forms.ValidationError(u'Please use a JPEG, '
                    'GIF or PNG image.')

            #validate file size
            if len(avatar) > (20 * 1024):
                raise forms.ValidationError(
                    u'Avatar file size may not exceed 20k.')

        except AttributeError:
            """
            Handles case when we are updating the user profile
            and do not supply a new avatar
            """
            pass

        return avatar

A: Example:
models.py:
class YouModel(models.Model):
    .............You field ................
    user_avatar = models.ImageField((upload_to="You/media/uploads", blank=True) # You need to configure media in settings.py
    ........... You fields ..............

class YouModelForm(ModelForm)
    class Meta:
        model = YouModel
        fields = ['user_avatar']

views.py:
from .models import YouModel, YouModelForm

def youfunc(request):
    youtemplate = YouModelForm()
    if request.method == POST:
        youform = YouModelForm(request.POST, request.FILES)
        if youform.is_valid():
           youform.save()
           return HttpResponseRedirect('http://www.You.url') # or other
    youquery = .objects.order_by('user_avatar').last()
    return render(request, "YouProject/YouHtml.html", {'youtemplate': youtemplate, 'youquery': youquery})

I tired to write. You need configure django and write first file upload from user. You can visit to my website and look and decide - this is what You want? my website http://www.webmamoffice.org/en and go to UperVote or http://www.webmamoffice.org/en/upervote


text:
Q: Can I select last, first row of GROUP BY query in MySQL? [Using MySQL]
There is a table messages that contains data as shown below:
Id   Name   Other_Columns
-------------------------
1    A       A1
2    A       A2
3    A       A3
4    B       B1
5    B       B2
6    C       C1
7    A       A4
8    A       A5

What query will return the following result?
1    A       (A3 - A1)
4    B       (B2 - B1)
6    C       (C1 - C1)
7    A       (A5 - A4)

A: SELECT Bottom_one.Id,Bottom_one.Name ,Bottom_one.Other_Columns

FROM `T1` as Top_one

Right JOIN T1 AS Bottom_one
ON Top_one.Id = Bottom_one.Id - 1

WHERE Top_one.Name IS NULL OR Top_one.Name != Bottom_one.Name

Gives a close result:
Id  Name    Other_Columns
1   A       A1
4   B       B1
6   C       C1
7   A       A4

And this :
SELECT Top_one.Id,Top_one.Name ,Top_one.Other_Columns

FROM `T1` as Top_one

Left JOIN T1 AS Bottom_one
ON Top_one.Id = Bottom_one.Id - 1

WHERE Bottom_one.Name IS NULL OR Top_one.Name != Bottom_one.Name

gives the other limits in Other_Columns
Id  Name    Other_Columns
3   A       A3
5   B       B2
6   C       C1
8   A       A5

I have no idea how to combine them into one SQL statement. (Of course it's trivial to do programmatically)
Here's a table dump if anybody else wants to play with it.
CREATE TABLE IF NOT EXISTS `T1` (
  `Id` int(11) NOT NULL auto_increment,
  `Name` varchar(255) NOT NULL,
  `Other_Columns` varchar(255) NOT NULL,
  PRIMARY KEY  (`Id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=9 ;

INSERT INTO `T1` (`Id`, `Name`, `Other_Columns`) VALUES
(1, 'A', 'A1'),
(2, 'A', 'A2'),
(3, 'A', 'A3'),
(4, 'B', 'B1'),
(5, 'B', 'B2'),
(6, 'C', 'C1'),
(7, 'A', 'A4'),
(8, 'A', 'A5');

Nice Puzzle!

A: Try this
select min(ID) as FirstId,Name,
       Concat(max(Other_columns),"-",min(Other_Columns)) as Ans
from msgtable
group by Name


text:
Q: Installing Gunicorn using Cygwin How can I install Gunicorn using Cygwin?
I cant seem to find the Gunicorn Package on Cygwin...Unless I'm understanding the issue on github wrong, I think it does support Gunicorn.
Also I found this in the changelog:

0.17.2 / 2013-01-07

*

*optimize readline

*make imports errors more visiblle when loading an app or a logging class

*fix tornado worker: don't pass ssl options if there are none

*fix PEP3333: accept only bytetrings in the response body

*fix support on CYGWIN platforms


text:
Q: Multiple animated images in a Icon? I'm working on a simple game as a learning exercise. The game consists of a grid of squares, each of which has a background image and can contain any number of objects and player tokens layered on top of each other. At the moment, the board is just a JPanel, and the images are drawn using drawImage() in the paintComponent() method. This technically works, but it's rather clunky and probably not the best way to do it. Now, I'd like to be able to repaint a given square without repainting the whole board, and it seems my original implementation is lacking.
The solution I came up with was to have the squares represented by a custom Icon class, and the board by a JPanel with a GridLayout containing the custom Icons. The problem there is that eventually, some of the background or object images will be animated, and there may be multiple animated things on a square. I was thinking I'd do this with animated GIFs.
I remember reading that using an ImageObserver in the drawImage method will cause the animation to show up, but it doesn't look like Icon is a ImageObserver. Would using the board JPanel as the ImageObserver be a good idea? Is there a better way to do it besides animated GIFs?
The other solution that came up was a grid of JLayeredPanes with JLabels containing the appropriate images layered on each other, but for some reason, that seems like swatting a fly with a sledgehammer.

A: Depending on context, use an instance of javax.swing.Timer or java.util.Timer to pace the animation. You can repaint the icon, as shown here, or replace the icon, as shown here.

A: Maybe Animated Icon will give you some ideas.


text:
Q: IIS SMTP TLS encryption I enabled TLS in IIS SMTP Virtual Server with a self-signed server certificate. Made sure that the certificate has the FQDN of the server.
Checked the TLS encryption checkbox in Virtual SMTP > Properties > Delivery tab > Outbound Security.
When I try to send mail using Pickup folder in c:\inetpub\mailroot the email does not get delivered with TLS. Also, the TLS encryption checkbox becomes unchecked automatically.
Do you know what might be causing this problem?
Regards
John

A: I think you did the same error as me... all I wanted is my outgoing emails to be tls encrypted and remove the "gmail security warning" on my messages.
If you're using the integrated IIS SMTP service from windows server, you don't need to install any certificates to do that.
The solution IS NOT to hit the "require tls encryption" in the "Access" tab.
Instead, go to the "Delivery" tab, hit "Outbound Security", then check "TLS encryption".

A: Self-signed certs does not work for SMTP, that's why it's unchecked.
Worth noting that IIS SMTP can only use implicit TLS where the connection is encrypted from start and not the wide used explicit TLS where a secure connection starts after the STARTTLS command is sent.


text:
Q: How is equal_range supposed to work? #include <boost/property_tree/ptree.hpp>
#include <string>
#include <iostream>

int main()
{
    boost::property_tree::ptree ptree;
    const std::string entry = "server.url";
    ptree.add( entry, "foo.com" );

    auto range = ptree.equal_range( entry );
    for( auto iter = range.first ; iter != range.second ; ++iter )
        std::cout << iter->first << '\n';
}

I don't understand why this code is not printing. As there could be many server.url entries, I was trying to access them using equal_range.

A: equal_range doesn't work with paths. After the add, your ptree looks like this:
<root>
  "server"
    "url": "foo.com"

But the equal_range is looking for children named "server.url" directly within the root node.
Also, you probably want to print out it->second.data(), because the former would just print "server.url" for every found entry.
Here's the corrected code:
#include <boost/property_tree/ptree.hpp>
#include <string>
#include <iostream>

int main()
{
    boost::property_tree::ptree ptree;
    const std::string entry = "server.url";
    ptree.add( entry, "foo.com" );

    auto range = ptree.get_child("server").equal_range( "url" );
    for( auto iter = range.first ; iter != range.second ; ++iter )
        std::cout << iter->second.data() << '\n';
}


text:
Q: How to install a Chrome Extension not in the Downloads folder in Chrome OS? The file picker in Chrome OS only shows the Downloads folder. How can we load an unpacked extension in Chrome that isn't in the Downloads folder?

A: My suggestion would be to create a project folder within the download folder and load it from there. I wanted to do the same thing but Chrome OS doesn't seem to be able to create folders outside of the download folder unless it's done in your Google Drive.


text:
Q: X server display configuration page will not load The X Server Display Configuration Page will not load due to "failed to query NoScanout for screen 0".
So, the  Display Control Panel in System Settings does not recognize that the second monitor exists and it thinks that the primary monitor unknown.  How do I get ubuntu to recognize both my monitors and set them up in twinview?  Please give detailed instructions as I am very new to this.  I am running Ubuntu 11.10
I have a Dell u2410 and a Vizio va19l hdtv10t lcd displays. running from an Nvidia Geforce4 MX400 video card. The Dell is using the video card's vga interface and the Vizio is using its hdmi input from the the video card's dvi interface. The resolution of both is set to 1600x1080.  Everything works perfectly in Windows 7.

A: I had exactly the same problem, and updating the NVIDIA driver to current (280 instead of 173) solved my problem.
See also my answer in this thread.


text:
Q: Gradle [META-INF/persistence.xml] was not found I am building my JPA/EJB project using gradle and getting this warning:
$ gradle jar
:compileJava
Note: Creating static metadata factory ...
Note: The persistence xml file [META-INF/persistence.xml] was not found. NO GENERATION will occur!! Please ensure a persistence xml file is available either from the CLASS_OUTPUT directory [META-INF/persistence.xml] or using the eclipselink.persistencexml property to specify its location.
2 warnings
:processResources UP-TO-DATE
:classes
:jar

My project structure:
   ProjectX
   |-src
   |---main
   |-----java
   |-------domain
   |-------ejb
   |-----resources
   |-------META-INF
   |-----------persistence.xml

The interesting part is that the persistence.xml ends up in the target jar artifact:
$ jar -tf target/projectx.jar
META-INF/
META-INF/MANIFEST.MF
domain/
domain/Employee.class
ejb/
ejb/EmployeeEJB.class
META-INF/persistence.xml

Why is there complain that the [META-INF/persistence.xml] even though it is there?
The gradle file:
apply plugin: 'java'
project.buildDir = 'target'
sourceSets.all {
    output.resourcesDir = output.classesDir
}
jar{
    destinationDir=project.buildDir
}
repositories {
    mavenCentral()
}
dependencies {
    compile 'org.glassfish:javax.ejb:3.0.1','org.eclipse.persistence:javax.persistence:2.0.0'
}

I have quickly tested with maven now and ther is no such warning there.

A: The persistence.xml is required at compile time. One way to achieve this is:
sourceSets.main.output.resourcesDir = sourceSets.main.output.classesDir
compileJava.dependsOn(processResources)

A: In fact the solution suggested by @peter-niederwieser to set your main resources and classes dir to same location results in duplicated entries in your jar archive. Basically, it's twice the original size, don't know if there are other problems.
So to fix this, you have to add
sourceSets.main.output.resourcesDir = sourceSets.main.output.classesDir
jar {
    duplicatesStrategy = 'exclude'
}

to your build.gradle.

A: META-INF should be in the root of your classpath (/src/main/java/META-INF)

A: The persistence.xml should be in src/main/resources/META-INF. This worked for me. Please not that this was a non spring project


text:
Q: How do I make a rectangle change color when a ball hits it the first and second time and then make it disappear on the third hit? I am making a brick breaker game and right now the ball hits a brick (a rectangle) and it breaks on the first hit. I want it so that the first time the ball hits the brick, it changes to light red and the second to red and then on the third hit, it breaks.
#brick list
rectInfo = [rX, rY]
allRectInfo = [rectInfo[:] for i in range(numRects)]
allRectInfo[0] = [45, 20, True]
allRectInfo[1] = [45, 60, True]
allRectInfo[2] = [45, 100, True]
allRectInfo[3] = [45, 140, True]
allRectInfo[4] = [195, 20, True]
allRectInfo[5] = [195, 60, True]
allRectInfo[6] = [195, 100, True]
allRectInfo[7] = [195, 140, True]
allRectInfo[8] = [345, 20, True]
allRectInfo[9] = [345, 100, True]
allRectInfo[10] = [345, 60, True]
allRectInfo[11] = [345, 140, True]
allRectInfo[12] = [495, 140, True]
allRectInfo[13] = [495, 100, True]
allRectInfo[14] = [495, 60, True]
allRectInfo[15] = [495, 20, True]
allRectInfo[16] = [645, 20, True]
allRectInfo[17] = [645, 60, True]
allRectInfo[18] = [645, 100, True]
allRectInfo[19] = [645, 140, True]

#when the ball hits the bricks
for i in range (numRects):
  if allRectInfo[i][2] == True:
    rect (allRectInfo[i][0], allRectInfo[i][1], rectW, rectH)
       if allRectInfo[i][1]-25 <= y <= allRectInfo[i][1]+74 and
    allRectInfo[i][0]-5.5 <= x <= allRectInfo[i][0]+150:
            incry = incry * (-1)
            allRectInfo[i][2] = allRectInfo[i][2] - 1
            score = score + 1
            hits = hits + 1

A: Instead of an boolean attribute, the 3rd element of the allRectInfo[i] tuple, has to be the number of hits, initialized by 0:
allRectInfo[0] = [45, 20, 0]
allRectInfo[1] = [45, 60, 0]
allRectInfo[2] = [45, 100, 0]
# [...]

Increment the hit counter when a hit is identified:
for i in range (numRects):
      if # [...]

            # [...]

            allRectInfo[i][2] += 1

Define an array of colors and use the color dependent on the brick:
brickcolor1 = # [...]
brickcolor2 = (255, 128, 128)
brickcolor3 = (255, 0, 0)
brickcolors = [brickcolor1, brickcolor2, brickcolor3]

currentcolor = brickcolors[allRectInfo[i][2]]

The brick breaks if a brick has reached the hit limit. Skip the brick in this case:
for i in range (numRects):
    if allRectInfo[i][2] < 3:
        # [...]

All together that may look as follows:
for i in range (numRects):

    if allRectInfo[i][2] < 3:

        currentcolor = brickcolors[allRectInfo[i][2]]
        fill(*currentcolor)
        rect(allRectInfo[i][0], allRectInfo[i][1], rectW, rectH)

        if allRectInfo[i][1]-25 <= y <= allRectInfo[i][1]+74 and allRectInfo[i][0]-5.5 <= x <= allRectInfo[i][0]+150:
            incry = incry * (-1)
            score = score + 1

            allRectInfo[i][2] += 1


text:
Q: JAVA - Is it a bug in java.util.Calendar class or what? I have faced the same problem many times.
The Same Problem was With This Question and Got Solution Like the Same,
How to compare known hours ad current hour in android?
Problem :
When I use Calendar calCurr = Calendar.getInstance(); to get the Calendar object of current date and time, It always return me wrong.
I have put logs and checked it and to make it correct I had to add in years and months and then I got the correct object for Current Date and Time.
See My Example :
    Calendar calCurr = Calendar.getInstance();
    Log.i("Time in mili of Current - Normal", ""+calCurr.getTimeInMillis());
                // see what it gives? dont know why?

    Date date = new Date();
    calCurr.set(date.getYear()+1900, date.getMonth()+1, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
                // so added one month to it

    Log.i("Time in mili of Current - after update", ""+calCurr.getTimeInMillis());
                // now get correct

Question :

*

*Why it's giving the wrong output?

*Is it a bug in there or My concept about the Calendar class is wrong?

*tell me what should have been done
for that?

A: It works perfectly as expected if you change to getDate() it outputs :

Time in mili of Current - Normal Wed Apr 04 11:34:34 BST 2012
Time in mili of Current - after update Fri May 04 11:34:34 BST 2012

What do you expect ? And in milleseconds it also equals 30 days :

Time in mili of Current - Normal 1333535834557
Time in mili of Current - after update 1336127834557

and the calculation is (difference, divided by milliseconds in a day) :
1336127834557 - 1333535834557 = 2 592 000 000

2592000000 / 86400000 = 30

And todays date in milliseconds after 1970 is 1333536754 ... which fits, I don't see a problem.
EDIT
Your Problem is you are setting Month like 3 for march...there you need to set 2..cause months are indexed from 0 to 11.

A: Do not use date.getXXX(). Do not use any setter or getter except Date.getTime(). They are all deprecated. Using them would cause unexpected results.
If you call Calendar.getInstance(), it is already set to the current date. If you want to set or add days, months, whatever, set them on the calendar.
E.g. calCurr.set(Calendar.MONTH,2) or calCurr.add(Calendar.DAY,1).

A:
Calendar months are zero-indexed. So when want to set for March its 2 not 3

Also, Don't set year, month and date from the Date object.  If you must initialise a Calendar to a date, do it like this:
   Calendar cal = Calendar.getInstance();
   cal.setTime(date);

be aware that your Date object might be a different locale to what you think it is.

A: It is NOT a bug, the Calendar is returning what it should (at least here it is).
Calendar calCurr = Calendar.getInstance();
Log.i("Time in mili of Current - Normal", ""+calCurr.getTimeInMillis());
            // see what it gives? dont know why?

I got 1333546375707 milliseconds, which is the correct value (also calculated by hand).
Which value are you expecting here? How you know it is wrong?

Date date = new Date();
calCurr.set(date.getYear()+1900, date.getMonth()+1, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
            // so added one month to it

Why adding ONE to the month? Month of both Date and Calendar are zero-based - no need to add 1.

EDIT
Calculating by hand (approximated):
2012  - 42 years * 365.24 days/year * 86400 seconds/day
April - (31 + 29 + 31) days * 86400
4th   - 3 days * 86400
13:30 - 13.5 hours * 3600 seconds/hour
        ====================
        1333553112 seconds

A: When Calendar object is created by using Calendar.getInstance() the instance variable "time" in the Calendar object is set and this value will get changed only if you use
Calendar.setTimeInMillis() function.
Code snippet from Calendar object:
public long getTimeInMillis() {
        if (!isTimeSet) {
        updateTime();
    }
        return time;
    }

Here "isTimeSet" will become "true" when Calendar.getInstance() is called and it returns "time" every time without updating the time.
This is the reason you get the same value of time every time you call
calCurr.getTimeInMillis();
Hope this helps.

A: It's the weird implementation of Calendar.
For some reasons January is month 0, and years are not very logical as well.
I recommend Joda time library.

A: We are using below lines of code for finding current date and time It's working fine our side.
            java.util.Calendar calc = java.util.Calendar.getInstance();

        int day = calc.get(java.util.Calendar.DATE);
        int month = calc.get(java.util.Calendar.MONTH)+1;
        int year = calc.get(java.util.Calendar.YEAR);

        String dayStr,monthStr;
        if(day<10){
            dayStr = "0"+day;
        }else{
            dayStr = ""+day;
        }
        if(month<10){
            monthStr = "0"+month;
        }else{
            monthStr = ""+month;
        }
        /*String currentdate = monthStr+"/"+dayStr+"/"+year+" ";*/
        String currentdate = dayStr+"/"+monthStr+"/"+year+" ";

        /*String currenttime = currentdate + String.valueOf(calc.get(java.util.Calendar.HOUR_OF_DAY))+ ":"+
        String.valueOf(calc.get(java.util.Calendar.MINUTE))+":"+String.valueOf(calc.get(java.util.Calendar.SECOND));*/

        return currentdate;

A: Java Date Based API  is not properly designed.
in future versions I think some problems of The API are planned to address.
I would recommend to use JodaTime.


text:
Q: VB.NET variable initialization problem on Publish Is there any way to stop Visual Studio from removing variable initializations prior to publish?
I have a variable:
Dim myString as String: myString = Nothing

When I click publish, Visual Studio removes ": myString = Nothing"
and then during build it complains "myString is used before it is initialized".  If I do a build (instead of publish) this doesn't happen.

A: This appears to be more a warning. It's perfectly legal to initialize a string using the colon separator, but likely it's being optimized out.
Your code:
Dim myString as String: myString = Nothing

is the equivalent of:
Dim myString as String = Nothing

which is the equivalent of:
Dim myString as String

as Strings default to Nothing by default, at least in the all the more recent versions of VB/ASP I can find
And as such will trigger that warning.  whether or not it affects your output? that's on you :)


text:
Q: A textbook for numerical analysis (with solution manual) This semester I'm studying numerical analysis in university. Our textbook is Numerical Analysis by David.R. Kincaid and E. Ward. Cheney. It is a very good and strong book in numerical analysis with a lot of good exercises but the problem is that it doesn't have any solution manual and I cannot check whether I solved problems true or false. As the main important thing in this course is the ability of solving problem, I'm looking for a good textbook in numerical analysis with strong exercises and also with solution manual.
furthermore, I know that Kincaid's book 6th edition has solution manual but our textbook is its 1991 edition which doesn't have any solution manual and its exercises are completely different with 6th edition. Also the 6th edition of this book as I know doesn't have as many questions as its 1991 edition has, so it is not a good book for me.
Any help would be appreciated.

A: You can read "An introduction to Numerical Analysis" by David.F.Mayers. Also another would be "Numerical Methods" by Dahlquist and Bjorck which I think has solutions.


text:
Q: Prove affine independence of these points I am having some trouble with this problem.
I want to prove that the following points are affine independent.
Let $k\geq 2$ and $i\in\{0,1,\dots,2k\}$ we define $S_i =(s_i^t)$ where $s_i^{i+2t (\bmod 2k+1)}=1$ for $t\in\{0,1,\dots,k-1\}$ and $s_i^t=0$ in the other cases, $s_i\in \mathbb{R}^{2k+1}$. Let now $X$ be defined as $\left\{ S_{i}\,:\, i\in\{0,1,\dots,2k\}\right\}$, I need to show that the points in $X$ are affine independent.
Any advice?
Regards,
John

A: The $S_i$ are actually linearly independent vectors in $\mathbb R^{2k+1}$ so they are certainly affinely independent.
Let $P$ be the $(2k+1)\times(2k+1)$ matrix with general entry $t^j_i=1$ if $j\equiv i+1\hbox{ (mod $2k+1$)}$ and $0$ otherwise. This is the matrix of a linear tranformation that simply shifts the coordinates of every vector one position to the right (and the last coordinate becomes the first one).
Let $S$ be the matrix whose rows are the coordinates of the $S_i.$ Then
$$S=I+P^2+\ldots+P^{2(k-1)}$$
Because $P$ represents a coordinate shift, repeating it $2k+1$ times leaves every vector unchanged:
$$P^{2k+1}=I$$
and therefore all eigenvalues $\omega$ of $P$ are complex numbers that satisfy $\omega^{2k+1}=1.$ Apart from $\omega=1$ these numbers all satisfy $\omega^2\neq1$ and $\omega^{2k}\neq1.$
The eigenvalues $\lambda$ of $S$ all have the form
$$\lambda=1+\omega^2+\ldots+\omega^{2(k-1)}=\frac{1-\omega^{2k}}{1-\omega^2}$$
where the second equality holds only for $\omega\neq1$ but in any case all eigenvalues of $S,$ and thus its determinant, are nonzero. This shows that the rows of $S$ are linearly independent.


text:
Q: jQuery regex match function always returns false I try to make a simpel form valitation function in jQuery, but in some way this function always returns that de input is false. Can you help me out?
<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

Formulier

      <form role="form" id="validate">

    Email address:
    <input type="text" class="form-control" id="email" data-regex="^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}$">

    Password:
    <input type="password" class="form-control" id="pwd" data-regex="/^[a-z0-9_-]{6,18}$/">

    <input type="checkbox"> Remember me

  <button type="submit" class="btn btn-default">Submit</button>
</form>

I don't see were I'm wrong... can you help me out?
I tried with 'alert' to see the values of $(this).val and $(this).attr('data-regex') but this seems all fine to me.

A: Anything read from DOM is string
You've to use the RegExp constructor and pass the string to it to convert the string to Regular Expression.
if ($(this).val().match(new RegExp($(this).attr('data-regex')))) {
                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Also, note that there is no need of delimiter slashes in the string.
And make sure to double escape the some metacharacters if needed
For example, to match digits use
\\d

I'll also suggest to use RegExp#test to check if the string satisfies the regex instead of String#match
if (new RegExp($(this).data('regex')).test($(this).val())) {

Also, the jQuery code can be shortened.
$("form#validate :input").on("change paste keyup", function () {
    $(this).toggleClass('notoke', !new RegExp($(this).data('regex')).test($(this).val()));
});

Working Demo


text:
Q: Collapsing toolbar issue with RecyclerView I have a CollapsingToolbarLayout in layout, below that I have placed a  RecyclerView. it works perfect and the parallax effects comes smoothly when the RecyclerView scrolls, but the issue, is suppose if the RecyclerView has less items and there is nothing to scroll, still it scolls and an empty space shows at the bottom. what my requirment is it shouldn't scroll if the RecyclerView can accomodate all the views in the visible screen, is there any way to do this ?
layout
<android.support.design.widget.CoordinatorLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/container_id"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <include layout="@layout/toolbar"/>

    <android.support.v7.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/bg_color"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

</android.support.design.widget.CoordinatorLayout>

toolbar.xml
<android.support.design.widget.AppBarLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/app_bar_layout"
        android:layout_width="match_parent"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true">

    <android.support.design.widget.CollapsingToolbarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

        <ImageView
                app:layout_scrollFlags="scroll"
                app:layout_collapseMode="parallax"
                android:layout_below="@+id/toolbar"
                android:minHeight="250dp"
                android:layout_height="300dp"
                android:layout_width="match_parent"/>

        <android.support.v7.widget.Toolbar
                app:layout_collapseMode="pin"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:gravity="center"
                android:layout_gravity="top"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

            <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                <ToggleButton
                        android:layout_centerVertical="true"
                        android:layout_margin="@dimen/dimen_xs"
                        android:layout_width="20dp"
                        android:layout_height="20dp"
                        android:gravity="center"
                        android:layout_alignParentEnd="true"
                        android:layout_alignParentRight="true"
                        android:textOff=""
                        android:textOn=""/>

            </RelativeLayout>
        </android.support.v7.widget.Toolbar>
    </android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>


text:
Q: Combination of group's math php function Looking for a function in php for possible element combinations of unknown number of groups like
{x, y...z}...{x,y...z}
example:
A:{1,2,3,4},B:{5,6},C:{a,b,c}

Result:
ABC
15a
15b
15c
16a
16b
16c
25a
25b
25c
26a
26b
26c
35a
35b
.
.
.
46c

I just need something like this but this is not working
$array = array( 'A' => array(1, 2, 3, 4), 'B' => array(5, 6). 'C' => array('a', 'b', 'c'))

function makeCombinations($array){
    foreach($array as $value){makeCombinations($array)
    }
}

A: try this.
Assuming A ,B , C were arrays
$a = array(1,2,3,4);
$b = array(5,6);
$c = array("a","b","c");

foreach($a as $values)
    foreach($b as $values2)
        foreach($c as $values3)
            echo $values."".$values2."".$values3."\n";

Demo


text:
Q: How do you set the Customvalidation in Metadata file, If the Metadata is in different Model project My silverlight solution has 3 project files

*

*Silverlight part(Client)

*Web part(Server)

*Entity model(I maintained the edmx along with Metadata in a seperate project)

Metadata file is a partial class with relavent dataannotation validations.
[MetadataTypeAttribute(typeof(User.UserMetadata))]
public partial class User
{
    [CustomValidation(typeof(UsernameValidator), "IsUsernameAvailable")]
    public string UserName { get; set; }
}

Now my question is where I need to keep this class UsernameValidator
If my Metadata class and edmx are on Server side(Web) then I know I need to create a .shared.cs class in my web project, then add the proper static method.
My IsUserAvailable method intern will call a domainservice method as part of asyc validation.
   [Invoke]
    public bool IsUsernameAvailable(string username)
    {
        return !Membership.FindUsersByName(username).Cast<MembershipUser>().Any();
    }

If my metadata class is in the same project as my domain service is in then I can call domain service method from my UsernameValidator.Shared.cs class.
But here my entity models and Metadata are in seperate library.
Any idea will be appreciated
Jeff wonderfully explained the asyc validation here
http://jeffhandley.com/archive/2010/05/26/asyncvalidation-again.aspx
but that will work only when your model, metadata and Shared class, all are on server side.

A: There is a kind of hack to do this. It is not a clean way to do it it, but this is how it would probably work.
Because the .shared takes care of the code generation it doesn't complain about certain compile errors in the #if brackets of the code. So what you can do is create a Validator.Shared.cs in any project and just make sure it generates to the silverlight side.
Add the following code. and dont forget the namespaces.
#if SILVERLIGHT
using WebProject.Web.Services;
using System.ServiceModel.DomainServices.Client;
#endif

#if SILVERLIGHT
            UserContext context = new UserContext();
            InvokeOperation<bool> availability = context.DoesUserExist(username);
            //code ommited. use what logic you want, maybe Jeffs post.
#endif

The compiler will ignore this code part because it does not meet the condition of the if statement. Meanwhile on the silverlight client side it tries to recompile the shared validator where it DOES meet the condition of the if-statement.
Like I said. This is NOT a clean way to do this. And you might have trouble with missing namespaces. You need to resolve them in the non-generated Validator.shared.cs to finally let it work in silverlight. If you do this right you can have the validation in silverlight with invoke operations. But not in your project with models and metadata like you would have with Jeff's post.
Edit: I found a cleaner and better way
you can create a partial class on the silverlight client side and doing the following
public partial class User
    {
        partial void OnUserNameChanging(string value)
        {
            //must be new to check for this validation rule
            if(EntityState == EntityState.New)
            {
                var ctx = new UserContext();
                ctx.IsValidUserName(value).Completed += (s, args) =>
                {
                    InvokeOperation invop = (InvokeOperation) s;
                    bool isValid = (bool) invop.Value;

                    if(!isValid)
                    {
                        ValidationResult error = new ValidationResult(
                            "Username already exists",
                            new string[] {"UserName"});
                        ValidationErrors.Add(error;
                    }
                };
            }
        }
    }

This is a method generated by WCF RIA Services and can be easily partialled and you can add out-of-band validation like this. This is a much cleaner way to do this, but still this validation now only exists in the silverlight client side.
Hope this helps


text:
Q: SQL Update column from one table to another I'm a beginner in SQL however I have two tables one LibraryTable where I have list of songs, and another table called Playlist, I'm using netbeans to program a prototype jukebox, and I can add songs from the Library to my playlist, and I can increment playcount of all the song that where added to the playlist, however both LibraryTable and Playlist have a column called playcount, I want know how I would go about updating the playcount column in LibraryTable with the the playcount column in my Playlist table.

A: You can do joins in UPDATE statements.
UPDATE L
SET L.Playcount = P.Playcount
FROM Playlist P
INNER JOIN LibraryTable L
ON P.SongID = L.SongID


text:
Q: Let $f:[a,b]\to\mathbb R$ be Riemann integrable on $[c,b] $ for all $c\in(a,b).$ Thus $f$ is Riemann integrable on $[a,b].$
Let $f:[a,b]\to\mathbb R$ be Riemann integrable on $[c,b] $ for all $c\in(a,b).$  Thus $f$ is Riemann integrable on $[a,b].$

I know that if we have a bounded $f$ then the statement is true. However I wonder what happens if the function is not bounded, so for example we have
$$ f(x) = \left\{
        \begin{array}{ll}
            \infty & \quad x = 0 \\
            x & \quad x > 0
        \end{array}
    \right. $$
Will, in that case, f be integrable on $[c,b]$ for all $c\in(0,b)$ but not integrable on $[0,b]$?

A: A Riemann integrable function has to be bounded, basta. Consider the example
$$f(x):={1\over\sqrt{x}}\quad(0<x\leq1),\qquad f(0):=0\ .$$
This $f$ is unbounded on $[0,1]$, but integrable on any subinterval $[c,1]$, $c>0$. Therefore the Riemann integral $\int_{[0,1]} f(x)\>{\rm d}x$ does not exist. Nevertheless the improper integral
$$\int_0^1 f(x)\>dx:=\lim_{c\to0+}\int_c^1 f(x)\>dx=\lim_{c\to0+}\bigl(2\sqrt{1}-2\sqrt{c}\bigr)$$
converges, and has the value $2$.


text:
Q: How can I increase the bullet size in a li? The bullets in IE8 are so small, I tried changing the font-size, but that didn't work.
Code:

item 1

item 2

Is there any way to do this without using an image for the bullet?

A: You could do this in an IE8 conditional comment...
ul {
   list-style: none;
}

ul li:before {
   content: "•";
   font-size: 170%; /* or whatever */
   padding-right: 5px;
}

jsFiddle.
In IE7, you could prepend the bullet via JavaScript and style it accordingly.

A: You can also do:
li::marker{
   content:"\25A0";
   font-size: 1.5rem;
   color: black;
   vertical-align: bottom;
}

A: Internet Explorer doesn't seem to natively support sizing of the bullets from list-style-type with font-size as Firefox and Chrome appear to. I do not know if this is a known problem or bug.
There are workarounds, but sometimes an image is the quickest and more widely supported "fix".

A: IE8+ does scale the bullets but not for every font size.
My fix is based on the fact the bullets for Verdana are larger than for Arial. I use css to set Verdana for li, at the same time I add extra spans around li's contents to keep the original font. Also, as Verdana can makes the lines higher, I may need to use line-height to make up for that, but that depends on the browser.
Also I can use bigger font size for li to make the bullets even larger, then I'll have to use still smaller line-height.
ul {
    font: 12px Arial;
}
ul li {
    font-family: Verdana;
    line-height: 120%;
} /* font-size: 14px; line-height: 100%; */
ul li span {
    font: 12px Arial;
}

item 1

item 2


text:
Q: Dynamically generate cases for switch statement using an array I'm creating a script to auto generate an RSS feed for the various sections of my website. I've queried by database and have an array of data which represents each section called $showData. I'm using a switch statement to setup various variables depending upon the section of the site. Instead of having to change this script each time I add a show, I'd like the case in my switch statement to be dynamic.
<?php
switch($section){
    case 'show1':
        $title = $showData['show1'] . ' Title';
        $description = $showData['show1'] . ' Description';
        break;
    case 'show2':
        $title = $showData['show2'] . ' Title';
        $description = $showData['show2'] . ' Description';
        break;
}
?>

I attempted to use a foreach loop to create each case, but you can't put that inside a switch statement. Someone else in another post I read suggested using eval().
Here's my code that I tried, that doesn't work.
<?php
switch($showFilter)}
    foreach($showFilters as $key => $value){
        case $key:
        $title = $value;
        $description = $value;
        break;
    }
}
?>

Here's a print_r of the array
Array
(
    [show1] => The Name of Show One
    [show2] => The Name of Show Two
)

A: Instead of using a switch block, could you not just try:
$title = $showData[$section] . ' Title';
$description = $showData[$section] . ' Description';


text:
Q: Yeoman grunt build does not throw any warning/error but the resulting dist is not working In an angular application, I either do grunt build or grunt serve:dist to build my production files and deploy them on a remote server. Everything looks fine and I can't see any warning message in the yeoman logs. yo doctor is also happy ("Everything looks all right!").
The problem is, whenever I go to my dist/index.html, I get the following message from the console:

Failed to load resource: the server responded with a status of 404
  (Not Found).     http://localhost:9000/components/portal/portal.html
Error: [$compile:tpload] Failed to load template:
  components/portal/portal.html

portal.html being the first template to be displayed in the app when it is not minified. I am surprised that the app is trying to get a resource in components/ since all the html should now be in dist/index.html right?
I am using Yeoman version 1.4.6 with the default GruntFile.js from the angular generator. More particularly, the build task is defined as follow:
grunt.registerTask('build', [
    'clean:dist',
    'wiredep',
    'useminPrepare',
    'concurrent:dist',
    'autoprefixer',
    'concat',
    'ngAnnotate',
    'copy:dist',
    'cdnify',
    'cssmin',
    'uglify',
    'filerev',
    'usemin',
    'htmlmin'
  ]);

What could possibly be the cause of my problem? Feel free to request more information.

A: In the Gruntfile.js they say
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

So the problem was that part of my project was located more than one level down the root. Changing {,*/}* by **/* in the tasks involved resolved the issue.


text:
Q: Numero de repetições em uma lista Preciso resolver o seguinte exercício:
Faça uma função chamada contaPalavras. Essa função deve receber uma lista como entrada.
Cada elemento da lista recebida pela função é uma outra lista de palavras.
A função deve retornar o total de palavras sem contar as repetições, a palavra que mais se repetiu e a palavra que menos repetiu.
até agora eu fiz o seguinte:
def contaPalavras(lista):
ord = []
rep=[]
total=0

for sublist in lista:
    for val in sublist:
        ord.append(val)
ord=sorted(ord)

repeticoes=0
for x in range(0,len(ord)-1):
   if ord[x]==ord[x+1]:
     repeticoes+=1
     if x == len(ord)-2:
       print(ord[x],',',repeticoes+1)
   else:
     print(ord[x],',',repeticoes+1)
     repeticoes=0

a lista utilizada foi:
lista = [
    ['Angola','Chade','Gana'],
    ['Chade','Angola','Gana','Togo'],
    ['Togo','Gana','Chade','Eritreia'],
    ['Chade','Togo','Angola']
]

até agora eu consigo printar o número de repetições, mas não sei como pegar o que mais se repete, o que menos se repete e o total da lista sem as repetições

A: vamos começar com a lista de palavras sem repetição.
Crie um array novo, ele irá conter as palavras que não serão repetidas.
palavras_sem_repeticao = []

Agora, verifique se a palavra que será adicionada já está contida no array novo.
if palavra not in palavras_sem_repeticao:
    palavras_sem_repeticao.append(palavra)
else:
    print(f"A palavra {palavra} já foi armazenada")

Para encontrar as palavras que mais foram repetidas, você precisará de um array que contenha TODAS essas palavras.
Agora, verifique o número de vezes que a palavra 'x' se repete dentro desse array.
Ex.
array_completo = ["banana", "pera", "banana", "laranja"]
array_completo.count("banana") # deverá retornar 2

Crie um laço de repetição que verifica todas as palavras, e em seguida você terá o número de vezes que cada palavra se repete dentro do array, agora basta pegar o maior e menor valor.


text:
Q: django admin - selecting a single model to publish to site Hey, I'm making a popup radio player with an attached shoutbox with django and i'm having trouble getting the admin functionality I want.
I have two models:
1) A Stream (which represents a certain radio stream that the admin can publish to play on the frontpage - i.e. there are multiple saved streams, but only one is playing on the frontpage at a time, at the discretion of the admin)
2) A Shout (a shout that has been entered into the shoutbox, and is associated to a certain stream, i.e. every stream has multiple shouts that are entered by users of the site.)
I want the admin to be able to log into the back end, create multiple streams, but only select one to be published at any one time. Presumabley each stream should have an attribute (i.e is_published) and I should create an admin action to perform a check of every stream, and publish only the correct one? Is this the correct way to go about it or am I missing something

A: The only potential problem I forsee is, what if someone has already connected and is listening to a stream before the admin changes it.  Should that person hear the new stream or continue to hear the stream they were listening to?
Other than that, the way you've described it, I could see it working.  You could make a url/view which always returns the current stream, like /stream/current/.  The view for that URL will always get the most current Stream model...
def current_stream(request, *args, **kwargs):
   # Get first stream marked as published
   s = Stream.objects.filter(is_published=True)[1][0]
   return do_streaming_stuff(s)

Because you're going to probably use the "set this stream as active stream" elsewhere in your app, you could make it a part of your Stream model...
class Stream(models.Model):
    is_published = models.BooleanField()

    def set_as_active_stream(self, do_save=True):
        enabled_streams = Stream.objects.filter(is_published=True)
        for s in enabled_streams:
            s.is_published=False
            s.save()
        if do_save:
            self.is_published=True
            self.save()

    def save(self, *args, **kwargs):
        if self.is_published:
            # No need to double save, since we're already saving it
            self.set_as_active_stream(do_save=False)
        super(Stream, self).save(*args, **kwargs)


text:
Q: How can i call a method on ES6 class outside it? I try to make a decorator for class and gain deeper understanding of how things work with es6 classes. So i stumbled upon a question — are there any way to access class internals from outside since can't invoke it as a function
Example: given following function transpiled by Babel:
function App() {
    (0, _classCallCheck3.default)(this, App);

    var _this = (0, _possibleConstructorReturn3.default)(this, (0, _getPrototypeOf2.default)(App).call(this));

    _this.returnState = _this.returnState.bind(_this);
    return _this;
  }

are there any ways to access the method returnState from outside?


text:
Q: Does a rolling ball take slower to reach the ground than a dropped non rotating ball from the same height? I know in a ramp this isn't true but there, the path is one dimensional.
However, here after the rolling ball goes off of the edge with a certain angular velocity, is the object's angular velocity constant? I think it is constant as  no net torque is being produced.
So is it correct to say that a rolling ball and non rolling ball will reach the ground at the same time when pushed off a table at the same time?

A: Let's call the falling direction $z$ ($-z$ to be exact).
The rotation of the ball causes a (small) force perpenticular to the moving direction (so some combination of the $x$ and $y$ direction), due to the difference speed of the air flow to the sides of the ball Magnus effect. As soon as the ball gets velocity components in $x$ or $y$ direction, the force from the Magnus effect gets a small (positive) $z$ component, which hence lowers the gravitational force and the acceleration in $-z$ direction.
So no, they would not reach the ground at the same time. The difference depends on the angular velocity of course and will be small, though.


text:
Q: How to unset the element from an array of objects I have an array of operating systems ($os2) and i would like to remove all elements from array $phones , which dont have one of these operating systems. So i did this, but for some reason it's not working...
$os2 = array("BlackBerry", "Android");
if(count($os2)!=0)
{
    for($i = 0; $i<count($phones); $i++)
    {
        if(!in_array($phones[$i]->os, $os2))
        {
            unset($phones[$i]);
        }
    }
}

This is one element from the phones array:
[0] => Equipment Object
        (
            [carrierDescription:Equipment:private] => T-Mobile
            [carrierId:Equipment:private] => 59
            [manufacturerID:Equipment:private] => 13
            [manufacturerName:Equipment:private] => BlackBerry
            [manufacturerCode:Equipment:private] => Curve 9360
            [productId:Equipment:private] => 60558
            [currentEquipmentID:Equipment:private] => 29305
            [equipmentName:Equipment:private] => BlackBerry Curve 9360 Black
            [equipmentType:Equipment:private] => Smartphone
            [equipmentShortDescription:Equipment:private] =>
            [equipmentLongDescription:Equipment:private] => The BlackBerry Curve 9360 for T-Mobile is the next Curve in BlackBerry's line of smartphones. Running the latest BlackBerry 7 operating system and utilizing the powerful BlackBerry 7 Webkit-browser, the BlackBerry Curve 9360 provides an intuitive smartphone experience, perfect for those who depend on their smartphone to keep their personal and work lives organized. Encased in a sleek package, including a wide 2.4 inch screen, full QWERTY keyboard and navigation track-pad, the BlackBerry Curve 9360 is ideal for efficient mobile communication. This new smartphone is also equipped with essential smartphone features such as a 5 megapixel camera with flash, video recorder, and WiFi connectivity for voice and data for a premium smartphone experience, The new Curve 9360 delivers the world's best mobile communications and social experiences with the latest release of BlackBerry Messenger, or BBM.
            [sugRetailPrice:Equipment:private] => 400
            [displayPrice:Equipment:private] => $999.99
            [equipmentPrice:Equipment:private] => 0
            [numericCost:Equipment:private] => 0
            [rebateAmount:Equipment:private] => $0.00
            [priceAfterRebate:Equipment:private] => Free
            [rebateDescription:Equipment:private] => Free Gift
            [equipmentImageFileSmall:Equipment:private] => images/phones/60558_s.jpg
            [equipmentImageFileMedium:Equipment:private] => images/phones/60558_m.jpg
            [equipmentImageFileLarge:Equipment:private] => images/phones/60558_l.jpg
            [manufacturerLogo:Equipment:private] => _images/logos/manufacturers/selected_manu_blackberry.gif
            [purchaseMode:Equipment:private] => Add a Line
            [productLink:Equipment:private] => r.aspx?p=BlackBerry%20Curve%209360%20Black&c=T-Mobile&r=wowphonefinder&mode=1&s=1
            [upc:Equipment:private] => 610214626622
            [compatibleAccessoriesPageURL:Equipment:private] => DeviceSpecificAccessories.aspx?referringdomain=wowphonefinder&refcode1=standarddatafeed&refcode2=&productid=60558
            [mods:Equipment:private] =>
            [os:Equipment:private] => BlackBerry
            [tethering:Equipment:private] =>
            [hotspot:Equipment:private] =>
            [html:Equipment:private] => HTML
            [triG:Equipment:private] => 3G
            [fourG:Equipment:private] =>
            [fiveMP:Equipment:private] =>
            [bluetooth:Equipment:private] => bluetooth
            [camera:Equipment:private] => camera
            [mail:Equipment:private] => mail
            [gps:Equipment:private] => gps
            [international:Equipment:private] => international
            [mp3:Equipment:private] => MP3
            [vcast:Equipment:private] =>
            [wifi:Equipment:private] => wifi
            [tscreen:Equipment:private] =>
            [appstore:Equipment:private] => appstore
            [fcamera:Equipment:private] =>
            [ptt:Equipment:private] =>
            [rugged:Equipment:private] =>
            [sbluetooth:Equipment:private] =>
            [qwerty:Equipment:private] => qwerty
            [nocolor:Equipment:private] => Curve 9360
            [colors:Equipment:private] => Black Black
            [hasShort:Equipment:private] =>
            [hasReview:Equipment:private] =>
            [hasAlternative:Equipment:private] =>
            [hasAlternativeExpert:Equipment:private] =>
            [order:Equipment:private] =>
            [review:Equipment:private] =>
            [id] => 260
        )

Btw...its working this way, but i will be really happy if someone have the solution without using the another variable, just with unset method...
if(count($os2)!=0)
{
    $ph = array();
    foreach($phones as $phone)
    {
        foreach($os2 as $o)
        {
            if($phone->os == $o)
            {array_push($ph,$phone);}
        }
    }
    $phones = $ph;
}

Does anybody see what am I doing wrong? :)
Thanks for your answers...

A: This: $os2 = ("BlackBerry", "Android"); is NOT an array.
I am not even sure what it is. PHP will probably throw errors and warnings at you about it if you had them on.
An array in php is formed like this:
$os2 = array("BlackBerry", "Android");

A: $os2 = ("BlackBerry", "Android");

is a syntax error. It should be:
$os2 = array("BlackBerry", "Android");

To unset a particular array element by its value:
if (($key = array_search('Android', $os2, TRUE)) !== FALSE) {
    unset($os2[$key]);
}

A: If you look at the line:
[os:Equipment:private] => BlackBerry

You see that os is a private variable, so you can't get it by using $object->os, you will need to use it's getter.


text:
Q: Issue to get height of a div with jquery I got some trouble to get the height of a div with jquery.
I create the div in the html and affect some text to it when I click a button. After that I want to get the height of that div to vertically align it in the parent div, But the Height() function of jquery return 0 to me.
In the debug console of google chrome I see the height of the div then I point at it, but the height is still not returning the value.
JS FIDDLE DEMO
Here is my result on JS FIDDLE

I got google chrome Version 35.0.1916.114 m

A: The height of the div#lblMsgBoxMessage is 0 because when you try to use :
$("#lblMsgBoxMessage").height()

the div element is hided.
You can try by clicking on the div#click again, and then the height is available because the element was already displayed.
You have to set the height after the :
$("#msgBox").show();

like this : fiddle

A: Elements with display: none (including children of elements with display: none) have no height.  You need to show the element first in order to get its height.
If you move this line:
// display height of the message in the button
$("#click").text($("#lblMsgBoxMessage").height());

Underneath this line:
// display
$("#msgBox").show();

You'll be able to see the height.  JSFiddle: http://jsfiddle.net/FcJgz/416/


text:
Q: Neo4j native api data not picked by Spring Data Repos I've got some data that has been pumped into a neo4j instance using the native api. The same instance is used by an app backed by Spring data graph. The repositories fail to find the data. I'm assuming that this is an issue due to indexes and/or missing properties.
When the data is pumped in the following properties are set:
node.setProperty("__type__", "com.x.x.Class");

Index is set as follows:
Index<Node> typeIndex = indexManager.forNodes("__types__");
typeIndex.add(node, "className", "com.x.x.Class");

Any clues/help is appreciated.

A: imamc,
I'd appreciate it if you posted a simple test that reproduces the problem, preferably to https://groups.google.com/forum/?fromgroups#!forum/neo4j
But off hand, what you said makes sense, I do not have any other tips. But if we get some code/ test to work on, we might be able to help.
Lasse


text:
Q: Convergence of Newton method I have showed using Taylor's theorem that the error after n iterations $e_n$ satisfies $e_{n+1}=Ce_n^2.$
I am now asked to show that to guarantee an error of less than $10^{-M}$ we need approximately $\log_{10}(M) $ iterations.
How would I go about showing this?

A: $|Ce_{k+1}|\le|Ce_k|^2$ implies $$10^M\sim|Ce_n|\le|Ce_0|^{2^n}$$ which will give with twice applying the logarithm give an a-priori estimate of the step number.


text:
Q: 'invalid key error' recaptcha, is my views.py wrong? Below I have a signup form. I get no errors in python shell, I have tried to do this with the def signup(request) part but I get 'request' not defined. My keys are correct, I have checked. This makes sense to me, but I am confused as to how to pass this 'request' on correctly in views.py
class SignUp(generic.CreateView):
    form_class = forms.UserCreateForm
    success_url = reverse_lazy('login')
    template_name = 'signup.html'

    def signup(request):
        recaptcha_response = request.POST.get('g-recaptcha-response')
        data = {
            'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
            'response': recaptcha_response
        }

        r = requests.post('https://www.google.com/recaptcha/api/siteverify', data = data)
        result = r.json()

        if result['success']:
            form.save()
            messages.success(request, 'Success')

        else:
            messages.error(request, 'Invalid reCAPTCHA. Please try again.')

A: Try with session() and json.loads():
class SignUp(generic.CreateView):
    form_class = forms.UserCreateForm
    success_url = reverse_lazy('login')
    template_name = 'signup.html'

    def signup(request):
        recaptcha_response = request.POST.get('g-recaptcha-response')
        data = {
            'secret': settings.GOOGLE_RECAPTCHA_SECRET_KEY,
            'response': recaptcha_response
        }

        s = requests.session()

        r = s.post('https://www.google.com/recaptcha/api/siteverify',
                           data = data)
        result = json.loads(r.text)

        if result['success']:
            form.save()
            messages.success(request, 'Success')

        else:
            messages.error(request, 'Invalid reCAPTCHA. Please try again.')


text:
Q: PHP 7 error con un array de semana no es posible crear un array $dia en que vaya guardando los dias de la semanas tal que asi :
$dia[] = "Lunes";
$dia[] = "Martes";
$dia[] = "Miercoles";
$dia[] = "Jueves";
$dia[] = "Viernes";

Y luego cuando quiera acceder a una determinada posicion simplemente poner un indice dentro de los corchetes []  por ejemeplo asi:
esto : $dia[2] deberia ser Miercoles.
¿Por que no funciona?
Mi LOG ERROR (son dos errores) :
Fatal error: Uncaught Error: [] operator not supported for

Error: [] operator not supported for strings

A: Si puedes hacer eso, solo asegurate de inicializar el array:
$dia   =  array(); // inicilizar array

$dia[] = "Lunes";
$dia[] = "Martes";
$dia[] = "Miercoles";
$dia[] = "Jueves";
$dia[] = "Viernes";

A: Todavía están ocurriendo cambios dentro de las mismas sub-versiones de PHP 7. Lo que ocurre aquí es un claro ejemplo de ello.
Tu código funciona en PHP 7.0, pero a partir de PHP 7.1 terminará en un error.
En el Manual de PHP, y en las notas de contribución del mismo se expone un caso parecido parecido, sólo que en el código se usa una asignación por referencia. Esto funcionaba en PHP 7.0, pero no en PHP 7.1+. Ver también aquí una comparación sobre el resultado según diferentes versiones de PHP.
Aquí se expone otro ejemplo, donde este código funciona en PHP 7.0:
<?php
    $a = "";
    $a[] = "hello world";
    var_dump($a);
?>

Pero en PHP 7.1+ arroja un error fatal.
O esto, que funciona diferente entre PHP 7.0 y PHP 7.1:
<?php
    $a = "";
    $a[0] = "hello world";
    var_dump($a);
    // 7.1: string(1) "h"
    // pre-7.1: array(1) {  [0]=>  string(11) "hello world" }
    //-------------------------------------------------------
    $a = "";
    $a[5] = "hello world";
    var_dump($a);
    // 7.1: string(6) "     h"
    // pre-7.1: array(1) {  [0]=>  string(11) "hello world" }
?>

¿Por qué motivo? Porque $a se declaró como una cadena y luego intentó usarse como un array.

Conclusión
La tendencia es que PHP se haga cada vez más restrictivo (ver aquí diferencias entre versiones y sub-versiones de PHP). Durante mucho tiempo PHP con su permisividad nos acostumbró a ciertas malas prácticas que son impensables en otros lenguajes (como el caso de $a de más arriba).
No hay que alarmarse, sino ponerse manos a la obra desde ya, adoptado buenas prácticas como la de no usar una variable sin antes declararla, o no cambiar arbitrariamente entre tipos de variables.
Para obligarnos a ello, entre sus nuevas características más relevantes PHP 7 tiene un modo estricto, que sería bueno activar en todos nuestros programas que escribamos en la versión 7. Es una sola línea, debe ser la primera, al principio del script:
declare(strict_types=1);


text:
Q: Class does not have the property in JSP If my JSP is :
<c:forEach items="${listTable1}" var="row">
    ${row['class'].getField('id') }

</c:forEach>

I get this:
public java.lang.Long org.sdbrother.model.Table1.id
public java.lang.Long org.sdbrother.model.Table1.id
public java.lang.Long org.sdbrother.model.Table1.id
public java.lang.Long org.sdbrother.model.Table1.id
public java.lang.Long org.sdbrother.model.Table1.id
...
public java.lang.Long org.sdbrother.model.Table1.id

The object of class org.sdbrother.model.Table1 has the field id and id is a public field of the Table1 class.
But if my JSP is:
<c:forEach items="${listTable1}" var="row">
    ${row.id}

</c:forEach>

I get the following exception:
org.apache.jasper.JasperException: javax.el.PropertyNotFoundException: The class 'org.sdbrother.model.Table1' does not have the property 'id'.

Thanks!


text:
Q: JS — Trying to return AJAX data I've been struggling with getting the data out of an AJAX call using jQuery.  I'm using RequireJS so my JavaScript can be more maintainable/modular.  I've only been using RequireJS for a few days, so I may or may not be doing this right.  Just looking for a way to keep my JS modular and clean.
Here is what I have so far.  I know for a fact that it's getting the correct data because if I console.log(data[Math.floor(Math.random()*data.length)]), the data is there.  The JSON file is long so I won't show you that, just take my word for it — it works.
var maze;
define(["jquery"], function($){
    $.ajax("js/mazes.json", {
        dataType: "json",
        type: "get",
        success: function(data){
            var maze = data[Math.floor(Math.random()*data.length)];
        }
    });
    return {
        randomMaze: maze
    };
});

I also tried this (declaring maze within anonymous function)
define(["jquery"], function($){
    var maze;
    $.ajax("js/mazes.json", {
        dataType: "json",
        type: "get",
        success: function(data){
            var maze = data[Math.floor(Math.random()*data.length)];
        }
    });
    return {
        randomMaze: maze
    };
});

I don't know what I'm doing wrong.  Just trying to return data[Math.floor(Math.random()*data.length)]

A: jQuery.ajax() success returns results asynchronously , maze may not be defined when called synchronously outside of success at
return {
        randomMaze: maze
    };

Try returning jQuery promise object $.ajax() from function , returning object within asynchronous success callback
 // return jQuery promise object
 return $.ajax("js/mazes.json", {
        dataType: "json",
        type: "get",
        success: function(data){
            // return object as jQuery promise value
            return {
                     randomMaze: data[Math.floor(Math.random()*data.length)];
            }
        }
    });

See also How do I return the response from an asynchronous call?


text:
Q: Best practice for build / deployment of docker images I've just finished the basic pipeline for my angular application, which runs in a Node image in docker. So, the process works as follows: push to Gitlab > Hook to Jenkins Build > Deployment script to docker build image and push to Quay > Publish script to prompt Rancher service to upgrade the container and refresh the image > Complete.
Now, the problem I have is that the base node image is quite large, meaning when I am pushing a simple change, it takes a long while to complete the build pipeline (~8 minutes). This seems unreasonable for every tiny change, and the push to Quay and subsequent publish to the Rancher platform means I'm moving around 250mb up to quay and 250mb to Rancher.
I have several "micro-services" planned for deployment, but if each time I want to deploy one to a development environment and move that much data around each time, it seems somewhat counter productive... Is what I am doing wrong, what am I missing, and is there any guidelines for best practice when building/deploying/hosting container based services?

A: First some info on images, builds, registries and clients.
Images and Layers
Docker image builds work with layers. Each step in your Dockerfile commits a layer that is overlaid on top of the previous.
FROM node                   ---- a6b9ffdcf522
RUN apt-get update -y        --- 72886b467bd2
RUN git clone whatever        -- 430615b3487a
RUN npm install                - 4f8ddac8d3b5 mynode:latest

Each layer that makes up an image is individually identified by a sha256 checksum. The IMAGE ID in docker images -a is a short snippet of that.
Running dockviz images -t on a build host will give you a better idea of the tree of layers that can build up. While a build is running you can see a branch grow, and then the final layer is eventually tagged but that layer stays in the tree and maintains a link to it's parents.
Build Caching
Docker builds are cached by default at each build step. If the RUN command in the docker file hasn't changed or COPY source files your are copying haven't changed then that build step should not need to run again. The layer stays the same, as does the sha256 checksum ID and docker attempts to build the next layer.
When docker gets to a step that does need to be rebuilt, the image "tree" that dockviz presents will branch off to create the new layer with a new checksum. Any steps after this then need to run again and create a layer on the new branch.
Registries
Registries understand this layering too. If you only change the top most layer in your newly tagged image, that's the only layer that should need to be uploaded to the registry (There are caveats to this, it works best with a recent docker-1.10.1+ and registry 2.3+) The registry will already have a copy of most of the image id's that make up your new "image" and only new layers will need to be sent.
Clients
Docker registry clients deal with layers in the same way. When pulling an image it actually downloads the individual layers (blobs) that make up the image. You can see this from the list of image ids printed when you docker pull or docker run a new image. Again, if most of the layers are the same then the update will only need download those top most layers that have changed saving precious time.
Minimising build time
So the things you want to focus on are

*

*Keep the image sizes small

*Take advantage of build caching

*Make use of common "tagged" parent images.

Keep the image sizes small
The main way to save time is to not have anything to do in the first place.
The less data in an image the better.
If you can avoid using a full OS, do it. When you can run apps on the busybox or alpine image, it makes the Docker gods smile. alpine + a node.js build is less than 50MB. Go binaries are a great example of minimising size too. They can be statically compiled, and have no dependencies so can even be run on the blank scratch image.
Take advantage of Dockers build caching
It's important to have your most frequently changing artefacts (most likely your code) as a late entry in your Dockerfile. The build will slow down if the build has to update the complete 50MB of data for one little file change that invalidates the cache for a build step.
There will always be some changes that invalidate the entire cache (like updating the base node image). These you just have to live with once in a while.
Anything else in the build that infrequently updates, should go to the top of the Dockerfile.
Make use of common "tagged" parent images
Although image checksumming has been somewhat fixed from Docker 1.10 onwards, using a common parent image guarantees that you will be starting from the same shared image ID where ever you use that image with FROM.
Previous to Docker 1.10, Image ID's were just a random uuid. If you had builds running on multiple hosts, layers could all be invalidated and replaced depending on which host built them. Even if the layers were in fact the same thing.
Common parent images also help when you have multiple services and multiple Dockerfiles that are largely the same.  Whenever you start repeating build steps in multiple Dockerfiles, pull those steps out into a common parent image so layers are definitely shared between all your services.  You are essentially getting this already by using the node image as your base.
Node.js tricks
If you are running an npm install after your code deploy every build and you have a number of dependencies, the npm install causes a lot of repeated work that doesn't actually change much each build. It could be worthwhile to have a workflow to build your node_modules prior to code changes. Then the npm install only needs to run you when package.json is updated
FROM node
WORKDIR /app
COPY package.json /app/package.json
RUN npm install && rm -rf ~/.npm
COPY . /app/
CMD [ "node", "/app/server.js" ]

Staged build
If you rely on npm packages with native modules, you will sometimes need to install a complete build chain in the container to run the npm install. Staged builds can now easily separate the build image from the run image.
FROM node:8 AS build
WORKDIR /build
RUN apt-get update \
 && apt-get install build-essential;
COPY package.json /build/package.json
RUN npm install; \
 && rm -rf ~/.npm;

# Stage 2 app image
FROM node:8-slim
WORKDIR /app
COPY --from=build /build/node_modules /app/node_modules
COPY . /app/
CMD [ "node", "/app/server.js" ]

Other things
Make sure your build host has ssd's and a good internet connection, because there will be times you have to do a full rebuild so the quicker it is, the better. AWS usually works well because the packages and images you are pulling and pushing are probably hosted on AWS as well. AWS also provide a image registry services (ECR) for only the cost of storage.


text:
Q: Defining the range in nested loops I am a beginner in python and I am trying to better my understanding of nested loops so that I can make star patterns. However while experimenting I came across something that completely confused me.
Here to print out 1-3 exacty 3 times using the inner loop of a nested loop works completely fine.
'''
for outer in range(1,4):
    for inner in range(1,4):
        print(f"O: {outer}, I {inner}")

OUTPUT
O: 1, I 1
O: 1, I 2
O: 1, I 3
O: 2, I 1
O: 2, I 2
O: 2, I 3
O: 3, I 1
O: 3, I 2
O: 3, I 3

However if I want to accomplish the same thing but this time I make the range of the inner loop the range of the outer loop, then i get this:
for outer in range(1, 4):
        for inner in range(1, outer+1):
            print(f"O: {outer}, I: {inner}")

O: 1, I: 1
O: 2, I: 1
O: 2, I: 2
O: 3, I: 1
O: 3, I: 2
O: 3, I: 3

Does anyone know why? Thank you.

A: You are attempting to use the enumerator in this process.
When you define your for loop as:
for outer in range(x, x):

outer is the enumerated value, not the explicit range you have predefined.
I would suggest using a separate integer value (or equivalent) for this operation.
For example
int upperRange = 4
for outer in range(1, upperRange ):
    for inner in range(1, upperRange +1):
        print(f"O: {outer}, I: {inner}")

i hope this helps!

A: outer changes on each iteration. You likely want to define a variable or use a function argument to use the same bounds for both ranges.
def test(n):
  for outer in range(1, n):
    for inner in range(1, n):
      print(f"O: {outer}, I: {inner}")


text:
Q: OpenCV Distance transform is not working as it supposed to I am trying to use OpenCV to divide an image with resolution 2048x2048 into smaller images for some *pixels with resolution 90x90 around that pixel. Later on those smaller images I want to use foveation. I followed this example on foveation an image, but instead python I am using C++.
Image foveation in Python
       Mat mask = Mat::ones(Size(90,90), CV_8UC1) * 255;
       circle(mask, CvPoint(45,45), 30, 0, -1);

       Mat out; // = Mat::ones(Size(90,90), CV_32FC1) * 0;
       distanceTransform(mask, out, CV_DIST_L2, CV_DIST_MASK_PRECISE);

       int scale_factor = 10;
       Mat filtered = outputImage.clone();
       Mat img_float;
       filtered.convertTo(img_float,CV_32F,1,0);

       for(int k = 0; k < 90; k++){  // y
            for(int l = 0; l < 90; l++){  // x
                if(out.at<float>(k,l) == 0.0) continue;

                float mask_val = ceil(out.at<float>(k,l)/scale_factor);
                if(mask_val <= 3) mask_val = 3;

                int beginx = l - int(mask_val/2);
                if (beginx < 0)
                    beginx = 0;

                int beginy = k - int(mask_val/2);
                if (beginy < 0)
                    beginy = 0;

                int endx = l+int(mask_val/2);
                if (endx >= 90)
                    endx = 90-1;

                int endy = k+int(mask_val/2);
                if (endy >= 90)
                    endy = 90-1;

                int num = 0;
                float total = 0;
                for (int a = beginx; a < endx; a++){
                    for(int b = beginy; b < endy; b++){
                        num ++;
                        total += img_float.at<float>(a,b);
                    }
                }

                filtered.at<float>(k,l) = (total/num);
            }
       }

       namedWindow( "Display window", WINDOW_AUTOSIZE );
       imshow( "Display window", filtered );
       waitKey(0);
       imwrite( ss.str(), filtered, compression_params );

In another question here I read that instead of using 3 or 5 as a parameter in distanceTransform I should use CV_DIST_MASK_PRECISE.
The problem is that my Mat out is sometimes black, and sometimes white with a circle but it can not be saved or used in the code.
Here are the results:

But when I use the python script I don't have a problem:

Specifications:

*

*OS: Ubuntu 14.04

*CPU: i7-2600 3.50GHz

*RAM: 8GB

OpenCV ver. 3.0.0
*I said for some pixel, ~ 3 millions pixels.
EDIT
Here is the rest of the code. This part in the question goes right before saving the cropped image.
http://pastebin.com/49rLhDcF
Mat outputImage = temp( Rect(lx, ty, abs(rx - lx), abs(by-ty)));
ps: Because there a lot of pixel, after generating large amount of images I get Segmentation fault (core dumped). I know this has to do with the memory and I am trying it to fix it, but I like to hear also your opinion.

A: Problem solved,
I just add this lines.
I used Gaussian Blur to smooth the whole picture, and then I copied the value of the original pixel to preform the effect I want.
 for(int j = 0; j <  pixels_gray.size(); j++) {
               int x = pixels_gray[j].x;
               int y = pixels_gray[j].y;
               int lx = pixels_gray[j].lx;
               int rx = pixels_gray[j].rx;
               int ty = pixels_gray[j].ty;
               int by = pixels_gray[j].by;

               Mat outputImage = image_original( Rect(lx, ty, abs(rx - lx), abs(by-ty)));

               Mat mask = Mat::ones(Size(90,90), CV_8UC1) * 255;
               CvPoint      c = cvPoint(45, 45);
               circle(mask, c, 30, 0, -1);

               Mat smooth;

               for (int i=1; i<11; i=i+2){
                    GaussianBlur( outputImage, smooth, Size( i, i ), 0, 0 );
                }

                for(int my = 0; my < 90; my++){
                    for(int mx = 0; mx <90; mx++){
                        Scalar colour = mask.at<uchar>(Point(mx, my));
                        if(colour.val[0]==255) continue;
                        smooth.at<Vec3b>(my,mx)[0] = outputImage.at<Vec3b>(my,mx)[0];
                        smooth.at<Vec3b>(my,mx)[1] = outputImage.at<Vec3b>(my,mx)[1];
                        smooth.at<Vec3b>(my,mx)[2] = outputImage.at<Vec3b>(my,mx)[2];
                    }
                }

               stringstream ss;
               ss << dir << "gray_" << y << "_" << x << ".png";
               imwrite( ss.str(), smooth, compression_params );

           }


text:
Q: Keeping a constant window size with WM WINDOWS in tcl Morning all,
I have a tcl/tk application and for the windows size I have the following code:
wm title . "Relay Switch Application"
wm attributes . -alpha "1"
wm geometry . 1600x500+100+100

Within the window, there is 3 labelframes positioned at:

x1: 10
  x2: 200
  x3: 320

On my PC, each labelframe are side by side with about 20 pixel gaps between them.
On my work laptop, the second labelframe is over lapping the first.
How do I change or add to my code so the windows contents are postioned correctly for whatever screen resolution?
Thank you in advance.

A: It's a fact of GUIs that absolute positioning of windows (either within a main window with place or of the top level with wm geometry) is usually a bad idea. This is because of little things like screen pixel densities varying or font widths changing and so on, but it's just something that you have to put up with. Instead, you should write your application to use Tk's other geometry managers, as those adapt to the size of the content and the amount of overall screen space that the OS and user conspire to give you.
For example, here's how to put three labelframes side-by-side with pack:
# Make some labelframes
labelframe .x1 -text "This is X1"
labelframe .x2 -text "This is X2"
labelframe .x3 -text "This is X3"

# Lay them out
pack .x1 .x2 .x3 -side left -fill both -expand yes
# You might want to experiment with the -padx and -pady options

If you need complex placement rules, such as stacking in several directions or making one window a size that is a multiple of the size of another, you'll probably use grid, which is a geometry manager that is sophisticated enough to handle almost all layouts you can conceive of in normal GUIs. It'd be fairly simple for this case:
# Put the labelframes in the grid…
grid .x1 .x2 .x3 -sticky nsew

# … and define how the system expands
grid columnconfigure {0 1 2} -weight 1
grid rowconfigure 0 -weight 1