text:
Q: OnException is not called on production server I have an MVC 4 application in which the base controller overrides the OnException method as below. Everything works fine in development (IIS Express 8.5) but the method is not called once the app is deployed to production (2012 R2/IIS 8.5). The user sees the standard YSOD error message.
public override void OnException(ExceptionContext filterContext)
{
   //Code here
}

I have confirmed that the web.config files for both applications are identical. The CustomErrors section of the web.config file is set to "On"
   <customErrors mode="On" />

I have compared the application files very carefully and there are no differences in the deployments. I am expecting the issue is in an IIS setting that I cannot seem to locate via Google or by poking around.
Thanks for your help!

A: An exception raised within the OnException method may cause your application to behave as if that method is not being called. My problematic implementation included a call to save off the error message to a custom Windows error log, but the execution permissions assigned to the IIS application pool's identity where inadequate to create the new event log source. Once I removed the logging logic, the issue resolved. Here are the details. (I have since added the logging logic back once I proved this works).
This is what worked for me:
First, ensure that web.config is configured properly. Two snippets to pay attention to are:
<system.web> <customErrors mode="On" /> </system.web>

and
<system.webServer>
     <httpErrors errorMode="DetailedLocalOnly" />
</system.webServer>

Second, the following is in my base controller, from which all other controllers in the application inherit:
        protected override void OnException(ExceptionContext filterContext)
        {
            if (filterContext.ExceptionHandled)
            {
                return;
            }

            filterContext.Result = Error(filterContext.Exception.Message,filterContext.Exception.StackTrace);
            filterContext.ExceptionHandled = true;
        }

        public ActionResult Error(string Message, string StackTrace, string ReturnUrl)
        {
            ViewBag.ErrorMessage = Message;
            ViewBag.StackTrace = StackTrace;
            ViewBag.ReturnUrl = ReturnUrl;

            return View("~/Views/Shared/MyError.cshtml");
        }


text:
Q: Trying to POST from Postman - getting 405 error in Flask REST API Trying to use Postman to test and see if my post method of an API I'm building works. I keep getting a 405 error, suggesting to me that the functionality of posting isn't even available. But it's a pretty straightforward class, so I can't see what's wrong.
from flask.views import MethodView
from flask import jsonify, request, abort

class BookAPI(MethodView):

    books = [
        {"id":1, "title":"Moby Dick"},
        {"id":2, "title":"Grapes of Wrath"},
        {"id":3, "title":"Pride and Prejudice"}
    ]

    def get(self):
        return jsonify({"books": self.books})

    def post(self):
        if not request.json or not 'title' in request.json:
            abort(400)

        book = {
        "id": len(self.books) + 1,
        "title": request.json['title']
        }

        self.books.append(book)
        return jsonify({'book':book}), 201

The get method is working fine. I can see it on my localhost. But when I try to post to my localhost with postman - 405 error
This is all I'm posting to http://localhost/books/
{
   "title": "Frankenstein"
}

A: Thanks for the additional details, I tried running your application and it does work for me, the only change I made is the actual URL. You have registered your books api under the /books prefix. This is the specific place in your code https://github.com/branhoff/wishlist-api/blob/ee9fc696069d98513a89c249d23874d429684d54/book/views.py#L7
curl -X POST -H "Content-Type: application/json" -d '{"title": "GoT"}' http://localhost:80/books/

redpajama_set_name: RedPajamaStackExchange


text:
Q: reference SVG cursor from the same document I want to use a custom cursor in my SVG file.
The cursor is defined in the same SVG file as the rest of my document:
<defs>
  <g id="cursor-symbol">
     <circle fill-opacity="0.8" fill="white" r="10.0" cx="10.0" cy="10.0" stroke="black" stroke-width="2.0" stroke-opacity="1"/>
     <line y2="20.0" x1="10.0" x2="0.0" transform="rotate(45.0, 10.0, 10.0)" y1="10.0"/>
  </g>
</defs>

Then I tried to use that cursor, but can't find out how to reference it:
<rect cursor="url(#cursor-symbol)" x="0" y="0" width="100" height="100" />

The attribute value seems to be invalid.
I also created a cursor element and tried with that:
<defs>
  <g id="cursor-symbol">
    <circle fill-opacity="0.8" fill="white" r="10.0" cx="10.0" cy="10.0" stroke="black" stroke-width="2.0" stroke-opacity="1"/>
    <line y2="20.0" x1="10.0" x2="0.0" transform="rotate(45.0, 10.0, 10.0)" y1="10.0"/>
  </g>
  <cursor id="cursor" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#cursor-symbol"/>
</defs>
...
<rect cursor="url(#cursor)" x="0" y="0" width="100" height="100" />

but to no avail.
How to I reference such a cursor that is defined in the same document?


text:
Q: Convert query result from struct to string for another Golang package I have searched for a solution on the net and in SO, but found nothing that apply to return values. It is a simple sql query with several rows that I want to return. Error handling not included:
func Fetch(query string) (string) {

    type User struct{
        id string
        name string
    }

    rows, err := db.Query(query)

    users := make([]*User, 0)
    for rows.Next() {
      user := new(User)
      err := rows.Scan(&user.id, &user.name)
      users = append(users, user)
    }

    return(users)
}

I get this error when compiling:

cannot use users (type []*User) as type string in return argument

How should I do to get a correct return value?
The expected input is

JD John Doe --OR-- {id:"JD",name:"John Doe"}

A: Add this to your code:
type userSlice []*User

func (us userSlice) String() string{
    var s []string
    for _, u := range us {
        if u != nil {
            s = append(s, fmt.Sprintf("%s %s", u.id, u.name))
        }
    }
    return strings.Join(s, "\n")
}

type User struct{
  id string
  name string
}

In your Fetch function replace the last return statement like this:
func Fetch(query string) (string) {
  // Note that we declare the User type outside the function.
  rows, err := db.Query(query)

  users := make([]*User, 0)
  for rows.Next() {
    user := new(User)
    err := rows.Scan(&user.id, &user.name)
    users = append(users, user)
  }

  return(userSlice(users).String()) // Replace this line in your code
}

A: If you have to return a String you can use the encoding/json package to serialize your user object, but you have to use fields that begin with capital letters for them to be exported. See the full example:
import (
    "encoding/json"
)

func Fetch(query string) (string) {

    type User struct{
        Id string  // <-- CHANGED THIS LINE
        Name string // <-- CHANGED THIS LINE
    }

    rows, err := db.Query(query)

    users := make([]*User, 0)
    for rows.Next() {
      user := new(User)
      err := rows.Scan(&user.id, &user.name)
      users = append(users, user)
    }

    return(ToJSON(users)) // <-- CHANGED THIS LINE
}

func ToJSON(obj interface{}) (string) {
    res, err := json.Marshal(obj)
    if err != nil {
      panic("error with json serialization " + err.Error())
    }
    return string(res)
}


text:
Q: Attach command with parameter to KeyUp event I am currently transforming a medium size WPF project to MVVM and I ran into a problem that I wasn't able to solve, yet. Maybe you could help me out?
The target framework is .NET 3.5.1.
I have a list view that gets its items from the underlying view model. That view model is exposing a command to remove the selected items from the list view. Therefore the command parameter is bound to the SelectedItems property of the list view.
<ListView ItemsSource="{Binding MyItems}"
          x:Name="MyListView"
          SelectionMode="Extended">
</ListView>
<Button x:Name="MyRemoveButton"
        Content="Remove item"
        Command="{Binding RemoveItemCommand}"
        CommandParameter="{Binding ElementName=MyListView, Path=SelectedItems}">

My intention is to execute this command not only when pressing a button, but also when the KeyUp event is fired on the list view and the pressed key is "delete".
I was close to finding the solution when I stumbled upon interaction triggers in this example:
http://joyfulwpf.blogspot.com/2009/05/mvvm-invoking-command-on-attached-event.html?showComment=1250325648481#c3867495357686026904
Now the problem with this demo is that the command parameter is the pressed key, but in my case I need the command parameter to be the SelectedItems property and I need the command to execute only on a specific key.
Is there any way to do this without much overhead and in the MVVM way?
Something like this would be awesome:
<i:Interaction.Triggers>
   <i:EventTrigger EventName="KeyUp">
      <local:CommandAction Command="{Binding RemoveItemCommand}"
                           CommandParameter={Binding ElementName=MyListView, Path=SelectedItems}
                           EventArgument="Key.Delete"/>
   </i:EventTrigger>
</i:Interaction.Triggers>

A: To do it in the MVVM way you need to bind "SelectedItems" property of the ListView to your ViewModel, so you could use it from your commands and wouldn't need to pass it via CommandParameter.

A: How strict is your separation requirement? If you don't have designers using Blend, then put a call to a ViewModel method into the KeyUp or PreviewKeyUp event handler in your code-behind.


text:
Q: Double randomly adds 0.000000000000001 I have this code:
double timeTillTick = 15.0;
private void lower_Tick(object sender, EventArgs e)
{
    if (timeTillClear > 0)
    {
        timeTillClear -= 0.1;
        clearingIn10SecondsToolStripMenuItem.Text = "Clearing in " + timeTillClear + " seconds.";
    }
    else
    {
        lower.Enabled = false;
    }
}

lower ticks once every 100 milliseconds. When it:

*

*Gets to 8

*Gets to 5

*Gets to 1

it increases by 0.000000000000001. Why?

A: Much like 1/3 cannot be represented exactly using decimal notation (0.333333...), 0.1 cannot be represented exactly as floating point number, which is internally using binary notation (aka IEEE-754). That's why you get that inherent error.


text:
Q: Pingfederate IdP Discovery I am looking to do IdP Discovery and i need to do this with Pingfederate Software. End Goal here is customers will request access to a resource. Then get redirected to an IdP where they see a logon form ... input their email address and then depending on their email domain they get redirected to another IdP where authentication will take place. SAML Assertion will get posted back and the customer can then access the application.
I know pingfederate has persistent cookie etc but i dont think this will work well. Has anyone tried IdP Discovery in Pingfederate?

A: The PingFederate Standard IdP Discovery is a cookie based mechanism that identifies the IdP, or matching of entityID to IdP. We have used the OOTB PingFederate capability and found it does work well for certain use cases and business requirements for user experience. This blog describes alternative approaches that are popular within industry to accomplish IdP Discovery. We have found that most service providers tend to use one of the forms of IdP Discovery described in the blog.  The real driver for the implementation approach is business requirements for user experience. For PingFederate, if you choose not to use the out of the box cookie mechanism, then you will need to implement one of the other design patterns. I do know that there are Ping System Integration partners that have expertise and implementations of each of the design patterns described.


text:
Q: Confusion regarding K-fold Cross Validation In K fold cross validation, we divide the dataset into k folds, where we train the model on k-1 folds and test the model on the remaining fold. We do so until all the folds were assigned as the test set. In every of these iterations, we will train a new model that is independent of the model created from the previous iteration ( every iteration uses a new instance of the model). So my question is, if I divide my dataset into train and test sets, then I have used only the training set for the k cross validation process, and since every iteration uses a new model, what is the output model from this k fold cross validation process that I should use to evaluate it ( calculates the ROC curve, F1-score, precision and so on) using the test set ??  (As I have different models for every iteration). One way to implement k fold cross validation is to use sklearn.model_selection.cross_val_score and this returns only an array of scores of the model for each run of the cross validation and this confirms my problem, where there is no model is  returned to be further evaluated by the test set. What should I do in this case ?

