text:
Q: SearchDelegate does not call buildResults method I have a list view and an Appbar. The Appbar has a search icon on which I am calling the SearchDelegate. Following is my code for SearchDelegate
class StudentSearch extends SearchDelegate<StudentModel> {
  final Observable<StudentModel> studentModelDataList;

  StudentSearch(this.studentModelDataList);

  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(
          icon: Icon(Icons.clear),
          onPressed: () {
            query = "";
          }),
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
        icon: Icon(Icons.arrow_back),
        onPressed: () {
          close(context, null);
        });
  }

  @override
  Widget buildResults(BuildContext context) {
    return Text(query);
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    return StreamBuilder(
        stream: studentModelDataList,
        builder: (context, AsyncSnapshot<StudentModel> snapshot) {
          if (!snapshot.hasData || snapshot.data == null) {
            return Center(
              child: CircularProgressIndicator(),
            );
          }

          final results = snapshot.data.studentModelData.studentData
              .where((a) => a.studName.toLowerCase().contains(query.toLowerCase()))
              .toList();

          if (snapshot.data != null) {
            return Refresh(
              year_id: "2",
              schoolId: "1",
              lastIndex: "0",
              disciplineId: "1",
              child: ListView.builder(
                itemBuilder: (context, int index) {
                  return ListTile(
                    onTap: (){
                      print(snapshot.data.studentModelData.studentData[index].studName);
query = snapshot.data.studentModelData.studentData[index].studName;
                          close(context, snapshot.data);

                    },
                    title: Text(results[index].studName),
                    subtitle: Text('${results[index].studentEmail} '),
                    trailing: Column(
                      children: [
                        Icon(Icons.comment),
                        Text('${results[index].classCode}'),
                      ],
                    ),
                  );
                },
                itemCount: results.length,
              ),
            );
          }
        });
  }
}

What I understand from the documentation is that whenever I enter an item to be searched, the SearchDelegate first shows buildSuggestions and then  buildResults. So I am trying to search by a student name and the buildSuggestions method works properly but when I click on an item of buildSuggestions, it does not show me buildresults

A: BuildSuggestions is meant to do just that, build a list of suggestions to whatever is typed in the search bar. The listener responds to each and every change to the Text Field state. This could be used to provide autocomplete suggestions to the user.
BuildResults is called when the user calls for the results by clicking on the "magnifying glass" button on the keyboard, or whatever is used to "submit" the results indicating that the user has finished their typing and is requesting the results of the text search.
You can see an explanation here Flutter's Search Support (The Boring Flutter Development Show, Ep. 10)
Taken from the documentation for  buildResults(BuildContext context) → Widget "The results shown after the user submits a search from the search page."

A: Try Calling the buildResults function at the ontap() session in your ListTile widget. Also call the data you want displayed by the BuildResults inside it like this
     @override
     Widget buildResults(BuildContext context,["Data you want displayed when you click
     search"]) {
     return Text(query);
      }

And in the suggestion area like this
 onTap: () =>

                         Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => Scaffold(
                                    appBar: AppBar(
                                        backgroundColor:
                                            Colors.blueGrey[900],
                                        title: new Text(
                                          "Country",
                                          style: TextStyle(
                                              color: Colors.white),
                                        )),
                                    body: buildResults(context)),
                              )),

Ofcourse this is just for an Example however you want to call the buildResults "lies in your court". This is how it works, The buildResult(context) takes the context in this case the data you are using from "final results" whether in "BuildResults(BuildContext, context)" and displays as called or used in-code like this
final results = snapshot.data.length;
            results = filteredUsers
                 .where((a) => (a.region.contains(query))
                      || a.region.contains(query)
                     )
                 .toList();

return ListView.builder(
                        itemCount: results.length,
                         itemBuilder: (context, index) => Column(
                           crossAxisAlignment: CrossAxisAlignment.center,
                           mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                           mainAxisSize: MainAxisSize.max,
                           children: <Widget>[
              //As used in-code
                          Text(${results[index].region})
                             ]))

So in my case "Data you want displayed when you click
search"=[Results] represented like this
 @override
  Widget buildResults(BuildContext context, [results]) {
//How you want your BuildResult page to look like
}

A: You can also use this code to call buildResult
onTap: () {
       showResults(context);
}


