text:
Q: Binding to the model for property changes On another post (Prism BindableBase.SetProperty()), @brian-lagunas said he prefers to expose the Model as a property and bind the View to the model properties.  He gave the following example code:
 public class MyViewModel : BindableBase
 {
     private Person _myPerson;
     public Person Person
     {
         get { return _myPerson; }
         set { SetProperty(ref _myPerson, value); }
     }
 }

However, I'm unsure how I'm to bind to the properties.  Does this notify of property changes?
Update:
Is this how I would implement INPC on the model?  If so, what have I gained that I would not have had by putting the properties in the view model which already supports INPC?
public class Person : INotifyPropertyChanged
{
    private string _FirstName;
    private string _LastName;
    public string FirstName { get { return _FirstName; } set => SetProperty(ref _FirstName, value); }
    public string LastName { get { return _LastName; } set => SetProperty(ref _LastName, value); }
    private void SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
    {
        if (!Equals(storage,value))
        {
            storage = value;
            OnPropertyChanged(propertyName);
        }
    }
    private void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    public event PropertyChangedEventHandler PropertyChanged;
}

A: Given the following model:
public class Person
{
   public string FirstName { get; set; }
}

Binding to the FirstName property, any update to FirstName would not have a notification of property changes. The only way to accomplish this is if your model implements INotifyPropertyChanged.
That said, binding directly to a model can be an excellent strategy. As a common example if you have a ListView, you can usually bind to an ObservableCollection<SomeModel> safely. If you're working with a relatively small dataset and can afford the overhead of reloading your data source then your pretty safe all the way around.
Now as far as how to bind to a property, given:
public class ViewAViewModel : BindableBase
{
    private Person _myPerson;
    public Person MyPerson
    {
        get { return _myPerson; }
        set { SetProperty( ref _myPerson, value ); }
    }
}

Your XAML Markup would look something like:
<Label Text="{Binding MyPerson.FirstName}" />

UPDATE:
As described in your updated question, yes you could implement INotifyPropertyChanged like that. Remember it's already done for you with BindableBase so given your example you could simply inherit from BindableBase... Another good option is if you use MvvmHelpers from James Montemagno you could use his ObservableObject on your Models and the BaseViewModel for your ViewModels which gives you properties like Title, SubTitle, Icon, IsBusy, IsNotBusy.
The benefit of doing this of course is that you now have an ability to bind directly to a Model. A View rarely knows just about a Model consider the following:
Person Model
public class Person : BindableBase
{
    private string _firstName;
    public string FirstName
    {
        get { return _firstName; }
        set { SetProperty( ref _firstName, value ); }
    }

    private string _lastName;
    public string LastName
    {
        get { return _lastName; }
        set { SetProperty( ref _lastName, value ); }
    }

    private DateTime _dob;
    public DateTime DOB
    {
        get { return _dob; }
        set { SetProperty( ref _dob, value ); }
    }
}

User Profile ViewModel
public class UserProfileViewModel : BindableBase, INavigationAware
{
    INavigationService _navigationService { get; }
    IPageDialogService _pageDialogService { get; }

    public UserProfileViewModel( INavigationService navigationService, IPageDialogService pageDialogService )
    {
        _navigationService = navigationService;
        _pageDialogService = pageDialogService;
        DoFooCommand = new DelegateCommand( () => _pageDialogService.DisplayAlertAsync( "Alert", "Foo", "Ok" ) );
    }

    private bool shouldSave = false;

    private string _title;
    public string Title
    {
        get { return _title; }
        set { SetProperty( ref _title, value ); }
    }

    private Person _user;
    public Person User
    {
        get { return _user; }
        set { SetProperty( ref _user, value ); }
    }

    public DelegateCommand DoFooCommand { get; }

    public void OnNavigatingTo( NavigationParameters parameters )
    {
        Title = AppResources.UserProfilePageTitle;
        User = parameters.GetValue<Person>( "currentUser" );
        User.PropertyChanged += ( sender, e ) => shouldSave = true;
    }

    public void OnNavigatedFrom( NavigationParameters parameters )
    {
        if( shouldSave )
        {
            // Do your persistence here.
        }
    }

    public void OnNavigatedTo( NavigationParameters parameters )
    {
        User.DOB = new DateTime( 2017, 1, 1 );
    }
}

User Profile View
<ContentPage Title="{Binding Title}">
    <StackLayout>
        <Label Text="First Name" />
        <Entry Text="{Binding User.FirstName}" />
        <Label Text="Last Name" />
        <Entry Text="{Binding User.LastName}" />
        <Label Text="{Binding User.DOB}" />
        <Button Text="Do Foo" Command="{Binding DoFooCommand}" />
    </StackLayout>
</ContentPage>

Given this code there should be a couple of things worth noting:
1) Our ViewModel consists of various things that have nothing what so ever to do with our Model like Commands, or properties like the Title. It is also likely consuming various services like the INavigationService or IPageDialogService
2) Second we may want to restrict which properties a user can edit and the ViewModel can edit.
3) If our model implements INotifyPropertyChanged we can attach an event handler to let us know that our model changed after we set it so we can persist those changes.
4) It makes the XAML more readable about our intent. We aren't binding to some magic property called FirstName. We are really binding to our Person model's FirstName property.

A:
I'm unsure how I'm to bind to the properties.

To bind to properties of model you have to data bind to property which exposes model and its property, i.e. if you have exposed your model with property 'Person'
and want to bind to Name property of person, you'll need no bind to 'Person.Name'.

Does this notify of property changes?

https://msdn.microsoft.com/en-us/library/dn736263(v=pandp.50).aspx
SetProperty method will take care of notifying property change.


text:
Q: php memcached persistence between requests I am having a difficulty understanding why memcached connection doesn't persist between requests. I use this code to test if memcached remembers the added servers:
$mc = new Memcached('cache1');
var_dump($mc->getServerList());
$mc->addServer('127.0.0.1', 11211);

the result I expected was that on each page load the var_dumped getServerList array would grow with added servers but I keep getting 0 servers in the list.
Do I have a wrong assumption of how memcached persistence is supposed to work?
Or is there some PHP setting I need to change?
Obviously the following works but it's not persisted through different requests:
$mc = new Memcached('cache1');
var_dump($mc->getServerList());
$mc->addServer('127.0.0.1', 11211);
$mc2 = new Memcached('cache1');
$mc2->addServer('127.0.0.1', 11211);
var_dump($mc->getServerList()); // as expected it shows 2 servers so it is persisted within the request but not across requests

phpinfo says fastCGI is enabled if it matters.
I read all these warnings regarding adding servers without checking if they already exist but right now it doesn't matter because they never exist...
Thank you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Defining a math symbol of variable sizes in XeTeX with \Umathchardef I need to use a character in a TrueType font as a math symbol. Having seen morbusg's answer, I tried something like this:
\font\mymathtfont="Times New Roman"
\font\mymathsfont="Times New Roman/S=7" at 7pt
\font\mymathssfont="Times New Roman/S=5" at 5pt
\newfam\mymathfam
\textfont\mymathfam=\mymathtfont
\scriptfont\mymathfam=\mymathsfont
\scriptscriptfont\mymathfam=\mymathssfont
\Umathchardef\mysym 3 \mymathfam "1D76

The command \mysym does print the symbol, but when the font size in the article changes (for example by adding \fontsize{14.4pt}{1.3\baselineskip}\selectfont after \begin{document}), the size of the symbol printed by \mysym remains the same. I speculate that it is because the font sizes are fixed when the font is selected, so what is the correct way to select the font in this case? Thanks!

A: Setting up math fonts is a delicate matter and you don't need it for just a few symbols.
\documentclass{article}
\usepackage{amsmath}
\usepackage{fontspec}

\newfontfamily{\timesnewroman}{Times New Roman}