A: If you use K-fold cross validation (CV) for hyper parameter tuning, you should train a single model on the entire training set with the best found hyper-parameters and test on the test set.
If you use K-fold CV for performance evaluation (like in sklearn cross_val_score), then you don't need to split your dataset into train/test. The performance reported in each fold will be a test performance. People usually average them or get all the predictions and then evaluate the entire dataset. This is usually done to assess performance when the dataset is small and there isn't a single model output for this case, nor the aim is to have it.


text:
Q: Azure login cli for github actions without subscrition I was reading this documentation https://github.com/azure/login#configure-a-service-principal-with-a-federated-credential-to-use-oidc-based-authentication
And I have found that we can use azure login cli with allow-no-subscriptions parameter.
So my question is that what is the purpose of this parameter? although we have already defined the subscription id in the repository's secret when we can run this command
az ad sp create-for-rbac --name "myApp" --role contributor \
                            --scopes /subscriptions/{subscription-id}/resourceGroups/{resource-group} \
                            --sdk-auth

Because it outputs, subscription id, tenant id, secret id, client id.
Surprisingly, if I create app registration through azure portal I get an error
Error: : No subscriptions found for ***.
Error: Az CLI Login failed. Please check the credentials and make sure az is installed on the runner. For more information refer https://aka.ms/create-secrets-for-GitHub-workflows

Although the subscription id well defined in the secrets.
And if I just use that parameter
allow-no-subscriptions=false

Then I have no issue and it works like charm.

A: For creating rbac from your local machine you need to upgrade az module and need to login Azure CLi using  az login
az upgrade , az login

 az ad sp create-for-rbac --name "myApp" --role contributor \
                            --scopes /subscriptions/{subscription-id}/resourceGroups/{resource-group} \
                            --sdk-auth

*The service principle is mapped to contributor role and subscription scope. *
Please find the below screenshot

For reference, please check this Az CLI Login failed. Please check the credentials and make sure az is installed on the runner


text:
Q: How to use directory paths stored in property file in ANT dirset or fileset? I need to store some directory paths in property files for ant. So I have file that contains for example:
plugins.system=plugins\\whatever
plugins.content=plugins\\example

this.is.fine=plugins
this.also.does.not.work=plugins/example

The problem is, that dirset or fileset does not find the directory. I belive, that it's due escaping. When I set property directly in build.xml without double slashes it works fine. Is there any way how to "unescape" properties when I load them?
Thank you for answer.


text:
Q: Xamarin Forms MasterDetailPage MasterBounds can someone tell me how to edit the value for MasterBounds in XF-MasterDetailPage.
My changes have no effect (MasterDetailPageRenderer/Android):
protected override void OnLayout(bool changed, int l, int t, int r, int b)
{
  base.OnLayout(changed, l, t, r, b);
  if (page != null && page.MasterBehavior == MasterBehavior.Split)
  {
    if (((IMasterDetailPageController)page).MasterBounds.Y > 0)
    {
      Rectangle rect = ((IMasterDetailPageController)page).MasterBounds;
      rect.Y = 0;
      ((IMasterDetailPageController)page).MasterBounds = rect;
    }
  }
}

I need to do this, because the value for Y is wrong on some Devices, so there is a bit of space at the top.
Thanks!

A: In case someone else needs this, here is the solution:
public override void AddView(Android.Views.View child)
{
  child.GetType()?.GetProperty("TopPadding")?.SetValue(child, 0);
  base.AddView(child);
}


text:
Q: Does Mixpanel Analytics for Android work when offline? I know that flurry tracks offline data from android sessions but I want to try mixpanel. Has anybody used mixpanel for offline apps?

A: I worked on the Android library at Mixpanel, and I can tell you that we will safely queue up your Mixpanel data when there is no Internet connection available. It will be sent out the next time an Internet connection is available.


text:
Q: My strategy.entry() is not executing at all I've just recently started pine scrip and I wrote this code backtest a strategy, however the strategy.entry() function seems not to be working. I've even changed it such that it has nothing to do with the rest of the code at all and it still doesn't work. I'm wondering if anyone knows what might be stopping my strategy.entry() to not working at all.
strategy("Higher High", overlay=true, calc_on_every_tick=true, initial_capital=5000, currency='USD', commission_type=strategy.commission.cash_per_order, commission_value=10, pyramiding=50)
Period = input.int(7,"Pivot Point Period", minval = 1)
showSR = input(defval = true, title="Show Support/Resistance Level Extensions")
showPP = input(defval = true, title="Show Pivot Points Labels")
ShowFB = input(true, title="Show Fractal Break Arrows")

float pivotHigh = na //swing high
float pivotLow = na //swing low
pivotHigh := ta.pivothigh(Period, Period)
pivotLow := ta.pivotlow(Period, Period)

valuewhen_1 = ta.valuewhen(pivotHigh, high[Period], 1) // return the most recent occurence of a condition; in this case, the most 2nd recent time (so the last-last time) there was a pivot high
valuewhen_2 = ta.valuewhen(pivotHigh, high[Period], 0) //returns the most recent pivot high
higherhigh = na(pivotHigh) ? na : valuewhen_1 < valuewhen_2 ? pivotHigh : na //higher high returns the price of the most recent pivot high IF it is greater than the last pivot high
lowerhigh = na(pivotHigh) ? na : valuewhen_1 > valuewhen_2 ? pivotHigh : na
valuewhen_3 = ta.valuewhen(pivotLow, low[Period], 1)
valuewhen_4 = ta.valuewhen(pivotLow, low[Period], 0)
higherlow = na(pivotLow) ? na : valuewhen_3 < valuewhen_4 ? pivotLow : na
lowerlow = na(pivotLow) ? na : valuewhen_3 > valuewhen_4 ? pivotLow : na
////////////////

upTrend = close > high[1]
strategy.entry('Long', strategy.long, qty=10, when=upTrend, limit=close, comment = 'Long', oca_name = 'x', oca_type=strategy.oca.cancel)

////////////////
plotshape(showPP ? higherhigh  : na, title='HH', style=shape.triangledown, location=location.abovebar, color=color.new(color.green,50), text="HH",textcolor=color.new(color.green,50),offset = -Period)
plotshape(showPP ? higherlow  : na, title='HL', style=shape.triangleup, location=location.belowbar, color=color.new(color.green,50), text="HL",textcolor=color.new(color.green,50),offset = -Period)
plotshape(showPP ? lowerhigh  : na, title='LH', style=shape.triangledown, location=location.abovebar, color=color.new(color.red,50), text="LH",textcolor=color.new(color.red,50),offset = -Period)
plotshape(showPP ? lowerlow  : na, title='LL', style=shape.triangleup, location=location.belowbar, color=color.new(color.red,50), text="LL",textcolor=color.new(color.red,50),offset = -Period)

///showing the resistance and support (of pivot points)

float resistance = na
float support    = na
support    := pivotLow  ? pivotLow  : support[1]
resistance := pivotHigh ? pivotHigh : resistance[1]

plot(showSR and support    ? support    : na, color = showSR and support    ? color.new(color.teal,50) : na, style = plot.style_circles, offset = -Period)
plot(showSR and resistance ? resistance : na, color = showSR and resistance ? color.new(color.red,50)  : na, style = plot.style_circles, offset = -Period)

A: Fireshot, you only have entry calls in this strategy. Trades are executing, but we cannot calculate trades without closed trades. I have 50 open positions after pyramiding to your limit, they we have held since as we need to use strategy.exit, or strategy.close to exit a trade


text:
Q: Why do multiple font sizes display inside Plain TextBox? This is not a question about how to change the font size. Rather, why is the size of my font changing by itself as I type (or paste) when it's inside a plain TextBox control which, as you should know, only supports one color, one font, and one font size at any given time.
My code:
using(FontDialog d = new FontDialog())
{
   // The usual properties...
   if(d.ShowDialog() == DialogResult.OK)
   {
      textbox1.Font = d.Font;
   }
}

The font is set at 8pt. If I paste plain text into it, the top line will be 9 to 10pt while the bottom line is noticeably smaller (about 8 pt).
It doesn't matter which font, font style, or font size I choose; this keeps happening!

Update
Thanks for all your help thus far.To answer your recent questions below:
My app is targetting .NET 4.5.
There's no mix up in the code, since I was able to reproduce this problem in a new Windows Forms project with nothing but a Form, a TextBox and a Button that calls the FontDialog.
To answer the question about my Video drivers, I did require support for an app I purchased a few weeks ago and they told me to run DXDiag, they got back to me saying my Video Card driver is out of date, however I didn't think it was because I always check every few months. I then went to the manufacturer's website and it said that I already have the latest drivers installed for my system.
Windows Update also says there are no new available updates. I'll check for a new version of drivers again, though.

I also did a test in a new blank project where I display the font being used by the TextBox before calling FontDialog.ShowDialog(), and after it has been shown and after the new font has been set and everything matches - yet there is still the issues after changing font/font size inside the textbox.

A: I suspect that the High-DPI screen that you are using is not using an exact multiple of 96 DPI. When in this situation Windows renders your application to a virtual screen that is 96 DPI and then rescales the result to the new DPI. Having a DPI that is not an exact multiple of 96 can cause rounding errors when the application's display is rescaled and as a result fonts can end up looking uneven.
Try setting your DPI to one of the sizes in Appendix C of Microsoft's Writing High-DPI Win32 Applications guide.


text:
Q: Programatically generating contour map in Unity 3d over a flat surface I am working on a project in Unity3D in which I have to Generate a contour map from data obtained from formulas separately over a flat surface.
I have a simple  2d surface rotated in 3d. Imagine a surface such as this:
. . .
. . .
. . .
I want to generate (not just apply texture of a) contour on this surface on the basis of temperature data at different points on it. This not permanent and recalculation of data will show new contours.
Data of temperature will be mathematically created from formulas like this:

34 54 79
56 80 108
89 110 120

Is there any way to do this?
I am looking for possible technique and code that may help but any help in getting the desired result would be very helpful.

A: First, I would see here about how to create a heightmap of your model. From there, you have the contours found, you only need to include the texture and draw the lines. Since heightmaps are grayscale, it is easy to find the contours (or create a topographic map), if you use an approach similar to the one found here. You need only apply contours onto the texture, and you have your contour map.
Just to overview

*

*Create a heightmap

*Create a script to find the contours (probably using blob detection)

*Apply the contoured image (probably a binary image) onto the texture so the topographic lines are visible


text:
Q: How to add symbol or text to php variable I'm building a shortcode for woocommerce, I was wondering how I can add some text just before the $order_id variable.
Current code

 Order '. $order_id .'