text:
Q: Accessing bound context in user controls code behind Question is much like this question- just didn't pan out for me
So how do I access a Property on a WPF usercontrol bound via Parent's Xaml in, from the Controls Code behind?
PS: Other controls bound to Properties of the TowerBase model passed in are binding. ( I just can't access the model passed in in the code behind ).
UserControl: x and y are null and I can't figure out why
public partial class TowerControl : UserControl
{
    public TowerBase model = new TowerBase(); //Trying to set this model

    public TowerControl()
    {
        InitializeComponent();
        var x = ((TowerBase)this.DataContext); //Or Extract from binding
        var y = model;
    }
    ...

From the parent's xaml:
    ...
    <controls:TowerControl Grid.Row="1" Grid.Column="0" x:Name="Tower" DataContext="{Binding Tower}" />
    ...

Parent Model:
    ...
    public TowerBase Tower { get; set; }
    ...

A: That is because UserControl's DataContext would not be set by the time it is in constructor. Listen to Loaded event of user control and in handler you will get the DataContext
<UserControl Loaded="UserControl_Loaded">

private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
    var x = this.DataContext;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mysql not being updated Im trying to update a database using php.
The site im working on , i have a local copy and a copy on a server.
It works locally , but on the server it shows that it worked , but does not update the database.
I have checked that the id and data variables do actually have a value and teh connection is working.
This is my code :
<?php
include("../../config/connect.php");
if($_GET['id'] and $_GET['data'])
{
    $id = $_GET['id'];
$data = $_GET['data'];
$key = $_GET['key'];

    echo $id;
     echo "
";
    echo $data;
    echo "
";
    echo $key;
    echo "
";

if(mysqli_query($connection, "update userbadges set level='$data' where id='$id'"));
    echo 'success';
}
?>

Edit Connect.php
<?php
$connection = mysqli_connect('localhost', 'myusername', 'mypassword', 'leaderboard');
?>

A: You need to be checking everything to do with the mysqli_ calls
connect.php
<?php
    $connection = mysqli_connect('localhost', 'myusername',
                                 'mypassword', 'leaderboard');
    if (!$connection) {
        die('Connect Error (' . mysqli_connect_errno() . ') '
        . mysqli_connect_error());
}

Your code:
<?php
   include("../../config/connect.php");
   if( isset($_GET['id'], $_GET['data'], $_GET['key']) ) {
     $data = $_GET['data'];
     $id   = $_GET['id'];
     $key  = $_GET['key'];

     echo $id;
     echo "
";
     echo $data;
     echo "
";
     echo $key;
     echo "
";

     $result = mysqli_query($connection,
                            "update userbadges set level='$data' where id='$id'");
     if(! $result) {
         echo mysqli_error($connections);
         exit;
     }
     echo 'database update ' . mysqli_affected_rows($connection) . ' rows';
  } else {

     echo 'One of the required params is missing';
     if ( $_GET ) {
         print_r($_GET);
     }
?>

Now if there is a problem like you forgot to change the mysql connection userid and password, or your hosting company use a seperate database server so localhost is not right, you will be told about the error.


text:
Q: Can the Windows 7 Bootloader detect Windows 8? I currently have Windows 8 installed and want to install Windows 7 (better'd be Windows XP). But I know that the Windows 7 Bootmanager will replace the Windows 8 Bootmanager, and I´m not sure if the Windows 7 Bootmanager will view Windows 8 as a boot option.
Reinstalling Windows 8 is NOT AN OPTION.

A: Windows adds OSs to the boot loader by reading the MBR on each disk. It does not distinguish newer or older versions. Nor does it have a list of known OSs to look for. You can install in any order. Although it is recommended to install Linux disros last. I was dual booting Windows 7 and Windows 8 with the Windows 7 boot loader and had no problems whatsoever. I eventually got rid of it because I found myself on Windows 8 more often because of new features I like in the core of it. Hate the Metro UI though.
Also if you find that the boot loader does not list a specific OS you can add it to the list manually. Or you can load up Windows 8 and get that boot loader to be the main one again, see here.

A: The answer is: Yes, the Windows 7 Bootloader can detect the Windows 8 installation already on the Computer. I installed Windows 7 and at the first bootup the bootloader offered me to boot Windows 8.


text:
Q: Unschedule update method in cocos2d-x I want to unschedule update method after 5 minutes of game start.
I scheduled my update method in constructor of my class.
scheduleUpdate();

I am trying to unschedule my selector by calling stop update method. But it's not unscheduling.
runAction(Sequence::createWithTwoActions(
        DelayTime::create(5.0f),
        CallFuncN::create(this, callfuncN_selector(GameScene::stopupdate))));

Stopupdate method :-

    unscheduleUpdate();

A: Firstly, DelayTime::create(5.0f) will create delay of 5 secs. Not 5 minutes.
Have you check with some log or etc that code reaches stopUpdate method ?
CallFuncN is used when function accepts CCNode * param.
You should use CallFunc.
And i am guessing, that is this->unsheduleUpdate();
Also, if this all doesn't help,
use schedule() to custom schedule a function.
You can set this to frame rate and on repeat, so it works same as a scheduleUpdate.
unschedule() to unschedule it.


text:
Q: Click on EditText's drawable right with Espresso How could be possible to click on EditText's right drawable (check the screenshot)? I have tried several ways but I always get stuck.
public static Matcher<View> withEditTextDrawable(final int resourceId) {
    return new BoundedMatcher<View, EditText>(EditText.class) {
        @Override
        protected boolean matchesSafely(final EditText editText) {
            // ????

            return false;
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("with drawable from resource id: ");
            description.appendValue(resourceId);
        }
    };
}

A: I solved it using the Material Component TextInputLayout and TextInputEditText
In your xml:
 <com.google.android.material.textfield.TextInputLayout
            style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
            android:id="@+id/til_location"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:endIconMode="custom"
            app:endIconDrawable="@drawable/ic_edit_location"
            app:endIconTint="@color/colorAccent"
            app:hintEnabled="false"
            app:endIconContentDescription="open map icon">

            <com.google.android.material.textfield.TextInputEditText
                android:id="@+id/et_address"
                android:textColor="@color/colorAccent"
                android:layout_height="wrap_content"
                android:layout_width="match_parent"
                tools:text="3 streenasdasdasd"/>

        </com.google.android.material.textfield.TextInputLayout>

The trick here is to set the app:endIconMode="custom" then add your drawable as u want.
In java class:
you can use the setEndIconOnClickListener and do what you want as below:
tilLocation.setEndIconOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //do click
        }
    });

A: For people that have this problem right now as of 1/7/2021 (European format).
I had the same problem and solved it like this:
In your xml, maybe you have something like this:
<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/edittext_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/edittext_hint"
    app:endIconMode="clear_text"
    app:endIconCheckable="true"
    app:endIconTint="@color/colorSemiTranspBlack"
    app:endIconContentDescription="clear text">

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/eddittext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</com.google.android.material.textfield.TextInputLayout>

As you saw the above xml code, i added app:endIconContentDescription="clear text".
grab from the xml, app:endIconContentDescription="clear text" and add onView(withContentDescription("clear text")).perform(click()); in your Instrumented test method, in your test class, like:
    @Test
    public void testEdittext(){
    onView(withId(R.id.eddittext)).perform(typeText("Type something."));
    onView(withContentDescription("clear text")).perform(click());
    }

Forgot to say that this onView(withId(R.id.note_title)).perform(typeText("Type something.")); is the line that you must first write something in the edittext, so that the end icon(eddittext's right drawable) will show up and then click it.

A: Had to develop this custom action and matcher to test our discard drawables on the right of some text fields,

this will click any drawable (left, top, right, bottom) of a TextView in an Espresso test.
Usage:
onView(withId(id)).perform(clickDrawables());

Method:
public static ViewAction clickDrawables()
{
    return new ViewAction()
    {
        @Override
        public Matcher<View> getConstraints()//must be a textview with drawables to do perform
        {
            return allOf(isAssignableFrom(TextView.class), new BoundedMatcher<View, TextView>(TextView.class)
            {
                @Override
                protected boolean matchesSafely(final TextView tv)
                {
                    if(tv.requestFocusFromTouch())//get fpocus so drawables become visible
                        for(Drawable d : tv.getCompoundDrawables())//if the textview has drawables then return a match
                            if(d != null)
                                return true;

                    return false;
                }

                @Override
                public void describeTo(Description description)
                {
                    description.appendText("has drawable");
                }
            });
        }

        @Override
        public String getDescription()
        {
            return "click drawables";
        }

        @Override
        public void perform(final UiController uiController, final View view)
        {
            TextView tv = (TextView)view;
            if(tv != null && tv.requestFocusFromTouch())//get focus so drawables are visible
            {
                Drawable[] drawables = tv.getCompoundDrawables();

                Rect tvLocation = new Rect();
                tv.getHitRect(tvLocation);

                Point[] tvBounds = new Point[4];//find textview bound locations
                tvBounds[0] = new Point(tvLocation.left, tvLocation.centerY());
                tvBounds[1] = new Point(tvLocation.centerX(), tvLocation.top);
                tvBounds[2] = new Point(tvLocation.right, tvLocation.centerY());
                tvBounds[3] = new Point(tvLocation.centerX(), tvLocation.bottom);

                for(int location = 0; location < 4; location++)
                    if(drawables[location] != null)
                    {
                        Rect bounds = drawables[location].getBounds();
                        tvBounds[location].offset(bounds.width() / 2, bounds.height() / 2);//get drawable click location for left, top, right, bottom
                        if(tv.dispatchTouchEvent(MotionEvent.obtain(android.os.SystemClock.uptimeMillis(), android.os.SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, tvBounds[location].x, tvBounds[location].y, 0)))
                            tv.dispatchTouchEvent(MotionEvent.obtain(android.os.SystemClock.uptimeMillis(), android.os.SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, tvBounds[location].x, tvBounds[location].y, 0));
                    }
            }
        }
    };
}

This is a refinement I made to select a specific drawable to click:

Usage:
onView(withId(id)).perform(new ClickDrawableAction(ClickDrawableAction.Right));

Method:
public static class ClickDrawableAction implements ViewAction
{
    public static final int Left = 0;
    public static final int Top = 1;
    public static final int Right = 2;
    public static final int Bottom = 3;

    @Location
    private final int drawableLocation;

    public ClickDrawableAction(@Location int drawableLocation)
    {
        this.drawableLocation = drawableLocation;
    }

    @Override
    public Matcher<View> getConstraints()
    {
        return allOf(isAssignableFrom(TextView.class), new BoundedMatcher<View, TextView>(TextView.class)
        {
            @Override
            protected boolean matchesSafely(final TextView tv)
            {
                //get focus so drawables are visible and if the textview has a drawable in the position then return a match
                return tv.requestFocusFromTouch() && tv.getCompoundDrawables()[drawableLocation] != null;

            }

            @Override
            public void describeTo(Description description)
            {
                description.appendText("has drawable");
            }
        });
    }

    @Override
    public String getDescription()
    {
        return "click drawable ";
    }

    @Override
    public void perform(final UiController uiController, final View view)
    {
        TextView tv = (TextView)view;//we matched
        if(tv != null && tv.requestFocusFromTouch())//get focus so drawables are visible
        {
            //get the bounds of the drawable image
            Rect drawableBounds = tv.getCompoundDrawables()[drawableLocation].getBounds();

            //calculate the drawable click location for left, top, right, bottom
            final Point[] clickPoint = new Point[4];
            clickPoint[Left] = new Point(tv.getLeft() + (drawableBounds.width() / 2), (int)(tv.getPivotY() + (drawableBounds.height() / 2)));
            clickPoint[Top] = new Point((int)(tv.getPivotX() + (drawableBounds.width() / 2)), tv.getTop() + (drawableBounds.height() / 2));
            clickPoint[Right] = new Point(tv.getRight() + (drawableBounds.width() / 2), (int)(tv.getPivotY() + (drawableBounds.height() / 2)));
            clickPoint[Bottom] = new Point((int)(tv.getPivotX() + (drawableBounds.width() / 2)), tv.getBottom() + (drawableBounds.height() / 2));

            if(tv.dispatchTouchEvent(MotionEvent.obtain(android.os.SystemClock.uptimeMillis(), android.os.SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, clickPoint[drawableLocation].x, clickPoint[drawableLocation].y, 0)))
                tv.dispatchTouchEvent(MotionEvent.obtain(android.os.SystemClock.uptimeMillis(), android.os.SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, clickPoint[drawableLocation].x, clickPoint[drawableLocation].y, 0));
        }
    }

    @IntDef({ Left, Top, Right, Bottom })
    @Retention(RetentionPolicy.SOURCE)
    public @interface Location{}
}

A: Perfect answer from @dareniott .
I just made it in kotlin:
import android.graphics.Point
import android.support.annotation.IntDef
import android.support.test.espresso.UiController
import android.support.test.espresso.ViewAction
import android.support.test.espresso.matcher.BoundedMatcher
import android.support.test.espresso.matcher.ViewMatchers.isAssignableFrom
import android.view.MotionEvent
import android.view.View
import android.widget.TextView
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.Matchers.allOf

class ClickDrawableAction(@param:Location @field:Location private val drawableLocation: Int) : ViewAction {
    override fun getConstraints(): Matcher<View> {
        return allOf(isAssignableFrom(TextView::class.java), object : BoundedMatcher<View, TextView>(TextView::class.java) {
            override fun matchesSafely(tv: TextView): Boolean {
                return tv.requestFocusFromTouch() && tv.compoundDrawables[drawableLocation] != null
            }

            override fun describeTo(description: Description) {
                description.appendText(DESCRIPTION_HAS_DRAWABLE)
            }
        })
    }

    override fun getDescription(): String {
        return DESCRIPTION_CLICK_DRAWABLE
    }

    override fun perform(uiController: UiController, view: View) {
        val tv = view as TextView
        if (tv.requestFocusFromTouch())
        {
            val drawableBounds = tv.compoundDrawables[drawableLocation].bounds
            val clickPoint = arrayOfNulls<Point>(SIZE_CLICK_POINT)
            clickPoint[LEFT] = Point(tv.left + drawableBounds.width() / HALF_DIVISOR, (tv.pivotY + drawableBounds.height() / HALF_DIVISOR).toInt())
            clickPoint[TOP] = Point((tv.pivotX + drawableBounds.width() / HALF_DIVISOR).toInt(), tv.top + drawableBounds.height() / HALF_DIVISOR)
            clickPoint[RIGHT] = Point(tv.right + drawableBounds.width() / HALF_DIVISOR, (tv.pivotY + drawableBounds.height() / HALF_DIVISOR).toInt())
            clickPoint[BOTTOM] = Point((tv.pivotX + drawableBounds.width() / HALF_DIVISOR).toInt(), tv.bottom + drawableBounds.height() / HALF_DIVISOR)
            clickPoint[drawableLocation]?.let { point ->
                if (tv.dispatchTouchEvent(
                                MotionEvent.obtain(
                                        android.os.SystemClock.uptimeMillis(),
                                        android.os.SystemClock.uptimeMillis(),
                                        MotionEvent.ACTION_DOWN,
                                        point.x.toFloat(),
                                        point.y.toFloat(),
                                        0)
                        )) {
                    tv.dispatchTouchEvent(
                            MotionEvent.obtain(
                                    android.os.SystemClock.uptimeMillis(),
                                    android.os.SystemClock.uptimeMillis(),
                                    MotionEvent.ACTION_UP,
                                    point.x.toFloat(),
                                    point.y.toFloat(),
                                    0))
                }
            }

        }
    }

    @IntDef(LEFT, TOP, RIGHT, BOTTOM)
    @Retention(AnnotationRetention.SOURCE)
    annotation class Location

    companion object {
        const val LEFT = 0
        const val TOP = 1
        const val RIGHT = 2
        const val BOTTOM = 3
        const val SIZE_CLICK_POINT = 4
        const val HALF_DIVISOR = 2
        const val DESCRIPTION_HAS_DRAWABLE = "has drawable"
        const val DESCRIPTION_CLICK_DRAWABLE = "click drawable "
    }
}


text:
Q: How to animate(shrink and Expand) to array of UIButtons I have to perform shrink and expand animation for array of UIButtons. For single UIButton I am doing like this...
 UIButton *button = [self.destinationButtonsArray objectAtIndex:0];
 [UIView beginAnimations:@"shrink" context:(__bridge void *)(button)];
    [UIView animateWithDuration:0.7f delay:0 options:UIViewAnimationOptionAutoreverse |                UIViewAnimationCurveEaseInOut | UIViewAnimationOptionRepeat | UIViewAnimationOptionAllowUserInteraction  animations:^{

        [UIView setAnimationRepeatCount:3];

        CGAffineTransform t  = CGAffineTransformMakeScale(1.2f, 1.2f);
        button.transform = t;

    } completion:^(BOOL finished) {
        button.transform = CGAffineTransformMakeScale(1.0f, 1.0f);}];

How can i achieve same effect for array of UIbutons.

A: You can make use of category. Declare a UIButton category and add method to perform the animation.
UIButton+Transform.h
@interface UIButton (Transform)

- (void) applyAnimation;

@end

UIButton+Transform.m
@implementation UIButton (Transform)

- (void) applyAnimation {
    [UIView beginAnimations:@"shrink" context:self];
    [UIView animateWithDuration:0.7f
                          delay:0
                        options:UIViewAnimationOptionAutoreverse
                                | UIViewAnimationCurveEaseInOut
                                | UIViewAnimationOptionRepeat
                                | UIViewAnimationOptionAllowUserInteraction
            animations:^{
                     [UIView setAnimationRepeatCount:3];
                    CGAffineTransform t  = CGAffineTransformMakeScale(1.2f, 1.2f);
                    self.transform = t;
            }
            completion:^(BOOL finished) {
                self.transform = CGAffineTransformMakeScale(1.0f, 1.0f);
            }
     ];
}

@end

Call the method on the array as follows
[self.destinationButtonsArray makeObjectsPerformSelector:@selector(applyAnimation)];

This will call the animation method on all buttons in the array.
Hope that helps!

A: Use a for inside the animation block, something like:
[UIView beginAnimations:@"shrink" context:(__bridge void *)(button)];
        [UIView animateWithDuration:0.7f delay:0 options:UIViewAnimationOptionAutoreverse |                            UIViewAnimationCurveEaseInOut | UIViewAnimationOptionRepeat |     UIViewAnimationOptionAllowUserInteraction  animations:^{

    [UIView setAnimationRepeatCount:3];

    CGAffineTransform t  = CGAffineTransformMakeScale(1.2f, 1.2f);

    for (UIButton button in self.destinationButtonsArray) {
        button.transform = t;
    }
} completion:^(BOOL finished) {
    for (UIButton button in self.destinationButtonsArray) {
        button.transform = CGAffineTransformMakeScale(1.0f, 1.0f);}];
    }
}];