\DeclareRobustCommand\mysym{%
  \mathrel{\text{\normalfont\timesnewroman\symbol{"1D76}}}%
}

\begin{document}

$a\mysym b+\sum_{a\mysym b}X$

\Huge

$a\mysym b$

\end{document}


text:
Q: Position altair legend top-center I would like to position an altair legend top-center. Getting it to the top is simple enough by passing legend=alt.Legend(title=None, orient="top"). I also gather that this is possible in vega-lite but am having trouble making that all work together.
`

A: Altair does not yet support the layout property that newer versions of Vega-Lite support, but you can position your legend manually following the approach used in one of the other answers to the linked question.
For example:
import altair as alt
from vega_datasets import data

source = data.cars()

alt.Chart(source).mark_circle(size=60).encode(
    x='Horsepower',
    y='Miles_per_Gallon',
    color=alt.Color('Origin', legend=alt.Legend(
        orient='none',
        legendX=130, legendY=-40,
        direction='horizontal',
        titleAnchor='middle'))
)


text:
Q: Returning the rest of the string with stringtokenizer Looked for over an hour and cannot seem to find a way to implement this.
I have a stringtokenizer object that is breaking apart a string(a mathematical expression). After reaching a certain point I want to be able to just take what is left of the string after the current position(I want to then use it recursively)
If I do
StringTokenizer sTokenizer = new StringTokenizer(expression);
//operations with some of the tokens here
System.out.println(sTokenizer.nextToken());

it will delimit by spaces.
I tried
sTokenizer.nextToken(null)

but that just throws a null pointer exception.
I know I could just put some random string in the parameter that is unlikely to show up in the expression, but that isn't ideal.
If I were implementing this with substrings
expression.substring(currentposition)

would work, but I need stringtokenizer.
In short, I'm trying to figure out a way to retrieve the remainder of a string(that is being used by stringtokenizer) as a single token.

A: You can use sTokenizer.nextToken(""). It is close to what you are looking for. This returns the rest of the String as a single token including the delimiter.  Example:
public static void main(String[] args){
    String expression = "a b c d e";
    StringTokenizer sTokenizer  = new StringTokenizer(expression);
    System.out.println(sTokenizer.nextToken());
    System.out.println(sTokenizer.nextToken(""));
}

Output:
a
 b c d e


text:
Q: TSQL with Group By Count and Rank Let's say I have the following:
DECLARE @Name TABLE (Name VARCHAR(MAX));

INSERT INTO @Name VALUES ('bob'),('bob'),('john'),('john'),('mark'),('mark'),('mark'),('lisa');

SELECT  Name,
COUNT(Name) AS TOTALS
FROM @Name
GROUP BY Name
ORDER BY TOTALS DESC;

How can I also use Rank() or Dense_Rank() to get the rankings based on the counts?

A: If you want a rank column, you can use it with group by:
SELECT n.Name, COUNT(*) as TOTALS,
       RANK() OVER (ORDER BY COUNT(*) DESC) as Total_Rank
FROM @Name n
GROUP BY n.Name
ORDER BY TOTALS DESC;

A: Try this:
SELECT *
    , RANK() OVER(ORDER BY totals DESC) AS Rank
FROM
(
    SELECT  Name,
    COUNT(Name) AS TOTALS
    FROM @Name
    GROUP BY Name
) a


text:
Q: SQL division by zero i have a query that in a sub query calculates amount by dividing two of the columns. I get this error that i have division by zero, but actually i don't have 0 or NULL values. Here is the query:
SELECT
(SELECT ISNULL((IznosIni/VrednostIni),0)
from  plPlataF f1
where plPresmetka_id in
    (select plPresmetka_id from plPresmetka where f_vlezno=1 and Kod ='01')
and f1.plPlataS_id=s.plPlataS_id)
FROM plPlataS s
WHERE plPlataH_Id = 171

when i run this query (i only concatenate the two values with '---' in between)
SELECT
(SELECT CONVERT(NVARCHAR(20),IznosIni)+'---'+CONVERT(NVARCHAR(20),VrednostIni)
from  plPlataF f1
where plPresmetka_id in
    (select plPresmetka_id from plPresmetka where f_vlezno=1 and Kod ='01')
and f1.plPlataS_id=s.plPlataS_id)
FROM plPlataS s
WHERE plPlataH_Id = 171

i get results :
32414.00---168.00
37613.00---168.00
31341.00---168.00
49148.00---168.00
110507.00---168.00
36601.00---168.00
37895.00---168.00
59699.00---168.00
43978.00---168.00
50991.00---168.00
36601.00---168.00
48087.00---168.00
45921.00---168.00
59499.00---168.00
37613.00---168.00
37613.00---168.00
34850.00---168.00
33632.00---168.00
33632.00---168.00

There is no 0 anywhere!!!
Can someone please help i don't understand what the problem might be.
Thanks in advance.

A: Since you are using ISNULL, I'm guessing this is TSQL. You should always take into account on division about the possibility of dividing by zero. You can use NULLIF for this:
SELECT
(SELECT ISNULL((IznosIni/NULLIF(VrednostIni,0)),0)
from  plPlataF f1
where plPresmetka_id in
    (select plPresmetka_id from plPresmetka where f_vlezno=1 and Kod ='01')
and f1.plPlataS_id=s.plPlataS_id)
FROM plPlataS s
WHERE plPlataH_Id = 171

A: It seems like your RDBMS is evaluating the division before it applied the where filter. This is entirely legal.
You need to guard against that possibility like this:
case when VrednostIni = 0 then null else ISNULL((IznosIni/VrednostIni),0 end


text:
Q: How to connect different deployments in Kubernetes? I have two back-end deployments, REST server and a database server, each running on some specific ports. The REST server internally calls a database server.
Now how do I refer my database server deployment in my REST server deployment so that they can communicate with each other?

A: first, define a service for your DB server, that will create sort of a loadbalancer (internal kube integration based on iptables in most cases). With that, you will be able to refer to it by service name or fqdn like mydbsvc.namespace.svc.cluster.local. Which will return "Cluster IP" to that loadbalancer.
Then it's just an issue of regular app config to point it to your DB on mydbsvc, preferably by means of env variable like say DB_HOST=mydbsvc set in your REST API deployment manifest (pod template envs)

A: *

*Expose your deployments as service. For example, kubectl expose ...

*Connect/Allow these to communicate by creating network policies.

Service object (of database) will give you a virtual (stable) IP. Depending upon the type of service your rest code can call DB via clusterIP/externalName/externalIP/DNS.


text:
Q: QGIS 3.10 atlas / composer, avoid missing text edge of map? How to avoid missing texts near edge between map images?
I have vector topographic map which need to cut through map names.
When I create atlas project using Composer, those cutting text are missing from both maps. How to solve this problem?
I am using 3.10 version


text:
Q: Every time I restart a specific Windows Service, I have to re-enter logon details I have set up the Azure Devops build agent running as a Windows service. Every time I restart/start the service I get a popup

Error 1069 The service did not start due to a logon error

If I go into the service Log On settings and re-enter the same credentials, it will now start. Each time I do this I get a popup

The account  has been granted the Log On As A Service right

But why would this be? It seems like the right is not 'sticking' somehow?

A: This is probably due to a group policy overwriting your local policy. Please see "Why does my Windows Service keep forgetting its password?" for the details.


text:
Q: Fluent nHibernate , IDictionary Confusion Using the following classes..
public class Trait
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
}
public class Sheet
{
    public virtual int Id { get; set; }
    public virtual IDictionary<Trait, int> Influences { get; set; }
}

I have tried to map them using Fluent nHibernate, as such.
public class TraitMap : ClassMap<Trait>
{
    public TraitMap()
    {
        Id(x => x.Id);
        Map(x => x.Name);
        Table("Traits");
    }
}
public class SheetMap : ClassMap<Sheet>
{
    public SheetMap()
    {
        Id(x => x.Id);

        HasManyToMany<Trait>(x => x.Influences)
            .Schema("Sheets")
            .Table("Influences")
            .ParentKeyColumn("Trait")
            .ChildKeyColumn("Sheet")
            .AsMap<int>("Rating")
            .Cascade.All();

        Table("Sheets");
    }
}

This does not work. I get the exception.

Exception occurred getter of Trait.Id

Now, if I change the Dictionary up to look like this..
public class Sheet
{
    public virtual int Id { get; set; }
    public virtual IDictionary<int, Trait> Influences { get; set; }
}

Basically making the int the Key, and the Trait the value (not what I want), it does work. Can anyone explain this, and how I can more appropriately reproduce what I am trying to do?

I think the reasoning is because when I specify HasManyToMany<Trait> I am specifying the Value element of the collection. However this is not my intention.

I want to look things up by the Name of the Key, not the Name of the Value. While I realize this is technically an 'acceptable' solution, it kind of goes against the Dictionary convention. I'd prefer to take a more convention over solution approach, if at all possible - and I'd like to better understand what is actually going on under the hood.

A: What you want is what <composite-index> mapping in hbm would give you.  I believe that instead of AsMap, you'd want AsEntityMap.   However, look at this thread which talks about a rewrite (in august) of the fluent mapping for Maps that makes all of the above obsolete.
EDIT : For AsEntityMap, and other options, take a look at this SO question and answer
  HasMany<Trait>(x => x.Influences)
    .KeyColumn("key column name")
    .AsEntityMap("referenced column name")
    .Entity("dict value", v=> v.Type<int>());

Also, you say you're on the latest version - the latest release is 1.1, but trunk is 2.0, and is very different, and much further along. If you're not on 2.0+, you wouldn't see the methods posted in most of the help threads like the one linked above.


text:
Q: SDL_Rect: What is the formula to get a rectangle in the center of the screen? I'm currently trying my hand at SDL and would like to know how to go about getting a rectangle in the center of the screen.
For example, let's say I have a 640x480 screen, and I want a rectangle that is half the width and height of those resolutions to be in the middle of the screen. I know it would be:
SDL_Rect centerRect = { 640 / 4, 480 / 4, 640 / 2, 480 / 2 };
Is there a formula that would allow me to put any rectangle of any width and height in the middle each time?
Note: I'm not trying to find the co-ordinates of the center point of the rectangle. Just the co-ordinates for the top left point when all I have to go by is the width and height of the screen and rectangle.

A: Origin of your screen is top/left.
Middle of the screen:
xcenter = w / 2; ycenter = h/2;

Left upper point:
x = xcenter - (winrect.width()/2);
y = ycenter - (winrect.height()/2);

Now you only have to place your window there.


text:
Q: Merge two branches based on the diff I'm looking for a way to merge two different branches looking at the code patches instead of the commits. But I would also want to keep parts of the original commits(the hash would obviously change).
I'm able to solve the first part by doing the following steps:
git merge feature_branch --squash --no-commit
git reset HEAD
git add -p

but with these steps, the history of the commit is lost.


text:
Q: Integral Equation with Non convergent Eigenfunction Expansion Let $K(x,y)=K(y,x)$ be a continuous symmetric function.
The integral equation
$$\varphi(x)=\lambda\int_a^b K(x,y)\varphi(y)dy$$ has eigenvalues $\lambda_n$ and eigenfunctions $\varphi_n(x)$. It is known that if
$$\sum\limits_{n=1}^{\infty}\frac{\varphi_n(x)\varphi_n(y)}{\lambda_n}$$ converges uniformly then it converges to $K(x,y)$.
What is an example of $K(x,y)$ where the series does not converge to $K(x,y)$ ?
The interval $[a,b]$ is finite.
Perhaps an example with $$\sum\frac{\sin(nx)\sin(ny)}{n} ?$$


text:
Q: CountA using data in the worksheet in order to reference external file I'm trying to get this bit of code working:
Sub GetExternalData()

    Dim wbPath As String, WorkbookName As String
    Dim WorksheetName As String, CellRef As String
    Dim Ret As String, i As Long, N As Long

    For i = 1 To Sheets("x").Cells(Rows.Count, 1).End(xlUp).Row

        wbPath = Sheets("x").Cells(i, 1).Value
        WorkbookName = Sheets("x").Cells(i, 2).Value
        WorksheetName = Sheets("x").Cells(i, 3).Value
        CellRef = Sheets("x").Cells(i, 4).Value

        Ret = Application.WorksheetFunction.CountA("'" & wbPath & "[" & WorkbookName & "]" & _
              WorksheetName & "'!" & Range("C:C").Select)

        Sheets("x").Cells(i, 5).Value = ExecuteExcel4Macro(Ret)

    Next i
End Sub

Basically, I have a folder path in column 1, file name in column 2 and worksheet name in column three. I want to take these and find the number of items in column C of the reference file.
Currently the equation only outputs a value of 1 when there are 30 some values in the column. Wondering if there is something wrong with how I am calling the COUNTA function, result of which is later used in ExecuteExcel4Macro. Originally it was just meant to call a specific value in ref file (value at C2), for which it did work.

A: ExecuteExcel4Macro can be used to read individual cells, but you can't pass any function to it: only if it's a valid Excel 4.0 macro function (see https://exceloffthegrid.com/download/4095/)
Easiest to do this by opening the workbooks:
Sub GetExternalData()

    Dim wbPath As String, WorkbookName As String
    Dim WorksheetName As String, CellRef As String
    Dim Ret as long, i As Long, N As Long

    With ThisWorkbook.Worksheets("x")
        For i = 1 To .Cells(.Rows.Count, 1).End(xlUp).Row

            wbPath = .Cells(i, 1).Value
            WorkbookName = .Cells(i, 2).Value
            WorksheetName = .Cells(i, 3).Value
            'CellRef = .Cells(i, 4).Value

            With Workbooks.Open(wbPath & "\" & WorkbookName).Worksheets(WorksheetName)
                Ret = Application.CountA(.Columns("C"))
                .Parent.Close False
            End With
            .Cells(i, 5).Value = Ret

        Next i
    End With
End Sub


text:
Q: Faz diferença usar LONGTEXT ao invés de VARCHAR(255) Eu gostaria de saber se eu usar LONGTEXT ao invés de VARCHAR(255) causaria mais "lag", qual teria uma vantagem maior ??

A: Sim, faz diferença.
Esses dois tipos de dados são armazenados de formas diferente no banco de dados e tem funcionamentos diferentes. Por exemplo, você consegue indexar uma coluna do tipo VARCHAR, mas não pode indexar uma coluna do tipo TEXT ou LONGTEXT
Só use LONGTEXT se for para armazenar uma granda quantidade de texto nessa coluna (ela pode armazenar até 4GB). Do contrário, para informações textuais mais simples, prefira VARCHAR.


text:
Q: Dialogflow parameter entity similar to Alexa's AMAZON.SearchQuery I've developed an Alexa skill and now I am in the process of porting it over to a Google action. At the center of my Alexa skill, I use AMAZON.SearchQuery slot type to capture free-form text messages. Is there an entity/parameter type that is similar for google actions? As an example, see the following interactions from my Alexa skill:
Alexa, tell my test app to say hello everyone my name is Corey
-> slot value = "hello everyone my name is Corey"
Alexa, tell my test app to say goodbye friends I'm logging off
-> slot value = "goodbye friends I'm logging off"

A: Yes, you have a few options depending on exactly what you want to accomplish as part of your Action.
Using @sys.any
The most equivalent entity type in Dialogflow is the built-in type @sys.any. To use this, you can create an Intent, give it a sample phrase, and select any of the text that would represent what you want included in the parameter. Then select the @sys.any entity type.
Afterwards, it would look something like this.

You may be tempted to select all the text in the sample phrase. Don't do this, since it messes up the training and parsing. Instead use...
Fallback Intents
The Fallback Intent is something that isn't available for Alexa. It is an Intent that gets triggered if there are no other Intents that would match. (It has some additional abilities when you're using Contexts, but thats another topic.)
Fallback Intents will send the entire contents of what the user said to your fulfillment webhook. To create a Fallback Intent, you can either use the default one that is provided, or from the list of Intents select the three dot menu next to the create button and then select "Create Fallback Intent"

So you may be tempted to just create a Fallback Intent if all you want is all the text that the user says. If that is the case, there is an easier way...
Use the Action SDK
If you have your own Natural Language Processing / Understanding (NLP/NLU) system, you don't need Dialogflow in the mix. You just want the Assistant to send you the result of the speech-to-text processing.
You can do this with the Action SDK. In many ways, it is similar to how ASK and Dialogflow work, but it has very basic Intents - most of the time it will just send your webhook a TEXT intent with the contents of what the user has said and let you process it.

A: Most of the Platform based ASR systems are mainly built on 3 main parameters
1. Intent - all sorts of logic will be written here
2. Entity - On which the intent will work
3. Response - After executing all the process this is what the user will able to hear.
There is another important parameter called webhook, it is used to interact with an external API.
the basic functionalities are the same for all the platforms, already used dialogflow(google developed this platform- supports most of the platforms even Alexa too), Alexa, Watson(developed by IBM).
remember one thing that to get a precise result giving proper training phases is very much important as the o/p hugely depends on the sample input.


text:
Q: How can I solve an implicit equation without the symbolic toolbox? I have an equation like this:
(5+x)^2/15+(x-4)^2/10=100

Can MATLAB solve this equation directly, without having access to the symbolic toolbox? If it can not do this, how can I resolve this problem?

A: It's possible, but requires some hand work.
Your function is a polynomial:
x^2/6 - (2*x)/15 + 49/15 = 100

When pulling the 100 to the left hand side, we can find the roots:
roots([1/6 -2/15 -1451/15])
ans =
   24.4948
  -23.6948

where the argument is specified as the prefactors in decreasing order of power.
Code with which I found the polynomial (requires the Symbolic Math toolbox):
syms x
fun = (5+x)^2/15+(x-4)^2/10-100;
f = simplify(fun);

A: How about using an anonymous function:
f=@(x)(5+x)^2/15+(x-4)^2/10-100;
X0=1; % initial guess
x_out=fzero(f,X0);


text:
Q: Change Activity Monitor update speed? When viewing the CPU Load on Activity Monitor today, I was curious as how to make Activity Monitor update the chart and data faster.
Is there a setting to change the update speed for Activity Monitor?

A: To change the update speed, open Activity Monitor and select View > Update Frequency.
You can choose between three options:

*

*Very often (1 sec)

*Often (2 sec)

*Normal (5 sec)


text:
Q: SwiftUI: I want to reduce the spacing between the sections in this list The goal is to have the two sections in the list separate, but closer together, nearly touching; about a 16px gap. The design of the default list is what is wanted for the design.
I have tried using .listRowInsets(top: , .leading: , .bottom: , .trailing: ), but that just screws up view of the GoPremium() button, cutting off the image, etc.
I tried placing GoPremium() outside the List but in the VStack, but then the background does not match the rest of the list(which is the intended background for the design). It also does not conform to the frame I want, being too wide. .frame(width: 382, height: 140 It seems like there's a point where the image won't get any less wide, unless it is put in the List.
struct SettingsView: View {
    @State var pageSelected: String?
    @State var pages: [String] = ["Add your own", "Notifications", "About", "Instagram", "Twitter", "Email", "Terms of Service", "Privacy Policy"]

    var footer: some View {
        Text("footer")
            .font(.body).fontWeight(.bold)
            .foregroundColor(.black)
            .frame(maxHeight: .infinity, alignment: .bottom)
            .padding(.bottom)
    }

    var body: some View {
        List {
            Section {
                GoPremium()
                    .listRowInsets(EdgeInsets())
            }
            ForEach(pages, id: \.self) { item in
                Button {
                    self.pageSelected = item
                } label: {
                    Text(item)
                        .font(.callout).fontWeight(.semibold)
                        .foregroundColor(.black)
                }
            }
        }
        .scrollDisabled(true)
        .navigationBarBackButtonHidden(true)
        .navigationBarTitle("Settings", displayMode: .large)
        .navigationBarItems(leading: BackButton())
        .overlay(footer)
    }
}

The gap between the GoPremium() section and the ForEach loop is too big.
GoPremium() is a struct containing a button:
struct GoPremium: View {
    var body: some View {
        VStack {
            Button {
            } label: {
                Image("goPremium")
                    .resizable()
                    .aspectRatio(contentMode: .fill)
                    .overlay(
                        VStack(alignment: .leading, spacing: 12) {
                            Text("Go Premium")
                                .font(.title2).fontWeight(.bold)
                            Text("Access all **********, ******, *****, and remove ads!")
                                .multilineTextAlignment(.leading)
                                .shadow(radius: 1, x: 0, y: 3)
                        }
                        .padding()
                        .foregroundColor(.white))
            }
            .cornerRadius(12)
            .shadow(radius: 3, x: 0, y: 5)
            Spacer(minLength: 7)
        }
    }
}


text:
Q: How to sort two types of menus one based on Id and other normal to make it smooth moving to pages? I have this website http://dryadavbhatta.com.np/, my menu is id based to scroll on the page for menus except for publication and forum page, So How can I sort my menu smooth when moving from publication to education or other like moving from home to others menu except for last two menus?

A: Publication and Forum are two completely different pages... There is no way to animate that page change unless you move them into the single page application the rest of your site is under.
So basically, take the code for those two pages, put it in the original page and then the same way you performed smooth scrolling between every other section apply that to publication and forum.


text:
Q: Memory efficient representation of ``model.matrix`` Assume we have a large data.table object with model variables:
library(data.table)
library(magrittr)
library(pryr)
library(caret)

df <- rnorm(10000000, 0, 1) %>% matrix(., ncol = 10) %>% as.data.table
df[,factor_vars:=LETTERS[sample(1:26, 1000000, replace = T)]]
df[,factor_vars2:=LETTERS[sample(1:5, 1000000, replace = T)]]

I'm looking for an efficient way of making a model variable matrix from the data. At the moment the best way I've found is by using caret::dummyVars in the following manner:
dd_object <- dummyVars(~ -1 + V1 + V2 + V3 + V4 + V5 + V6 + V7 +
                         V8 + V9 + V10 + I(as.character(factor_vars)) +
                         I(as.character(factor_vars2)),
                       data = df)

Note that this creates a very convenient object for exporting and recreating without the original data.
object_size(dd_object)
R> 17.3 kB

On the other hand, same as with the base::model.matrix, it still retains the inefficiencies of the matrix object when dealing with many zeroes, i.e.:
MM1 <- predict(dd_object, newdata = df)
object_size(MM1)
R> 392 MB
object_size(df)
R> 96 MB

Note that the sizes can blow up very easily with more dummy variables added and etc., this is just for demonstration purposes.
My question: I want to use the same model-matrix object for various known modelling packages (glm,glmnet,xgboost and etc). The sparse matrix representation from Matrix packages does sound nice and efficient, but not every package is able to work with it, and as.matrix(.) transformation is a pain in that case.
Are there any known solutions for my case? I'm looking for something with greater efficiency than the base matrix (possibly like sparse matrices) and the capability of forming a storeable model.matrix object just like caret::dummyVars is able to do.
The desired workflow could be something along the lines of
fread %>% predict(dummyVars_object, newdata =.) %>% predict(some_Model, newdata =.)


text:
Q: C++ undefined reference to class that uses template I'm pretty new with templates, so please don't be harsh on me if my code is very wrong :)
This is the header file for a class Key that uses a template:
//Key.h
#ifndef KEY_H
#define KEY_H

#include "../Constants.h"

template<class KeyType>

class Key
{
    public:
        Key<KeyType>(KeyType initial);
        KeyType increment();

    private:
        KeyType current;

};

#endif /* KEY_H */

This is the .cpp file of Key class:
//Key.cpp
#include "Key.h"

template<class KeyType> Key<KeyType>::Key(KeyType p_initial)
{
    this->current = p_initial;
}

template<class KeyType> KeyType Key<KeyType>::increment()
{
    this->current ++; //KeyType should implement this operator
}

So what's the problem? I try to create an instance of Key somewhere else in my code, like this:

Key songID (0); // ERROR: undefined reference to Key<int>::Key(int)

and then use

songID.increment(); // ERROR: undefined reference to Key<int>::increment()

A: Two points:

*

*Remove <KeyType> from Key<KeyType>(KeyType initial); you don't need it.

*And, move class implementation from .cpp file to .h  file. Thie article is useful: Why can't I separate the definition of my templates class from its declaration and put it inside a .cpp file?


text:
Q: Performant text search in a large number of XML text nodes and decide if a pattern occurs once I have XML files with size about 50MB to a maximum of 2GB with tens or hundreds of thousands of mycomment elements that have only a text node. The path to mycomment node is not fix and not defined and thus //mycomment is the only way to get all of them. Length of mycomment/text() is about 50 to 500 chars. I need to search for one pattern in all mycomment text nodes in order to categorize the file. If pattern " mypattern1234 " is found in one of the text nodes variable hit is set to 1 else it is empty. Is it a good solution to calculate hit like this:
  <xsl:variable name="hit">
    <xsl:if test="//mycomment[contains(text(),' mypattern1234 ')]">1</xsl:if>
  </xsl:variable>

:-) I'm using XSLT v1.0. Thank you.

A: You're not going to be able to handle a 2GB input document unless you switch to a streaming XSLT 3.0 processor such as Saxon-EE.
If you're using a streaming processor then I would suggest doing it as
<xsl:source-document href="input.xml" streamable="yes">
  <xsl:if test="//text()[parent::comment][contains(.,' mypattern1234 ')]>1</xsl:if>
</xsl:source-document>

It's a bit less overhead to only look at the text nodes and then examine their context, rather than to matching the element nodes and then setting up a search for the child text nodes.
I would expect a 2Gb search to run in about a minute, depending on your hardware. However, the scan of the source document should stop as soon as a match is found, so if you find a match near the start of the document it will be much faster than this.

A: It is not clear whether the mycomment elements can have mixed contents or text nodes interleaved with comments or processing instructions. Normally, if you expect the mycomment elements to only have text content, I would check on mycomment[contains(., ' foo ')], there is no need to select down to text node children. If you want to do that, then I would use mycomment/text()[contains(., ' foo ')], your check of text() as the argument to contains would select the first text child node, so in e.g. <mycomment>foo <!-- a comment --> mypattern1234 </mycomment> the text would not be detected.
As for efficiency, that will depend very much on the XSLT processor used.

A: Aside from XML technologies ripgrep makes searching orders of magnitude faster:
#!/bin/zsh

DATABASE="$1"
SEARCH_PATTERN="$2"

if [ "${#SEARCH_PATTERN}" != 0 ] && [ "${#DATABASE}" != 0 ] ; then

RAWHIT=`rg -C 5 "$SEARCH_PATTERN" "$DATABASE"`

if [ "${#RAWHIT}" != 0 ] ; then
HIT=`echo $RAWHIT | rg -c -U "<comment>.*$SEARCH_PATTERN.*</comment>"`
if [ "${#HIT}" != 0 ] ; then
    echo "Pattern found"
else
    echo "Pattern not found"
fi
else
    echo "Pattern not found"
fi
else
    echo "Missing Search Pattern or Database"
fi

Running and time measurement on i5 platform:
> time ./run.sh DB50C1000000P.xml Foo4711
Pattern found
./run.sh DB50C1000000P.xml Foo4711  0,23s user 0,58s system 98% cpu 0,828 total

> time ./run.sh DB50C1000000P.xml Foo4711a
Pattern not found
./run.sh DB50C1000000P.xml Foo4711a  0,23s user 0,59s system 98% cpu 0,829 total

Database download: Database

A: Comparing the techniques - XPath with XQuery or XSLT and ripgrep:

*

*Solution 1 (M.H.): //comment[contains(.,'searchpattern')]

*Solution 2 (M.S.): //comment[contains(text(),'searchpattern')]

*Solution 3 (M.K.): //text()[parent:comment][contains(.,'searchpattern')]
Platform:
MacBook, i5, macOS v10.15.4, 16GB RAM
XML Database:
Size: 2.46GB
Number of comment element nodes (have a single text node where the pattern will be searched) = 5914102
Number of other element nodes (not comment) = 11829597
XQuery v3.1, BaseX v9.3.2
 > time java -Xmx10g -cp /Users/ms/Projekte/basex/BaseX.jar org.basex.BaseX -bsolution=1 -bdatabase=DB50C1000000P -bpattern=Foo4711 run.xqy
 Solution 1: Pattern found
 java -Xmx10g -cp /Users/ms/Projekte/basex/BaseX.jar org.basex.BaseX    run.xq  28,96s user 2,82s system 188% cpu 16,826 total

 > time java -Xmx10g -cp /Users/ms/Projekte/basex/BaseX.jar org.basex.BaseX -bsolution=1 -bdatabase=DB50C1000000P -bpattern=Foo4711a run.xqy
 Solution 1: Pattern not found
 java -Xmx10g -cp /Users/ms/Projekte/basex/BaseX.jar org.basex.BaseX    run.xq  42,62s user 4,05s system 140% cpu 33,233 total

 > time java -Xmx10g -cp /Users/ms/Projekte/basex/BaseX.jar org.basex.BaseX -bsolution=2 -bdatabase=DB50C1000000P -bpattern=Foo4711 run.xqy
 Solution 2: Pattern found
 java -Xmx10g -cp /Users/ms/Projekte/basex/BaseX.jar org.basex.BaseX    run.xq  29,25s user 2,70s system 196% cpu 16,271 total

 > time java -Xmx10g -cp /Users/ms/Projekte/basex/BaseX.jar org.basex.BaseX -bsolution=2 -bdatabase=DB50C1000000P -bpattern=Foo4711a run.xqy
 Solution 2: Pattern not found
 java -Xmx10g -cp /Users/ms/Projekte/basex/BaseX.jar org.basex.BaseX    run.xq  47,45s user 4,84s system 143% cpu 36,341 total

 > time java -Xmx10g -cp /Users/ms/Projekte/basex/BaseX.jar org.basex.BaseX -bsolution=3 -bdatabase=DB50C1000000P -bpattern=Foo4711 run.xqy
 Solution 3: Pattern found
 java -Xmx10g -cp /Users/ms/Projekte/basex/BaseX.jar org.basex.BaseX    run.xq  30,09s user 2,70s system 195% cpu 16,773 total

 > time java -Xmx10g -cp /Users/ms/Projekte/basex/BaseX.jar org.basex.BaseX -bsolution=3 -bdatabase=DB50C1000000P -bpattern=Foo4711a run.xqy
 Solution 3: Pattern not found
 java -Xmx10g -cp /Users/ms/Projekte/basex/BaseX.jar org.basex.BaseX    run.xq  45,42s user 4,32s system 148% cpu 33,413 total

XSLT v3.0, SaxonEE v9-9-1-7J
 > time java -Xmx10g -jar /Users/ms/Projekte/SaxonEE9-9-1-7J/saxon9ee.jar  -s:empty.xml -xsl:run.xsl -o:out.xml database=DB50C1000000P.xml pattern=Foo4711 solution=1
 Solution 1: Pattern found
 java -Xmx10g -jar /Users/ms/Projekte/SaxonEE9-9-1-7J/saxon9ee.jar -s:empty.xm  27,43s user 5,88s system 134% cpu 24,719 total

 > time java -Xmx10g -jar /Users/ms/Projekte/SaxonEE9-9-1-7J/saxon9ee.jar  -s:empty.xml -xsl:run.xsl -o:out.xml database=DB50C1000000P.xml pattern=Foo4711a solution=1
 Solution 1: Pattern not found
 java -Xmx10g -jar /Users/ms/Projekte/SaxonEE9-9-1-7J/saxon9ee.jar -s:empty.xm  30,28s user 9,06s system 131% cpu 29,964 total

 > time java -Xmx10g -jar /Users/ms/Projekte/SaxonEE9-9-1-7J/saxon9ee.jar  -s:empty.xml -xsl:run.xsl -o:out.xml database=DB50C1000000P.xml pattern=Foo4711 solution=2
 Solution 2: Pattern found
 java -Xmx10g -jar /Users/ms/Projekte/SaxonEE9-9-1-7J/saxon9ee.jar -s:empty.xm  27,55s user 4,44s system 158% cpu 20,202 total

 > time java -Xmx10g -jar /Users/ms/Projekte/SaxonEE9-9-1-7J/saxon9ee.jar  -s:empty.xml -xsl:run.xsl -o:out.xml database=DB50C1000000P.xml pattern=Foo4711a solution=2
 Solution 2: Pattern not found
 java -Xmx10g -jar /Users/ms/Projekte/SaxonEE9-9-1-7J/saxon9ee.jar -s:empty.xm  34,47s user 5,24s system 177% cpu 22,324 total

 > time java -Xmx10g -jar /Users/ms/Projekte/SaxonEE9-9-1-7J/saxon9ee.jar  -s:empty.xml -xsl:run.xsl -o:out.xml database=DB50C1000000P.xml pattern=Foo4711 solution=3
 Solution 3: Pattern found
 java -Xmx10g -jar /Users/ms/Projekte/SaxonEE9-9-1-7J/saxon9ee.jar -s:empty.xm  16,13s user 0,62s system 130% cpu 12,816 total

 > time java -Xmx10g -jar /Users/ms/Projekte/SaxonEE9-9-1-7J/saxon9ee.jar  -s:empty.xml -xsl:run.xsl -o:out.xml database=DB50C1000000P.xml pattern=Foo4711a solution=3
 Solution 3: Pattern not found
 java -Xmx10g -jar /Users/ms/Projekte/SaxonEE9-9-1-7J/saxon9ee.jar -s:empty.xm  47,26s user 1,56s system 110% cpu 44,247 total

Result
Good Case: There is a at least one comment with the search pattern
Fastest (16,13s):
Solution 3 (M.K.) on XSLT v3.0, SaxonEE v9-9-1-7J
Slowest (30,09s):
Solution 3 (M.K.) on XQuery v3.1, BaseX v9.3.2
Bad Case: There is no comment with the search pattern
Fastest (30,28s):
Solution 1 (M.H.) on XQuery v3.1, BaseX v9.3.2
Slowest (47,26s):
Solution 3 (M.K.) on XQuery v3.1, BaseX v9.3.2
Scripts and XML Database
https://gitlab.com/ms152718212/xslxqyfindpattern
Solutions with non XML technologies
ripgrep (rg)
> time rg -C 5 'Foo4711' DB50C1000000P.xml | rg -c -U '<comment>(?s:[^<]*)Foo4711(?s:[^<]*)</comment>'
4

rg -C 5 'Foo4711' DB50C1000000P.xml  0,27s user 0,72s system 90% cpu 1,094 total

rg -c -U '<comment>(?s:[^<]*)Foo4711(?s:[^<]*)</comment>'  0,01s user 0,01s system 1% cpu 1,092 total

> time rg -C 5 'Foo4711a' DB50C1000000P.xml | rg -c -U '<comment>(?s:[^<]*)Foo4711a(?s:[^<]*)</comment>'

rg -C 5 'Foo4711a' DB50C1000000P.xml  0,24s user 0,66s system 93% cpu 0,957 total

rg -c -U '<comment>(?s:[^<]*)Foo4711a(?s:[^<]*)</comment>'  0,01s user 0,01s system 1% cpu 0,957 total


text:
Q: How to add numbers given as a list of tuples given in the form: ('name', number) def highest_n_scores(scores, n = 5):
Each player plays the game some number of times, each time resulting in a tuple (name, score) for how much that player scored in the game. Given all games played as a list of such tuples, add up the n highest scores for each individual player as the total score for that player. Create and return a list that contains tuples (name, total) for the players and their total scores, sorted in ascending order by name. If some player has played fewer than n times, just add up the scores of whatever games that player has played.
The code is below but I wanted to know if there is a more efficient way of doing this and it also doesn't seem to work using the tester.
def highest_n_scores(scores, n):

    bill = sorted([p for (t,p) in scores if t == 'bill'])
    jack = sorted([p for (t,p) in scores if t == 'jack'])
    sheldon = sorted([p for (t,p) in scores if t == 'sheldon'])
    tina = sorted([p for (t,p) in scores if t == 'tina'])
    amy = sorted([p for (t,p) in scores if t == 'amy'])
    bob = sorted([p for (t,p) in scores if t == 'bob'])

    scoreBill = sum(bill[-n:])
    scoreJack = sum(jack[-n:])
    scoreSheldon = sum(sheldon[-n:])
    scoreTina = sum(tina[-n:])
    scoreAmy = sum(amy[-n:])
    scoreBob = sum(bob[-n:])

    return sorted([('bill', scoreBill), ('jack', scoreJack), ('sheldon', scoreSheldon), ('tina', scoreTina), ('amy', scoreAmy), ('bob', scoreBob)])

I get the correct result, but the tester for all values however, the tester I was given to test the code says my answer is wrong.
list :
[('bill', 10), ('jack', 6), ('sheldon', 3), ('tina', 2), ('amy', 3), ('sheldon', 6), ('tina', 7), ('jack', 2), ('bob', 3), ('bob', 4), ('bill', 3), ('bill', 9), ('sheldon', 5), ('amy', 2), ('jack', 7), ('sheldon', 5), ('sheldon', 7), ('bill', 1), ('bill', 9), ('sheldon', 5), ('bill', 2), ('bill', 6), ('jack', 6), ('bob', 4), ('tina', 5), ('sheldon', 4), ('sheldon', 2), ('amy', 6), ('bob', 7), ('jack', 2), ('bob', 5), ('sheldon', 9), ('jack', 5), ('amy', 9), ('bob', 7), ('tina', 6), ('tina', 2), ('amy', 7), ('jack', 10), ('tina', 4), ('bob', 5), ('jack', 10), ('bob', 7), ('jack', 5), ('amy', 4), ('amy', 8), ('bob', 4), ('bill', 8), ('bob', 6), ('tina', 6), ('amy', 9), ('bill', 4), ('jack', 2), ('amy', 2), ('amy', 4), ('sheldon', 1), ('tina', 3), ('bill', 9), ('tina', 4), ('tina', 9)] when n = 3

list return :
[('amy', 26), ('bill', 28), ('bob', 21), ('jack', 27), ('sheldon', 22), ('tina', 22)]

A: You currently are creating as many variables as the names, which is not very efficient and scalable, instead you could think on using a dictionary to store your information
You can start by collecting all scores in a dictionary, with the key as the name and the value as the list of scores. You then iterate over the dictionary, and for each name, you sort the score in descending order, and find the sum of the first n elements.
The code will look like:
scores = [('bill', 10), ('jack', 6), ('sheldon', 3), ('tina', 2), ('amy', 3), ('sheldon', 6), ('tina', 7), ('jack', 2), ('bob', 3), ('bob', 4), ('bill', 3), ('bill', 9), ('sheldon', 5), ('amy', 2), ('jack', 7), ('sheldon', 5), ('sheldon', 7), ('bill', 1), ('bill', 9), ('sheldon', 5), ('bill', 2), ('bill', 6), ('jack', 6), ('bob', 4), ('tina', 5), ('sheldon', 4), ('sheldon', 2), ('amy', 6), ('bob', 7), ('jack', 2), ('bob', 5), ('sheldon', 9), ('jack', 5), ('amy', 9), ('bob', 7), ('tina', 6), ('tina', 2), ('amy', 7), ('jack', 10), ('tina', 4), ('bob', 5), ('jack', 10), ('bob', 7), ('jack', 5), ('amy', 4), ('amy', 8), ('bob', 4), ('bill', 8), ('bob', 6), ('tina', 6), ('amy', 9), ('bill', 4), ('jack', 2), ('amy', 2), ('amy', 4), ('sheldon', 1), ('tina', 3), ('bill', 9), ('tina', 4), ('tina', 9)]

def highest_n_scores(scores, n = 5):

    scores_dict = {}

    #Make a dictionary of name to list of scores
    for name, score in scores:
        #Set the default value of the dict as an empty list
        scores_dict.setdefault(name, [])
        #Append the score to the name
        scores_dict[name].append(score)

    result_list = []

    #Iterate over the dictionary
    for name, score in scores_dict.items():

        #For total score, sort the list in descending order, and take the sum of first n elements
        total_score = sum(sorted(score, reverse=True)[:n])
        result_list.append((name, total_score))

    return result_list

print(highest_n_scores(scores, 3))

and the output will be
[('bill', 28), ('jack', 27), ('sheldon', 22), ('tina', 22), ('amy', 26), ('bob', 21)]

A: using a dict you could do this.
def highest_n_scores(scores, n):
    result = dict()
    for name , score in scores:
        if name in result.keys():
            result[name].append(score)
        else:
            result[name] = []
            result[name].append(score)

    for key , item in result.items():
        result[key] = sum(result[key][-n:])

    return sorted(result.items(), key=lambda kv: kv[1] , reverse=True)


text:
Q: How do I convert all accounts on a dovecot IMAP server from one Maildir layout to another? I am currently running dovecot 2.x on a server with the following layout for mailboxes:
mail_location = maildir:~/Maildir

I would like to change the layout to this format:
mail_location = maildir:~/Maildir:LAYOUT=fs:INBOX=~/Maildir/INBOX

Is there a way to convert the mailbox layout for all mail accounts currently on the server? I was looking at dsync, but all examples in Dovecot's wiki are for converting between mbox and Maildir.
I was also looking at potentially writing a script to manually rename directories/move files around to match the new format, but wasn't sure whether that would mess with UIDs or other dovecot internals.

A: Because you do not need to change anything inside each Maildir directory (i.e. inside the folder that contains the cur, new, tmp directories and the dovecot indices), moving the directories around with a script will be perfectly safe, and quite sufficient.
The only exception to this is for INBOX itself, because you have it directly in ~/Maildir now and you would like to move it to a subdirectory. But even then, I think that a script that is careful about what files it moves and which ones it doesn't is the best way to go. If you move every plain file from ~/Maildir to ~/Maildir/INBOX (covers all Dovecot index files) plus cur, new, tmp (covers the contents themselves) and leave all other subdirectories alone (covers other folders) then I think that should do the trick.


text:
Q: Unable to pass template data to golang container with embedded FS I am trying to containerise my Golang application using Docker swarm.
I noticed that in my local computer, the template data is passed properly, however, inside the container, it seems that the template data is not being passed. I am using embedded FS to store the template and using Caddy to proxy pass to the front-end service (if it's relevant).
Just wondering if anyone has encountered this issue, thank you very much in advance! Additionally it seems that using {{print .BrokerURL "/handle"}} does NOT automatically add double quote in the fetch() function which also results in error...
Please find below the relevant code and file:
File structure

Makefile
FRONT_BINARY=frontEndApp

# Build the binary
env GOOS=linux CGO_ENABLED=0 go build -o ${FRONT_BINARY} ./cmd/web

Dockerfile
FROM alpine:latest

RUN mkdir /app

COPY frontEndApp /app

CMD ["/app/frontEndApp"]

DockerSwarm.yml
front-end:
    image: front-end:1.0.1
    deploy:
      mode: replicated
      replicas: 1
    environment:
      BROKER_URL: "http://backend"

main.go
package main

import (
    "embed"
    "fmt"
    "html/template"
    "log"
    "net/http"
    "os"
)

func main() {
    // Only / because we only have 1 page
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        render(w, "test.page.gohtml")
    })

    fmt.Println("Starting front end service on port 8081")
    err := http.ListenAndServe(":8081", nil)
    if err != nil {
        log.Panic(err)
    }
}

// embed templates folder to read only filesystem
//
//go:embed templates
var templateFS embed.FS

func render(w http.ResponseWriter, t string) {
    // Go template files to be parsed together with the given template
    partials := []string{
        "templates/base.layout.gohtml",
        "templates/header.partial.gohtml",
        "templates/footer.partial.gohtml",
    }

    // Add the page to the slice
    var templateSlice []string
    templateSlice = append(templateSlice, fmt.Sprintf("templates/%s", t))

    // Combine the templates with the page
    for _, x := range partials {
        templateSlice = append(templateSlice, x)
    }

    // Parse the page and templates
    tmpl, err := template.ParseFS(templateFS, templateSlice...)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    var data struct {
        BrokerURL string
    }
    data.BrokerURL = os.Getenv("BROKER_URL")

    if err := tmpl.Execute(w, data); err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
}

base.layout.gohtml
{{define "base" }}
    <!doctype html>

    {{template "header" .}}

    {{block "content" .}}

    {{end}}

    {{block "js" .}}

    {{end}}

    {{template "footer" .}}

{{end}}

footer.partial.gohtml
{{define "footer"}}

                Copyright ©

{{end}}

header.partial.gohtml
{{define "header"}}

        <meta charset="UTF-8">
        <meta name="viewport"
              content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Microservices in Go</title>
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

{{end}}

test.page.gohtml
{{define "js"}}


text:
Q: Bluemix public CF App protect/private REST Endpoint I have a public Bluemix CF APP which exposes a REST Service. I would like to have the option, that the public url bound to the CFApp would be inaccessible from outside. The REST Service itself should only be usable from other CF Apps in my org, for example over API Management. I don't want to implement an own security mechanism for it, because API Management provides already everything I need to control, which clients will access my service. So some kind of private route inside Bluemix public, only available to runtimes and services in my Bluemix organisation.

A: This is not currently possible with IBM Bluemix, due to limitations in Cloud Foundry.
All bound routes are accessible from the external network.
If you want to have a private API exposed, you have the following options.

*

*Add authentication to the REST API, managing the credentials as a user-provided service bound to all the apps. The API will be accessible externally but only by users with the credentials.

*Use an application service, like a message queue, to expose an internal RPC-style API. Applications can bind to the same service and it will only be accessible internally.


text:
Q: Django TastyPie PUT Nested User Model Correctly I'm trying to go with-the-grain using Django TastyPie to update my models.  I have an Identity model, acting as a wrapper around default Django user model:
class Identity(ProfileBase):
    user = models.OneToOneField(User, related_name='identity')
    avatar = models.ImageField(upload_to=avatar_upload_path, blank=True,
        null=True)

I have my UserResource:
class UserResource(ModelResource):

    class Meta:
        resource_name = 'user'
        queryset = User.objects.all()
        fields = ['email', 'first_name', 'last_name']
        include_resource_uri = False

And I have my IdentityResource:
class IdentityResource(ModelResource):
    user = fields.ToOneField(UserResource, 'user', full=True)

    class Meta:
        resource_name = 'identity'
        queryset = Identity.objects.select_related()
        fields = ['user', 'avatar']
        always_return_data = True
        include_resource_uri = False

        authentication = OAuthTokenAuthentication()
        authorization = Authorization()

I'm currently successfully updating first_name, last_name using the ModelResource obj_update method within IdentityResource:
def obj_update(self, bundle, request, **kwargs):
    print 'updating object'
    bundle = self.full_hydrate(bundle)
    bundle.obj.user = request.user
    user = bundle.data['user']
    bundle.obj.user.first_name = user['first_name']
    bundle.obj.user.last_name = user['last_name']
    return super(IdentityResource, self).obj_update(bundle, request, user=request.user)

I want to make a PUT request and optionally update any field on the user or identity models (first_name, last_name on user, or the avatar field on identity). I would rather not have to manually access each field from the bundle data and set them on models manually, as I have done above.
How can I do this naturally in TastyPie?  Can someone explain a better approach to solving this problem?  Any direction is GREATLY appreciated. :)

A: Here's my shot at providing an answer that attempts to leverage Tastypie as much as possible.
It is a little more generic than the OP's request (it will update any user, not just the one logged in). In the real world you would probably want to add some sort of authentication/authorization.
from tastypie.resources import ModelResource
from tastypie.authorization import Authorization
from django.contrib.auth.models import User
from myapp.account.models import Identity

class IdentityResource(ModelResource):
    class Meta:
        queryset = Identity.objects.all()

class UserResource(ModelResource):
    class Meta:
        queryset = User.objects.all()
        allowed_list_methods = ['get']
        allowed_detail_methods = ['get','put']
        authorization = Authorization()

    def dehydrate(self, bundle):
        identity_bundle = self.build_identity_bundle(bundle)
        identity_bundle = IdentityResource().full_dehydrate(identity_bundle)
        return identity_bundle

    def obj_update(self, bundle, request, **kwargs):
        user_bundle = super(UserResource, self).obj_update(bundle, request, **kwargs)
        identity_bundle = self.build_identity_bundle(user_bundle)
        IdentityResource().obj_update(identity_bundle, request)
        return user_bundle

    def build_identity_bundle(self, user_bundle):
        identity_bundle = IdentityResource().build_bundle(
                obj=user_bundle.obj.get_profile(),
                data=user_bundle.data
            )
        return identity_bundle

What the example supports is:

*

*GET a flattened User+Identity resource

*PUT a flattened User+Identity resource, updating both models

You would want to register the UserResource in the API, and probably not the IdentityResource.

A: You could do something like this.
# Find all properties in user model.
properties = [prop for prop in bunder.obj.user if not prop.startswith('__')]
bundle_user = bundle.data['user']
# Find the property in bundle user and set it back on user if it exists.
for property in properties:
  if property in bundle_user:
    setattr(bundle.obj.user, property, bundle_user[property])

A: Maybe I'm missing the point but did you try a PATCH-method request? Tastypie will take all the sent attributes and update them in the database leaving all not-send attributes untouched.


text:
Q: php display wrong date first, sorry if my English is not so good.
so, I have this problem in the date() function in my localhost and also in the free hosting, the function always display wrong time.
I use XAMPP
php.ini timezone in my localhost is : Africa/Casablanca my location
on my localhost when I run this code
echo date("D, m/d/Y H:i:s a T e");

It gives this out put : Mon, 09/14/2015 00:24:36 am WEST Africa/Casablanca
when I should get Mon, 09/13/2015 23:24:36 pm GMT GMT
1 hour of difference
so, when I add this code in my script nothing change date_default_timezone_set('Africa/Casablanca');
But when I replace Africa/Casablanca by GMT
It display the correct time like this Mon, 09/13/2015 23:24:36 am GMT GMT
in the free hosting it's not the same the previous code display this out put
Sun, 09/13/2015 18:24:39 pm EDT America/New_York
and with date_default_timezone_set('Africa/Casablanca'); the time is  correct
Mon, 09/13/2015 23:24:36 am WEST Africa/Casablanca
but with date_default_timezone_set('GMT');  again one hour of difference
Sun, 09/13/2015 22:58:59 pm GMT GMT
Does any one have a solution.
thanks, and have a good day

A: Daylight savings is not applied to GMT.  Try using Europe/London instead.


text:
Q: Many to many relationship in Laravel I'm trying to build an application on Laravel 5.3 where my models, database and controllers are in separate folders. I have the following folder structure:
Nitseditor
    System
        Controllers
        Database
            2016_12_28_130149_create_domains_table.php
            2017_01_06_193355_create_themes_table.php
            2017_01_07_140804_create_themes_domains_table.php
        Models
            Domain.php
            Theme.php

I'm making a relationship in domain with many to many relationship i.e.
public function themes()
{
    return $this->belongsToMany('Nitseditor\System\Models\Domain');
}

I've named the table domain_theme inside the 2017_01_07_140804_create_themes_domains_table.php
Now I'm trying to get the theme name which belongs to the domain in the controller something like this:
$flashmesage = new Domain;

foreach ($flashmesage->themes as $theme)
{
    return $theme->theme_name;
}

I'm getting an error:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'nitswebbuilder.domain_domain' doesn't exist (SQL: select domains.*, domain_domain.domain_id as pivot_domain_id from domains inner join domain_domain on domains.id = domain_domain.domain_id where domain_domain.domain_id is null and domains.deleted_at is null)

A: sorry for my short comment as answer... I have not enough reputation for comment,
change your themes() method to :
public function themes()
{
    return $this->belongsToMany('Nitseditor\System\Models\Theme');
}

see Here for more info

A: Table name should be called domain_theme. If you've used corrent names for foreign keys and have built correct relationships, whereHas() will work for you:
$domainName = 'example.com';

$themes = Theme::whereHas('domains', function($q) ($domainName) {
    $q->where('domain_name', $domainName);
})->get();

Then show all themes names:
@foreach ($themes as $theme)
    {{ $theme->theme_name }}
@endforeach


text:
Q: Saving multiple images and naming them indvidually? I'm trying to take a screenshot of a region, in a loop, save the screenshots to a folder and rename them so they don't overwrite each other.
I'm wanting a folder full of images with unique names, ideally timestamps but I've not figured that out at all yet so I'm using a counter for now.
import pyautogui as py

                    for image in image_list:
                        screenshot = py.screenshot(region=(x,y,w,h)
                        save_path = r'C:\'
                        count = count + 1
                        name_of_file = count
                        completeName = os.path.join(save_path, name_of_file+".png")
                        screenshot.save(completeName)

Is giving me this error;
Exception has occurred: TypeError
unsupported operand type(s) for +: 'int' and 'str'
    completeName = os.path.join(save_path, name_of_file+".png")

I've tried:

*

*Wrapping name_of_file+ with str: completeName = os.path.join(save_path, (str(name_of_file+".png")))
But I get the same error message.
I tried:

*

*swapping the + for a ,

*wrapping everything completeName = os.path.join(str(save_path), (str(name_of_file,".png")))
And those gave me a different error message: TypeError: decoding to str: need a bytes-like object, int found

A: The error says that it your variable is not a float therefore:
completeName = os.path.join(save_path, name_of_file+".png")

should read:
completeName = os.path.join(save_path, str(name_of_file)+".png")

Consider using pathlib to construct paths in your script. This is a more robust way that using r"C:\".

A: You can try with file_name_<>.png like-
(This format works on cv2.write. Hopefully should work in pyautogui too)
count = 0

completeName = "<save_path>/screenshot_%d.png" %count
count = count + 1
screenshot.save(completename)


text:
Q: Laravel Stripe Checkout Workflow I have a small question about the Stripe workflow and there is one area in particular where I would like to know your opinion and experience. My setup is: Laravel 8 and "stripe/stripe-php": "^7.97".
The workflow as I understand it:

*

*Client wants to pay with stripe

*Client sends XHR request to application server (Laravel)

*The server generates a Stripe payment intent with the Stripe Key.

*Stripe sends back a key.

*The server passes this key on to the client.

*Stripe JS is loaded (https://js.stripe.com/v3/)

*Stripe JS renders a payment form (credit card number etc).

*The client enters his credit card details.

*The client then clicks on "pay".

*Stripe receives the client's credit card information along with the Stripe Payment Intent Key.

*If the data is correct, the payment process is successfully completed at Stripe.

*Stripe sends back the payment status information to the client as a response.

*This information will then be sent from the client to the server.

*The server can mark the order as completed.

My questions:
a) Have I understood the workflow correctly?
b) Would you already store the order in the database at the payment intention (Point 3.) or only at the last point (Point 14.)?

A: a) Your understanding is correct. But for Step 13 and 14 you would want to use Webhook to complete your order on Server instead. More intuitive guide is on Stripe's official document.

b) On Point 3 you can create an order but need to mark its status something like uncompleted. On Point 14 you can mark it completed and start providing your service. The reason is the customer can drop off between (ie not providing Card detail and simply close the browser).


text:
Q: update session variables inside Javascript I have a page called index.php where i have all my php functions, javascripts and html tags.
Upon button click (add to cart) event i want to call a php function ( addtToCart($itemID) ) to update session variables. Can you tell me how to implement this in my code ?
<?php
session_start();
$_SESSION['Mid']="";
$_SESSION['$UserName']="test"; ?>

//html part
<button id='cart'
onclick="<script>idk how to call my function here</script>"
class="w3-button">ADD TO CART</button>

 //my php function
<?php
  function addToCart($Mid){
    if(!isset($_SESSION['$UserName'])){
            header('Location:signin.html');
    }
    $_SESSION['Mid'].="+".$Mid;
    echo "<script type='text/javascript'>alert(\"ADDED TO CART\");</script>";
  }
?>

A: Use an aJax call to call another PHP script that updates it:
        var SendInfo= {     "your": data,
                            "your1": data1 };

        $.ajax({
                type: 'POST',
                url: 'https://yourscript.com/updatesession.php',
                data: SendInfo,
                contentType: "application/x-www-form-urlencoded; charset=UTF-8",
                traditional: true,
                success: function (data) {
                    //dostuff
                }
        });


text:
Q: What does gets.chomp do? I was also wondering if I always have to put the exclamation point after .capitalize!
print "What's your first name? "
first_name = gets.chomp
first_name.capitalize!

print "What's your last name? "
last_name = gets.chomp
last_name.capitalize!

print "What city are you from? "
city = gets.chomp
city.capitalize!

print "What state or province are you from? "
state = gets.chomp
state.capitalize!.upcase!

puts "Your name is #{first_name} #{last_name} and you're from #{city}, #{state}!"

A:
What does gets.chomp do?

If you type denisreturn then gets would return "denis\n" where \n is the line feed character from the return key. chomp removes such trailing newline:
"denis\n".chomp
#=> "denis"

I was also wondering if I always have to put the exclamation point after .capitalize!

In general, a bang method is a method like any other: (from the documentation for method names)

The bang methods (! at the end of method name) are called and executed just like any other method.

But:

[...] by convention, a method with an exclamation point or bang is considered dangerous.

Dangerous can mean various things, depending on the context. For built-in methods from Ruby's core library it usually means:

[...] that when a method ends with a bang (!), it indicates that unlike its non-bang equivalent, permanently modifies its receiver.

So capitalize! (with !) will modify first_name: (the method's receiver)
first_name = 'denis'    #=> "denis"
first_name.capitalize!  #=> "Denis"
first_name              #=> "Denis"

capitalize! will also return nil if the string is already capitalized:
first_name = 'Denis'    #=> "Denis"
first_name.capitalize!  #=> nil
first_name              #=> "Denis"

Whereas capitalize (without !) will always return a new (capitalized) string, leaving first_name unchanged:
first_name = 'denis'    #=> "denis"
first_name.capitalize   #=> "Denis"
first_name              #=> "denis"

Apparently, the capitalize call above doesn't make much sense because the return value is not used anywhere. You usually want to do something with that new string like assigning it to a variable:
capitalized_first_name = first_name.capitalize

or passing it to a method:
puts "Your name is #{first_name.capitalize}"

A: chomp removes the linebreak character at the end of the string input.
Adding the ! will mutate the value of your variable. It is not required. It depends on your use case.
foo = 'foo'
foo.capitalize
print foo
=> 'foo'

bar = 'bar'
bar.capitalize!
print bar
=> 'Bar'

A: Of course you don't need the "!". Let's try to get by without them:
print "What's your first name? "
first_name = gets.chomp.capitalize

print "What's your last name? "
last_name = gets.chomp.capitalize

print "What city are you from? "
city = gets.chomp.capitalize

print "What state or province are you from? "
state = gets.chomp.upcase

puts "Your name is #{first_name} #{last_name} and you're from #{city}, #{state}!"

There you go. You can avoid mutation and just manipulate your strings with standard methods. No "!" methods need apply!
ps: capitalize followed by upcase is the same as just upcase.


text:
Q: Intel Graphics card problem with Kernel 4.10 and prime select crash I have a Dell XPS-15 9560 with Windows 10 pre-installed. It has 2 graphics cards, a NVIDIA GTX 1050 and an Intel 620 Kabylake GT2.
I install ubuntu 16.04 through live-USB. The installation finishes and everything seems functional. It is using the default Intel graphics card and kernel 4.10.0-36.
When I try to shut down, this happens. I am stuck on this screen, watching these random error messages and having to force-shutdown.
Debugging:
-When I use an older kernel, there are no errors and it shuts down normally. I do get this screen on startup but no crashes/freezes.
-Ubuntu doesn't recognize the NVIDIA card right off the bat. When I install the proprietary nvidia drivers everything works across the board (I can even shutdown in kernel 4.10!) but the laptop is always using the NVIDIA card, meaning that I only have 1-2h battery life.
-HOWEVER, and this is the strangest part, when I try through 'NVIDIA X Settings'/'PRIME profiles' to change to the Intel card which WAS working perfectly before, all hell breaks loose. I get errors when I try to shut down, and failure on boot.
Why does the change of a kernel solve the first problem? Why when I update NVIDIA's drivers I can't go back to Intel? All this makes no sense..
I've tried everything, read through every post, followed any tactic suggested in similar posts to no avail. Any insight or ideas for further debugging would be welcome.

A: Open /etc/default/grub with your favorite editor . Replace   GRUB_CMDLINE_LINUX_DEFAULT="quiet splash" with
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash acpi_rev_override=1"
Save and exit
Run the command:
Sudo update-grub


text:
Q: Why ss -e doesn't show uid? I have a debian VM, here the info:
las@Client:~$ cat /etc/os-release
PRETTY_NAME="Debian GNU/Linux 8 (jessie)"
NAME="Debian GNU/Linux"
VERSION_ID="8"
VERSION="8 (jessie)"

When I type ss -nte I expect to see the uid of the process that uses the socket because of the -e option, but it doesn't appear and I can't figure it out why. Here's the output:
las@Client:~$ ss -nte
State       Recv-Q Send-Q                    Local Address:Port                      Peer Address:Port
ESTAB       0      176                      192.168.56.201:22                        192.168.56.1:50468  timer:(on,204ms,0) ino:12286 sk:ffff88000e7f3140 <->

How can I solve this?

A: The ss command (any version) will display an uid only if it's not zero. Here's the source for the Debian 8 jessie version:
    if (show_details) {
        if (s.uid)
            printf(" uid:%u", (unsigned)s.uid);
        printf(" ino:%u", s.ino);
        printf(" sk:%llx", s.sk);
        if (opt[0])
            printf(" opt:\"%s\"", opt);
    }

The test if (s.uid) makes it not display the information each time the socket owner's uid value is 0.
Additional tests (but using kernel 5.6 and a matching ss from iproute2 5.6.0), show that indeed a normal user can know the owner's uid of an other socket even if not owned by itself. So the absence of the uid: entry can mean only two things: owned by the root user, or owned by the kernel (which is different, but can't be distinguished here).
In your case, as the sshd daemon is running as root, all TCP sockets related to it will be owned by root, even if sshd grants a non-root login. The user login granted by sshd is not connected to any TCP socket: it's connected to the sshd daemon (or a separate instance of it) through master/slave PTYs or else with pipes. So ss can't be used to match a TCP connection to a user locally logged in through incoming ssh.


text:
Q: MissingBackpressureException: Could not emit buffer due to lack of requests I've received a bug report including MissingBackpressureException: Could not emit buffer due to lack of requests for an RxJava Flowable, but I'm struggling to create a simple test case the demonstrates the problem (maintaining the structure of the Flowable).
Here's the test I'm trying to put together, which maintains the same stages in the pipeline:
int inputEvents=10000;

CountDownLatch completed = new CountDownLatch(1);
Flowable<List<String>> flowable = Flowable.<String>create(e -> {

    System.out.println(Thread.currentThread().getName() + ": Will send");
    for (int counter = 0; counter < inputEvents; counter++) {
        e.onNext("" + counter);
        Thread.sleep(5);
    }
    System.out.println(Thread.currentThread().getName() + ": Completed sending");
    e.onComplete();
}, BackpressureStrategy.DROP)
    .onBackpressureDrop(s -> System.out.println("Backpressure, dropping " + Arrays.asList(s)))
    .buffer(1, TimeUnit.SECONDS)
    .doOnNext(strings -> System.out.println("\t" + Thread.currentThread().getName() + ": Buffered: " + strings.size() + " items"))
    .observeOn(Schedulers.io(), false)
    .doOnNext(strings -> {
        System.out.println("\t" + "\t" + Thread.currentThread().getName() + ": Waiting: " + strings.size());
        Thread.sleep(5000);
    });

flowable
    .subscribe(s -> System.out.println("\t" + "\t" + "onNext: " + s.size()),
            error -> {
                throw new RuntimeException(error);
            },
            () -> {
                System.out.println("\t" + "\t" + "Complete");
                completed.countDown();
            });

completed.await();

In production, we get MissingBackpressureException: Could not emit buffer due to lack of requests with the following stack trace:
io.reactivex.rxjava3.exceptions.MissingBackpressureException: Could not emit buffer due to lack of requests
        at io.reactivex.rxjava3.internal.subscribers.QueueDrainSubscriber.fastPathEmitMax(QueueDrainSubscriber.java:87)
        at io.reactivex.rxjava3.internal.operators.flowable.FlowableBufferTimed$BufferExactUnboundedSubscriber.run(FlowableBufferTimed.java:207)
        at io.reactivex.rxjava3.internal.schedulers.ScheduledDirectPeriodicTask.run(ScheduledDirectPeriodicTask.java:39)
        at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
        at java.util.concurrent.FutureTask.runAndReset(Unknown Source)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(Unknown Source)
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
        at java.lang.Thread.run(Unknown Source)

So I think this relates to downstream work from the buffer.
However, no matter how long I block in the doOnNext I can't reproduce the problem. Example output:
main: Will send
    RxComputationThreadPool-1: Buffered: 197 items
        RxCachedThreadScheduler-1: Waiting: 197
    RxComputationThreadPool-1: Buffered: 196 items
    RxComputationThreadPool-1: Buffered: 197 items
    RxComputationThreadPool-1: Buffered: 197 items
    RxComputationThreadPool-1: Buffered: 196 items
    RxComputationThreadPool-1: Buffered: 197 items
        onNext: 197
        RxCachedThreadScheduler-1: Waiting: 196
    RxComputationThreadPool-1: Buffered: 197 items
    RxComputationThreadPool-1: Buffered: 197 items
    RxComputationThreadPool-1: Buffered: 196 items
    RxComputationThreadPool-1: Buffered: 197 items
    RxComputationThreadPool-1: Buffered: 197 items
        onNext: 196
        RxCachedThreadScheduler-1: Waiting: 197
    RxComputationThreadPool-1: Buffered: 197 items
    RxComputationThreadPool-1: Buffered: 197 items
...

I was expecting, as the Thread.sleep(5000) takes so long, we would get back pressure.
Is there a way of simulating this, ideally in a test using TestScheduler/TestSubscriber (to avoid the Thread.sleep()s)?

A: I was able to reproduce the MissingBackpressureException by increasing the rate at which your events are emitted, increasing the max number of events, and reducing the rate at which the consumer processes them.
The buffer that's overflowing is the default observeOn(...) operator's buffer of size 128. Since it's receiving a new list once a second, it will take at least a couple of minutes of back pressure before it will overflow.
Note, you can override this default buffer size by passing it as an arg to observeOn(...).
Getting back to backpressure handling, I think the main issue with your pipeline is the buffer(1, TimeUnit.SECONDS) operator. If you look at the javadoc:

Backpressure:This operator does not support backpressure as it uses
  time. It requests Long.MAX_VALUE upstream and does not obey downstream
  requests.

As a result of the above your onBackPressureDrop(...) never gets invoked. I think you fix this by placing onBackPressureDrop(...) after buffer(...). Doing so results in your Backpressure, dropping... message.
You should be able to unit test this using:
TestScheduler.advanceTimeBy(long, TimeUnit). Though I have to admit, I haven't tried it yet.


text:
Q: while true python doesn't work as intended I'm trying to run an instruction continuosly and only when I press "e" the loop must stop, the code is:
while True:
    Code = "Hello world"
    print(Code)
    if keyboard.read_key() == "e":
        break

The problem I get is that only when I press another key (not "e") on the keyboard it prints "hello world" but I want the code to print it even if I don't press anything

A: The point is that keyboard.read_key() is waiting for you to insert a key, think at it as an input


text:
Q: Dates as regressors in linear regression I recently read this post:
Does it make sense to use a date variable in a regression?
Where the accepted answer says that dates can be used as regressors. So what I have done so far is the following:
My start date is January 1, 2018, so this is day 0. January 2, 2018 is day 1 and so on, so December 31 is day 364. I also have data for 2019, so I made January 1, 2019 day 365, January 2, 2019 day 366 and so on. The thing is, I also have categorical variables that I converted to dummy variables using One Hot Encoding. So my data looks like this basically:
Day     Feature1     Feature2     Feature3
0       0             1             0
1       1             0             0
2       0             1             0
3       0             0             1
...
400     0             0             1

The question is: day is always increasing, so what I would think is that scaling so that it takes values between 0 and 1 (using MinMaxScaler in Python for example) would be a good idea. However, if I want to forecast what happens in day 401, how do I enter this value in the model that (I believe) is of the following form:
$y = \beta_0+\beta_1(Day)+\beta_2(Feature1)+\beta_3(Feature2)+\beta_4(Feature3)$
If Day is a number between 0 and 1, how will day be also a number between 0 and 1 if scaling only applies until day 400?


text:
Q: Using multiple contexts .Net core My project depends on 2 different DB in 2 different projects and I want to make a join between 2 tables from each other and this my API code I've used
            var mBranch = (from Branch in _context.M_Branch.Where(p => p.BrnchNo == id)
                       join Dalel in _Erp_Context.Dalel on Branch.BrnchDebit equals Dalel.DalelNo into bt
                           from tt in bt.DefaultIfEmpty()
                           select new M_Branch
                           {
                               BrnchNo = Branch.BrnchNo,
                               BrnchCredit = Branch.BrnchCredit,
                               BrnchDalelDebit = tt.DalelDesc,
                               BrnchDebit = Branch.BrnchDebit,
                               BrnchDalelCredit = tt.DalelDesc,
                               BrnchDesc = Branch.BrnchDesc,
                               BrnchNotice = Branch.BrnchNotice,
                               BrnchUserNo = Branch.BrnchUserNo
                           }).FirstOrDefault();

but it says I can't use 2 different DB Context so I ended up with this solution I've found
EntityFramework context across multiple projects or joining between two contexts
but it always gets me this error

System.NullReferenceException: Object reference not set to an instance of an object.

what's the solution and what's the best way to deal with Contexts more regularly and don't affect in memory or performance

A: You might use a synonym in your database. You could create a synonym of Dalel table in _context database, or you could create M_Branch synonym in _Erp_Context, whichever makes more sense. Then you would be able to add these synonyme tables into your context in EF.
This post shows an example of using a synonym with EF: Entity Framework Code First with SQL Server Synonyms


text:
Q: DAX time intelligence functions with nested filters I have a data structure like this
DateRoll    Dataset Date    Value   Customer
Month   Online  1/1/2018    10  Cust1
Month   Online  2/1/2018    11  Cust1
Month   Online  3/1/2018    12  Cust1
Month   Online  4/1/2018    22  Cust1
Quarter Online  1/1/2018    33  Cust1
Quarter Online  4/1/2018    22  Cust1

I have to calculate previous quarter value, I tried different ways but it's not working
1 - Not returning any value.
CALCULATE (
        SUM ( 'Data_Rollup_KPI_DNR'[Value] ),
        DATEADD ( 'Data_Rollup_KPI_DNR'[Date].[Date], -1, QUARTER ),
        FILTER ( Data_Rollup_KPI_DNR, Data_Rollup_KPI_DNR[DateRoll] = "Quarter")
    )

2--Nested - Returning overall total
CALCULATE (
        CALCULATE (
            SUM ( 'Data_Rollup_KPI_DNR'[Value] ),
            DATEADD ( 'Data_Rollup_KPI_DNR'[Date].[Date], -1, QUARTER )
        ),
        FILTER ( Data_Rollup_KPI_DNR, Data_Rollup_KPI_DNR[DateRoll] = "Quarter" )
    )

3--Nested --Returning overall total
CALCULATE (
        CALCULATE (
            SUM ( 'Data_Rollup_KPI_DNR'[Value] ),
            FILTER ( Data_Rollup_KPI_DNR, Data_Rollup_KPI_DNR[DateRoll] = "Quarter" )
        ),
        DATEADD ( 'Data_Rollup_KPI_DNR'[Date].[Date], -1, MONTH )
    )

Tried PREVIOUSQUARTER function too, but its not returning any value.

A: To take advantage of built in DAX time intelligence functions you will need to to have a contiguous set of dates. I would recommend using a date table. The following code can be used to create a date/calendar table in your model:
Celndar =
Var MinDate = MIN(Data_Rollup_KPI_DNR[Date])
Var MaxDate = MAX(Data_Rollup_KPI_DNR[Date])
Var BaseCalendar = CALENDAR(MinDate, MaxDate)
RETURN
    GENERATE (
        BaseCalendar,
        VAR BaseDate = [Date]
        VAR YearDate =
            YEAR ( BaseDate )
        VAR MonthNumber =
            MONTH ( BaseDate )
        VAR YrMonth =
            100 * YEAR ( BaseDate )
                + MONTH ( BaseDate )
        VAR Qtr =
            CONCATENATE ( "Q", CEILING ( MONTH ( BaseDate ) / 3, 1 ) )
        RETURN
            ROW (
                    "Day", BaseDate,
                    "Year", YearDate,
                    "Month Number", MonthNumber,
                    "Month", FORMAT ( BaseDate, "mmmm" ),
                    "Year Month", FORMAT ( BaseDate, "mmm yy" ),
                    "YrMonth", YrMonth,
                    "Qtr", Qtr
            )
    )

Once this table exists, mark it as a 'date' table and create a relationship with
Data_Rollup_KPI_DNR[Date]

Then, you can write the following measure to obtain the results you are searching for:
PQSum =
CALCULATE (
    SUM ( 'Data_Rollup_KPI_DNR'[Value] ),
    PREVIOUSQUARTER ( 'Calendar'[Date] )
)

Hope that helps!
*Edited
You can also create a ranking column to index in a measure:
Rank =
RANKX (
    FILTER (
        'Data_Rollup_KPI_DNR',
        'Data_Rollup_KPI_DNR'[DateRoll] = EARLIER ( 'Data_Rollup_KPI_DNR'[DateRoll] )
    ),
    'Data_Rollup_KPI_DNR'[Date].[Date],
    ,
    ASC
)

Then you can reference a previous quarter using something like the following:
PQSum2 =
CALCULATE (
    SUM ( 'Data_Rollup_KPI_DNR'[Value] ),
    FILTER (
        'Data_Rollup_KPI_DNR',
        'Data_Rollup_KPI_DNR'[Rank]
            = MAX ( 'Data_Rollup_KPI_DNR'[Rank] ) - 1
    ),
    'Data_Rollup_KPI_DNR'[DateRoll] = "Quarter"
)

but this is hard coded and just plain nasty!

A: Date functions are working well when you are using @ Day level.
Following link would be helpful to resolve your issue,
https://community.powerbi.com/t5/Desktop/Lead-and-Lag-in-DAX/td-p/649162

A: Echoing @steliok that a date dimension is the proper way to handle this; there are plenty of date table templates out there, and a date dimension will work with your data model. If you really really can't add to your data structure for some reason, this should work:
BaseValue = SUM ( 'Data_Rollup_KPI_DNR'[Value] )

PriorQuarter =
VAR CurrentDate = MAX ( 'Data_Rollup_KPI_DNR'[Date] )
VAR CurrentYear = YEAR ( CurrentDate )
VAR CurrentMonth = MONTH ( CurrentDate )
VAR FirstMonthOfCurrentQuarter =
    SWITCH (
        TRUE (),
        CurrentMonth IN {1,2,3}, 1,
        CurrentMonth IN {4,5,6}, 4,
        CurrentMonth IN {7,8,9}, 7,
        CurrentMonth IN {10,11,12}, 10
    )
// DATE() does the right thing with negative month args
VAR PriorQuarterDate = DATE ( CurrentYear, FirstMonthOfCurrentQuarter - 3, 1 )
RETURN
    CALCULATE (
        [BaseValue],
        ALL ( 'Data_Rollup_KPI_DNR'[DateRoll], 'Data_Rollup_KPI_DNR'[Date] ),
        'Data_Rollup_KPI_DNR'[Date] = PriorQuarterDate,
        'Data_Rollup_KPI_DNR'[DateRoll] = "Quarter"
    )

This relies on DATE being clever, which it is. DATE ( 2019, -2, 1 ) = DATE ( 2018, 10, 1 ).
Ultimately, my question is why can't you just source the un-rolled up data from the same place that the ETL process is sourcing it?


text:
Q: Prove that the equation $ e^{x}+x^{3}=10+x $ has a unique solution on the open interval $(-\infty,\infty)$. Prove that the equation
$$
e^{x}+x^{3}=10+x
$$
has a unique solution on the open interval $(-\infty,\infty)$.
Letting $f(x)=e^{x}+x^{3}-10-x$, $f(0)<0$ and $f(10)>0$, so by the IVT there must be a solution in the interval $(0,10)$.
Now I must show there cannot be more than one solution.  Generally for these proofs you assume that there is at least 2 solutions and show a contradiction.  Letting the solutions be a and b ($a<b$ WLOG) I want to use Rolle's theorem to show that $f'(x)=e^{x}+3x^{2}-1$ cannot be zero (giving the contradiction).  The problem is $f'(0)=0$.  So how do I proceed?

A: You can observe that if $x <-1$ then $X^3-X < 0$, thus
$$f(x) <e^{-1}-10 <-9$$
Also if $x \in [-1, 1]$ we have $x^3 \leq 1$ and $-x \leq 1$ thus
$$f(x) \leq e+2-10 < -5$$
Therefore there is no solution $x \leq 1$.
Now apply your technique on $(1, \infty)$. It is easy to show tha on this interval $f'(x) >0$.

A: Prove that $f(x)$ is injective over positive real numbers.
$$f'(x) > 0, \forall x\geq0 \text{ appart for 0  and } f\in C^{\infty} (\mathbb{R}, \mathbb{R}) \implies f \text{ injective } $$
Then $\forall(a, b) \in \mathbb{R^+}^2, f(a) = f(b) \iff a=b$
And $\forall x<0, f(x) < 0$ as $x^3-x\leq1$ and $e^x<1$


text:
Q: What is the main difference between AST and JDT Java model? What their advantages and disadvantages if they used to analyze the code?

A: The JDT Java model is much higher level: it gives a structure of your project, but is limited (roughly) to definitions: packages, classes, fields, methods.
The AST is much lower level. It represents the source code faithfully, including method bodies.
The Java model is usually very fast to access, while the AST requires full Java parsing and is slower.


text:
Q: Python Pandas pkl dataframe version The pickle files I saved previously now could not be read back using .read_pickle().
The error message I got is: ImportError: cannot import name 'PY36'.
The current version of Pandas is :Version: 0.23.1.
Not sure what version was used to create the pickle files.
Please help.
Python version currently used:3.5.3 |Anaconda custom (x86_64)
Believe the old version created the pickle file is:
3.6.1 |Anaconda custom (4.4.0).
It was working before.
Additional information
data_cn=data_cn.append(pd.read_pickle(os.path.expanduser("~/Documents/RZSX-TF/SHF-margin.pkl")))

  File "//anaconda/lib/python3.5/site-packages/pandas/io/pickle.py", line 68, in read_pickle
    """

  File "//anaconda/lib/python3.5/site-packages/pandas/io/pickle.py", line 62, in try_read
    2    2    7

  File "//anaconda/lib/python3.5/site-packages/pandas/compat/pickle_compat.py", line 117, in load
    # 19939, add timedeltaindex, float64index compat from 15998 move

  File "//anaconda/lib/python3.5/pickle.py", line 1043, in load
    dispatch[key[0]](self)

  File "//anaconda/lib/python3.5/pickle.py", line 1351, in load_stack_global
    self.append(self.find_class(module, name))

  File "//anaconda/lib/python3.5/pickle.py", line 1392, in find_class
    __import__(module, level=0)

  File "//anaconda/lib/python3.5/site-packages/pandas/core/indexes/base.py", line 17, in <module>
    from pandas.core.arrays import ExtensionArray

  File "//anaconda/lib/python3.5/site-packages/pandas/core/arrays/__init__.py", line 2, in <module>
    from .categorical import Categorical  # noqa

  File "//anaconda/lib/python3.5/site-packages/pandas/core/arrays/categorical.py", line 14, in <module>
    from pandas.core.dtypes.missing import isna, notna

  File "//anaconda/lib/python3.5/site-packages/pandas/core/dtypes/missing.py", line 10, in <module>
    from .common import (is_string_dtype, is_datetimelike,

  File "//anaconda/lib/python3.5/site-packages/pandas/core/dtypes/common.py", line 4, in <module>
    from pandas.compat import (string_types, text_type, binary_type,

ImportError: cannot import name 'PY36'

A: It looks like a version error. Since the error is ImportError: cannot import name 'PY36', it means you should upgrade your version of Python to Python 3.6


text:
Q: No log statement is printing using websphere 8.0 I have one application running in WAS8.

*

*we have a jar - commons-logging-1.1.1.jar in WEB-INF/lib

*we have one properties file - commons-logging.properties
the content of the file is
priority=1
org.apache.commons.logging.LogFactory=org.apache.commons.logging.impl.LogFactoryImpl

*we have org.apache.commons.logging.LogFactory file in WebContent/META-INF/services
the content of the file is
org.apache.commons.logging.impl.Log4jFactory
The log files are created but nothing is written in it. It is not showing any error in the log files in log of appserver.
Please let me know if I am missing something.
Please note: if I keep commons-logging.properties in /opt/IBM/WebSphere/80/AppServer/profiles/AppSrv01/properties, then it works perfectly fine. It is writing in the log files. But as I heard it is not standard practice so I can't keep the file in that place. I have to find some alternative way.
Please help me.

A: If it is not a requirement to have separate log files for your web application, you can simply remove the commons-log jar and properties from your module (war) and your log statements will write to SystemOut.log according to the log level settings in the WebSphere console (which can be changed at runtime, by the way).
If you must separate application logging, you can refer to this infocenter article that lays out the combination of commons-log jar location, commons-log properties values, and application classloader settings (Parent-First, Parent-Last, commons-log.jar bundled or not, etc) to achieve the desired results.


text:
Q: Trouble Understanding URL Rewrite to Proxy to Another Server I am sorry if this is really simple and I am not paying attention. I need to redirect a url query (https://1.2.3.4:19999/abc/start?userid={digit string}) to be processed by another server (https://5.6.7.8/operate?service=checkuser&userid={digit string}).
So far I've failed to do this correctly (this is my latest attempt):
    RewriteCond %{REQUEST_URI} ^/abc/ [NC]
    RewriteCond %{QUERY_STRING} ^/abc/start?
    RewriteRule ^/abc/(.*) https://5.6.7.8/operate?service=checkuser&userid= [P]

Please can someone correct me?

A: You really don't need the first condition because the rewrite rule takes care of that. You can try this rule here.
RewriteEngine On
RewriteCond %{QUERY_STRING} userid=(.*)
RewriteRule ^/?abc/start$ https://5.6.7.8/operate?service=checkuser&userid=%1 [P]


text:
Q: iOS - centralizing CAGradientLayer into parent UIView I have a bgLayer: CAGradientLayer with bigger dimensions then it's parent view bgView. The layer is being inserted correctly using bgView.layer.insertSublayer, but I can't create the frame of my bgLayer centralized with my smaller bgView.
How could I centralize my bgLayer into my bgView?

A: I believe this is what you mean...
Larger Gradient view centered on smaller UIView. First image is with .clipsToBounds = true, second image .false.:

Both images use the same view size: 100 x 100 and the same gradient size: 150 x 150. You can paste this code into a Playground page to see how it works.
import UIKit
import PlaygroundSupport

let container = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 300))

container.backgroundColor = UIColor(red: 0.3, green: 0.5, blue: 1.0, alpha: 1.0)

PlaygroundPage.current.liveView = container

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // 150 x 150 frame for the gradient layer
        let gFrame = CGRect(x: 0, y: 0, width: 150, height: 150)

        // 100 x 100 frame for the View
        let vFrame = CGRect(x: 100, y: 100, width: 100, height: 100)

        let v = UIView(frame: vFrame)
        self.view.addSubview(v)

        // add a border to the UIView so we can see its frame
        v.layer.borderWidth = 2.0

        // set up the Gradient Layer
        let gradient = CAGradientLayer()
        gradient.colors = [UIColor.red.cgColor,UIColor.yellow.cgColor]
        gradient.locations = [0.0, 1.0]
        gradient.startPoint = CGPoint(x: 0.0, y: 0.0)
        gradient.endPoint = CGPoint(x: 1.0, y: 1.0)

        // set the initial size of the gradient frame
        gradient.frame = gFrame

        // center the gradient frame over (or inside, if smaller) the view frame
        gradient.frame.origin.x = (v.frame.size.width - gradient.frame.size.width) / 2
        gradient.frame.origin.y = (v.frame.size.height - gradient.frame.size.height) / 2

        // add the gradient layer to the view
        v.layer.insertSublayer(gradient, at: 0)

        // set to true to clip the gradient layer
        // set to false to allow the gradient layer to extend beyond the view
        v.clipsToBounds = true

    }

}

let vc = ViewController()
container.addSubview(vc.view)


text:
Q: Ошибка при введении команды pip в командную строку При установке выдает ошибку UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 1210: ordinal not in range(128).
Версия Python 2.7, в папке Scripts файлы pip присутствуют. Что делать?