Current output is Order: 39800
Output I want to get Order: #39800
I would like to add the pound sign (#) just before the number. Is there a specific way to do this? Also, does the same rule apply to text ?

A: I guess you can use

 Order #'. $order_id .'

or

 Order '. sprintf("#%d", $order_id) .'


text:
Q: Target values for neural network I've been using MATLAB's neural network toolbox to generate good for character recognition. I wanted to develop my own to compare against and also try and use different methods for weight updates. I've got the network to return only values between 0 and 1. I was wondering how I can adapt this so that the network returns say 1, 2, 3, 4; numbers corresponding to rows in my data matrix, where each row is a different letter.

A: Usually when talking about character multiple character recognition it is a good approach to instead of using only 1 output to use an output for each of the characters you have.
So if you have 10 characters (say digits from 0-9) you can have N inputs (1 per pixel) and 10 outputs (1 per character). Like that you can not only get a result, but analize how good is your NN tuned and how good is your result precision.
So if you input an image and the result is  [0.2 0.1   0.98   0.3 0.12 0.2 0.1 0.4 0.1 0.2] you know that the NN is pretty well tuned and the result is very accurate, but instead if you get [0.4 0.1 0.6 0.54 0.5 0.3 0.5 0.3 0.57 0.2] you know that even if the number seems to be the same as before, the fiability of the result is much lower.
Having said that you can just train you NN to give you a nu,ber from 0 to 1 for each case, if you still want to do it with 1 output.
 0 ->0
 1->0.1
 2->0.2
 ...

Still I can assure you that your result are going to be worse like this. Use 1 output from 0 to 1 for each digit!


text:
Q: Can't see my session values in the after login page I have a login page where when a username and password are correct, I save the id and username of the logged person in sessions:
$result = $conn->prepare("SELECT * FROM login WHERE username= :u AND password= :p");
$result->bindParam(':u', $user);
$result->bindParam(':p', $password);
$result->execute();
$rows = $result->fetch(PDO::FETCH_NUM);
if($rows > 0) {
    $_SESSION['username'] = $user;
    $_SESSION['login_id'] = $id_logged;
    header("location: ./pages/home.php");
}

In home.php I am trying to echo those 2 sessions:
<?php
require_once('../include/global.php');
$user = $_SESSION['username'];
$id_logged = $_SESSION['login_id'];
echo $dentist_user;
echo $id_logged;
?>

But I only see the username without its ID.
global.php code is:
<?php

session_start();

    $DB_host = "localhost";
    $DB_user = "";
    $DB_pass = "";
    $DB_name = "";
    if(!isset($_SESSION['username']) && !isset($_SESSION['login_id'])){
        header("Location: ../index.php");
    }
    else{
        try
        {
             $conn = new PDO("mysql:host={$DB_host};dbname={$DB_name}",$DB_user,$DB_pass);
             $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
             $conn->exec("SET CHARACTER SET utf8mb4");
        }
        catch(PDOException $e)
        {
             echo $e->getMessage();
        }
    }
?>


text:
Q: Cortana activation issues I've upgraded 3 computers to Win 10 successfully. One is a laptop and the other two desktops. Activating Cortana on the laptop worked fine. I moved on to one of the desktops and now I am having a problem. I am using my Hotmail/Outlook account as my Microsoft account to activate Cortana. On the desktop, I enter the user name and password, as I did on the laptop, click next and the next page wants me to enter my "old" password one more time. I re-enter the same password, since I assume that is what it is calling for, and click next. The next window tells me that my password is incorrect, but it is correct. I didn't have this issue with the laptop activation. Does anyone know why this might be happening? I need to solve this then activate Cortana on the second desktop PC. I'm frankly surprised that I have to enter all of this info on each computer. Maybe there is a way to sync Cortana, but I don't know if that is possible.
I also had the problem of no sound when I did the upgrade on one desktop PC, but I went online and downloaded the correct Win 10 driver and it works again. These have, so far been my only two issues.

A: This answer comes a week late but hopefully it might help someone who comes across the same issue.
When Cortana asks you to enter your old password one last time, enter the password of the account you are logged on to the computer. For example if you log on to the computer with username john and password 0x00FF00-is-Blue, type in that password.


text:
Q: Java как выдать уведомление в трее Windows 10 Необходимо выдать уведомление вроде этого
Как сделать подобное на java. Если есть костыль только для Windows то тоже подойдет
Пробовал это, но не получилось

A:
Пробовал это, но не получилось

Не очень информативно. Вот примерно такой же пример, но максимально упрощённый:
import java.awt.*;

public class Test {

public static void main(String[] args) throws Exception {
    if (SystemTray.isSupported()) {
        SystemTray tray = SystemTray.getSystemTray();

        java.awt.Image image = Toolkit.getDefaultToolkit().getImage("images/tray.gif");
        TrayIcon trayIcon = new TrayIcon(image);
        tray.add(trayIcon);
        trayIcon.displayMessage("Test.", "This is a message to test notifications in Windows 10",
                TrayIcon.MessageType.INFO);
    }
}

}
Вот снимок экрана после его запуска в среде разработки IntellyJ IDEA, под управлением Java 8, ОС Windows 10:

A: Попробуй, вот эту библиотеку TrayNotification, мне кажется это то, что тебе нужно


text:
Q: Strange Behavior with AWS S3 Lifecycle Policy As we know that we can not move objects to S3 IA or S3 IA One Zone only after passing 30 days.
So when we try to migrate those objects after one day in S3 for example.We will get this message:

Now.My question why this is not happening with Glacier.In fact,I could change the Lifecycle policy to make transition to Glacier even after one day in S3 Standard which is normally is not possible because Glacier request that objects are stored for at least 90 days.So we expect to get a message same like for S3 IA.

A:
My question is why this is not happening with Glacier.

Because this is only applicable for transitioning TO s3- standard-IA or s3 one zone IA. There is no limitation to transition TO Glacier
As per docs Before you transition objects from the S3 Standard or S3 Standard-IA storage classes to S3 Standard-IA or S3 One Zone-IA, you must store them at least 30 days in the S3 Standard storage class.

Glacier request that objects are stored for at least 90 days

There is misunderstanding on your part 90 days holds good when object is stored inside glacier stored class not for that object has to be stored for 90 days in other class
From docs

Number of days you plan to keep objects archived – S3 Glacier Flexible Retrieval and S3 Glacier Deep Archive are long-term archival solutions. The minimal storage duration period is 90 days for the S3 Glacier Flexible Retrieval storage class and 180 days for S3 Glacier Deep Archive.


text:
Q: Enforcing side effects in python Is there a tool that enables you to annotate functions/methods as "pure" and then analyzes the code to test if said functions/methods are side effect free ?

A: In the Python world, the question doesn't make much sense since objects have so much say in what happens in a function call.
For example, how could you tell if the following function is pure?
def f(x):
   return x + 1

The answer depends on what x is:
>>> class A(int):
        def __add__(self, other):
            global s
            s += 1
            return int.__add__(self, other)

>>> def f(x):
        return x + 1

>>> s = 0
>>> f(A(1))
2
>>> s
1

Though the function f looks pure, the add operation on x has the side-effect of incrementing s.


text:
Q: How to add all img in folder to CImage array element? I have some trouble with that problem ;(
I don't know how to add img to CImage array element.
I want like these operation to do.↓
    image[0].Load(_T("./data/notice.bmp"));
    image[1].Load(_T("./data/11.bmp"));
    image[2].Load(_T("./data/22.bmp"));
    image[3].Load(_T("./data/13.bmp"));
    image[4].Load(_T("./data/25.bmp"));
    image[5].Load(_T("./data/7.bmp"));
    image[6].Load(_T("./data/16.bmp"));
    image[7].Load(_T("./data/20.bmp"));
    image[8].Load(_T("./data/18.bmp"));
    image[9].Load(_T("./data/3.bmp"));
    image[10].Load(_T("./data/8.bmp"));

I want to add bmp files to CImage array named image!
I think maybe there is some way to do this at once. :0
I found 'dirent.h' on Google.
But I don't know how to use this correctly to do my work.. ;(
    DIR             *d;
    struct dirent   *dir;
    CImage image[MAX_IMAGE];
    d = opendir("./data/");
    int i=0;

    if(d)
    {
            while ((dir = readdir(d)) != NULL)
            {
                    i++;
                    image[i] = *dir->d_name;
            }
            closedir(d);
    }

There is occur some error
    image[i] = *dir->d_name;

How to get fix it? ;((

A: image is an array of elements of type CImage, dirent::d_name is of type char …[256].
Those two don't get together. I think you want to use something like
image[i].Load(dir->d_name);

but this is still rather bad style. You should use a std::vector<CImage> or a std::list<CImage> instead.


text:
Q: Given some conditions on a PDE, how to compute curves that obey these conditions? I made a very silly algorithm to "approximate" functions in order to understand partial differential equations (I'm trying to learn by myself so I'm mostly trying to draw graphs to see what  is going on). We get $(x,f(x))$, compute $a_0=\{x_0,f(x_0) \}$ and then we construct the following points:
$$a_n=(x_{n-1},f(x_{n-1}))+(1,f'(x_{n-1}))\qquad n=1,2,3,...$$
So far, it seems to be working:

So I took the following partial differential equation with the following conditions:
$$\begin{array}{cc}\begin{array}{c}u_{tt}=u_{xx}\hspace{34mm}\\\end{array}&\begin{array}{c} t\in (0,+\infty) \quad x\in(0,1) \\\end{array}\\\begin{array}{c}u(0,t)=u(1,t)=0\hspace{18mm} \\\end{array}&\begin{array}{c}t\geq 0 \hspace{28mm}\\\end{array}\\\begin{array}{c}u(x,0)=f(x) \quad u_t(x,0)=g(x)\\\end{array}&\begin{array}{c}x\in[0,1] \hspace{22mm}\\\end{array}\\\end{array}$$
And used $f(x)=x(1-x)  \sin (2 \pi  x)$ and $g(x)=\sin(x)$. So the conditions we have in the problem seems to be saying that $u(x,t)$ must be contained in the following red curves:

I tried to do the following: Find "solution points" for these conditions and make an analogy with the algorithm I did previously. So we have:
We get $(x,t,f(x))$, compute $a_0=\{x_0,0,f(x_0 ,0) \}$ and then we construct the following points:
$$a_n=(x_{n-1},t_{n-1},\overbrace{f(x_{n-1})}^{u(x,0)})+(0,1,\overbrace{g(x_{n-1})}^{u_t (x,0)})\qquad n=1,2,3,...$$
But I am really confused: This doesn't yield anything near the actual partial differential equations I did and I tried a lot of different things. What am I missing?


text:
Q: Проблема с выводом словаря Имеется словарь d. Напишите программу, которая в цикле принимает от пользователя пары чисел: key и value. Если ключ key есть в словаре d, то добавьте значение value в список, который хранится по этому ключу. Если ключа key нет в словаре, то нужно добавить значение в список по ключу 2*key. Если нет и ключа 2*key, то нужно добавить ключ 2*key в словарь и сопоставить ему список из переданного элемента [value]. Вывести полученный словарь.
d = {}
while(True):
    key = input()
    if key == "":
        break
    value = input()
    if value == "":
        break
if key in d:
    d[key].append(value)
elif 2 * key in d:
    d[2 * key].append(value)
else:
    d[2 * key] = []
    d[2 * k].append(value)
print(d)

Словарь выводится не так, как нужно.

A: if key in d:
    d[key].append(value)
else:
    d.setdefault(2 * key, []).append(value)
print(d)


text:
Q: Update excel with data from datatable I have an Excel file template that my office use to filter their data, i need just update the first sheet "data", i have here my code, i spent more than 3 days to build this routine. But i find out that is REALLY SLOW, now but i think  there is a fastest way to do this.
What can i do?
    private void EsportaInTemplateExcelVL(string NomeFile)
    {

        string fileNameTemp = NomeFile;//System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".xlsx";
        string FileXls = Application.StartupPath + @"\Support\PrintFormat\VL_LAB_updated.xls";

        if (!File.Exists(FileXls))
        {
            MessageBox("File template VL_LAB_updated.xls not found");
            return;
        }

        System.IO.File.Copy(FileXls, fileNameTemp);
        Excel.Application excelApp = new Excel.Application();

        Excel.Workbook wb = excelApp.Application.Workbooks.Open(fileNameTemp, Type.Missing, Type.Missing,
                                                  Type.Missing, Type.Missing,
                                                  Type.Missing, Type.Missing,
                                                  Type.Missing, Type.Missing,
                                                  Type.Missing, Type.Missing,
                                                  Type.Missing, Type.Missing,
                                                  Type.Missing, Type.Missing);

        Excel.Sheets excelSheets = excelApp.Worksheets;// var ws = excelApp.Worksheets;
        Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item("DATA");

        string[] col = { "A", "B", "C", "D", "E", "F", "G", "H", "I","J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X","Y", "Z" };

        //Head Columns
        for (int C = 0; C < dt.Columns.Count ; C++)
        {
            string Cella = col[C].ToString() + (0 + 1).ToString();//i parte da zero

            Excel.Range excelCell = (Excel.Range)excelWorksheet.get_Range(Cella, Cella);
            excelCell.Value = dt.Columns[C].ColumnName;
        }

        //all data
        for (int i = 0; i < dt.Rows.Count ; i++)
        {
            for (int C = 0; C < dt.Columns.Count ; C++)
            {
                string Cella = col[C].ToString() + (i + 2).ToString();

                Excel.Range excelCell = (Excel.Range)excelWorksheet.get_Range(Cella, Cella);
                excelCell.Value = "'" + dt.Rows[i][C].ToString();
            }
        }

            wb.Close(true);
            excelApp.Quit();
            MessageBox("Done");

    }

A: You are using ranges but you are defining cells one by one.
The good solution is to define cells by range (x rows and x columns)
This is much faster in Excel

A: I propose to use Data Engine to export your data to Excel as it is faster than excel object model. Take a look at following scenario if it fits your needs.
Step 1
Add a new project to your solution. In this demo I named it "MyExtensions".
Step 2
After creating the project, add a new class. In this demo I named it "Extensions".
using System;
using System.Data;
using System.Data.OleDb;
using System.Collections.Generic;
using System.Linq;

namespace MyExtensions
{
    public static class Extensions
    {
    }
}

Step 3
Add following methods to this class.
Method 1
// This method returns Dictionary to convert
// .Net types to Excel types
static Dictionary<Type, string> GetTypeConverter(this OleDbConnection oleDbConnection)
{
    string typeName = "TypeName";
    string dataType = "DataType";
    string columnSize = "ColumnSize";
    Dictionary<Type, string> dictionary = new Dictionary<Type, string>();
    var table = oleDbConnection.GetSchema("DataTypes");
    foreach (DataRow row in table.Select().OrderBy(r => r[columnSize]))
    {
        var type = Type.GetType(row[dataType].ToString());
        if (!dictionary.Keys.Contains(type))
        {
            dictionary.Add(type, row[typeName].ToString());
        }
    }
    return dictionary;
}

Method 2
// This method is helper method. This action will be repeated.
// So it is better to make it an extension method.
public static DataColumn[] ToArray(this DataColumnCollection collection)
{
    var columns = new DataColumn[collection.Count];
    collection.CopyTo(columns, 0);
    return columns;
}

Method 3
// This method adds a new Worksheet to Excel file
private static void CreateWorksheet(this DataTable dataTable, string name,
    OleDbConnection oleDbConnection, Dictionary<Type, string> converter)
{
    var columns = dataTable.Columns.ToArray();
    var query = columns
        .Select(c => $"{c.ColumnName} {converter[c.DataType]}");
    var str1 = string.Join(", ", query);
    var cmdText = $"CREATE TABLE [{name}] ({str1})";
    using (var oleDbCommand = new OleDbCommand(cmdText))
    {
        oleDbCommand.Connection = oleDbConnection;
        oleDbCommand.ExecuteNonQuery();
    }
}

Method 4
// This method exports contents of DataTable.
private static void Export(this DataTable dataTable,
    string worksheetName, OleDbConnection oleDbConnection)
{
    var columns = dataTable.Columns.ToArray();
    var str1 = string.Join(", ", columns.Select(c => $"[{c.ColumnName}]"));
    var str2 = string.Join(", ", columns.Select(c => $"?"));
    var cmdText = $"INSERT INTO [{worksheetName}] ({str1}) VALUES({str2})";
    var parameters = columns.Select(c => new OleDbParameter()).ToArray();

    using (var oleDbCommand = new OleDbCommand(cmdText))
    {
        oleDbCommand.Connection = oleDbConnection;
        oleDbCommand.Parameters.AddRange(parameters);
        var rows = dataTable.Select();
        foreach (var row in rows)
        {
            for (int i = 0; i < columns.Length; i++)
            {
                parameters[i].Value = row[i];
            }
            oleDbCommand.ExecuteNonQuery();
        }
    }
}

Method 5
// This method creates Worksheet in Excel file then
// exports contents of DataTable.
public static void Export(this DataTable dataTable,
    string excel_FileName, string worksheetName)
{
    var builder = new OleDbConnectionStringBuilder()
    {
        Provider = "Microsoft.ACE.OLEDB.12.0",
        DataSource = excel_FileName
    };
    builder.Add("Extended Properties", "Excel 12.0");

    using (var oleDbConnection = new OleDbConnection(builder.ConnectionString))
    {
        oleDbConnection.Open();
        var converter = oleDbConnection.GetTypeConverter();
        dataTable.CreateWorksheet(worksheetName, oleDbConnection, converter);
        dataTable.Export(worksheetName, oleDbConnection);
    }
}

Step 4
Create a new empty excel file in "My Documents" folder. Name it "Template.xlsx".
Step 5
Now we can use our API in a real situation. I created a console application and added the class library to references node of the project.
I added to my console application a new class to generate a sample DataTable to test to export it to excel.
using System;
using System.Data;

namespace ConsoleApp1
{
    class Factory
    {
        public static DataTable GetSample()
        {
            DataTable dataTable = new DataTable()
            {
                TableName = "DataTable1"
            };
            dataTable.Columns.Add("Id", typeof(int));
            dataTable.Columns.Add("LastName", typeof(string));
            dataTable.Columns.Add("FirstName", typeof(string));
            dataTable.Columns.Add("DateOfBirth", typeof(DateTime));
            dataTable.Rows.Add(1, "John", "Robinson", new DateTime(1980, 6, 12));
            dataTable.Rows.Add(2, "Sara", "Connor", new DateTime(1986, 2, 7));
            return dataTable;
        }
    }
}

Here is Main method of the console application
using System;

namespace ConsoleApp1
{
    using MyExtensions;

    class Program
    {
        static void Main(string[] args)
        {
            var dataTable = Factory.GetSample();
            var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            var filePath = $"{path}\\Template.xlsx";
            dataTable.Export(filePath, "Data");
        }
    }
}

I had it run and it was successful.


text:
Q: Python - Group by a dataframe with a tolerance (with example) I'm trying to create a groupBy and giving a tolerance of +-1 seconds for example
Something like
groupby(['Column1', 'Column2', 'EpochTimeInMs'])
I tried to truncate it to minutes (epoch_value - epoch_value%60000) to group all values in the same minutes together
This works when the data frame is like
1 | 2 | 1659460439
1 | 2 | 1659460438

Result
1 | 2 | 1659460380

But for example if one value has 17:13:59 (in epoch) and the other 17:14:00 (in epoch) it will create 2 different rows like this
1 | 2 | 1659460439
1 | 2 | 1659460440

Result
1 | 2 | 1659460380
1 | 2 | 1659460440

Can you please point me in some way i can give it a tolerance or can pick those situations like in the join_asof since truncate to hours will be such a big interval it will not work?
Something like
data = {'Name': ['Tom', 'Joseph', 'Joseph'], 'Weight': ['60', '75', '75'], 'RegisterTime': ['1659460439', '1659460439', '1659460440']}
df = pd.DataFrame(data)
and would come something like
Tom    | 60 | 1659460380
Joseph | 75 | 1659460380


text:
Q: How to add JVM arguments for Spring Boot project in VS Code? I'm trying out VS Code by moving a project I did on Eclipse to it. I had a run configuration in Eclipse for this project which had the following JVM arguments:
--module-path lib/javafx-sdk-13/lib --add-modules=javafx.controls

Of course this "lib" folder and its contents followed to the new VS Code project folder but I don't know where to put those JVM arguments in vsCode, the equivalent of the run configurations with Eclipse essentially.  I tried putting them in the args section of the launch.json file with no success.
I am using the spring boot dashboard to launch the project if that makes a difference.
Here is my launch.json:
{
"configurations": [
    {
        "type": "java",
        "name": "Spring Boot-BudgetApplication<budget>",
        "request": "launch",
        "cwd": "${workspaceFolder}",
        "console": "internalConsole",
        "mainClass": "com.someone.budget.BudgetApplication",
        "projectName": "budget",
        "args": ["--module-path","lib/javafx-sdk-13/lib","--add-modules=javafx.controls"]
    }
]

}

A: The solution was placing the args in the vmArgs section like so :
"vmArgs": "--module-path=lib/javafx-sdk-13/lib --add-modules=javafx.controls"

A: Just add it in the launch.json file.
{
    "version": "0.2.0",
    "configurations": [
        {
            "type": "java",
            "name": "Application",
            "request": "launch",
            "mainClass": "mypackage.Application",
            "projectName": "myproject",
            "vmArgs": "-Darg1=60000 -Darg2=120000"
        }
    ],
}


text:
Q: How to convert N-D slice to indexes in NumPy? Given any N-tuple of slices (aka N-D slice) in NumPy how to convert it to corresponding indexes of N-D array represented as tuple of 1D arrays (indexes along each axes)? E.g. if we have np.nd_slice_to_indexes next code:
import numpy as np
print(np.nd_slice_to_indexes(np.s_[1 : 3]))
print(np.nd_slice_to_indexes(np.s_[1 : 3, 5 : 11 : 2]))

should print
(array([1, 2]),)
(array([1, 1, 1, 2, 2, 2]), array([5, 7, 9, 5, 7, 9]))

It is common for NumPy to represent indexes of N-D array as N-tuple of 1-D arrays of same length (each element of k-th array in tuple represents next index along k-th dimension). E.g. np.nonzero returns such N-tuple in code
print(np.nonzero([[0, 1, 1], [1, 1, 0]])) # Non-zero elements in 2D array.
# (array([0, 0, 1, 1], dtype=int64), array([1, 2, 0, 1], dtype=int64))

Same behavior should be achieved like in Pythonic function below, but in a more efficient (performant) way:
Try it online!
import numpy as np

def nd_slice_to_indexes(nd_slice):
    assert type(nd_slice) in [tuple, slice], type(nd_slice)
    if type(nd_slice) is not tuple:
        nd_slice = (nd_slice,)
    def iter_slices(slices):
        if len(slices) == 0:
            yield ()
        else:
            for i in range(slices[0].start, slices[0].stop, slices[0].step or 1):
                for r in iter_slices(slices[1:]):
                    yield (i,) + r
    *res, = np.vstack(list(iter_slices(nd_slice))).T
    return tuple(res)

print(nd_slice_to_indexes(np.s_[1 : 3]))
print(nd_slice_to_indexes(np.s_[1 : 3, 5 : 11 : 2]))
print(nd_slice_to_indexes(np.s_[1 : 3, 5 : 11 : 2, 8 : 14 : 3]))
# (array([1, 2]),)
# (array([1, 1, 1, 2, 2, 2]), array([5, 7, 9, 5, 7, 9]))
# (array([1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2]), array([5, 5, 7, 7, 9, 9, 5, 5, 7, 7, 9, 9]), array([ 8, 11,  8, 11,  8, 11,  8, 11,  8, 11,  8, 11]))

A: Thanks to suggestion of @hpaulj solved task efficiently using np.mgrid.
Try it online!
import numpy as np

def nd_slice_to_indexes(nd_slice):
    grid = np.mgrid[{tuple: nd_slice, slice: (nd_slice,)}[type(nd_slice)]]
    return tuple(grid[i].ravel() for i in range(grid.shape[0]))

print(nd_slice_to_indexes(np.s_[1 : 3]))
print(nd_slice_to_indexes(np.s_[1 : 3, 5 : 11 : 2]))
print(nd_slice_to_indexes(np.s_[1 : 3, 5 : 11 : 2, 8 : 14 : 3]))
# (array([1, 2]),)
# (array([1, 1, 1, 2, 2, 2]), array([5, 7, 9, 5, 7, 9]))
# (array([1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2]), array([5, 5, 7, 7, 9, 9, 5, 5, 7, 7, 9, 9]), array([ 8, 11,  8, 11,  8, 11,  8, 11,  8, 11,  8, 11]))


text:
Q: Ruby - Test whether database connection is possible I am looking to implement a way to test the database connection for our application.
We are currently having connectivity issues and therefore want to be able to check connectivity without having to login.
Is there a way to display a page stating database connection is up or database connection is down dependent upon whether connection fails. If any additional information is needed please let me know.
Only beginning to learn the ropes so apologies if I'm short on detail.

A: You can check if the connection is possible by running the following script:
require './config/environment.rb' # Assuming the script is located in the root of the rails app
begin
  ActiveRecord::Base.establish_connection # Establishes connection
  ActiveRecord::Base.connection # Calls connection object
  puts "CONNECTED!" if ActiveRecord::Base.connected?
  puts "NOT CONNECTED!" unless ActiveRecord::Base.connected?
rescue
  puts "NOT CONNECTED!"
end


text:
Q: Regexp for a valid user-agent I'm trying to write a regexp that validates if a user-agent given by a user is valid.
I've found http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html section "14.43 User-Agent":

14.43 User-Agent
The User-Agent request-header field contains information about the user agent originating the request. This is for statistical purposes, the tracing of protocol violations, and automated recognition of user agents for the sake of tailoring responses to avoid particular user agent limitations. User agents SHOULD include this field with requests. The field can contain multiple product tokens (section 3.8) and comments identifying the agent and any subproducts which form a significant part of the user agent. By convention, the product tokens are listed in order of their significance for identifying the application.
  User-Agent     = "User-Agent" ":" 1*( product | comment )

Example:
  User-Agent: CERN-LineMode/2.15 libwww/2.17b3

but I'm not really sure what does it mean 1*. Could anybody explain it or write the regexp?
Thanks!

A: If you look at the notation at the start of the RFC, you can see that N*M rule means N to M repetitions of rule. N is optional, and defaults to zero. M is optional, and defaults to infinity. In normal regular expressions, this translates to: rule{N,M}
In your case, 1* means one or more repetitions. In normal regular expressions, you can use the postfix + operator: rule+


text:
Q: Restructure Pandas DataFrame I have the following DataFrame:

play_id
position
frame
x
y

1
A_1
1
0.1
0.1

1
A_2
1
0.1
0.1

1
B_1
1
0.1
0.1

1
A_1
2
0.1
0.1

1
A_2
2
0.1
0.1

1
B_1
2
0.1
0.1

2
A_1
1
0.1
0.1

2
B_1
1
0.1
0.1

2
B_2
1
0.1
0.1

2
A_1
2
0.1
0.1

2
B_1
2
0.1
0.1

2
B_2
2
0.1
0.1

And I want to reformat to (Multi-Index columns):

position
A_1
A_1
A_1
A_1
A_2
A_2
A_2
A_2
B_1
B_1
B_1
B_1
B_2
B_2
B_2
B_2

coord
x
x
y
y
x
x
y
y
x
x
y
y
x
x
y
y

frame
1
2
1
2
1
2
1
2
1
2
1
2
1
2
1
2

play_id

1
0.1
0.1
0.1
0.1
0.1
0.1
0.1
0.1
0.1
0.1
0.1
0.1
NaN
NaN
NaN
NaN

2
0.1
0.1
0.1
0.1
NaN
NaN
NaN
NaN
0.1
0.1
0.1
0.1
0.1
0.1
0.1
0.1

Importantly, note that not all positions exist for all play_ids. This will result in some cells being empty.

A: *

*sort_values() so index is in order you want

*set_index() existing columns

*sick() the coords

*name everything

*unstack() to get multi-index columns

df = pd.read_csv(io.StringIO("""play_id position    frame   x   y
1   A_1 1   0.1 0.1
1   A_2 1   0.1 0.1
1   B_1 1   0.1 0.1
1   A_1 2   0.1 0.1
1   A_2 2   0.1 0.1
1   B_1 2   0.1 0.1
2   A_1 1   0.1 0.1
2   B_1 1   0.1 0.1
2   B_2 1   0.1 0.1
2   A_1 2   0.1 0.1
2   B_1 2   0.1 0.1
2   B_2 2   0.1 0.1"""), sep="\t")

df = df.sort_values(["position","frame","play_id"]).set_index(["position","frame","play_id"]).stack()
df.reindex(df.index.set_names(["position","frame","play_id","coord"])).unstack([0,1,3])

output
position  A_1                 A_2                 B_1                 B_2
frame       1         2         1         2         1         2         1         2
coord       x    y    x    y    x    y    x    y    x    y    x    y    x    y    x    y
play_id
1         0.1  0.1  0.1  0.1  0.1  0.1  0.1  0.1  0.1  0.1  0.1  0.1  NaN  NaN  NaN  NaN
2         0.1  0.1  0.1  0.1  NaN  NaN  NaN  NaN  0.1  0.1  0.1  0.1  0.1  0.1  0.1  0.1


text:
Q: Как передать PHP в HTML? Есть нюанс, может подскажите если есть возможность, как правильно сделать? А то уже голову сломал...
if ( ! is_user_logged_in() ) {
if ( ! is_single() ) {
echo '

    <iframe src="player.vimeo.com/video/<?php echo
    carbon_get_post_meta($current_episode->ID, 'crb_vimeo_video_id'); ?>"
    width="100%" height="100%" frameborder="0" webkitallowfullscreen=""
    mozallowfullscreen="" allowfullscreen="">

';
 }
}

A: Вот вам третий вариант... Тоже рабочий :)
Я его предлагаю, потому что, он ближе к рекомендованному применению кода.
PHP очень удобен тем, что такую задачу как Ваша можно решить сразу тремя способами. Именно благодаря, такому "дружелюбному" подходу к разработчику PHP И стал одним из самых востребованных языков.
if ( ! is_user_logged_in() ) {
    if ( ! is_single() ) {
        $varembed = carbon_get_post_meta($current_episode->ID, 'crb_vimeo_video_id');

        echo "

";
    }
}

A: Сделайте так:
<?php
if ( ! is_user_logged_in() ) {
    if ( ! is_single() ) {
        ?>

            <iframe
                    src="player.vimeo.com/video/<?php echo carbon_get_post_meta( $current_episode->ID, 'crb_vimeo_video_id' ); ?>"
                    width="100%" height="100%" frameborder="0" webkitallowfullscreen=""
                    mozallowfullscreen="" allowfullscreen="">

        <?php
    }
}

A: if ( ! is_user_logged_in() ) {
    if ( ! is_single() ) {
        echo '

            ID, "crb_vimeo_video_id").'"
            width="100%" height="100%" frameborder="0" webkitallowfullscreen=""
            mozallowfullscreen="" allowfullscreen="">

';
     }
}


text:
Q: NoReverseMatch - Resetting password in Django I have found many similar questions to this issue. This question was one of them, but it didn't solve my problem, so I will ask my own question.
I'm making a password reset page on my website. But when I go to http://localhost:8000/users/reset-password and enter my email and clicks on 'Reset my password', then Django throws a NoReverseMatch error at me.
The error is:
NoReverseMatch at /users/reset-password/
Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name.

I believe there's something wrong with how I write my urlpatterns.
I've tried:

*

*Making my own views and templates.

*Rewriting all my urlpatterns.

My Code
urls.py:
"""Defines URL Patterns for users."""

from django.urls import re_path
from django.contrib.auth.views import (
    LoginView, PasswordResetView, PasswordResetConfirmView,
    PasswordResetDoneView,
)

from . import views

urlpatterns = [
    # Login Page.
    re_path(r'^login/$', LoginView.as_view(template_name='users/login.html'),
            name='login'),

    # Logout Page.
    re_path(r'^logout/$', views.logout_view, name='logout'),

    # Registration Page.
    re_path(r'^register/$', views.register, name='register'),

    # Password reset Page.
    re_path(r'^password_reset/$', PasswordResetView.as_view(
        # This is the only line I added in this file.
        template_name='users/password_reset_email.html'
    ),
            name='password_reset'),

    # Password reset done Page.
    re_path(r'^password_reset/done/$', PasswordResetDoneView.as_view(),
            name='password_reset_done'),

    # Password reset confirm Page.
    re_path(r'^password_reset/confirm/'
            + '(?P<uidb64>[0-9A-Za-z]+)/(?P<token>.+)/$',
            PasswordResetConfirmView.as_view(),
            name='password_reset_confirm'),
]

My own users/password_reset_email.html:
{% load i18n %}{% autoescape off %}
{% blocktrans %}You're receiving this email because you requested a password reset for your user account at {{ site_name }}.{% endblocktrans %}

{% trans "Please go to the following page and choose a new password:" %}
{% block reset_link %}
{{ protocol }}://{{ domain }}{% url 'users:password_reset_confirm' uidb64=uid token=token %}
{% endblock %}
{% trans "Your username, in case you've forgotten:" %} {{ user.get_username }}

{% trans "Thanks for using our site!" %}

{% blocktrans %}The {{ site_name }} team{% endblocktrans %}

{% endautoescape %}

Update:
I got something right. Now I get a NoReverseMatch at /users/password_reset/
Reverse for 'password_reset_confirm' with keyword arguments '{'uidb64': '', 'token': ''}' not found. 1 pattern(s) tried: ['users/password_reset/confirm/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$']. I got to this error by using my own template of djangos password_reset_email.html, where I modified the line: {% url 'password_reset_confirm' uidb64=uid token=token %} to {% url 'users:password_reset_confirm' uidb64=uid token=token %}. Now i'm almost certain that i'm just writing my urls or regexes wrong.
I have edited my question to show the new code.

A: I finally got it.
Here is the answer to the problem.
Now I get a ConnectionRefusedError, which means that I now only need to set up an SMTP Server for emails, and then it should work! The thing I was missing all the time was, that I wasn't pointing out what email template I wanted to use. I just set the email template as the template, so Django couldn't render it correctly. Here is the updated code for urls.py where path(r'password-reset/') is changed:
from django.urls import path, reverse_lazy
import django.contrib.auth.views as auth_views

from . import views

urlpatterns = [
    # Login Page.
    path(r'login/', auth_views.LoginView.as_view(
        template_name='users/login.html'
    ),
         name='login'),

    # Logout Page.
    path(r'logout/', views.logout_view, name='logout'),

    # Registration Page.
    path(r'register/', views.register, name='register'),

    # Password reset page.
    path(r'password-reset/', auth_views.PasswordResetView.as_view(
        email_template_name='users/password_reset_email.html',
        success_url=reverse_lazy('users:password_reset_done')
    ), name='password_reset'),

    # Password reset done page.
    path(r'password-reset/done/',
         auth_views.PasswordResetDoneView.as_view(),
         name='password_reset_done'),

    # Password reset confirm page.
    path(r'password-reset/confirm/<uidb64>/<token>/',
         auth_views.PasswordResetConfirmView.as_view(),
         name='password_reset_confirm')
]

Everything else is correct.
I got the answer from this answer.


text:
Q: sql join between two dates Let's say i have two tables:
employees:
Name    id    beg_eff_date    end_eff_date    group
Jack    101a  01-01-16        03-31-16        4
Jack    101a  04-01-16        12-31-99        3

Sales
emp_id    sale_amt    sale_date
101a      25          01-22-16
101a      28          04-10-16

my desired output:
emp_id    sale_amt    sale_date    name    group
101a      25          01-22-16     Jack    4
101a      28          04-10-16     Jack    3

This is the code I'm using, but it seems to not be working in at least one case (with my real dataset), so I want to be sure I'm writing correctly:
select sales.emp_id, sales.sale_amt, sales.sale_date,
    emp.name, emp.group
from sales
inner join employees emp
    on sales.emp_id = emp.id
where sales.sale_date between emp.beg_eff_date and emp.end_eff_date

The goal here is to get the group number that the employee was in at the time of the sale.
Thanks a ton!

A: Your commentors appear to be on the right track.  Your BETWEEN clause seems to be working on text data, not date data.  You're going to have to force it into a date data-type for it to work.  You may want to consider changing your source tables to always use the date data-type for their dates.  Then you won't need to use the following mess every time you want to do date-math.  "This mess":
select sales.emp_id, sales.sale_amt, sales.sale_date,
    emp.name, emp.group
from sales
inner join employees emp
    on sales.emp_id = emp.id
where CONVERT(Date, iif(RIGHT(sales.sale_date, 2) < 50, '20', '19') + RIGHT(sales.sale_date, 2) + '-' + LEFT(sales.sale_date, 2) + '-' + SUBSTRING(sales.sale_date, 4, 2))
between
  CONVERT(Date, iif(RIGHT(emp.beg_eff_date, 2) < 50, '20', '19') + RIGHT(emp.beg_eff_date, 2) + '-' + LEFT(emp.beg_eff_date, 2) + '-' + SUBSTRING(emp.beg_eff_date, 4, 2))
and
  CONVERT(Date, iif(RIGHT(emp.end_eff_date, 2) < 50, '20', '19') + RIGHT(emp.end_eff_date, 2) + '-' + LEFT(emp.end_eff_date, 2) + '-' + SUBSTRING(emp.end_eff_date, 4, 2))

A: This is the type of effective date logic I used to use a while ago so pardon the old sql syntax:
select sales.emp_id, sales.sale_amt, sales.sale_date,
    emp.name, emp.group
from sales, employees emp
where sales.emp_id = emp.id
and emp.group in
  (select emp2.group
   from employees emp2
   where emp2.emp_id = emp.emp_id
   and sales.sale_date between emp2.beg_eff_date and emp2.end_eff_date)

I'm assuming those eff_date columns are actual date types.


text:
Q: Is there a way to streamline moving cell references in VBA code? I have a report that provides a snapshot of information from the prior day, then I click a button (VBA code) upon completion and it takes data stored in certain cells on the report tab and moves it to another tab where its position is re-organized so I can track the data on a trend line.
On the Trend tab if I highlight column C, for example, and insert a new column it pushes all of the data to the right but the cell references in my VBA code don't change. So when I need to re-organize the trend tab to incorporate more/different data it's becoming more laborious to go back to the VBA code and update all of the cell references.
Is it possible to reference the cells in my VBA code, in a way that they will change in concert with the data in the trend tab if I move things around?

A: If anyone else has this question this is great info.
https://learn.microsoft.com/en-us/office/vba/excel/concepts/cells-and-ranges/refer-to-named-ranges


text:
Q: How to get the previous record id when Ids are not in a sequence order I have a table with id and name. But id is not saving in a sequence order. when I have a specific id at that time I want to get the previous record id.

Id
name

1
john

15
wick

18
suthi

35
kandu

179
keerthi

201
nuwan

If I have a id as 179. I want to get the previous record id. Please provide me a query for get the pervious column id.

A: You can use this query to get the previous value(if it exists) if you have one :
select max(id) from table1 where id < your_current_id_value

If your your_current_id_value is 179, then you will get 35, but if you have 1, then you will get nothing.

A: You can try with in MySQL:
SELECT * FROM table WHERE id < @Your_id LIMIT 1

In SQL server:
SELECT * FROM table as table1
INNER JOIN table as table2
on table1.ID = (table2.ID -1)

A: Your data I added some values for test considering Preivous ID is smaller than Current ID
create table MYTABLE(
   Id   INTEGER  NOT NULL
  ,name VARCHAR(70) NOT NULL
);
INSERT INTO MYTABLE
(Id,name) VALUES
(1,'john'),
(3,'suthi'), ----test previous record id
(8,'kandu'), ----test previous record id
(15,'wick'),
(17,'keerthi'), ----test previous record id
(18,'suthi'),
(35,'kandu'),
(40,'nuwan'), ----test previous record id
(179,'keerthi'),
(201,'nuwan');

your desired query
SELECT A.NAME,
       A.CurrentID,
       B.PreviousID
FROM   (SELECT Max(ID) CurrentID,
               NAME
        FROM   MYTABLE
        GROUP  BY NAME) A
       JOIN (SELECT Min(ID) PreviousID,
                    NAME
             FROM   MYTABLE
             GROUP  BY NAME) B
         ON A.NAME = B.NAME
            AND A.CurrentID > B.PreviousID

Output

NAME
CurrentID
PreviousID

kandu
35
8

keerthi
179
17

nuwan
201
40

suthi
18
3

dbfiddle


text:
Q: MVC 4 - Error message from controller is not being displayed in view I have an MVC website that when a field loses focus it will read a backend database and determine if the value is valid. If the value is valid it will fill in two other fields on the page. The problem I am having is when the value is invalid and I want to display an error message just like a validation message under the text box.
The view....
@Html.ValidationSummary(true)
<div class="form-group">
    @Html.LabelFor(m => m.HSDRepCode)
    @Html.TextBoxFor(m => m.HSDRepCode, new { placeholder = "Enter your HSD Rep code...", @class = "contact-name" })
    @Html.ValidationMessageFor(m => m.HSDRepCode)
</div>

The calling script...
$("#HSDRepCode").blur(function () {
        $.ajax({
            url: "/CRM/ValidateHSDRep",
            type: "POST",
            data: $('form').serialize(),
            dataType: "json"
        }).done(function (model) {
            $("#HSDRepCode").val(model.HSDRepCode);
            $("#HSFirstName").val(model.HSFirstName);
            $("#HSLastName").val(model.HSLastName);
        });
    });

The model....
public class LeadInfo
{
    [Display(Name = "Products of Interest")]
    [Required(ErrorMessage = "Please select a product of interest")]
    public string Product { get; set; }

    [Display(Name = "HSD Rep code")]
    [Required(ErrorMessage = "Please enter your HSD Rep code")]
    [StringLength(6)]
    public string HSDRepCode { get; set; }

    [Display(Name = "HSD Rep first name")]
    [Required(ErrorMessage = "Please enter your first name")]
    public string HSFirstName { get; set; }

    [Display(Name = "HSD Rep last name")]
    [Required(ErrorMessage = "Please enter your last name")]
    public string HSLastName { get; set; }

    [Display(Name = "Doctor's first name")]
    [Required(ErrorMessage = "Please enter the doctor's first name")]
    public string FirstName { get; set; }

    [Display(Name = "Doctor's last name")]
    [Required(ErrorMessage = "Please enter the doctor's last nname")]
    public string LastName { get; set; }

    [Display(Name = "Doctor's phone number")]
    [Required(ErrorMessage = "Please enter the doctor's phone number")]
    [Phone]
    public string PhoneNumber { get; set; }

    [Display(Name = "Doctor's e-mail")]
    [Required(ErrorMessage = "Please enter the doctor's e-mail")]
    [EmailAddress]
    public string EmailAddress { get; set; }
}

and the controller....
public ActionResult ValidateHSDRep(LeadInfo leadInfo)
{
    HSDRep hsdRep = new HSDRep();

    hsdRep = CRMModels.ValidateHSDRepCode(leadInfo.HSDRepCode);

    if (hsdRep.FirstName != null)
    {
        leadInfo.HSFirstName = hsdRep.FirstName;
        leadInfo.HSLastName = hsdRep.LastName;

        return Json(leadInfo);
    }
    else
    {
        ModelState.AddModelError("HSDRepCode", "Invalid HS Representative Code");

        return Json(leadInfo);
    }
}

The controller routine is called when the textbox loses focus.
How do I display the message "Invalid Representative Code" under the text box "HSDRepCode"?
Thanks,
Gary
UPDATED: I have added the Ajax code that calls the controller function.
UPDATE 2: I changed the return to return Json.

A: Your ValidateHSDRep() method is returning json which has no concept of model state. In addition, you are unnecessarily degrading performance by sending the whole model to the view, then sending it all back again when you only need to send one property and return two. Change you script to send only the HSDRepCode value, and return only what you need
var url = '@Url.Action("ValidateHSDRep", "CRM");
$("#HSDRepCode").blur(function () {
  $.getJSON(url, { HSDRepCode: $(this).val() }, function(response) {
    if (response.ErrorMessage) {
      // do something with the error message
    } else {
      $("#HSFirstName").val(response.HSFirstName);
      $("#HSLastName").val(response.HSLastName);
      // remove any associated error message that may have been added in previous calls
    }
  });
});

and change the controller method to
public ActionResult ValidateHSDRep(string hSDRepCode)
{
  HSDRep hsdRep = CRMModels.ValidateHSDRepCode(hSDRepCode);
  if (hsdRep.FirstName == null)
  {
    return Json(new { ErrorMessage = "Invalid HS Representative Code" }, JsonRequestBehavior.AllowGet);
  }
  else
  {
    return Json(new { HSFirstName = hsdRep.FirstName, HSLastName = hsdRep.LastName; }, JsonRequestBehavior.AllowGet);
  }
}

However, since you are including @Html.ValidationMessageFor(m => m.HSDRepCode) in the view, you can handle the 'invalid code' using a RemoteAttribute on you model property
[Display(Name = "HSD Rep code")]
[Required(ErrorMessage = "Please enter your HSD Rep code")]
[StringLength(6)]
[Remote("IsHSDRepCodeValid", "CRM", ErrorMessage = "Invalid HS Representative Code")]
public string HSDRepCode { get; set; }

then add a controller method
public JsonResult IsHSDRepCodeValid(string HSDRepCode)
{
  // code to test if valid
  if(isValid)
  {
    return Json(true, JsonRequestBehavior.AllowGet)
  }
  else
  {
    return Json(false, JsonRequestBehavior.AllowGet) // displays default message defined in ErrorMessage property
    // or
    return Json("a custom message", JsonRequestBehavior.AllowGet)
  }
}

Refer also How to: Implement Remote Validation in ASP.NET MVC for more detail on using remote validation

A: First parameter of .AddModelError method is key, which in your case is HSDRepCode, not hsdrepcode.
So:
ModelState.AddModelError("HSDRepCode", "Invalid Representative Code");

It's working ? Thanks


text:
Q: How does mutate_all(.funs=~./sum(x)) work? I used this code to calculate relative abundance (cell/total of column) of a table I had. I don't understand how the . and ~ functions work.

A: The construct ~./sum(x) is technically a special type of R object called a formula
class(~./sum(x))
#> [1] "formula"

However, in tidyverse functions such as mutate_all, this formula is taken and converted into a lambda function, which is an anonymous function (i.e. a function that isn't named and is written in place as a parameter passed in a call to another function).
Internally, the formula is converted into a function with rlang::as_function. Suppose we wanted to write a function that just adds two to a variable. In base R we might write
add_two <- function(var){
  return(var + 2)
}

add_two(5)
#> [1] 7

In the tidyverse, we can use a formula as shorthand for this function, where the . becomes a shorthand for "the variable that was passed as a first argument to the function":
add_two <- rlang::as_function(~ . + 2)

add_two(5)
#> [1] 7

In functions such as mutate_all, the formula will automatically be passed through rlang::as_function, so if we wanted to add two to each column in our data frame, instead of writing:
mutate_all(.funs= function(var) {return(var + 2);})

we could write
mutate_all(.funs=~.+2)

In your case, the formula ~./sum(x) is effectively transformed into
function(var) {
  return(var / sum(x))
}

where x has to exist either as a column in your data frame or a variable in the calling environment.
The reasons for having it this way are that it saves typing and shortens lines of code. Inserting a function within a call to another function often leads to messy and poorly formatted code. This shorthand method helps to prevent that.
You can read more about anonymous functions and how they are used in the tidyverse here

A: mutate_all applies the function in .funs to all values. Each value (.) is divided by the sum(x), to get you the "relative abundance" which is essentially the fraction of the total value, which is the sum(x). You can think of ~ as a "function of". So you are saying each cell in the dataframe is a function of itself divided by the overall sum.

A: Suppose we have this dataset:
dataset <- data.frame(a = c(1,2,3,4),
                      b = c(2,3,4,5),
                      c = c(3,4,5,6))

And you want to divide all vectors by the total (ie. for vector a = 1/10, 2/10, 3/10, 4/10). To avoid writing for all variables, you can use mutate_all, and then a lambda using .funswhich says make a function that divides all values in each vector represented by the dot by the sum of all values in that vector.
dataset %>% mutate_all(.funs = ~./sum(.))

Hope this helps.


text:
Q: What is a react way to call rest api with post data? Say I have an API: http://localhost:123/amazon_api
In python I can call it with the following code, where data is just some values I want to pass to the API:
resp = requests.get(url, data={"optional1": optional1})

In react, there is a library called 'superagent' which seems to have similar functions:
Request.get(url, {"optional1": 1}).then((response) => {
    result = response;
});

However, it doesn't work as it seems the following cannot get passed in:
{"optional1": 1}

Does anyone know how to do this?

A: Isn't that caused by misused Superagent's API?
According to docs, what you're attempting won't work.
Do following following:
 request
   .get(url)
   // To transfer data over GET request, use query method
   .query({"optional1": 1})
   .then((response) => {
       //
   })

More info:
http://visionmedia.github.io/superagent/#get-requests


text:
Q: Call setLocationEnabled in another Button setLocationEnabled is a attribute that shows a button on the top of the map that makes the map go to the current place.
But I want to "hide" this Button and call the method on the another custom button. Is there a way? I don't wanna to create a big code to go to current location, it's not fast. I just wanna a button with the same function of the setLocationEnabled(true).
How do I do that?

A: I've dealt with a similar problem and I found a pretty detailed solution from here Google map for android my location custom button
Have fun!

A: As you may know, you can hide the current location button with the following:
UiSettings.setMyLocationButtonEnabled(false);

Now, if you want to perform this task manually, you'll have to do some work on your own. First, you will need to acquire the user's current location. This can be acquired (and updated) by overriding the onLocationChanged function of the LocationListener implementation. If you are unclear on how to do this, checkout the documentation describing it. This may prove useful as well!
Secondly, you'll need to target the user's location by setting the map's camera to look at it, and (possibly) set a marker in the location. Here's the function I used in one of my recent apps describing how to do so:
public void moveToLocation(Location input) {
    Double lat = (double) (input.getLatitude());
    Double lon = (double) (input.getLongitude());

    final LatLng location = new LatLng(lat, lon);

    setLocMarker(location);

    mainMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 16));

    //if you want the camera to have an "animated" effect, you can perform the following
    //mainMap.animateCamera(CameraUpdateFactory.zoomTo(16), 4000, null);
}

For more information regarding camera effects and animations, refer to this documentation.


text:
Q: Using ClickOnce Deployment need to include: Microsoft Save as PDF or XPS Office 2007 Add-In All,
We are using ClickOnce to deploy our WPF application and have the need to include the 2007 Microsoft Office Add-in: Microsoft Save as PDF or XPS.
Is there a way to include this exe file in the ClickOnce deployment?
Thank you,

A: You could try adding the .exe to the deployment (see here) and run check on program startup if it's installed, and run the process if not.

A: You need to get the install package for that. Then you can create a prerequisite package for it and deploy it as a prerequisite to your ClickOnce deployment.
To create the prerequisite package, you can use the Bootstrapper Manifest Generator, which is here.
You then copy this package to the a folder where the VS prerequisites are found. If you are using VS2010, that location is here:
C:\Program Files\Microsoft SDKs\Windows\v7.0A\Bootstrapper\Packages
If you are using VS2008, it's here:
C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bootstrapper\Packages
This post can be helpful explaining how to use the BMG. Be sure to add an Error Code of 0 for success, or it will always tell you the install failed.


text:
Q: WinrtXamlToolkit - Charting : ComException when use of INotifyPropertyChanged I'm currently using the line chart (from WinRT XAML Toolkit), and I'm facing a problem : everything goes right, but if my (In)DependentValue which is bound to my LineSeries contains a change notification (INotifyPropertyChanged), the toolkit raise a COMException.
I used the last version (1.4.1) of the toolkit from Nuget.
My XAML code :
<toolkitchart:Chart x:Name="AltitudeChart" Height="200">
  <toolkitchart:LineSeries
    IndependentValueBinding="{Binding Distance}"
    DependentValueBinding="{Binding Distance}"
    IsSelectionEnabled="True"
    DependentRangeAxis="{Binding ElementName=LeftAxis}"
    IndependentAxis="{Binding ElementName=BottomAxis}">
    <toolkitchart:LineSeries.DataPointStyle>
       <Style TargetType="toolkitchart:LineDataPoint">
         <Setter Property="Template">
           <Setter.Value>
             <ControlTemplate>
               <local:DetailedPushpin ManipulationDelta="DetailedPushpin_ManipulationDelta" ManipulationMode="TranslateY"/>
             </ControlTemplate>
           </Setter.Value>
         </Setter>
       </Style>
    </toolkitchart:LineSeries.DataPointStyle>
  </toolkitchart:LineSeries>
  <toolkitchart:Chart.Axes>
    <toolkitchart:LinearAxis x:Name="RightAxis" Orientation="Y" Location="Right"/>
    <toolkitchart:LinearAxis x:Name="LeftAxis" Orientation="Y" Location="Left" Foreground="White"/>
    <toolkitchart:LinearAxis x:Name="BottomAxis" Orientation="X" Location="Bottom" Foreground="White"/>
  </toolkitchart:Chart.Axes>
</toolkitchart:Chart>

And my C# code :
ObservableCollection<AltChartPoint> ChartPoints = new  ObservableCollection<AltChartPoint>();
AltChartPoint a = new AltChartPoint(12);
ChartPoints.Add(a);
a.Distance = 13; <-- Throw exception if the change is notified

...

public class AltChartPoint : INotifyPropertyChanged
{
  private double _distance;
  public double Distance
  {
    get { return _distance; }
    set
    {
      _distance = value;
      //NotifyPropertyChanged("Distance"); <-- Problem is here
    }
  }
}

Is it possible to make the chart update with an notified property update ?
Note that the same exception occured if i try to edit directly the LineDataPoint.DependentValue


text:
Q: Hibernate one to one bidirectional confusion I have example code to check how bidirectional relationship works.
@Getter
@Setter
@NoArgsConstructor
@ToString
@Entity
public class A {
   @Id
   @GeneratedValue
   private long aId;
    String name;
    String address;
    @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "b_id_FK")
    B b;
}

@Getter
@Setter
@NoArgsConstructor
@ToString
@Entity
public class B {
    @Id
    @GeneratedValue
    @Column(name = "b_id_PK")
    private long bId;
    private String name;
    private String address;
    @JoinColumn(name = "a_id", referencedColumnName = "aId")
    @OneToOne(mappedBy = "b", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    A a;
}

public void insertAB(){
    B b = new B();
    b.setName("B-Name");
    b.setAddress("B-Address");

    A a = new A();
    a.setName("A-Name");
    a.setAddress("A-Address");
    a.setB(b);
    b.setA(a);
    aRepository.save(a);
}

I can see this kind of table h2 table:-
A:-

B:-

For the B table I was expecting a column a_id as I mentioned in the code.
So I in my controller if I try to retrieve B as this:-
@GetMapping(value = "/getb/{id}")
public B getB(@PathVariable long id){
   var b =  bRepository.findById(id).get();
   return b;
}

{
"name": "B-Name",
"address": "B-Address",
"a": {
    "name": "A-Name",
    "address": "A-Address",
    "b": {
        "name": "B-Name",
        "address": "B-Address",
        "a": {
            "name": "A-Name",
            "address": "A-Address",
            "b": {
                "name": "B-Name",
                "address": "B-Address",
                "a": {
                    "name": "A-Name",
                    "address": "A-Address",
...........

It is like chain of A an B many of them. I am learning hibernate and table relationship. Obviously I misunderstand something. My intention is for bidirectional is that When I load A, I can access related B. Also when I load B, I can access related A. How can I achieve this goal?

A: This solution is not ideal, because :

*

*this will only remove the excessive datas from the json.

*Hibernate will do the same request and this risks to slow down your application.

*Not a good practise to set a jackson annotation (@JsonManagedReference) in a java entity.

==> You probably have to change relation-type
For the bidirectional one-to-one relationship this kind of annotation worked for me:-
@Getter
@Setter
@NoArgsConstructor
@ToString
@Entity
public class A {
   @Id
   @GeneratedValue
   private long aId;
    String name;
    String address;
    @JsonManagedReference // this for parent to avoid infinite recursion
    @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "b_id_FK") // B table foreign key in A table
    B b;
}

@Getter
@Setter
@NoArgsConstructor
@ToString
@Entity
public class B {
    @Id
    @GeneratedValue
    @Column(name = "b_id_PK")
    private long bId;
    private String name;
    private String address;
    @NotNull
    @JsonBackReference // this for child to avoid infinite recursion
    @JoinColumn(name = "a_id_FK") // A table foreign key in B table
    @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
    @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private A a;
}

This way I can have foreign key in both A and B table. So I can access bidirectionally.


text:
Q: firebase retrieves data from different child because of child_added event My firebase database contains a list of users and each user has list containing his position and timestamp.

  runner
    |__1f9097c12fcfeac3259bd2be4a976933
    |__27305d166e57b5fdf9b96142c7d28ab1
       |__-L6R_u41IeEDy7rQ9udG
       |  |__timestamp
       |  |__position
    |__887527fea0ebca4c416e154e7bb8c95d
       |__-L6_KYQravVkxXNVK6V1
       |  |__timestamp
       |  |__position
       |__-L6_KekNbzzNrLY8G-IY
       |  |__timestamp
       |  |__position
'887527fea0ebca4c416e154e7bb8c95d', '27305d166e57b5fdf9b96142c7d28ab1',.. etc are user's ID that is retrieved from mysql table. '-L6_KYQravVkxXNVK6V1', '-L6_KekNbzzNrLY8G-IY',.. etc are keys generated by firebase while pushing data.
I am querying for 1 particular user's position like this
firebase.database().ref().child("runner").child(key).orderByChild("timestamp").startAt(startdate).endAt(enddate).on("child_added", function(data) {...})
While querying for user 1's positions, if child is added for user 2, I am getting user 2's positions though the key in above query still points to user 1.

A: To fix this, then read the data once:
firebase.database().ref().child("runner").child(key).orderByChild("timestamp").startAt(startdate).endAt(enddate).once('value').then(function(snapshot) {
snapshot.forEach(function(child) {
var childData = child.val();
var timestamps=child.val().timestamp;
var position=child.val().position;
   )};
)};

more info here:
https://firebase.google.com/docs/database/web/read-and-write#read_data_once

A: I was getting different user's details, because while selecting each user, I was attaching a child_added event listener. While changing the user , I was not removing the listener from previous user. Hence, when new child is added to different user, I was getting his details. The Solution is while changing to different user, remove listener from previous user.
firebase.database().ref().child('runner/'+prev_key).off();


text:
Q: Make phone sleep after a call is made with intent Is it possible to make screen go to sleep after a call is made from a background app?
currently my app makes an emergency call using intent.ACTION_CALL even when phone is sleeping and it wakes it up to the dialer.
i want to make it go back to sleep right after the call started.

A: Make below permission in Menifest -
<uses-permission android:name="android.permission.WAKE_LOCK" />

Use below code to make phone screen go off -
    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
            "MyApp::MyWakelockTag");
//if you want to make phone go to sleep mode then use
    wakelock.acquire();
//if you want to make phone go off from sleep mode then use
    wakelock.release();

Hope this helps.


text:
Q: How to make image appear on the top of the first page in rmarkdown documents I try to put image file (logo.png) on the top of the first page of my document. I followed the guideline from here: Insert a logo in upper right corner of R markdown pdf document. However, the image still does not appear. My code is: I still don't know what's wrong with my codes. Thanks.
---
title: 'Theory'
date: "Fall 2021"
output:
  pdf_document:
    keep_tex: yes
    fig_caption: yes
    latex_engine: pdflatex
    template: Syllabus_template.tex
  html_document:
    df_print: paged
geometry: margin=1in

header-includes:
- \usepackage{fancyhdr}
- \usepackage{graphicx}
- \usepackage{eurosym}
- \usepackage{booktabs,xcolor}
- \pagestyle{fancy}
- \fancyhf{}
- \addtolength{\headheight}{1.0cm}
- \rhead{MainSky Stress Test Report - \today}
- \lhead{\includegraphics[width=6cm]{/Users/jj/Documents/logo.png}}
- \rfoot{Page \thepage}
- \fancypagestyle{plain}{\pagestyle{fancy}}

#Fill this in with any number of instructors. It uses a two column layout with a column break after each instructor.

# teachingassistant:
#  - name: Filler
#    email: filler@fill.com
#    officehours: W T
#    office: OfficeNumber
#    sections: '301'

classroom: 'Remote (either MS Teams or Zoom)'
fontsize: 11pt
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(timeDate)
library(tibble)
library(dplyr)
library(knitr)

#This code chunk sets up a table of meeting days for the course.
#You can set days of the week for course meetings (e.g. Monday and Wednesday).
#Semester start and end dates are selected and then university holidays like spring break are specified.

A: You can add an image to the title page like this:
---
title: 'Theory'
date: "Fall 2021"
output:
  pdf_document:
    keep_tex: yes
    fig_caption: yes
    latex_engine: pdflatex
    # template: Syllabus_template.tex
  html_document:
    df_print: paged
geometry: margin=1in

header-includes:
- \usepackage{graphicx}
- \usepackage{eurosym}
- \usepackage{booktabs,xcolor}
- \makeatletter\patchcmd{\@maketitle}{\begin{center}}{\begin{center}\includegraphics[width=3cm]{example-image-duck}\par}{}{}\makeatother

#Fill this in with any number of instructors. It uses a two column layout with a column break after each instructor.

# teachingassistant:
#  - name: Filler
#    email: filler@fill.com
#    officehours: W T
#    office: OfficeNumber
#    sections: '301'

classroom: 'Remote (either MS Teams or Zoom)'
fontsize: 11pt
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(timeDate)
library(tibble)
library(dplyr)
library(knitr)

#This code chunk sets up a table of meeting days for the course.
#You can set days of the week for course meetings (e.g. Monday and Wednesday).
#Semester start and end dates are selected and then university holidays like spring break are specified.


text:
Q: Dependencies issue while installing model card toolkit Model Card --> Model Card toolkit

I want to install a model card toolkit in my python virtual environment through this command:
pip install model-card-toolkit
 and I am facing this below issue, I have tried many times with different combinations but every time dependencies conflicts occurred.

Collecting model-card-toolkit
ERROR: Cannot install model-card-toolkit==0.1.0, model-card-toolkit==0.1.1, model-card-toolkit==0.1.2, model-card-toolkit==0.1.3, model-card-toolkit==1.0.0, model-card-toolkit==1.1.0 and model-card-toolkit==1.2.0 because these package versions have conflicting dependencies.

The conflict is caused by:
    model-card-toolkit 1.2.0 depends on tfx<1.6.0 and >=1.5.0
    model-card-toolkit 1.1.0 depends on ml-metadata<1.3.0 and >=1.2.0
    model-card-toolkit 1.0.0 depends on tensorflow-data-validation<0.27.0 and >=0.26.0
    model-card-toolkit 0.1.3 depends on tensorflow-data-validation<0.27.0 and >=0.26.0
    model-card-toolkit 0.1.2 depends on tensorflow-data-validation<0.27.0 and >=0.26.0
    model-card-toolkit 0.1.1 depends on absl-py<0.9 and >=0.7
    model-card-toolkit 0.1.0 depends on absl-py<0.9 and >=0.7

To fix this you could try to:
1. loosen the range of package versions you've specified
2. remove package versions to allow pip attempt to solve the dependency conflict

ERROR: ResolutionImpossible: for help visit https://pip.pypa.io/en/latest/user_guide/#fixing-conflicting-dependencies

**I have these packages installed**

    absl-py==1.0.0
    autopep8==1.6.0
    ml-metadata==0.13.1.dev0
    protobuf==3.19.3
    pycodestyle==2.8.0
    six==1.16.0
    toml==0.10.2

Can someone please help with which combination of packages should I have to install to resolve this issue?

Is there any other way to install the model card toolkit?

A: Possible cause: tfx does not currently support Python 3.9. model-card-toolkit will not be compatible with Python 3.9 until tfx is updated.


text:
Q: jars added to WEB-INF/lib doesn't get recognized when I try to import them : says the package doesn't exist I have added org.apache.commons.fileupload and org.apache.commons.io package into the WEB-INF/lib directory of my project based on google appengine. But when I try importing in the servlet files the compiler/IDE gives an error that this package doesn't exist. Why is that ?
The jar files added :

What can be the reason I am getting this error ? What should I do to solve this problem ?

A: You might also have to add them to your project's classpath.
for eclipse:
Right click the jar, select build path and add it to the build path, then try again.
for netbeans:
in the project properties window click libraries in the left panel. In the right panel add it to the compile classpath

A: General solution , whenever you get package does not exist then there are 2 things, 1- Its not at all present 2) its present but still the error is thrown.
The solution to this is to just add the jar to the classpath [so that your app finds it during compilation,execution)
I would suggest you to try Maven . Maven is a nice way by which you can organize this in a systematic way.

A: If the IDE gives the problem then update the jars in IDE project class path :)


text:
Q: iOS Swift3 check if a ViewController has been initialized Is there a way to check if a ViewController has been initialized in iOS? I have an unwind Segue which does not work i a certain ViewController has not been initialized before.

A: You can check it using isKindOf class,
if view.isKind(of:UIViewcontroller.self) {
   //do your code while you know the view is initialised.
}

A: Find root view-controller then used it.
if self == UIApplication.shared.keyWindow?.rootViewController {
    /*do stuff*/
}

or u can used it also
if self.window.rootViewController is MyViewController {
//do something if it's an instance of that class
}

A: UINavigationController manages the array(viewControllers) of all UIViewControllers which are invoked at that instance so do as below
For swift 3
let viewControllers: [UIViewController] = self.navigationController!.viewControllers
for aViewController in viewControllers {
if aViewController is YourViewController {

   // get vc here

    break
  }
}

For objective - c
for (UIViewController *controller in self.navigationController.viewControllers) {

        //Do not forget to import AnOldViewController.h
        if ([controller isKindOfClass:[YourViewController class]]) {

                   // get vc here
            break;
        }
    }


text:
Q: runas /savecred... don't accept cmdkey /add (credentials) I have a problem with runas /savecred ... and cmdkey /add....
I have a batch file contains this line:
runas /profile /savecred /user:MyDomain\MyUserName "MyProgram.exe"

I'm logging to my computer as Administrator and I want to execute MyProgram.exe with another user: MyUserName.
When I launch my batch file the firt time, it prompts for password for MyUserName, I type the password and it works nice !!!
For second time, it don't ask for password because /savecred has saved MyUserName and password in Windows Credential. cool !!
The information in Credential Manager
Internet or network adress: MyDomain\MyUserName (Interactive logon)
User name: MyDomain\MyUserName
Password: ............
Persistence: Logon Session

Now, I would like to avoid to type the password asked for the first time. For this I have used cmdkey.exe to add credential myself without /savecred by this line
cmdkey /add:domain:interactive=MyDomain\MyUserName /user:MyDomain\MyUserName /pass:***********

and i have removed /savecred from line runas
The information in Credential Manager
Internet or network adress: MyDomain\MyUserName
User name: MyDomain\MyUserName
Password: ............
Persistence: Logon Session

Look there is no (Interactive logon) in the first line. The poblem is when I launch the batch file, it prompt always to type password, it seems like the runas disacard the informaion saved by cmdkey !
So What I have missed?  Or what other things that /savecred save in the Windows Credentials?

A: Under windows 7, the runas/savecred (interactive logon) credential is saved in a HIDDEN file in the directory c:\users\username\appdata\roaming\microsoft\credentials.
If you move this file out of this directory, the credential is not displayed in the Windows credential manager. Move the file back into the referenced directory, and the credential reappears. No other manipulation or tweaking is necessary.
You should save the interactive logon by  running the runas /savecred command once and then moving the hidden encrypted file in and out as needed.

A: You probably do not want to use the /savecred option, anyhow, as this saves your password (encrypted) to the profile globally and unconditionally, for the user to run any time, with any command that they can start with "runas", not just the command you intended. Saving your password in a CMDKey alias is not a good idea, either. If you need to be able to run a command using alternate or elevated credentials, the preferred (and more secure) method is creating a Scheduled Task to run the command with alternate/elevated credentials. See my answer here https://superuser.com/a/903881/229612 for the details on how to do this, and other information.