text:
Q: Azure Database for PostgreSQL server - Permission denied to create a table space Context
In our application we have multiple tablespace, basically for allocating different sizes.
We are evaluating to deploy our application in Azure Database for PostgreSQL server.
Problem
While trying to create a table space we got the error
ERROR: permission denied to create tablespace "tec_large"
HINT: Must be a superuser to create a tablespace

On search we got to this information , which basically says

the server admin account is not part of the azure_superuser role. Since this service is a managed PaaS service, only Microsoft is part of the super user role.

Can someone please give a hint on this. Is this a no solution limitation of the Azure offer. Or Is there any possibility to hack around.


text:
Q: VB6 Error Handling in Properties -> Best practise? im using CodeSmart 2013 to analyze my VB6 projects.
The review function says i should add error handling (or at least "on error resume next") to my class-properties.
My properties typically look like this (in 99% cases):
Public Property Let PLZ(ByVal strPlz As String)
    myStrPLZ = strPlz
End Property

Public Property Get PLZ() As String
    PLZ = myStrPLZ
End Property

When i automatically add error handling it would look like this:
Public Property Let PLZ(ByVal strPlz As String)
    '<EhHeader>
    On Error GoTo PLZ_Err
    '</EhHeader>
    myStrPLZ = strPlz
    '<EhFooter>
    Exit Property

PLZ_Err:
    MsgBox Err.Description & vbCrLf & _
           "in TNV.frmSucheTeilnehmer.PLZ " & _
           "at line " & Erl, _
           vbExclamation + vbOKOnly, "Application Error"
    Resume Next
    '</EhFooter>
End Property

Public Property Get PLZ() As String
    '<EhHeader>
    On Error GoTo PLZ_Err
    '</EhHeader>
    PLZ = myStrPLZ
    '<EhFooter>
    Exit Property

PLZ_Err:
    MsgBox Err.Description & vbCrLf & _
           "in TNV.frmSucheTeilnehmer.PLZ " & _
           "at line " & Erl, _
           vbExclamation + vbOKOnly, "Application Error"
    Resume Next
    '</EhFooter>
End Property

is anyone practically doing error handling in properties? is this best practise? because this would be a lot of additional code to my projects (code overview decreases imho)
Thx for help!
Greetings from germany
SLimke

A: You should add error handling in just the same way as you would in any method (Sub/Function).
My rule of thumb is that if the method is only a couple of lines long and doesn't do anything exotic then there is no error handling required. The same can be said of a property Get/Set
Yes adding error handling to all your property getters and setters generates a lot of code so one option could be to use centralised error handling. See this post for some discussion of this: Centralized error handling in VB6

A: Don't take these guidelines (especially from a program written by someone with their own opinion of what "best practice" entails). I've never used it so I can't speak (nor do I doubt) it's quality... just saying.
MarkJ is also right. If you don't need any validation on property setting then just make them public variables. If you later need to add validation, making them into private variables and having the public Property Get/Let/Set instead won't break the interface and no other code changes are needed.
As for adding error handlers in every class property get/let? Why? Personally, I assume if someone is going to use my class they will at least take a moment to make sure they know what the !@#$ they are doing and how to use it. If they set a property so incorrectly that it causes a runtime (or compile-time) error then they will know right away.
If the value for setting the property is coming from the user, i.e.
MyClass.SomeProperty = Input("Enter something: ")

Then I personally think the error code should be placed there. i.e.
On Error GoTo StupidUser
MyClass.SomeProperty = Input("Enter something: ")
Exit Sub
ErrorHandler:
  MsgBox "You did not supply a correct value!", vbExclamation

Otherwise, what are you going to do when you handle an error in your class? Pass it on to a centralized error handler which will just create more code to follow and end up with the same result? The user being notified/written to a log/etc.?
I (again, personally... programming isn't black & white) prefer to put error handling code in the caller routine... the procedure that's using the class, setting properties, etc.
Any sort of "code optimizer/checker" is written by a person or multiple, and even reputable ones will bring up debate among those who use it on how it should work.
TL;DR: some recommendations can be safely ignored.

A: Why not use public fields instead of these boilerplate properties?
Public PLZ As String

If you later need to add logic, no problem! You can convert public fields to properties without breaking clients.


text:
Q: Plate editor: Cannot type in input element despite it being the active element I have created a custom Plate Plugin for hyperlinks that adds an inline element in which you can type the url and the text that shall be displayed. Thus far the element works the way I expect it to. The trouble comes when trying to insert it via hotkey. The desired behavior is for the element to automatically gain focus after it is inserted so that the user can type in it right away. Right now however, the element is inserted upon pressing the hotkey combination, becomes the active element, and yet the user has to manually click inside it to begin typing.
This is what my createHyperLinkPlugin.ts looks like:
import {
  KeyboardHandler,
  LinkPlugin,
  TElement,
  createPluginFactory,
  getPluginType,
  insertNodes,
  isUrl as isUrlProtocol,
  withLink,
} from '@udecode/plate';

import { HyperLinkElement } from './HyperLink';
import isHotkey from 'is-hotkey';

export const ELEMENT_LINK = 'a';

const insertLink: KeyboardHandler<{}, LinkPlugin> =
  (editor, { options: { hotkey } }) =>
  (e) => {
    const type = getPluginType(editor, ELEMENT_LINK);

    if (hotkey && isHotkey(hotkey, e)) {
      e.stopPropagation();
      e.preventDefault();

      insertNodes<TElement<HyperLinkElement>>(editor, {
        type,
        url: '',
        children: [{ text: ' ' }],
        properties: {
          displayText: '',
          isBeingEdited: true,
        },
      });
    }
  };

export const createHyperLinkPlugin = createPluginFactory<LinkPlugin>({
  key: ELEMENT_LINK,
  isElement: true,
  isInline: true,
  isVoid: true,
  props: ({ element }) => ({ nodeProps: { url: element?.url } }),
  handlers: {
    onKeyDown: insertLink,
  },
  withOverrides: withLink,
  options: {
    isUrl: isUrlProtocol,
    rangeBeforeOptions: {
      matchString: ' ',
      skipInvalid: true,
      afterMatch: true,
    },
    hotkey: 'mod+k',
  },
  then: (editor, { type }) => ({
    deserializeHtml: {
      rules: [
        {
          validNodeName: 'A',
        },
      ],
      getNode: (el) => ({
        type,
        url: el.getAttribute('href'),
      }),
    },
  }),
});

The HyperlinkComponent has two <input/> fields inside it, one of which gains focus on creation.
I encountered a very similar problem when adding the element by clicking on its corresponding button on the toolbar. There, i could fix it by using the onClick event instead of the onMouseDown event. It appeared that the mouseUp event that occured after the Element had been added somehow stole its focus.
I have observed something similar with the hotkey. If the hotkey is set to a singular key, for example 'k' and the onKeyUp handler is used, the element gains focus as one would expect and the user can immediately type in it. However, if the hotkey combination contains a modifier, the element is created, gains focus, but can not be written in before manually clicking on it. The chrome dev tools even tell me that the document.activeElement is indeed the input element I want to be able to type in.
Honestly I'm at a loss here as i don't even know whether this behavior is caused by plate, slate, react or just javascript itself. Thanks in advance to anyone who can share any insight into this.


text:
Q: Apply the action only to this element on the page Please tell me how to bind the displayCount function to the current filter_item? All that in $('.filter_item').each(function() { it works correctly, but function displayCount() { runs for all filter_item on the page.
jQuery(function($) {

    var count = 0;

    $('.filter_item').each(function() {

        count = $(this).find('input[type=checkbox].jet-checkboxes-list__input:checked').length;
        displayCount();

        $(this).find('input[type=checkbox].jet-checkboxes-list__input').bind('click' , function(e, a) {
            if (this.checked) {
                count += a ? -1 : 1;
                } else {
                count += a ? 1 : -1;
            }
            displayCount();
        });

    });

    function displayCount() {
        if (count == 0) {
            $('.count').hide();
            } else {
            $('.count').show();
            $('.count').text(count);
        }
    }
});

A: $('.count').hide();

Selects each element in the document which has the class count. So yes it will change every entry. If you want to change only the one you get by each you need to transfer $(this) to your displayCount() function
 function displayCount(element) {
    if (count == 0) {
        element.hide();
        } else {
        element.show().text(count);
    }
}

And call it like this
$('.filter_item').each(function() {

    var element = $(this).find('input[type=checkbox].jet-checkboxes-list__input:checked');
    count = element.length;
    displayCount(element);

    ....

});

A: Perhaps someone will need)
jQuery(function($) {

    $('.filter_item').each(function() {
        let that = this;
        let count = 0;
        count = $(this).find('input[type=checkbox].jet-checkboxes-list__input:checked').length;
        displayCount.call(that, count);

        $(this).find('input[type=checkbox].jet-checkboxes-list__input').bind('click' , function(e, a) {
            if (this.checked) {
                count += a ? -1 : 1;
                } else {
                count += a ? 1 : -1;
            }
            displayCount.call(that, count);
        });
    });

    function displayCount(count) {
        if (count == 0) {
            $('.count', this).hide();
            } else {
            $('.count', this).show().text(count);
        }
    }
});


text:
Q: Why are many options missing from the editor? I want to say for the record that I'm extremely new to anything related to Wordpress.
So my editor looks like this:

I see all sorts of screenshots and blog-posts everywhere that show a much much richer set of options in the editor. I can't set the font size / color, paragraphs, headings and much more. Why don't I have these options ?
I disabled every plugin -> nothing. I switched to a few other themes -> nothing.
It's very frustrating to having so few options for customizing how the blog text looks like.
I'm sure I'm missing something obvious here, but I can't figure out what.
PS 1: I have Wordpress 4.4.2 installed manually on my webhosting account.
PS 2: Everything else works great.

A: Switch your editor to use the visual mode instead of the text mode. You'll find this on the right-hand side of your editor. Also, see the item with a grey box around it in the below image. That's the "kitchen sink" button. It toggle's the rest of the toolbar for a deeper list of options.


text:
Q: Vue wait for the function to complete before sending the data My issue is I need to emit the data but when this function reaches emit the collection is empty, and it takes time get the collection data, so I always endup emitting empty collection data to the other component, is there a way for this?
  data() {
    return {
      kind: '',
      label: 'Choose files to upload',
      helperText: 'Select the files you want to upload',
      collection:[],
    }
  },
  methods: {

    async loadcsv(element) {
      let reader = new FileReader()
      let file = element[0].file
      reader.onload = async (e) => {
        let csvParsed = await d3.csvParse(reader.result)
        csvParsed.forEach(async (element)=> {
          let userInfo = await lookupUser(element['State'])
          if (userInfo) {
            this.collection.push(userInfo)
          } else {
            this.collection.push({
              id: Math.floor(Math.random() * 10000000),
              poi_country: getCountry(element['Country']),
              poi_email: element['Email'],
              poi_name: element['Name'],
              poi_serial: element['State'],
              collection_type: element['Order'],
              status: 'New',
            })
          }
        })
        //Empty collection []
        this.$emit('csvCollection', this.collection)
      }
      reader.readAsText(file)
    },
  },
}


text:
Q: I'm making a music bot with discord.py and I'm having some trouble with the play command The bot has play command that does 3 things it joins the voice channel if it isn't in the voice channel already, it plays songs(obviously) and it stores the songs in a dict called queues if the bot is already playing a song to then play it when the song ends. To do something like this you need the after statment on the voiceClients play command and it seems to be behaving quit weirdly. I've put some print commands to test the bot and it seems that the function that I put on the after statment is firing right away rather then when the song ends, I don't know if this is a bug or if I'm doing something wrong... anyway here's the code:

this is the function that plays after the play command

def continue(ctx):

   queues[ctx.guild.id].pop(0)

   print(f'function continue: {queues}')

   if len(queues[ctx.guild.id]) == 0:
       return

   Songs.play(ctx=ctx ,song=queues[ctx.guild.id][0])

and here is the play command

class Songs(commands.Cog):

   def __init__(self, bot):
       self.client = client

   @commands.command()
   async def play(self, ctx, *, song):

       if ctx.voice_client is None:
           await ctx.message.author.voice.channel.connect()
       else:
           if ctx.voice_client.channel != ctx.message.author.voice.channel:
               await ctx.send('You are not in the same channel as the bot!')
               return

       if ctx.guild.id in queues:
           queues[ctx.guild.id].append(song)
       else:
           queues[ctx.guild.id] = [song]

       print(f'function play: {queues}')

       if ctx.voice_client.is_playing():
           await ctx.send('Song added to queue! :thumbsup:')
           return

       ydl_opts = {'format': 'bestaudio'}
       with youtube_dl.YoutubeDL(ydl_opts) as ydl:
           if musica.startswith('https'):
               info = ydl.extract_info(song, download=False)
               URL = info['formats'][0]['url']
           else:
               info = ydl.extract_info(f'ytsearch:{song}', download=False)
               URL = info['entries'][0]['formats'][0]['url']

       FFMPEG_OPTIONS = {'before_options': '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5', 'options': '-vn'}
       ctx.message.guild.voice_client.play(discord.FFmpegPCMAudio(URL, **FFMPEG_OPTIONS), after=continue(ctx))

A: Ah, you have committed one of the classic Python blunders.  Look at this line:
       ctx.message.guild.voice_client.play(discord.FFmpegPCMAudio(URL, **FFMPEG_OPTIONS), after=continue(ctx))

When that line runs, the first thing it's going to do is call your function continue.  It will then pass the RESULT of that function call to the play function.  You don't want to CALL the function, you want to pass the function object:
       ctx.message.guild.voice_client.play(discord.FFmpegPCMAudio(URL, **FFMPEG_OPTIONS), after=continue)

If you really need the context in there, you'll have to use a lambda:
       ctx.message.guild.voice_client.play(discord.FFmpegPCMAudio(URL, **FFMPEG_OPTIONS), after=lambda: continue(ctx))

A: In the final line of your snippet:
ctx.message.guild.voice_client.play(discord.FFmpegPCMAudio(URL, **FFMPEG_OPTIONS), after=continue(ctx))

The after keyword-parameter expects a callable. You are not giving it that. You are invoking a function continue (not a great name for a function, by the way, because you shadow the builtin keyword), and bind the return value to after. Since your callable must accept a parameter ctx, the quick fix would be to pass in a lambda:
after=lambda: continue(ctx)


text:
Q: Error in Laravel 8 [ Argument 2 passed ] with command [php artisan make:controller Admin\HomeController] I am following a Youtube course, the teacher asks to integrate the AdminLTE template in this video: https://youtu.be/r8RKayPtijc
The problem arises once I run the command:

php artisan make:controller Admin\HomeController

The console responds to me:

In UrlGenerator.php line 120:
Argument 2 passed to Illuminate\Routing\UrlGenerator::__construct() must be an instance of Illuminate\Http\Request, null given,
called in ...\vendor\laravel\framework\src\Illuminate\Routing\RoutingServiceProvider.php on line 65

See console photo
I already tried:

*

*I investigated in the comments of the YouTube video to see if someone else happened to him but apparently it is only me.

*I looked into the error on Google but did not find anything similar to my error.

*Create a new Laravel project and verify that the command: php artisan make: controller Admin \ HomeController works and correctly created the folder and its respective file.

*Take the vendor \ laravel \ framework \ src \ Illuminate \ Routing \ RoutingServiceProvider.php file and replace it with mine.

*I reversed the code that the video asked to do.

Nothing worked for me, waiting for a prompt response to know how to correct this in future projects.


text:
Q: Multiple virtual inheritance from a single class in c++ The following code raises an ambiguity between Horse::getcolour() and Bird::getcolour() which is totally unanticipated as the classes Bird and Horse are virtually inherited by the class Pegasus which must have avoided this error.
class Animal {
    public:
        Animal(int itsAge):age(itsAge) { cout << "Animal Constructor.\n"; }
        virtual ~Animal() { cout << "Animal Destructor.\n"; }
        int GetAge() const { return age; }
        void SetAge(int itsAge) { age=itsAge; }
    private:
        int age;
};
class Bird: virtual public Animal {
    public:
        Bird(string colour,int itsAge);
        virtual ~Bird() { cout << "Bird Destructor.\n"; }
        void Fly() const { cout << "Flying!!!!\n"; }
        virtual void Chirp() const { cout << "Chirpppp!!!!\n"; }
        virtual string getcolour() const { return colour; }
    protected:
        string colour;
};
Bird::Bird(string colour,int itsAge):colour(colour),Animal(itsAge) {
    cout << "Bird Constructor.\n";
}
class Horse: virtual public Animal {
    public:
        Horse(string colour,int itsAge);
        virtual ~Horse() { cout << "Horse Destructor.\n"; }
        virtual void Whine() const { cout << "Whinnnnne!!!\n"; }
        virtual string getcolour() const { return colour; }
    protected:
        string colour;
};
Horse::Horse(string colour,int itsAge):colour(colour),Animal(itsAge) {
    cout << "Horse Constructor.\n";
}
class Pegasus:virtual public Horse,virtual public Bird { // inherits both Horse and Bird virtually
    public:
        Pegasus(string colour,int n,int itsAge);
        ~Pegasus() { cout << "Pegasus Destructor.\n"; }
        void Chirp() const { Horse::Whine(); }
    private:
        int nBelievers;
};
Pegasus::Pegasus(string colour,int n,int itsAge):Animal(itsAge),Horse(colour,itsAge),Bird(colour,itsAge),nBelievers(n) {
    cout << "Pegasus Constructor.\n";
}
int main() {
    Pegasus *p=new Pegasus("Black",44,4);
    cout << "Colour of this pegasus: " << p->getcolour(); // Error is thrown
    return 0;
}

Can anyone point out the fault in the code above and suggest me the correct logic/syntax if I am wrong? Thanks in advance.


text:
Q: How to use generated Angular client from Spring Boot REST API? I finally managed to generate an Angular client using this tutorial using the openapi-generator-maven-plugin.
I had to make a few adaptations e.g. using different dependencies
<!-- Spring Docs (Swagger) -->

<!-- TODO After version upgrades check https://github.com/springdoc/springdoc-openapi/issues/133 -->

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-core</artifactId>
    <version>1.1.49</version>
    <exclusions>
        <exclusion>
            <groupId>io.github.classgraph</groupId>
            <artifactId>classgraph</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-ui</artifactId>
    <version>1.1.49</version>
</dependency>

<dependency>
    <groupId>io.github.classgraph</groupId>
    <artifactId>classgraph</artifactId>
    <version>4.8.44</version>
</dependency>

and also had to add a few more arguments e.g. for the database driver etc.:
<profile>
    <id>angular</id>
    <build>
        <plugins>

            <!-- Code Generation -->

            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>build-helper-maven-plugin</artifactId>
                <version>3.0.0</version>
                <executions>
                    <execution>
                        <id>reserve-tomcat-port</id>
                        <goals>
                            <goal>reserve-network-port</goal>
                        </goals>
                        <phase>process-resources</phase>
                        <configuration>
                            <portNames>
                                <portName>tomcat.http.port</portName>
                            </portNames>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

            <!-- Spring Boot Maven plugin -->

            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <id>pre-integration-test</id>
                        <goals>
                            <goal>start</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>post-integration-test</id>
                        <goals>
                            <goal>stop</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <addResources>true</addResources>
                    <arguments>
                        <!--suppress MavenModelInspection -->
                        <argument>--server.port=${tomcat.http.port}</argument>
                        <argument>--spring.profiles.active=angular</argument>
                    </arguments>
                    <environmentVariables>
                        <JDBC_DATABASE_URL>jdbc:postgresql://localhost/mydatabase</JDBC_DATABASE_URL>
                        <JDBC_DATABASE_USERNAME>postgres</JDBC_DATABASE_USERNAME>
                        <JDBC_DATABASE_PASSWORD>root</JDBC_DATABASE_PASSWORD>
                    </environmentVariables>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.openapitools</groupId>
                <artifactId>openapi-generator-maven-plugin</artifactId>
                <version>4.2.2</version>
                <executions>
                    <execution>
                        <id>angular-client-code-generation</id>
                        <phase>integration-test</phase>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                        <configuration>
                            <!--suppress MavenModelInspection -->
                            <inputSpec>http://localhost:${tomcat.http.port}/v3/api-docs</inputSpec>
                            <output>${project.build.directory}/generated-sources/angular-client</output>
                            <generatorName>typescript-angular</generatorName>
                            <!--
                                Use this option to dump the configuration help for the specified generator
                                instead of generating sources:
                                <configHelp>true</configHelp>
                            -->
                            <configOptions>
                                <!--
                                    Put generator-specific parameters here, e.g. for typescript-angular:
                                    <apiModulePrefix>Backend</apiModulePrefix>
                                 -->
                            </configOptions>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

        </plugins>
    </build>
</profile>

But now, after the code has been generated, I am not able to follow the instructions as posted in the (generated) README.md:

@
Building
To install the required dependencies and to build the typescript
  sources run:
npm install
npm run build

publishing
First build the package then run npm publish
consuming
Navigate to the folder of your consuming project and run one of next
  commands.
published:
npm install @ --save
...

The reason: There is no package.json and therefore also no "build" script that could be executed in the first place.
Therefore, I am wondering whether there's something missing out or what I have to do to be able to use the generated code in my Angular clients.

A: I found the answer in Why does openapi-generator not create a package.json with typescript-angular?.
I had to set <npmName>tmsClientRest</npmName> for openapi-generator-maven-plugin:
<plugin>
    <groupId>org.openapitools</groupId>
    <artifactId>openapi-generator-maven-plugin</artifactId>
    <version>4.2.2</version>
    <executions>
        <execution>
            <id>angular-client-code-generation</id>
            <phase>integration-test</phase>
            <goals>
                <goal>generate</goal>
            </goals>
            <configuration>
                <!--suppress MavenModelInspection -->
                <inputSpec>http://localhost:${tomcat.http.port}/v3/api-docs</inputSpec>
                <output>${project.build.directory}/generated-sources/angular-client</output>
                <generatorName>typescript-angular</generatorName>
                <configOptions>
                    <!-- The missing part(s) -->
                    <npmName>restClientName</npmName>
                    <npmVersion>0.0.1</npmName>
                </configOptions>
            </configuration>
        </execution>
    </executions>
</plugin>

Note: In my case I also had to add npmVersion to make it "work" (it's still not working, just running into the next issue)

Update:
If you get something like

models.ts is not a module

it might be because you do not have any DTO objects yet. In my case I only had a simple REST Controller that returned a simple String. Just make sure you return (at least) a dummy object and model.ts gets populated with code and npm install && npm run build should finally work for example:
public static class HealthInfoDto {
    public String message = "I am alive, you see?";
}

@RequestMapping(value = "/health", method = RequestMethod.GET)
public @ResponseBody HealthInfoDto getHealth() {
    return new HealthInfoDto();
}

instead of just
@RequestMapping(value = "/health", method = RequestMethod.GET)
public @ResponseBody String getHealth() {
    return "Hello World!";
}


text:
Q: custom bokeh charts function not running     d = {"Fruits" : ["Apples","Bananas","Pears","Oranges","Melons"],
     "Ripe" : [10000,18000,19000,36000,50000],
     "Rotten" : [3000,8000,7000,10000,20000]
    }
df = pd.DataFrame(d)

df["Difference"]= df["Ripe"] - df["Rotten"]
df

I am working on this small dataframe and cant seem to apply custom colors on the function i created to generate vbars
source=ColumnDataSource(data=dict(fr=df.Fruits,
                                 ri=df.Ripe,
                                 ro=df.Rotten,
                                 di=df.Difference))
tooltips=[('Total','@ri')]

reds=['#f14331',
  '#f14432',
  '#f24633',
  '#f24734',
  '#f34935']

def vbar(source,x_range,x,top,color=reds):
    p=figure(toolbar_location=None,height=300,x_range=x_range,sizing_mode='stretch_width')
    p.xgrid.grid_line_color=None
    p.y_range.start=0

    p.vbar(x=x,top=top,source=source,width=0.8,color=color)

    p.add_tools(HoverTool(tooltips=tooltips))

    return p

p=vbar(source,x_range=df.Fruits,x='fr',top='ri')
show(p)

in the function parameter when i pass in a color such as'blue' it runs totally fine. but when i pass in a list of colors i.e reds, it throws an error:
    ---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Input In [151], in <cell line: 24>()
     20     p.add_tools(HoverTool(tooltips=tooltips))
     22     return p
---> 24 p=vbar(source,x_range=df.Fruits,x='fr',top='ri')
     25 show(p)

Input In [151], in vbar(source, x_range, x, top, color)
     15 p.xgrid.grid_line_color=None
     16 p.y_range.start=0
---> 18 p.vbar(x=x,top=top,source=source,width=0.8,color=color)
     20 p.add_tools(HoverTool(tooltips=tooltips))
     22 return p

File ~\Anaconda3\lib\site-packages\bokeh\plotting\_decorators.py:86, in glyph_method.<locals>.decorator.<locals>.wrapped(self, *args, **kwargs)
     84 if self.coordinates is not None:
     85     kwargs.setdefault("coordinates", self.coordinates)
---> 86 return create_renderer(glyphclass, self.plot, **kwargs)

File ~\Anaconda3\lib\site-packages\bokeh\plotting\_renderer.py:96, in create_renderer(glyphclass, plot, **kwargs)
     94 incompatible_literal_spec_values += _process_sequence_literals(glyphclass, glyph_visuals, source, is_user_source)
     95 if incompatible_literal_spec_values:
---> 96     raise RuntimeError(_GLYPH_SOURCE_MSG % nice_join(incompatible_literal_spec_values, conjuction="and"))
     98 # handle the nonselection glyph, we always set one
     99 nonselection_visuals = pop_visuals(glyphclass, kwargs, prefix='nonselection_', defaults=glyph_visuals, override_defaults={'alpha':0.1})

RuntimeError:

Expected line_color, fill_color and hatch_color to reference fields in the supplied data source.

When a 'source' argument is passed to a glyph method, values that are sequences
(like lists or arrays) must come from references to data columns in the source.

For instance, as an example:

    source = ColumnDataSource(data=dict(x=a_list, y=an_array))

    p.circle(x='x', y='y', source=source, ...) # pass column names and a source

Alternatively, *all* data sequences may be provided as literals as long as a
source is *not* provided:

    p.circle(x=a_list, y=an_array, ...)  # pass actual sequences and no source

i have also tried color='reds' with quotation marks
which gives a blank graph and spits out:
ERROR:bokeh.core.validation.check:E-1001 (BAD_COLUMN_NAME): Glyph refers to nonexistent column name. This could either be due to a misspelling or typo, or due to an expected column being missing. : key "fill_color" value "reds", key "hatch_color" value "reds", key "line_color" value "reds" [renderer: GlyphRenderer(id='22999', ...)]

any advice on how i can get my graph to run with my custom colors?

A: the issue was I had to specify the colors within the CDS
source=ColumnDataSource(data=dict(fr=df.Fruits,
                                 ri=df.Ripe,
                                 ro=df.Rotten,
                                 di=df.Difference,
                                 color=reds))
tooltips=[('Total','@ri')]

reds=['#e83b1e','#ea4e34','#ec624a','#ee7561','#f18978']

def vbar(source,x_range,x,top,color='color'):
    p=figure(toolbar_location=None,height=300,x_range=x_range,sizing_mode='stretch_width')
    p.xgrid.grid_line_color=None
    p.y_range.start=0

    p.vbar(x=x,top=top,source=source,width=0.8,color=color)

    p.add_tools(HoverTool(tooltips=tooltips))

    return p

p=vbar(source,x_range=df.Fruits,x='fr',top='ri')
show(p)


text:
Q: Why is the state of a quantum system called "Density $\textbf{Operator}$"? In quantum mechanics, a $d$-dimensional pure state is represented by a vector belonging to a $d$-dimensional Hilbert space $\mathcal{H}^d$. A mixed state is represented by a density matrix $\rho \in \mathcal{H}^{d} \otimes {\mathcal{H}^{d*}}$.
Where * denotes the dual.
Operators act on the state $\rho$. Why is $\rho$ called an operator when it is the object on which operators are acting? What am I missing?
Does this have something to do with the $C^*$ algebraic formulation of quantum mechanics?
If so please suggest some books on $C^*$ algebraic formulation of quantum mechanics.

A: The terminology can be confusing because in the phrases "state vector", "pure state", and "mixed state", the word "state" is being used in different ways.
The terms pure state and mixed state do not directly refer to a state vector in the Hilbert space, but to our state of knowledge about the physical system. If we say a system is in a pure state, that means that we can represent the system as a single state vector in Hilbert space.$^\star$ If we say the system is in a mixed state, it means that we do not know specifically what state vector represents the system; we can only assign probabilities for the system to be represented by any given state vector.
Pure states can be represented by a state vector in the Hilbert space. Mixed states cannot. On the other hand, while only a pure state can be represented by a state vector, both pure and mixed states can be represented by the density matrix.
The density matrix is an operator, not a state vector, by definition. A ket is a map that takes a bra and produces a complex number. A linear operator is a map that takes one bra and one ket and produces a complex number, and is a bilinear function of the bra and ket. The density matrix is the latter kind of mathematical object. This is clear from the usual way to represent the density matrix as an expansion over state vectors$^\dagger$
\begin{equation}
\hat{\rho} = \sum_a p_a |\Psi_a\rangle \langle \Psi_a|
\end{equation}
since given a bra $\langle b |$ and a ket $| k \rangle$, we see that $\langle b | \hat{\rho} | k \rangle$ is a complex number, and $\hat{\rho}$ is also bilinear function of the bra and ket.
The definitions of pure and mixed states have nothing in particular to do with $C^\star$-algebras, which are a way of formalizing the idea of an algebra of observables. You can understand the density matrix without that language.

$^\star$If the system is in a pure state, sometimes people will also refer to the state vector itself as the pure state. That's fine so long as the meaning is understood. In this answer, I want to try to clearly distinguish the concepts of a pure state, mixed state, and state vector, so I will intentionally avoid saying this.
$^\dagger$ Note this is not a definition of the density matrix, for example see this answer from Emilio Pisanty


text:
Q: Is the Wordpress HTTPS Plugin Still Safe To Use? I have a client who wants to accept Authorize.net donations on their website. We only have a need for one page to be secured for our purposes.
I've put a lot of research into this and it seems that the Wordpress HTTPS plugin would be the best option, with the least amount of brain damage.
However, I see that the plugin has not been updated in three years. Multiple forums and blogs say that it is still safe to use, but I want to know if anyone has/is currently using this plugin for similar purposes and if they have any advice for me before I go down this road? Thank you!

A: If you are looking to use HTTPS, I reccomend following this wordpress guide: https://make.wordpress.org/support/user-manual/web-publishing/https-for-wordpress/#implementing-https-for-wordpress
You can get a free SSL Certificate from: https://letsencrypt.org/
If you find difficulty setting it up, you can often pay your host a small fee to help set this up. Once set up, you just need to make sure all the links on the page are HTTPS and not HTTP. Really easy to fix with plugins like Velvet Blues URL.
The Wordpress HTTPS plugin just makes implementing the SSL a bit easier. I would discourage installing old plugins as they often have security flaws and can conflict with your theme / other plugins.

A: Wordpress HTTPS doesn't solely secure the site. It just allows a page/pages/sections to be forced to HTTPs. You still need a certificate.
Our company uses Wordpress HTTPS in combination with an SSL certificate installed to the server. We also process through Authorize.net, and have not experienced issues (WP 4.4.2); though, we're still updating our theme to be compatible with 4.5.x.

A: There is a Woocommerce setting to force SSL on the checkout page only. It's in Woocommerce > settings > checkout > Force secure checkout
As a side note, and someone correct me if I'm wrong on this, but I've recently heard that it actually doesn't matter if the page is loaded over https as the only connection that has to be a secure ssl connection is the one from the client's computer to authorize.net. Having the server send content to the user over https is just for show because everyone thinks this means their checkout is secure.


text:
Q: Is $ \max_{x\in\mathbb{R}^n} \{ f(x)+g(x) \} = \max_{x\in\mathbb{R}^n} f(x)+\max_{x\in\mathbb{R}^n} g(x) $ if $f$ and $g$ are affine in $\mathbb{R}$? Let $x \in \mathbb{R}^n$, and let $f(x)$ and $g(x)$ be two affine functions in $\mathbb{R}$.
Is the following property true?
$$
\max_{x\in\mathbb{R}^n} \{ f(x) + g(x) \} = \max_{x\in\mathbb{R}^n} f(x) + \max_{x\in\mathbb{R}^n} g(x)
$$
Of course, for arbitrary functions this is $\leq$ instead of $=$, but I need this property in a larger proof and I am not sure if it is true or false.
Could anyone verify, and possibly sketch a small proof?
Greatly appreciated.

A: This cannot be true since the maximum of an affine function $f$ on $\Bbb R^n$ is always $+\infty$ unless it's a constant function.


text:
Q: Replacement of deprecated textTheme in flutter I am a newbie in Flutter, and still getting familiar with terms and properties of it. Anyways, when I am using textTheme, and mention any property like title, button etc. it shows that the property is deprecated and shouldn't be used anymore. My assumption is textTheme is only deprecated, so what should I replace it with, so that it is not deprecated?

A: For title, you need to use  subtitle1 instead.
You can see the deprecated list from TextTheme source code in text _theme.dart. If you're using IntelliJ, you can view the source code by right-clicking the title property, then select Go To -> Declaration or Usages.
Here the excerpts for deprecated properties of text _theme.dart:
@Deprecated(
  'This is the term used in the 2014 version of material design. The modern term is headline1. '
  'This feature was deprecated after v1.13.8.'
)
TextStyle? display4,
@Deprecated(
  'This is the term used in the 2014 version of material design. The modern term is headline2. '
  'This feature was deprecated after v1.13.8.'
)
TextStyle? display3,
@Deprecated(
  'This is the term used in the 2014 version of material design. The modern term is headline3. '
  'This feature was deprecated after v1.13.8.'
)
TextStyle? display2,
@Deprecated(
  'This is the term used in the 2014 version of material design. The modern term is headline4. '
  'This feature was deprecated after v1.13.8.'
)
TextStyle? display1,
@Deprecated(
  'This is the term used in the 2014 version of material design. The modern term is headline5. '
  'This feature was deprecated after v1.13.8.'
)
TextStyle? headline,
@Deprecated(
  'This is the term used in the 2014 version of material design. The modern term is headline6. '
  'This feature was deprecated after v1.13.8.'
)
TextStyle? title,
@Deprecated(
  'This is the term used in the 2014 version of material design. The modern term is subtitle1. '
  'This feature was deprecated after v1.13.8.'
)
TextStyle? subhead,
@Deprecated(
  'This is the term used in the 2014 version of material design. The modern term is subtitle2. '
  'This feature was deprecated after v1.13.8.'
)
TextStyle? subtitle,
@Deprecated(
  'This is the term used in the 2014 version of material design. The modern term is bodyText1. '
  'This feature was deprecated after v1.13.8.'
)
TextStyle? body2,
@Deprecated(
  'This is the term used in the 2014 version of material design. The modern term is bodyText2. '
  'This feature was deprecated after v1.13.8.'
)

A:

textTheme is deprecated and shouldn't be used. This property is no
longer used, please use toolbarTextStyle and titleTextStyle instead.
This feature was deprecated after v2.4.0-0.0.pre.

Solution
Use toolbarTextStyle

  appBarTheme: AppBarTheme(
      color: Colors.white,
      elevation: 0.0,
      iconTheme: IconThemeData(color: Colors.black),
      toolbarTextStyle: Theme.of(context).textTheme.bodyText2,
      titleTextStyle: Theme.of(context).textTheme.headline6)),

A: Following ישו אוהב אותך's answer, and reading properly the documentation he or she kindly shared, you need to substitute title by headline6, not subtitle1.


text:
Q: If $ab \equiv 1 \pmod{p}$, is $a \equiv b \pmod{p}$? If $ab \equiv 1 \pmod{p}$, is $a \equiv b \pmod{p}$?
I can see that $b$ is an inverse of $a$ modulo p. But what property does the inverse of $a$ has but $a\bar{a} \equiv 1 \pmod{p}$?
Thank you

A: No, $a$ is congruent to its inverse mod $p$ iff $a\equiv \pm 1 \bmod p$.

A: Consider a set $P = \{1, 2, 3, ...., p-1\}$; $|P|=p-1, p > 2$ is prime.
Apart from $1$ and $p-1$, where
$$1^2 ≡ (p-1)^2 ≡ 1  \pmod p,$$
consider further two positive integers $m$ and $n$ such that neither are multiples of $p$. Therefore each are congruent modulo $p$ to two of the $p-3$ members of $P$.
Now, $mn ≡ 1 \pmod p$ implies that $mn - 1 = kp$ for some positive integer $k$.
This we can rewrite as
$$mn - kp = 1$$
The equation
$rx + sy = k (k, r, s, x, y ∈ ℕ)$
has solutions for $x$ and $y$ $\iff \gcd(x, y)$ divides $k$. In which case there are $\frac{k}{\gcd(x, y)}$ solutions.
Since $\gcd(m,p) = \gcd(n, p) = 1$ (and of course $1|1$), the above equation has a unique solution for the positive integers $m$ and $n$.
Now the only two members of $P$ which satisfy
$$mn ≡ 1 \pmod p ⇒ m ≡ n \pmod p$$
are
$$m, n ≡ 1 \pmod p \text{ and } m, n ≡ p-1 \pmod p$$
It follows that there are $\frac{p-3}{2}$ pairs of integers $m, n$ such that $$mn ≡ 1 \pmod p \text{ where }
m ≢ n \pmod p$$


text:
Q: Moved my project folder to another location and now xcworkspace wont open with my main project I just moved the folder where the entire project is located inside and after that when i try to launch my project with Xcode through the xcworkspace file, it just opens with the pod files ignoring my main project. Is there any way to reattach them?

A: With finder go the folder where your project is located. You can find it directly from Xcode if you click on the project file at the Navigator (left side of the screen) and the on the inspector (right) click on the arrow next to the file path and it will open the folder.
Then right click on the project file (somename.xcodeproj)and show package content. Then open project.pbxproj file with a text editor. Once opened you should find for lines with ** >>>>, ==== or <<<< ** symbols and remove the full lines. (I recommend you to make a copy of the file before touching anything). Save it, close everything and restart Xcode again. It should be ok.


text:
Q: My TripleDES wrapper doesn't work Swiftly following on from my last TripleDES-related question, here's my TripleDES wrapper code, which is used to encrypt and decrypt integers:
public static class Crypto {

    private static Byte[]    _fixedIv = new Byte[] { /* 8 random bytes, const */ };

    private static TripleDES _tripleDes;
    private static Byte[]    _key;

    static Crypto() {

        _tripleDes = TripleDES.Create();
        _tripleDes.Mode = CipherMode.CFB;

        String key = ConfigurationManager.AppSettings["cryptoKeyId"];
        _key = Convert.FromBase64String( key );
    }

    /// Encrypts the specified integer using the configuration-stored key.
    public static String EncryptID(Int32 id) {

        Byte[] input = new Byte[8]; // 64-bit block size
        Byte[] inputLo = BitConverter.GetBytes( id );
        for(int i=0;i<inputLo.Length;i++) input[i] = inputLo[i];

        ICryptoTransform tr = _tripleDes.CreateEncryptor( _key, _fixedIv );

        Byte[] output = new Byte[8];
        tr.TransformBlock( input, 0, input.Length, output, 0 );

        return Convert.ToBase64String( output );
    }

    /// Decrypts the specified string (storing an integer) using the configuration-stored key.
    public static Int32 DecryptID(String s) {

        Byte[] ciphertext = Convert.FromBase64String(s);

        ICryptoTransform tr = _tripleDes.CreateDecryptor( _key, _fixedIv );

        Byte[] output = new Byte[8];
        tr.TransformBlock( ciphertext, 0, ciphertext.Length, output, 0 );

        Byte[] outputLo = new Byte[4] { output[0], output[1], output[2], output[3] };
        return BitConverter.ToInt32( outputLo, 0 );
    }

}

When I run it, I get deterministic results for each input to EncryptID, but every call to DecryptID returns zero. I stepped into the code and say that the contents of the 'output' array are all zero (and tr.TransformBlock returns zero). Does anyone know what I'm doing wrong?
I tried calling tr.TransformFinalBlock but I got an exception:
'tr.TransformFinalBlock( ciphertext, 0, ciphertext.Length )' threw an exception of type System.Security.Cryptography.CryptographicException' base {System.SystemException}: {"Bad Data.\r\n"}

A: It turns out that for single blocks I should be using TransformFinalBlock for both encryption and decryption.
I also had to set algo.Padding to None to ensure that 8 bytes of clear is transformed into 8 bytes of ciphertext.


text:
Q: Lost customization after switching the WordPress theme I spent a lot of time creating a website page. Then it was not allowing me add a video, so I activated a new theme. Now every customization I did is lost. I do not even remember what the old theme was.
I cannot believe there is no way to retrieve it. Can someone help me restore my old customized theme.

A: WordPress does not keep track of these changes without the help of special 3rd party plugins. It's too late here, but there are a some precautionary steps before switching a theme:

*

*Copy snippets from your current theme (functions.php etc)

*Write down all analytics and adsense tracking codes

*Copy sidebar widgets like social links, advertisements, subscription or contact forms

*Make a FULL BACKUP!!!


text:
Q: Java - splitting String problem I've had a small problem with splitting a String in java as follows:
System.out.println(dexListMod.get(selNum-1).getClass().getName());
String dexListTempString = dexListMod.get(selNum-1);

The first line prints the class name of the Object returned from the index of selNum -1 in the Vector dexListMod. This outputs the following in the console:
java.lang.String

The second line defines a String of this same Object to split() later but, and this is the problem, the compiler says that they are incompatible types! Am I seeing this wrong, or is this a contradiction?
Thanks.

A: I assume that dexListMod is an untyped List i.e. a List of Object in which case the compiler does not know at compile time that dexListMod.get(selNum-1) is a String. At runtime the Object can report that it is actually a String, this is polymorphism in action.
What you need to do is cast it to a type or use a typed List. e.g.
if (dexListMod.get(selNum-1) instanceof String) {
    String s = (String) dexListMod.get(selNum-1);
    System.out.println(s);
}

A: The problem is that what matters for Java compiler is the static type of the object, not what it actually is at runtime.
Similarly, the following example is rejected by the Java compiler:
SuperClass a = new SubClass1();
a.SomeMethodInSubClass1ButNotInBaseClass(); // fails

If the compiler allowed this, you could have assigned something else to a like:
SuperClass a = new SubClass1();
a = new SubClass2(); // it doesn't have the method!
a.SomeMethodInSubClass1ButNotInBaseClass(); // would fail at runtime if allowed

In the general case, it's theoretically impossible to find the exact runtime type of a variable at compile time. The compiler remains conservative and simply fails to compile instead of assuming correctness and possibly failing at runtime (dynamic languages like Python usually choose the opposite design decision: assume correctness and potentially failing at runtime).
Your code snippet essentially demonstrates the same thing, where the return type of dexListMod.get method is probably Object, and it returns a String instance (which is derived from Object).
If you are sure about the runtime type of an object, Java requires you to be explicit about it and take the responsibility to manually cast it to the type you expect. Of course, the cast can potentially fail at runtime and throw an exception.

A: If you have not used Generics, the list will return Object, you will need an explicit cast.
if(dexListMod.get(selNum-1) instanceof java.lang.String){
  String dexListTempString = (String)dexListMod.get(selNum-1);
}

A: The problem is that in the second line it's expected to have a String type. Your vector hasn't been parametrized. So the compiler doesn't know which types of objects you store in it
If you store strings in the vector than you need to cast the value to String type
String dexListTempString = (String) dexListMod.get(selNum-1);

A: Try this and see what it outputs:
String dexListTempString;
System.out.println(dexListTempString.getClass().getName());

A: The type of the object returned from that call doesn't have to necessarily be a String.  It could return an Object.  Even though that Object is actually a String (as shown by your call to dexListMod.get(selNum-1).getClass().getName()), it must first be cast as a String before you can use it as such.

A: You haven't stated the declaration of dexListMod, but I assume that it its without any generic type parameter (Vector dexListMod) or with a type parameter that is a supertype of String, e.g. Vector<Object> dexListMod. The get method of such declaration does not return java.lang.String, but a supertype which may or may not be assignment compatible with String. The compiler enforces static assignment compatibility and therefore gives you this error message.
Use a cast and eventually a type check to assign the result:
Object val = dexListMod.get(selNum - 1)
if (val == null || val instanceof String) {
  // this if contains a check for null because null instanceof Type is always false.
  // If you want only non-null Strings, then just use "if (val instanceof String)"
  String dexListTempString = (String)val;
  // ...
}


text:
Q: Keep static class members in python multiprocessing I'm trying to keep a "static" defined multiprocessing Queue through multiple Processes, but it appears that this context is not copied to the new spawned process. Is there a way to keep them without storing them to derived process classes (so without self.q = A.q)?
main.py
from class_b import B

if __name__ == "__main__":
    b = B()
    b.start()

    while True:
        pass

class_a.py
from multiprocessing import Process, Queue

class A(Process):
    q = Queue()

    def __init__(self) -> None:
        super().__init__(daemon=True)

class_b.py
from multiprocessing import Process
from class_a import A

class B(Process):

    def __init__(self):
        super().__init__(daemon=True)
        print(A.q)

    def run(self):
        print(A.q)

console
<multiprocessing.queues.Queue object at 0x000001F77851B280>
<multiprocessing.queues.Queue object at 0x0000023C420C2580>

A: When you import from class_a.py to access A.q, then so does multiprocessing in its own process. Then there will be two copies. You should create it as a local in "main" and pass it into B.
from class_b import B
from multiprocessing import Queue

if __name__ == "__main__":
    q = Queue()
    b = B(q)
    b.start()

    while True:
        pass

Then make B store that reference for itself:
from multiprocessing import Process

class B(Process):

    def __init__(self, q):
        super().__init__(daemon=True)
        print(q)
        self.q = q

    def run(self):
        print(self.q)


text:
Q: How can I shuffle the indices of certain variables? I am recursively defining rational expressions in two sets of variables $x_i$ and $y_i$.  Specifically, for $m<n$, I am interested in replacing all degree-$m$ monomials of the following form: $$\prod_{i=1}^m \xi_i, \text{ where }\xi_i \in \{x_i,y_i\}.$$
I need to code the replacement rule $$\prod_{i=1}^m \xi_i \mapsto \sum_\sigma\prod_{j=1}^n \zeta_j, \text{ where }\zeta_j \in \{x_j,y_j\};$$ this sum is over all functions ("shuffles"?) $\sigma:[m]\rightarrow [n]$ where $\sigma(1)<\cdots <\sigma(m)$, and the replacement rule is: $$\zeta_j = \begin{cases} y_j,&\sigma(i)=j \: \text{ and } \:\xi_i=y_i\\x_j & \text{else}.\end{cases}$$
If I knew how to code such a shuffle function $\sigma:[m]\rightarrow [n]$, then maybe I could use Replace and be fine, but short of that, implementing the sum over the shuffles is beyond my current knowledge.  Is there a good approach to coding this up, or should I somehow reformulate my notation to make it more amenable to Mathematica?


text:
Q: How to encrypt actual storage/volume used by containers in Kubernetes environment? In case of cloud managed kubernetes, whether AWS EKS, Azure AKS or Google GKE, the option to use customer managed key always comes at the cost of storing the customer master key in the cloud provider's own vault/KMS (e.g. aws kms or azure vault). In this case the cloud provider still has access to customer encryption key (or at least it resides in the cloud environment).
What would be an ideal implementation for deploying the application in k8s environment and encrypting the storage with customer provided key but the knowledge of the keys should only be at customer side i.e. not stored anywhere inside the cloud provider due to privacy concerns?

A: You could use a 3rd party kubernetes storage provider like portworx that will take you across clusters and keep data encrypted.
https://docs.portworx.com/portworx-install-with-kubernetes/storage-operations/create-pvcs/create-encrypted-pvcs/


text:
Q: Trying to improve Encode::decode warning message: Segfault in $SIG{__WARN__} handler I am trying to improve the warning message issued by Encode::decode(). Instead of printing the name of the module and the line number in the module, I would like it to print the name of the file being read and the line number in that file where the malformed data was found. To a developer, the origial message can be useful, but to an end user not familiar with Perl, it is probably quite meaningless. The end user would probably rather like to know which file is giving the problem.
I first tried to solve this using a $SIG{__WARN__} handler (which is probably not a good idea), but I get a segfault. Probably a silly mistake, but I could not figure it out:
#! /usr/bin/env perl

use feature qw(say);
use strict;
use warnings;

use Encode ();

binmode STDOUT, ':utf8';
binmode STDERR, ':utf8';

my $fn = 'test.txt';
write_test_file( $fn );

# Try to improve the Encode::FB_WARN fallback warning message :
#
#   utf8 "\xE5" does not map to Unicode at <module_name> line xx
#
# Rather we would like the warning to print the filename and the line number:
#
#   utf8 "\xE5" does not map to Unicode at line xx of file <filename>.

my $str = '';
open ( my $fh, "<:encoding(utf-8)", $fn ) or die "Could not open file '$fn': $!";
{
    local $SIG{__WARN__} = sub { my_warn_handler( $fn, $_[0] ) };
    $str = do { local $/; <$fh> };
}
close $fh;
say "Read string: '$str'";

sub my_warn_handler {
    my ( $fn, $msg ) = @_;

    if ( $msg =~ /\Qdoes not map to Unicode\E/ ) {
        recover_line_number_and_char_pos( $fn, $msg );
    }
    else {
        warn $msg;
    }
}

sub recover_line_number_and_char_pos {
    my ( $fn, $err_msg ) = @_;

    chomp $err_msg;
    $err_msg =~ s/(line \d+)\.$/$1/;  # Remove period at end of sentence.
    open ( $fh, "<:raw", $fn ) or die "Could not open file '$fn': $!";
    my $raw_data = do { local $/; <$fh> };
    close $fh;
    my $str = Encode::decode( 'utf-8', $raw_data, Encode::FB_QUIET );
    my ($header, $last_line) = $str =~ /^(.*\n)([^\n]*)$/s;
    my $line_no = $str =~ tr/\n//;
    ++$line_no;
    my $pos = ( length $last_line ) + 1;
    warn "$err_msg, in file '$fn' (line: $line_no, pos: $pos)\n";
}

sub write_test_file {
    my ( $fn ) = @_;

    my $bytes = "Hello\nA\x{E5}\x{61}";  # 2 lines ending in iso 8859-1: åa
    open ( my $fh, '>:raw', $fn ) or die "Could not open file '$fn': $!";
    print $fh $bytes;
    close $fh;
}

Output:
utf8 "\xE5" does not map to Unicode at ./p.pl line 27
, in file 'test.txt' (line: 2, pos: 2)
Segmentation fault (core dumped)

A: Here is another way to locate where the warning fires, with un-buffered sysread
use warnings;
use strict;

binmode STDOUT, ':utf8';
binmode STDERR, ':utf8';

my $file = 'test.txt';
open my $fh, "<:encoding(UTF-8)", $file or die "Can't open $file: $!";

$SIG{__WARN__} = sub { print "\t==> WARN: @_" };

my $char_cnt = 0;
my $char;

while (sysread($fh, $char, 1)) {
    ++$char_cnt;
    print "$char ($char_cnt)\n";
}

The file test.txt was written by the posted program, except that I had to add to it to reproduce the behavior -- it runs without warnings on v5.10 and v5.16. I added \x{234234} to the end.  The line number can be tracked with $char =~ /\n/.
The sysread returns undef on error. It can be moved into the body of while (1) to allow reads to continue and catch all warnings, breaking out on 0 (returned on EOF).
This prints

H (1)
e (2)
l (3)
l (4)
o (5)

 (6)
A (7)
å (8)
a (9)
        ==> WARN: Code point 0x234234 is not Unicode, may not be portable at ...
 (10)

While this does catch the character warned about, re-reading the file using Encode may well be better than reaching for sysread, in particular if sysread uses Encode.
However, Perl is utf8 internally and I am not sure that sysread needs Encode.
Note. The page for sysread supports its use on data with encoding layers

Note that if the filehandle has been marked as :utf8 Unicode
  characters are read instead of bytes (the LENGTH, OFFSET, and the
  return value of sysread are in Unicode characters). The
  :encoding(...) layer implicitly introduces the :utf8 layer.
  See binmode, open, and the open pragma.

Note   Apparently, things have moved on and after a certain version sysread does not support encoding layers.  The link above, while for an older version (v5.10 for one) indeed shows what is quoted, with a newer version tells us that there'll be an exception.


text:
Q: How to use GELF HTTP input I'm trying to setup a GrayLog2 server and need to use the GELF HTTP input listener. I've made a small C# console program which sends test logs to the server. However it seems that only a couple of messages are actually parsed by gl2 and I cannot figure out why. E.g. the follwing program should create 5 logs pr. second. Gl2 maybe picks up 1 or 2 logs in total, no matter how long it runs. Has anyone succesfully used the GELF HTTP input and what am I missing here?
do
{
    var client = new RestClient("http://10.8.0.39:12201");
    var request = new RestRequest("gelf", Method.POST);
    request.RequestFormat = DataFormat.Json;
    var glog2 = new GLogEntry
    {
        host = "example.org",
        short_message = "Short message...",
    };
    request.AddBody(glog2);
    client.ExecuteAsync(request, r => { });
    Thread.Sleep(200);
} while (1 == 1);


text:
Q: Django HTTP Request get vs getlist behavior I had a Django form that submitted a list of values to my view. I first tried retrieving the list using the get method but discovered that it only returned the last one and I should be using getlist. After some stumbling around I found a closed Django bug that explained the motivation for this behavior:

The reasoning behind this is that an API method should consistently return either a string or a list, but never both. The common case in web applications is for a form key to be associated with a single value, so that's what the [] syntax does. getlist() is there for the occasions (like yours) when you intend to use a key multiple times for a single value.

I'm just wondering whether this is actually a best practice - it contradicts the way the get method works on other data structures, ie. dictionaries.

A: HTTP requests do support multiple values assigned to a one parameter (key). That's why people can use them and do (sometimes) use them. That's also why Django introduced the MultiValueDict structure.
Division into get() and getlist() is beneficial, because it helps you avoid errors and keeps your view code simple. Consider other behaviors, they all require more code to do exactly the same thing:

*

*get() always returning list.
In most use cases you pass just one value to a one key, so you would need to add [0] and provide default value as a list.
param = request.GET.get('param', ['default value',])[0]

*get() returning single value or a list, depending on number of values.
It is a drawback in HTML selects with multiple options allowed. People can select zero, one or more values. That means you'll need to convert single value to list or in opposite direction by yourself:
 params = request.GET.get('params', [])
 # Here you have absolutely no idea if this is a list or a single value
 # But you will need only one of that types

 # If you need list: ---------------------------------
 if not isinstance(params, list):
     params = [params,]

 objs = TestModel.objects.filter(id__in=params).all()

 # If you need single value: -------------------------
 if isinstance(params, list):
     params = params[0]   # Error if params is empty list...

obj = TestModel.objects.get(id=params)

*

*get() always returning single value. So how do you handle multiple values without getlist in that case?

So to answer your question there is an added value of get/getlist behaviour.


text:
Q: MySQL Workbench can see schema but not query I am running a MySQL Database on Amazon RDS (AWS). I have a Tomcat Server that can access the Database, so I know the Database is fine.
I am using MySQL Workbench, and have a local MySQL Server running. The MySQL Workbench can access the local MySQL server fine.
Then I connect MySQL Workbench to the remote MySQL Database (AWS RDS). The schema is visible and I can see all the tables. However, as soon as I try run a SQL statement against the Database, it just hangs.  I did originally create and populate the database from the same MySQL Workbench connection.
I am running locally on a MacOS. I have to Force Quit SQL Workbench.
If anyone can suggest what I can do to run SQL I would appreciate the advise.


text:
Q: I can't understand the order of the polynomial I'm reading a book called Bishop - Pattern Recognition and Machine learning.

M is the order of the polynomial.
I can't understand it. How can I find M? What's number M?

A: The order of the polynomial ($M$) is the highest exponent of $x$ that appears in the expression of the polynomial. For example, $x^2$ is a degree-2 polynomial and $1+3x+3x^2+x^3$ is a degree-3 polynomial


text:
Q: Unbalanced equipartitions Let $K$ be a compact convex set in the plane.
Say that a perimeter-halving partition of $K$
is a partition of $K$
into two pieces by a chord (a segment with endpoints
on the boundary $\partial K$) each of which includes
half of the perimeter of $K$.
For conciseness, call a perimeter-halving partition
an equipartition.
I am interested in equipartitions that leave the areas
of the two pieces unbalanced:
equal icing but unequal cake in the cake-cutting analogy.
For example, partitioning an equilateral triangle with
an altitude is an equipartition but also partitions the
area into equal halves.
Here is an equipartition that leads to one piece with
about 56% of the area and the other 44%
(if I've calculated correctly):

For a given $K$, finding the most unbalanced equipartition
seems like an interesting algorithmic challenge.
But my questions are a bit different:

Q1. Which shapes $K_{\mathrm{ext}}$ permit the most
  extreme unbalanced partition, in that the area ratio
  of the two halves is maximized over all shapes?

Perhaps $K_{\mathrm{ext}}$ is degenerate, only achieved in the limit?
Now consider repeated equipartitions.
Suppose your goal is to end up with the largest area piece
after $n$ equipartitions starting from a given $K=K_0$.
A natural strategy is to use the most unbalanced equipartition
on $K_0$, and to let $K_1$ be the larger-area half of
that 1st equipartition. Then use the most unbalanced equipartition
on $K_1$, and to let $K_2$ be the larger-area half of
that 2nd equipartition.
And so on, always at each step using the most unbalanced
equipartition and selecting the larger-area half for the next step,
ultimately leading to $K_n$.

Q2.
  Is that strategy optimal, or might it sometimes be better
  (resulting in a larger area $K_n$)
  to not use the most unbalanced equipartition at some step,
  or to select
  the smaller-area half for the next step?

One can ask similar questions reversing the roles
of perimeter and area. And the questions
may be generalized to $\mathbb{R}^d$.

Addendum. To answer a question in a now-deleted comment, the
context here is that any perimeter-halving of a convex polygon
results in a convex polyhedron when the two perimeter halves are
identified (glued together). For example, here is the polyhedron that results
from a particular perimeter-halving of a regular duodecagon:

This is Fig.25.40 (p.413) in Geometric Folding Algorithms.
More generally, a perimeter-halving folding of a convex shape $K$ results in a
convex body in $\mathbb{R}^3$.
I was seeking to understand how different can be the "top" and "bottom" of
the folded shape. The repeated-equipartitions question was primarily curiosity
in the same intellectual vicinity.


text:
Q: Scala & Spark: Querying native SQL without a registered tempview Is there a way to execute an SQL statement (including SELECT, FROM, WITH and different types of JOINs) without the need for registering a temp view priorly in Spark using Scala? The goal is to get a DataFrame without any detours from SQL code.
An example how it works (using an existing DataFrame and registering a tempview) is provided by the documentation:
// df is an existing DataFrame
df.createOrReplaceTempView("people")
val sqlDF = spark.sql("SELECT * FROM people")
sqlDF.show()

The problem with an existing DataFrame is, that only sub quantities of the underlying DataFrame, used for generating the tempview, can be selected. This becomes very impractical if the SQL statements use data from many different tables or Views. Something like
// SQL is directly executed on database
val dfView = spark.sql(connectionProperties,
                       "SELECT *
                        FROM DATABASE_USER.V_VIEW_IN_DATABASE v1
                        JOIN DATABASE_USER.V_VIEW2_IN_DATABASE v2
                        ON v1.key = v2.key")
dfView.show()

with automatic type inference would solve my problem. I'm chasing one potential path pointed out in this question.
Setup: Hadoop v.2.7.3, Spark 2.0.0, Intelli J IDEA 2016.2, Scala 2.11.8, Testcluster on Win7 Workstation, Oracle 12c database

A: Try:
import org.apache.spark.ml.feature.SQLTransformer

val df = spark.read.format("jdbc")
         .options(Map("url" -> "jdbc:postgresql://<server>:<port>/<db>?user=<user>&password=<password>", "dbtable" -> "<dbtable>"))
         .load()
val ans = new SQLTransformer()
    .setStatement("SELECT value + id AS points FROM __THIS__")
    .transform(df)
ans.show()

+------+
|points|
+------+
| 101.0|
| 202.0|
+------+

If you want some sugar coating:
object ImprovedDataFrameContext {
    import org.apache.spark.ml.feature.SQLTransformer

    implicit class ImprovedDataFrame(df: org.apache.spark.sql.DataFrame) {
        def T(query: String): org.apache.spark.sql.DataFrame = {
            new SQLTransformer().setStatement(query).transform(df)
        }
    }
}
import ImprovedDataFrameContext._

val df = spark.read.format("jdbc")
         .options(Map("url" -> "jdbc:postgresql://<server>:<port>/<db>?user=<user>&password=<password>", "dbtable" -> "<dbtable>"))
         .load()
         .T("<sql_query>")
         .show()

+------+
|points|
+------+
| 101.0|
| 202.0|
+------+


text:
Q: Solving this ODE through derivatives? I'm currently trying to solve a more complex system of ODE. In order to understand the environment more, I've simplified stuff a bit, such that I have arrived at
$$ \alpha F(x) = G(x) + F_x(x)\cdot(H(x, F(x)) $$
where I need to solve for $F$. $G$ and $H$ are known, and $\alpha > 0$. I can I can write this equation as - with $A_i$ denoting different non-zero constants -
$$ \alpha F(x) = \frac{A_0}{(A_0 + xA_1)^2}A_5 + F_x(x) \cdot \left[(1-x)A_2 + x \left(1-\left(\frac{A_4}{F(x)}\right)^\phi\right)^\frac{1}{\phi}\right] $$
My plan was to take the derivative w.r.t. $x$ several times, and hope that something cancels out, such that I get a clear representation for the i-th derivative of $F_x$, and then would work backwards.
However, even the central term, doesn't cancel out eventually as far as I can see.
$$ G(x) = \frac{A_0}{(A_0 + xA_1)^2}\\
G_x(x) = \frac{-2A_0 (A_0 + xA_1)A_1}{(A_0 + xA_1)^4} = \frac{-2A_0A_1}{(A_0 + xA_1)^3} = -2A_1\frac{G(x)}{(A_0 + xA_1)}\\
G_{xx}(x) = \frac{-2A_0A_1 3 (A_0 + xA_1)^2A_1}{(A_0 + xA_1)^6} = \frac{-2\cdot3A_0A_1A_1}{(A_0 + xA_1)^4} = 3A_1\frac{G_x(x)}{(A_0 + xA_1)}\\
G_{xxx}(x) = \frac{-2A_0A_1A_1 3 \cdot 4(A_0 + xA_1)^3A_1}{(A_0 + xA_1)^{8}} = \frac{-2A_0A_1A_1A_1 4\cdot 3}{(A_0 + xA_1)^5} = \frac{4A_1G_{xx}(x)}{(A_0 + xA_1)}$$
Such that, in general, for the ith partial derivative ($i > 1$), I believe it is true that
$$ \frac{\partial^i G(x)}{\partial x^i} = \frac{(i+1)A_1}{(A_0 + xA_1)} \frac{\partial^{i-1} G(x)}{\partial x^{i-1}}$$
This means that I can never take sufficiently many derivatives of $F(x)$ w.r.t. $x$ and hope that eventually stuff cancels out, or does it? How should I approach this problem?


text:
Q: jQuery UI Drag and Drop - expand height of drop area on hover I am trying to expand the height of a drop area using jQuery UI's drag and drop functionality and it doesn't seem to be working as I would expect.  Please see the following fiddle:
http://jsfiddle.net/pn226rj9/
Note that I am expanding the height from 10px to 120px on hover:
.ui-state-hover {
    height:120px !important;
}

What I would expect to happen is that when the drop area height grows, that becomes the 'new' height of the drop area and I can now hover over that entire area while still being in a hover state.
However, it looks like jQuery is remembering the original height of the drop area and treating that as the de facto height regardless of what I change it to.  This results in the hover state going away while appearing to still be in the drop area.
Is there anyway to make jQuery recognize this new height?

A: Set the refreshPositions attribute to true...
$("#draggable").draggable({ refreshPositions: true});

http://jsfiddle.net/pn226rj9/3/