text:
Q: Vue transition-group not animating properly when first list item is spliced from list I am struggling to figure out why my transition group is not animating properly on the removal of the first element from a list. I tried producing a minimal, reproducible example to share on my local machine first and was successful. I then copied the same code to CodeSandbox to share with StackOverflow but the issue no longer exists for some reason.
Here is the CodeSandbox example which works properly, and here is a recording of the same code producing the issue when served on my local machine.
In the recording, you'll see the first two elements are removed properly. They translate right and fade out, and the subsequent elements smoothly transition upwards to fill the voided space.
However, when I remove the first element on my next two clicks, the leaving element transitions properly but the subsequent elements jump instantly.
The issue is produced in Chrome, Firefox, and IE. Any idea why it's working properly in CodeSandbox but not my machine despite similar code?


text:
Q: Magento 2 Repositories and Database Transactions Almost every post I read states that I should be working on objects using Magento 2 repositories rather that instantiating objects using Magento 2 object factories.
That's what I started to do, and all was great until I wrote an small extension to programatically create a shipment whilst also writing a comment to the orders history table.
I would have expected to do something like this in a database transaction, so if there's a failure everything gets rolled back, but I just can't see how to use database transactions with repositories.
If I do something like
$order = $this->orderRepository->get($orderId);

$order->setSomething('something');

$transaction = $this->transactionFactory->create();

$transaction->addObject($order);

I get a warning in phpStorm of: Expected \Magento\Framwork\Abstract\Model, got \Magento\Sales\Api\Data\OrderInterface. Basically it looks like the database transaction object is expecting factory generated Models rather than repository generated objects. Does that mean that repositories don't actually support database transactions?

A: This is completely my opinion but I think M2 2.0 was released too soon and there were many inconsistencies in approach.
But it was a huge task to convert M1 without losing all the logic and lessons learnt. First there was the object manager. Useful in testing . Then generally speaking factory methods as they were direct ports of M1 logic. Completely logical. Why reinvent the wheel? Then came the principal of repositories (among other things i.e. search criteria). Generally they exist for most entities and work but not in all cases. And here we are today (with other concepts View models). Code is now more verbose but in theory should require minor adjustment as we move through further major releases.
The point I'm making is that I've learnt in M2 there are always exceptions to the rule. Some things work in areas but not in others. But mainly because the framework has evolved so much through the major releases.
That said take a look at my shipment console script and helper.
https://github.com/DominicWatts/AutoShipment/blob/master/Console/Command/AutoShip.php
https://github.com/DominicWatts/AutoShipment/blob/master/Helper/Shipment.php
I think that's doing what you are trying to do. But maybe I misunderstand.

redpajama_set_name: RedPajamaStackExchange


text:
Q: cannot import name 'url' from 'django.conf.urls' (/app/.heroku/python/lib/python3.9/site-packages/django/conf/urls/__init__.py) ImportError at /
cannot import name 'url' from 'django.conf.urls' (/app/.heroku/python/lib/python3.9/site-packages/django/conf/urls/__init__.py)
Request Method: GET
Request URL:    https://aas-system.herokuapp.com/
Django Version: 4.0.1
Exception Type: ImportError
Exception Value:
cannot import name 'url' from 'django.conf.urls' (/app/.heroku/python/lib/python3.9/site-packages/django/conf/urls/__init__.py)
Exception Location: /app/.heroku/python/lib/python3.9/site-packages/webpush/urls.py, line 1, in <module>
Python Executable:  /app/.heroku/python/bin/python
Python Version: 3.9.10
Python Path:
['/app/.heroku/python/bin',
 '/app',
 '/app/.heroku/python/lib/python39.zip',
 '/app/.heroku/python/lib/python3.9',
 '/app/.heroku/python/lib/python3.9/lib-dynload',
 '/app/.heroku/python/lib/python3.9/site-packages'
]
Server time:    Tue, 01 Feb 2022 07:52:34 +0000

A: It looks like you are using Django 4. In this version, url from django.conf.url no longer works.
https://docs.djangoproject.com/en/3.2/ref/urls/#url
So you have two options.
Use something below Django 3.2. I suspect that what you are doing on your local version. FYI, using pip freeze > requirements.txt in your local environment is a good way to save your configuration and it can simplify the installation in other env.
Or update your code. You should then try re_pathin order to do so
https://docs.djangoproject.com/en/4.0/ref/urls/#re-path

A: If you are using Django 4.0 and higher then django.conf.urls.url() is removed.
You can use re_path[Django-doc] in case of url, which also use regex as url.
from django.urls import path, re_path

urlpatterns = [
    re_path(r'^$', views.your_view_name),
]


text:
Q: Multiple Selection in Alert Dialog Good Day,
I created a method showDialog which will show an Alert Dialog and will list multiple data that I can select of. My problem is when I click OK, the next  method (myMethod()) i want to call is not being called. Can someone help me with this? Here is my code:
private void showDialog(List<String> list) {
    final CharSequence[] dialogList=  list.toArray(new CharSequence[list.size()]);
    final AlertDialog.Builder builderDialog = new AlertDialog.Builder(SharingActivity.this);
    builderDialog.setTitle("Select Item");
    int count = dialogList.length;
    boolean[] is_checked = new boolean[count];
    String result = "";

    builderDialog.setMultiChoiceItems(dialogList, is_checked,
            new DialogInterface.OnMultiChoiceClickListener() {
                public void onClick(DialogInterface dialog,
                                    int whichButton, boolean isChecked) {
                }
            });

    builderDialog.setPositiveButton("OK",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                    ListView list = ((AlertDialog) dialog).getListView();
                    // make selected item in the comma seprated string
                    StringBuilder stringBuilder = new StringBuilder();
                    for (int i = 0; i < list.getCount(); i++) {
                        boolean checked = list.isItemChecked(i);

                        if (checked) {
                            if (stringBuilder.length() > 0) stringBuilder.append(",");
                            stringBuilder.append(list.getItemAtPosition(i));

                        }
                    }

                    myMethod(stringBuilder.toString()); //this is the method

                }
            });

    builderDialog.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    ((TextView) findViewById(R.id.text)).setText("Click here to open Dialog");
                }
            });
    AlertDialog alert = builderDialog.create();
    alert.show();
}

Here is myMethod:
private void myMethod(String stringFriend){
Bundle extras = getIntent().getExtras();
byte[] byteArray = extras.getByteArray("image");

Bitmap image = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
//Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
SharePhoto photo = new SharePhoto.Builder()
        .setBitmap(image)
        .setCaption("")
        .build();
List<String> peopleIds =  new ArrayList<String>();
peopleIds.add(stringFriend);

SharePhotoContent content = new SharePhotoContent.Builder()
        .addPhoto(photo)
        .setPeopleIds(peopleIds)
        .build();

ShareApi.share(content, null);

}


text:
Q: Beyond configuration, allowing for flexibility on a per service call basis type of pattern Say you have a ecommerce app, and have an API call to create an order.
OrderService.create(...);
Order creation is a complicated process, many things will happen as a result of this call:

*

*shopping cart items will be used to create an order and order details

*email sent to customer

*inventory levels adjusted

*billing and shipping objects created and status changes

*etc.

Now say I only wanted to do a subset the steps from #1,2,3,4 or 5.
One approach would be a configuration setting, but that would apply to ALL OrderService.create calls regardless of who makes the call.
I want a design pattern or design that will allow me to choose what I want to happen on a PER call basis.
Is there a design pattern for this type of behaviour?  This is a new system and I want to read up on possible approaches.

A:
Is there a design pattern for this type of behaviour?

There's a solution, but I doubt it has been labelled a pattern, as this is a fairly elementary problem to solve. At best, I'd call it an authorization pattern.

I want a design pattern or design that will allow me to choose what I want to happen on a PER call basis.

The assumption here is that you want to predefine your rules, and then have the requests be treated accordingly. The only other option would be for each request to wait for manual (on the fly) user input, which doesn't sound like something you'd want.
Why am I telling you this? Well, the above conclusion proves that you need some way to format these predefined rules, in a way that your runtime can independently identify these requests and determine which rules to apply to them.
Here's where we hit a roadblock. You didn't specify how to distinguish these requests. "Per request" (as per your question) makes no sense. First of all, I doubt you're going to be creating an individual rule for every individual request that will be sent to your API. Secondly, you still haven't elaborated how a request will be identified. Is it by authorization token? Requester's IP address? Time of day? User account? Random dice roll?
For the sake of example now, I'm going to assume that you handle these based on the authenticated/authorized user account. How you include that information in the request (e.g. auth token) is an implementation detail that's up to you.
At a very barebones level, the data you need to describe your rules is something like this:
 USER     ACTIONS
===================
 Adam   |  2,3
 Ben    |  1,3,4
 Chris  |  1,2,3,4

I numbered the actions based on the bullet points you listed.
This data perfectly describes which actions a user is allowed to perform. This isn't the most future-proof implementation, but it actually does what you need it to do.
Further improvements to the below (barebones) examples are generally a good idea, but they depend on some design decisions you've made along the way. Since you didn't elaborate on the implementation details, neither can I.
Where do you store this data?
That's really up to you. There are plenty of ways to store data, each with their own benefits and drawbacks.

*

*Database - Great for configurability, especially if you want your users to be able to configure these rules. Somewhat of a performance bottleneck due to having to fire off a query.

*Config file - More cumbersome to configure (requires server access), requires an IO operation, but can pretty much ensure that only your developers can access this.

*Local file - same arguments as for the config file, but less obviously part of the codebase. Only an option if the config file is already too big.

*Hardcoded - This is the most performant option, but it's also the least configurable. Adjusting anything will require a redeploy. Any built version's ruleset is can be deterministically tested and won't ever change.

*...

It's unclear how often you're expecting to configure these rules, as well as who is going to be configuring them (end user, end user admin, developers, ...). Pick the storage option that suits you.
How do you check these rules?
Barring the specifics of fetching the data (which, as we discussed, can be done in different ways), the logic of checking the rules is fairly straightforward. Note that I'm using C# here. You didn't specify a language, so I'll comment the code to make sure you understand its purpose.
// Represents a row from the rule set (see data table example)
public class Rule
{
    public string UserId { get; set; }
    public List<int> AllowedActions { get; set; }
}

public class RuleChecker
{
    // Tells you if a certain user can perform a certain action
    public bool CanUserPerformAction(string userId, int actionId)
    {
        // Get rules from data storage
        List<Rule> rules = ...

        // Get the rule that matches the user ID
        var userRule = rules.SingleOrDefault(rule => rule.UserId == userId);

        // Check if such a rule exists
        if(userRule == null)
        {
            // No rule exists for user!
            return false;
        }

        // User exists, check their if allowed actions contains the requested action
        return userRule.AllowedActions.Contains(actionId);
    }
}

This is just a basic example. Certain improvements can be made, but they mostly depend on your implementation details, which you never elaborated on.
This rulechecker can then be used everywhere you need to check for a rule, e.g:
if(myRuleChecker.CanUserPerformAction(currentUser, sendEmailActionId))
{
    myMailSender.SendEmailTo(currentUser);
}

Again, this is just a basic example.

The above is a working but very barebones implementation. There are many more considerations here to improve the code, but they rely on certain decisions you make.

A: It sounds like the logic for creating the order exists in other services, and all the create() method is doing is using each service (in other words, it doesn't really contain any logic on its own).
For example, adjusting inventory levels on its own has nothing to do with creating an order. You could also adjust inventory levels by restocking.
I don't think you need a design pattern here. If the steps for creating the order already exist in other services there is nothing stopping you from simply calling those other services directly. A potential change here would be to encapsulate the state of the order in an object instead of doing it one shot in create() that way you can control the flow, though I can't think of a good reason to do that.

A: Looks like you are looking for a policy service or workflow service? As in "Process this order under the sales tax exempt rules" or "Here are the user properties, route the order accordingly, SMB customers this way, enterprise customers that way..."


text:
Q: How to insert Tensor second order notation in libreOffice Math? How to put double bar over a character in libreoffice math 5. As we use in second order tensors.

A: At least in LibreOffice 5, it appears to be possible simply by nesting the overline command:


text:
Q: How to add UILabel from a loop? Sorry for my english.
I want to display words separated in characters. i have different strings in "chars" array that contain single characters. i tried this one:
int x = 20;
int y = 20;
int screenx = self.view.bounds.size.width - 14;
for (NSString *string in chars){
    for (int i=0; i<messageLength; i++) {
        UILabel *display;
        display.text = [chars objectAtIndex:i];
        display.frame = CGRectMake(x, y, 14, 22);
        display.textColor = [UIColor whiteColor];
        x = x + 14;
        if (x >= screenx){
            x = 20;
            y = y + 20;
        }

    }
}

A: You should actually create the label and place it on your view.
UILabel *display = [[UILabel alloc] init];
display.text = [chars objectAtIndex:i];
display.frame = CGRectMake(x, y, 14, 22);
display.textColor = [UIColor whiteColor];
[self.view addSubView:display];


text:
Q: How to use packages generate by Ecore model - Android? As a part of my project, I created class diagram using Ecore diagram and generated a model out of it.. I used this tutorial as my reference ..http://www.vogella.com/articles/EclipseEMF/article.html...My question is once I have created the model (in section 4 of this tutorial "Generate Model Code")...how do I use this in my normal android project as like I import other packages in my simple android project..??
In section 6 of this tutorial its using those model in plug-in project..but I want to use that model code in my normal project..I hope u r getting what I am trying to ask..please ask me if u need more detail on this...thanks

A: I'm not sure the answer but this bugzilla says it has a port of EMF's runtime for Android:
https://bugs.eclipse.org/bugs/show_bug.cgi?id=296770


text:
Q: Was the Big Bang denser and hotter than a black hole? I know that the Big Bang theory states that the early Universe had a very high temperature and was extremely dense (thus causing a gravitational/space-time collapse) but if that's the case then wouldn't it be greater than that of a black hole (and thus become a black hole)? If not, how does the Big Bang create something denser/hotter without becoming a black hole or violating conservation of energy?

A: In order for gravitational collapse to happen, there has to be a way for matter to pick a point toward which to collapse.  It's true that the early universe was very dense, but it also comprised an infinite and uniform density distribution.  This means that every point would be just as good a "center" as any other point.  Since no point can be the center of collapse, you get no collapse.

A: The Schwarzschild solution for a black hole assumes the local spacetime is both largely flat (largely in universe terms) and static in time.
In comparison, the early universe was rapidly expanding and highly "bent". Simply put, the Schwarzschild solution does not apply.
A key difference is that the universe has a singularity in the past, while a black hole's singularity is in the future light cone. In that respect, the universe is sort of like a time-reversed black hole, where everything is "falling out" rather than in. But it's not really like that either, there's all sorts of subtle differences.
Just found this, he says it better than I ever could.


text:
Q: OCaml optimization of unfold followed by fold There is a well-known compiler optimization of an unfold followed by a fold, which is called hylomorphism (in other words: a loop). Simply put, instead of building a structure and destroying it immediately after, you plug the folding function directly on the generator of the structure, which results in an in-place loop that does not create the structure in memory at all.
For example, to sum some numbers input by the user, we could do
let sumInput () : int =
  List.fold_left (+) 0
    (List.init 1875 (fun _ -> read_int ()))

The intermediate structure is the list that stores the input numbers, constructed by List.init. I would expect OCaml's native compiler, ocamlopt, to optimize this as a tail-recursive loop like
let optimSumInput () : int =
  let rec optimInput_rec count sum =
    if count = 0 then sum
    else optimInput_rec (count-1) (sum + read_int ()) in
  optimInput_rec 1875 0

However, ocamlopt -s produces this assembly code, where we see both camlStdlib__list__init and camlStdlib__list__fold_left:
camlTestOptim__sumInput_80:
    .cfi_startproc
    subq    $8, %rsp
    .cfi_adjust_cfa_offset 8
.L102:
    movq    camlTestOptim__3@GOTPCREL(%rip), %rbx
    movq    $3751, %rax
    call    camlStdlib__list__init_204@PLT
.L100:
    movq    %rax, %rdi
    movq    $1, %rbx
    movq    camlTestOptim__2@GOTPCREL(%rip), %rax
    addq    $8, %rsp
    .cfi_adjust_cfa_offset -8
    jmp camlStdlib__list__fold_left_250@PLT
    .cfi_adjust_cfa_offset 8
    .cfi_adjust_cfa_offset -8
    .cfi_endproc
    .type camlTestOptim__sumInput_80,@function
    .size camlTestOptim__sumInput_80,. - camlTestOptim__sumInput_80

Is there a compiler switch that would optimize the list out ? In this particular example it won't accelerate much, but for more complicated structures than lists, it can make a difference.

A: No, OCaml's optimizing compiler is not doing such optimizations and, probably, won't ever do. This answers the posted question. Below is my personal opinion that is not an answer but a comment that I think is necessary to give for the right understanding of the language and why such optimizations should not be expected.
The optimizing compiler of OCaml is known for its predictability and ability to efficiently compile functional programs to machine code. It will not, however, translate bad programs into good ones, as the compiler follows closely the semantics of the language and belives that programmers know what they are doing. Unlike Haskell, OCaml is a strict imperative language with stronger semantics. It gives a programmer much more control over the execution process than Haskell, but that comes with a price, of course, as certain optimizations are hard if not impossible to implement. In OCaml, all expressions are impure (effectful) by default, so in order to remove an expression and substitute it with its value, the compiler has to prove that no effects are lost in the process. Another important aspect, that we should keep in mind when coming from the Haskell territory, is that OCaml is strict and OCaml lists are also strict inductive data type. Therefore, while in Haskell with the call-by-name semantics and lazy list such optimizations could be seen as natural, in OCaml it would be too far-going and essentially will violate the contract between the programmer and the compiler.
Since OCaml gives us, the programmers, much more control on the execution process, we have lots of different data structures, which are mathematically isomorphic but offer different tradeoffs. And it is our task as a programmer to choose a representation that best reflects our needs and constraints. Given your concrete example, a choice of a list as an underlying data structure is a little bit weird and not justified. However, the compiler trusts the programmer, and if a programmer decided to use lists here, it will follow the request.
A seasoned programmer will choose a better data structure here, e.g., Core's Sequence.t or Lwt's stream, or just the standard Seq.t iterator,
let rec ints () = match read_int () with
  | exception End_of_file -> Seq.Nil
  | s -> Seq.Cons (s,ints)

and we can define a sum of integers as
let sum = Seq.fold_left (+) 0

therefore our main function will look like
let main () =
  print_int (sum ints);
  print_newline ()

This code will not create any intermediate lists so deforesting will be applied naturally, without us having to rely on obscure compiler optimizations.
This distinction with Haskell draws a line between programming and pure mathematics, as while different sorts of lists are mathematically equivalent there is a great variety of implementations that are different from the programmer's perspective.
Therefore, OCaml relies on programmers to make this choice and is not trying to be more clever than a human. On the other hand, it provides a very powerful abstraction mechanism, which is a reification of Sigma-algebras, that lets us program against abstractions and remain in the world of pure mathematics when we want and return back to Earth when it is absolutely necessary.

A: There is currently no such switch. You probably need to use a Stream Fusion library like Strymonas Streams (see OCaml implementation).

When the execution reaches the run method, an optimized version of the stream will be compiled (emitted) and executed [...]. The resulted code will consist of a tight, for-loop.

The library does not have access to the compiler's internal, which might limit the extent to which it is integrated with the language and how the bytecode or native code is emitted. But this also leave the core language simple and with a straightforward semantics.
As an optimization pass in the compiler, it would optimize some expressions but not others; that might be a little bit more difficult for users (developers) to guess ahead of time how the code might behave at runtime (e.g. see how confusing tail-call elimination can already be). It has also a cost as a compiler feature, in terms of maintenance (e.g. testing, forward/backward compatibility).
That's some possible reasons, along with the lack of resources, for which doing the optimization directly in the compiler is not currently done, and maybe not desirable in the first place.


text:
Q: Global minimum is attained at the median I have the following homework problem.

Let $(x_1,x_2,\ldots,x_n)$ be an increasing sample of size $n$. Show that the function $$f: x\mapsto \sum_{k=1}^n |x_k-x|$$ obtains a global minimum at the median $$x_{1/2}=\begin{cases} x_{(n+1)/2},\qquad  & n \text{ odd} \\ 1/2 \left(x_{n/2}+x_{n/2+1}\right),\qquad &n \text{ even}\end{cases}.$$

My attempt
Firstly, since $f$ is not differentiable at $x_1,\ldots,x_n$, so these are all critical points. Also,
$$f'(x)=2k-n,\qquad x\in (x_k,x_{k+1}), k=0,1,\ldots,n.$$
Thus, if $n$ is even, then all the points in the interval $(x_{n/2}, x_{n/2+1})$ are also critical points.
In either case, $x_{1/2}$ is a critical point of $f$.  Moreover, $f'$ changes sign from negative to positive at $x_{1/2}$. Thus, $x_{1/2}$ is a local minimum of $f$.
How do I show it is also the global minimum?

A: Since $f'(x) = 0$ for all $x \in (x_{n/2},x_{n/2+1})$, $f$ must be constant in that region. That gives you enough information for comparing the critical points. Hope that helps


text:
Q: One JLabel disapears, when there are two Ok, so I have been working on this lottery program in Java, and my code is in the extreme beginning phase, and i am stuck on this one problem. So when I create 2 JLabels, and run the program, only one shows. I have been trying to find an answer for some while now so i hope someone can help. Here is my code:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Lottery extends JPanel implements ActionListener {

    private static final long serialVersionUID = 5815877011755522230L;
    private JTextField text;
    private JLabel title, subTitle;
    public final String Title = "Lottery";

    public static void main(String[] args) {
        make();

    }

    public Lottery() {

        title = new JLabel(Title, JLabel.CENTER);
        title.setFont(title.getFont().deriveFont(30.0f));
        add(title);

        subTitle = new JLabel("Lottery Numbers");
        subTitle.setHorizontalAlignment(JLabel.HORIZONTAL);
        setLayout(new BorderLayout());
        add(subTitle, BorderLayout.CENTER);

    }

    public static void make(){
        JFrame frame = new JFrame("Lottery");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Lottery hi = new Lottery();
        frame.setContentPane(hi);

        frame.setSize(600, 600);
        frame.setVisible(true);

    }

    public void actionPerformed(ActionEvent e) {

    }
}

So, if anyone is able to help me with this problem, it would be greatly appreciated.

A: I'd recommend you start by having a look at A Visual Guide to Layout Managers and How to Use Borders and having a look at the JavaDocs for BorderLayout may also shed some illumination on the course of your problem
You have two key problems...

*

*BorderLayout will only allow a single component to be managed at any of the five available positions and the default position is CENTER

*BorderLayout will ignore ALL components added BEFORE it was set

So, if we took your code and changed it to something like
public Lottery() {
    setLayout(new BorderLayout());

    title = new JLabel(Title, JLabel.CENTER);
    title.setFont(title.getFont().deriveFont(30.0f));
    add(title);

    subTitle = new JLabel("Lottery Numbers");
    subTitle.setHorizontalAlignment(JLabel.HORIZONTAL);
    add(subTitle, BorderLayout.CENTER);
}

you'd end up with the same problem, BUT, if we also provided additional constraints...
public Lottery() {
    setLayout(new BorderLayout());

    title = new JLabel(Title, JLabel.CENTER);
    title.setFont(title.getFont().deriveFont(30.0f));
    add(title, BorderLayout.NORTH);

    subTitle = new JLabel("Lottery Numbers");
    subTitle.setHorizontalAlignment(JLabel.HORIZONTAL);
    add(subTitle, BorderLayout.SOUTH);
}

will now place one label in the north position and one in the south

A: add(title);
add(subTitle, BorderLayout.CENTER);

look at this code , label .you didn't set the location of your label. so do the same thing as you did with subtitle . for example
add(title ,BorderLayout.NORTH );

A: The second subTitle overwrites the first Title and you have to add it after you set the Layout.


text:
Q: How can I rearrange celery flower default columns? I am using the following versions:
flower==0.9.3
celery==4.3.0
Which gives me the following display for a tasks page with several columns:

Each time I enter this page I end up rearranging the page to have columns in a different order and I change the ordering for the rows to be descending.
What I want to know is if there is some way to configure it to have the columns and rows in that order by default.  i.e. Name -> State -> args -> Result -> UUID descending instead of Name -> UUID -> State -> args -> Result ascending
I haven't been able to find any mention of this in the docs, is there a configuration I can use to achieve this?

A: Apparently there are no customizable column sorting in flower. According to the comment of flower's owner on Github issues [Jul 6, 2020]:

There are no plans to work on this feature at the moment until someone decides to contribute to the project.

But, there is a merged pull request into flower's master branch that makes flower show the recent tasks on top in tasks page [Ordered by Started DESC]. You can install the Development version in order to change the default sorting if it helps:
$ pip install https://github.com/mher/flower/zipball/master#egg=flower


text:
Q: Javascript infamous Loop issue? I've got the following code snippet.
function addLinks () {
    for (var i=0, link; i<5; i++) {
        link = document.createElement("a");
        link.innerHTML = "Link " + i;
        link.onclick = function () {
            alert(i);
        };
        document.body.appendChild(link);
    }
}

The above code is for generating 5 links and binding each link with an alert event to show the current link id. But It doesn't work. When you click the generated links they all say "link 5".
But the following code snippet works as our expectation.
function addLinks () {
    for (var i=0, link; i<5; i++) {
        link = document.createElement("a");
        link.innerHTML = "Link " + i;
        link.onclick = function (num) {
            return function () {
                alert(num);
            };
        }(i);
        document.body.appendChild(link);
    }
}

The above 2 snippets are quoted from here. As the author's explanation seems the closure makes the magic.
But how it works and How closure makes it work are all beyond my understanding. Why the first one doesn't work while the second one works? Can anyone give a detailed explanation about the magic?

A: We have 5 divs on the page, each with an ID ... div1, div2, div3, div4, div5
jQuery can do this ...
for (var i=1; i<=5; i++) {
    $("#div" + i).click ( function() { alert ($(this).index()) } )
}

But really addressing the problem (and building this up slowly) ...
STEP 1
for (var i=1; i<=5; i++) {
    $("#div" + i).click (
        // TODO: Write function to handle click event
    )
}

STEP 2
for (var i=1; i<=5; i++) {
    $("#div" + i).click (
        function(num) {
            // A functions variable values are set WHEN THE FUNCTION IS CALLED!
            // PLEASE UNDERSTAND THIS AND YOU ARE HOME AND DRY (took me 2 years)!
            // Now the click event is expecting a function as a handler so return it
            return function() { alert (num) }
        }(i) // We call the function here, passing in i
    )
}

SIMPLE TO UNDERSTAND ALTERNATIVE
If you can't get your head around that then this should be easier to understand and has the same effect ...
for (var i=1; i<=5; i++) {

    function clickHandler(num) {
        $("#div" + i).click (
            function() { alert (num) }
        )
    }
    clickHandler(i);

}

This should be simple to understand if you remember that a functions variable values are set when the function is called (but this uses the exact same thought process as before)

A: In the first example, you simply bind this function to the onclick event:
function() {alert(i);};

This means that on the click event js should alert the value of the addlink functions i variable. Its value will be 5 because of the for loop().
In the second example you generate a function to be bound with another function:
function (num) {
  return function () { alert(num); };
}

This means: if called with a value, return me a function that will alert the input value. E.g. calling function(3) will return function() { alert(3) };.
You call this function with the value i at every iteration, thus you create separate onclick functions for each links.
The point is that in the first example your function contained a variable reference, while in the second one with the help of the outer function you substituted the reference with an actual value. This is called a closure roughly because you "enclose" the current value of a variable within your function instead of keeping a reference to it.

A: Basically, in the first example you're binding the i inside the onclick handler directly to the i outside the onclick handler.  So when the i outside the onclick handler changes, the i inside the onclick handler changes too.
In the second example, instead of binding it to the num in the onclick handler, you're passing it into a function, which then binds it to the num in the onclick handler.  When you pass it into the function, the value of i is copied, not bound to num.  So when i changes, num stays the same.  The copy occurs because functions in JavaScript are "closures", meaning that once something is passed into the function, it's "closed" for outside modification.

A: Others have explained what's going on, here's an alternative solution.
function addLinks () {
  for (var i = 0, link; i < 5; i++) {
    link = document.createElement("a");
    link.innerHTML = "Link " + i;

    with ({ n: i }) {
      link.onclick = function() {
        alert(n);
      };
    }
    document.body.appendChild(link);
  }
}

Basically the poor mans let-binding.

A: Quoting myself for an explanation of the first example:

JavaScript's scopes are function-level, not block-level, and creating a closure just means that the enclosing scope gets added to the lexical environment of the enclosed function.
After the loop terminates, the function-level variable i has the value 5, and that's what the inner function 'sees'.

In the second example, for each iteration step the outer function literal will evaluate to a new function object with its own scope and local variable num, whose value is set to the current value of i. As num is never modified, it will stay constant over the lifetime of the closure: The next iteration step doesn't overwrite the old value as the function objects are independant.
Keep in mind that this approach is rather inefficient as two new function objects have to be created for each link. This is unnecessary, as they can easily be shared if you use the DOM node for information storage:
function linkListener() {
    alert(this.i);
}

function addLinks () {
    for(var i = 0; i < 5; ++i) {
        var link = document.createElement('a');
        link.appendChild(document.createTextNode('Link ' + i));
        link.i = i;
        link.onclick = linkListener;
        document.body.appendChild(link);
    }
}


text:
Q: How do i fix the Gallery Slider? I bought a tempalte website for a friend since i am no coder and tried to customize as far as possible.
This is the URL:
http://www.roxaneroffler.com
I have a problem with the gallery, it gets buggy when i add more than 6 or 7 images. It jumps from one image to the beginning and going back behaves weird as well.
I have no idea where to start.
Can you guys check the CSS code through the given website or do i have to post the CSS class? im afraid the horizontal gallery css class is too big.


text:
Q: Why is Yii2 using arrays for rules instead of objects? Rules in Yii2 models look like this:
[
    // checks if "level" is 1, 2 or 3
    ['level', 'in', 'range' => [1, 2, 3]],
]

Wouldn't it be better if they were objects like this?
[
  new RangeRule('level', [1, 2, 3])
]

A: You can use validator objects like this:
use yii\validators\Validator;
use yii\validators\NumberValidator;
use yii\validators\StringValidator;

class TestModel extends \yii\base\Model
{
    public $firstProperty;
    public $secondProperty;

    public function rules()
    {
        return [
            new NumberValidator(['attributes' => ['firstProperty'], 'integerOnly' => true, 'min' => 0, 'max' => 100]),
            new StringValidator(['attributes' => ['secondProperty'], 'max' => 5]),
        ];
    }
}

Moreover, you can decorate these objects as you want (using additional classes and methods):
class TestModel extends \yii\base\Model
{
    public $firstProperty;
    public $secondProperty;

    public function rules()
    {
        // Prepare Int validator
        $validatorInt              = new NumberValidator();
        $validatorInt->integerOnly = true;
        $validatorInt->min         = 0;
        $validatorInt->max         = 100;

        // Prepare String validator
        $validatorString      = new StringValidator();
        $validatorString->max = 5;

        // Make rules
        return [
            static::_makeRule(['firstProperty'], $validatorInt),
            static::_makeRule(['secondProperty'], $validatorString),
        ];
    }

    protected function _makeRule($attrName, Validator $validatorObj)
    {
        $validatorObj = clone $validatorObj;

        $validatorObj->attributes = (array)$attrName;

        $validatorObj->init();                          // Initializes validator and normalizes values

        return $validatorObj;
    }

}


text:
Q: Calculate the matrix from minimal polynomial and eigenspaces I need to find a matrix $A \in M(6,\mathbb C)$ that satisfies following:

*

*$e_1+e_2+e_3\in \ker(L_A-3\cdot \operatorname{id})^3 \setminus \ker(L_A-3*id)^2$

*$\operatorname{span}(e_1+e_4,e_5+e_6)= \operatorname{Eig}(L_A, 2)$

*$\mu_A=(t-3)^3(t-2)^2$

I think that $A$ is similar to the matrix in Jordan form
$$
        \begin{pmatrix}
        2 & 0 & 0&0&0&0 \\
        0&2&1&0&0&0 \\
        0&0&2&0&0&0\\
        0&0&0&3&1&0\\
        0&0&0&0&3&1\\
        0&0&0&0&0&3\\
        \end{pmatrix}
$$
But how do I find a basis to transform this matrix to $A$ without knowing what the matrix looks like? I only have 3 vectors, how do I compute the rest?

A: So before we start, note that the problem doesn't say find the matrix, so the answer may not be unique.
We have our Jordan Canonical form so in order to get a matrix so that those qualities are true, we can craft a similarity transformation that'll get us to such a matrix as is specified by the problem.
The first thing to note is that for a matrix $A$, $A = PBP^{-1} $, with $P$ being a representation of the basis. This property clearly still applies for $B$ in Jordan canonical form, so we can apply this here as well.
So, what we need is an invertible matrix such that the first two columns are eigenvectors $(e_1+e_4),(e_5+e_6) $, (or vice versa since the conditions didn't specify), and the sixth column is $(e_1+e_2+e_3)$. So, basically, we have:
$$ P =
\begin{bmatrix}
1 & 0 & ... & 1 \\
0 & 0 & ... & 1 \\
0 & 0 & ... & 1 \\
1 & 0 & ... & 0 \\
0 & 1 & ... & 0 \\
0 & 1 & ... & 0 \\
\end{bmatrix} $$
And now it's basically a fill in the blanks problem so that you make an inveritble $P$. Because there are only three vectors, it has quite a broad solution set. After you have your $P$, once you calculate $PJP^{-1} $, you'll have your new matrix $A$.


text:
Q: Location and GPS on API > 23 Hello I'm currently trying to implement an App where I want to track my GPS.
This is my code but unfortunately it's not working with my current API I'm using.
I've found a few codes but this is only for Activities. I'm trying to implement this in a Service.
public class TrackGPS extends Service {

GPSInformation gpsInfo;

private LocationManager locationManager = null;
private String selectedProvider = null;

@Override
public void onCreate() {
    locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);

    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    selectedProvider = locationManager.getBestProvider(criteria,true);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
    Date date = new Date();
    String timestamp = isoFormat.format(date);

    gpsInfo = new GPSInformation();
    gpsInfo.setTimestamp(timestamp);

    if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
   //THIS IS WHERE IT STARTS CRASHING AND I GET AN ERROR I NEED PERMISSION

       Location lastKnownLocation = locationManager.getLastKnownLocation(selectedProvider);

        if(lastKnownLocation != null) {
            gpsInfo.setLatitude(lastKnownLocation.getLatitude());
            gpsInfo.setLatitude(lastKnownLocation.getLongitude());
            gpsInfo.setValid(1);
        } else {
         .........
        }

    } else {
       ...........
    }

    HttpRequestTask task = new HttpRequestTask(gpsInfo);
    task.execute();

    stopSelf();
    return START_STICKY;
}

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

}


text:
Q: DataGridView bound to List does not reflect changes when adding objects to the List I wonder what I need to do in order to make the DataGridView behave as expected:
I do have a List<ioChannel> (named myList) of objects of this type:
public class ioChannel
{
    public string Name { get; set; }
    public int Id { get; set; }
}

I tried to bind the DataGridView to this list:
bs = new BindingSource { DataSource = myList };
dgvChannels.DataSource = bs;

Now I created a button that adds elements to myList:
private void btAddChannel_Click(object sender, EventArgs e)
{
    myList.Add(new ioChannel() { Id = myList.Count, Name = "My Channel" });
}

When I press the button, my List gets populated with new ioChannel's, but the dgvChannels does not add any rows. What do I need to do in order to make this happen?
BTW: When myList gets populated with some ioChannel´s before assigning the BindingSource as DataSource, the get shown properly in the grid.

A: As @Loathing commented BindingList worked for me too. How it will work :
BindingList<ioChannel> myList = new BindingList<ioChannel>();
dgvChannels.DataSource = myList;

BindingList has event that notifies changes in list. So that datagridview can notified to redraw itself, check this. For more information visit msdn.


text:
Q: Can not add line feed to string I have an Arduino Leonardo and trying to use it as a serial to USB converter. On Serial1 I have a string ending on a number. This number I'm trying to get via USB to the PC. It works very fine but I need a '\n' at the end and I don't know how. When I try it in the line Keyboard.println or Keyboard.write, I get a various number of lines with the expected number in splitted.
#include <Keyboard.h>
String myEAN ="";
const int myPuffergrosse = 50;
char serialBuffer[myPuffergrosse];
void setup() {
    Keyboard.begin();
    Serial1.begin(9600);
    delay(1000);
}
String getEAN (char *stringWithInt)
// returns a number from the string (positive numbers only!)
{
    char *tail;
    // skip non-digits
    while ((!isdigit (*stringWithInt))&&(*stringWithInt!=0)) stringWithInt++;
    return(stringWithInt);
}

void loop() {
    // Puffer mit Nullbytes fuellen und dadurch loeschen
    memset(serialBuffer,0,sizeof(myPuffergrosse));
    if ( Serial1.available() ) {
        int incount = 0;
        while (Serial1.available()) {
            serialBuffer[incount++] = Serial1.read();
        }
        serialBuffer[incount] = '\0';  // puts an end on the string
        myEAN=getEAN(serialBuffer);
        //Keyboard.write(0x0d);  // that's a CR
        //Keyboard.write(0x0a);  // that's a LF
    }
}

A: Since myEAN is a String, simply add the character...
myEAN += '\n';

Or, for a full carriage return/line feed combination:
myEAN += "\r\n";

See the doc: https://www.arduino.cc/en/Tutorial/StringAppendOperator
I suggest you use String in your getEAN function as well...
String getEAN(String s)
{
  // returns the first positive integer found in the string.

  int first, last;
  for (first = 0; first < s.length(); ++first)
  {
     if ('0' <= s[first] && s[first] <= '9')
       break;
  }
  if (first >= s.length())
    return "";

  // remove trailing non-numeric chars.
  for (last = first + 1; last < s.length(); ++last)
  {
     if (s[last] < '0' || '9' < s[last])
       break;
  }

  return s.substring(first, last - 1);
}


text:
Q: Sending email with SMTP, don't receive Delivery Notifications for On Failure I need to setup my company's "no reply" email account to receive notifications when an email fails to send.
I send emails using the System.Net.Mail.SmtpClient all the time. I use my own work email address for testing. But for production use, my company has a "no reply" account. Our "no reply" account also has a legitimate AD User account and inbox we use for monitoring purposes. No different in practice than my own account.
When testing with my work address, I get the DeliveryNotifications for OnSuccess and OnFailure.
When using the "no reply" address, I get the DeliveryNotification for OnSuccess, but it never gives me one for OnFailure.
Which is a problem because the OnFailure notifications are the only ones we care about. I just ran it with OnSuccess options for testing purposes. When using my work email, when I intentionally send an email to an invalid address, I receive the failure notification. The only thing I changed was the credentials to the production "noreply" address, and when I run the same tests, I get the success notifications just fine. But when I test with a bad address to get a failure, I receive nothing. Even though I got both on my own account.
Here's (the important bits of) my code:
using (SmtpClient client = new SmtpClient("mail.mycompany.com"))
{
    //I do the credentials thing here first...

    //build email
    MailMessage mailMessage = new MailMessage();
    mailMessage.From = new MailAddress("noreply@mycompany.com", "No Reply");
    mailMessage.To.Add(new MailAddress("thisisabademailaddressthatdoesntexist@mycompany.com"));
    mailMessage.Subject = "Test";
    mailMessage.Body = "Test";

    //notify on failure
    mailMessage.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

    //send
    client.Send(mailMessage);
}

I've tried using other API's like the Exchange Services. But I can't even get those to authenticate and send a successful test using my own credentials, let alone "no reply"'s. Using SMTP, I can at least get an email out at all. I'm wondering if the issue may lie elsewhere and not necessarily with my code. Especially since it works in all other scenarios except for the one that matters. I'm just out of ideas.


text:
Q: Symfony 5, How to display in a template, a variable where the current user is affiliated with a ManyToMany relations I want that when my current user goes to the page, he can see what subject matter he is affiliated with a ManyToMany relation.
My entity Matter
/**
 * @ORM\Column(type="string", length=255)
 */
private $name;

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="matters")
 * @ORM\JoinColumn(nullable=false)
 */
private $user;

/**
 * @ORM\ManyToMany(targetEntity="App\Entity\User", inversedBy="studentsMatters")
 */
private $student;

and my entity User
/**
 * @ORM\Column(type="string", length=255)
 */
private $fullname;

/**
 * @ORM\OneToMany(targetEntity="App\Entity\Matter", mappedBy="user")
 */
private $matters;

/**
 * @ORM\ManyToMany(targetEntity="App\Entity\Matter", mappedBy="student")
 */
private $studentsMatters;

and my controller to get the repository of Users and Matters
/**
 * @Route("/", name="student_index", methods={"GET"})
 */
public function index(MatterRepository $matterRepository, UserRepository $userRepository): Response
{
    return $this->render('student/index.html.twig', [
        'matters' => $matterRepository->findAll(),
        'users' => $userRepository->findAll(),
    ]);
}

So in my template, I try several things like that
{% for user in users %}
{% for matter in matters %}
    {% if matter.student == app.user.fullname %}

{{ matter.name }}

    {% endif %}
{% endfor %}
{% endfor %}

but it's doesn't work...

A: It's good, I found a solution to my problem!
First, I create a new entity which contains 2 OneToMany (one to put in relation my matters and the other, the users.
/**
 * @ORM\ManyToOne(targetEntity="App\Entity\Matter", inversedBy="studentUsers")
 * @ORM\JoinColumn(nullable=false)
 */
private $studentMatter;

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="studentUsers")
 */
private $user;

In my controller, I add these three lines to get send the current user.
$studentUser = new StudentUser();
$user = $this->getUser();
$studentUser->setUser($user);

Therefore, In my form, I just have to select the variable studentMatter that I want.
And to finish, I add as condition
{% if student_user.user.id == app.user.id %}

{{ student_user.studentMatter.name }}

{% endif %}

Thanks to everyone who took their time trying to help me :)


text:
Q: Get first column in dataframe that exists from list of column names Given a list of column names, only some or none exist in a dataframe, what's the least verbose way of getting the first existing column or None?
import pandas as pd

df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=["a", "b", "c"])

cols = ["d", "e", "c"]

This is fairly short but fails with StopIteration for no matching columns:
col = next(filter(lambda c: c in df, cols))

df[col]
0    3
1    6
Name: c, dtype: int64

Is there a better way?

A: You can do it with:
col = next(filter(lambda c: c in df, cols), None)

A: One idea:
col = next(iter(df.columns.intersection(cols, sort=False)), None)

A: @Learnings is a mess answered it beautifully and you should use that solution but here is another one line solution with walrus operator.
col = intersect[0] if (intersect:= [c for c in cols if c in df.columns]) else None


text:
Q: Conversion failed when converting the nvarchar value '00000000-0000-0000-0000-000000000000' to data type int I have a query that is getting some that is comparing a uniqueidentifier in the table and its a strange one.
SELECT *  FROM   vw_ryzex_CustomerAssets where BillToId='51ee47d2-eb97-4b12-8865-dab9a7f15a46'

So when i run this query i get the following error
Conversion failed when converting the nvarchar value '00000000-0000-0000-0000-000000000000' to data type int.
But when i select only the top 1000 i get the result and no error occurrs I tried Casting and converting checking nulls everything i could i tried following queries but did not work
SELECT * FROM   vw_ryzex_CustomerAssets_V2 where CAST(BillToId as nvarchar(200))=Cast('51ee47d2-eb97-4b12-8865-dab9a7f15a46' as nvarchar(200))

SELECT * FROM   vw_ryzex_CustomerAssets where (Case BillToId
                                                when '00000000-0000-0000-0000-000000000000' Then NEWID()
                                       ELSE BillToId
                                                END) = '51ee47d2-eb97-4b12-8865-dab9a7f15a46'

Can anyone help me on this please..?
This is the view definition
 ALTER VIEW [dbo].[vw_ryzex_CustomerAssets_V2] AS SELECT a.Id,
     '~/Reports/BillToAssetDetails.aspx?btid='
     + CONVERT(VARCHAR(256), a.BillToId)
     + '&vidx=1&caid='
     + CONVERT(VARCHAR(256), a.Id)                                     AS URL,
     '~/Reports/BillToAssets.aspx?btid='
     + CONVERT(VARCHAR(256), a.BillToId)
     + '&vidx=1&caid='
     + CONVERT(VARCHAR(256), a.Id)                                     AS EditUrl,
     LEFT(a.PartDescription, 50)                                       AS PartDescription,-- EKL:03042009
     a.Quantity,
     a.SerialNumber,
     /*    CASE ISNULL(s.Name,'') WHEN '' THEN a.Location ELSE s.Name + '(' + s.ErpId + ')
     '+ a.Location END AS Location, */
     a.Location,
     s.NAME + '(' + s.ErpId + ')'                                      AS SiteName,
     --a.OrderId,
     o.OrderGroupId                                                    AS OrderId,
     a.OrderErpId,
     a.OrderExt,
     a.OrderLine,
     a.DateCreated,
     a.DateModified,
     Isnull(ru.DisplayName, '')                                        AS ModifiedBy,
     a.BillToId,
     a.PartNo,
     b.NAME                                                            AS BillToName,
     b.Description                                                     AS BillToDescription,
     b.ErpId                                                           AS BillToErpId,
     b.DateCreated                                                     AS BillToDateCreated,
     b.DateModified                                                    AS BillToDateModified,
     b.ModifiedBy                                                      AS BillToModifiedBy,
     a.ProductId,
     --p.ProductPartNo,
     --p.ProductModel,
     --p.ProductDescription as ProductDescription,
     --p.ProductDateCreated,
     --p.ProductDateModified,
     --p.ProductModifiedBy,
     Isnull(ol.UnitPrice, '0')                                         AS UnitPrice,
     ol.SalesTax,
     Isnull(ol.TotalPrice, '0')                                        AS TotalPrice,
     ol.OrderErpId                                                     AS OrderLineId,
     Isnull(ol.QuantityOrdered, '0')                                   AS QuantityOrdered,
     Isnull(ol.QuantityShipped, '0')                                   AS QuantityShipped,
     -- o.Created AS OrderDate,
     Dateadd(mi, Datediff(mi, Getutcdate(), Getdate()), o.Created)     AS OrderDate,
     -- o.ShippedDate AS ShipDate,
     Dateadd(mi, Datediff(mi, Getutcdate(), Getdate()), o.ShippedDate) AS ShipDate,
     o.SalesPersonName                                                 AS SalesPersonDisplayName,
     o.BillingCurrency                                                 AS Currency,
     dbo.vw_PurchaseOrderPayments.PurchaseOrderPaymentNumber           AS CustPo,
     a.AssetNumber,
     a.CustomerReference,
     a.ModelNumber,
     a.CustomField1Value                                               AS xCust1,
     a.CustomField2Value                                               AS xCust2,
     s.Id                                                              AS ShipToId,
     s.AddressLine1                                                    AS Address1,
     s.AddressLine2                                                    AS Address2,
     s.AddressLine3                                                    AS Address3,
     s.City,
     s.Country,
     s.[State],
     s.ZipCode                                                         AS Zip
FROM   dbo.vw_PurchaseOrderPayments
     RIGHT OUTER JOIN dbo.vw_PurchaseOrders AS o
                   ON dbo.vw_PurchaseOrderPayments.OrderFormId = o.OrderFormId -- EKL:03042009 chg from OrderGroupId to OrderFormId
     RIGHT OUTER JOIN dbo.ryzex_CustomerAsset AS a
                      INNER JOIN dbo.ryzex_BillTo AS b WITH (NOLOCK)
                              ON a.BillToId = b.Id
                                 AND Isnull(a.Inactive, 0) = 0
                      LEFT OUTER JOIN dbo.ryzex_ShipTo AS s WITH (NOLOCK)
                                   ON a.ShipToId = s.Id
                                      AND b.Id = s.BillToId
                      LEFT OUTER JOIN dbo.ryzex_Product AS p WITH (NOLOCK)
                                   ON a.PartNo = p.ProductPartNo
                      LEFT OUTER JOIN dbo.vw_OrderLines AS ol
                                   ON a.OrderErpId = ol.OrderErpId
                                      AND a.OrderLine = ol.LineNumber
                   ON o.OrderErpNumber = a.OrderErpId
                      AND o.OrderExtensionNumber = a.OrderExt
     LEFT OUTER JOIN dbo.ryzex_Users AS ru WITH (NOLOCK)
                  ON a.ModifiedBy = ru.Id

The BillToId that is coming from ryzex_CustomerAsset tbl is a not null uniqueidentifier


text:
Q: Microsoft Bookings Graph APi Invalid filter clause I try to filter Microsoft Booking webapi customer endpoint (https://learn.microsoft.com/en-us/graph/api/bookingbusiness-list-customers?view=graph-rest-1.0) using the 1.0 C# Graph SDK based on customer email attribute, but the query always fails with invalid filter clause.
This is the filter expression:
var filterexpression = $"emailAddress eq 'stackoverflow@gmail.com'";

This is the query which using it:
            var customersCollection = await Resilience.Retry(() => _serviceClient.Solutions.BookingBusinesses[bookingbusiness].Customers
                .Request().Filter(filterexpression)
                .GetAsync());

Is filtering supported on bookings api endpoints, and if yes, what is went wrong here?

A: From the test in Graph Explorer only id property supports filtering.
Other properties like displayName, emailAddress, addresses and phones are not filterable right now.


text:
Q: Why gets "a" element split in Browser DOM I don't understand what's happening here.
My Source code looks like this (one a Element arround an H2 and a DIV):
<!DOCTYPE HTML>

Test 123

DLRG / SCHWIMMKURS

Das DLRG bietet auch im Jahr 2022 wieder Schwimmkurse an.

Bei Fragen und für die Anmeldung zum Schwimmkurs wenden Sie sich direkt an die Ortsgruppe, über
                        die Homepage der DLRG Ortsgruppe.

When rendered in Chrome (didn't check other browsers, yet) the DOM Insprectors shows it like this (multiple elements surrounding other elements):

Test 123

DLRG / SCHWIMMKURS

Das DLRG bietet auch im Jahr 2022 wieder Schwimmkurse an.

Bei Fragen und für die Anmeldung zum Schwimmkurs wenden Sie sich direkt an die Ortsgruppe, über
                        die Homepage der DLRG Ortsgruppe.

Can anyone explain me what's happening here and why? (I actually want the a beeing a clickable box arround all the CMS generated elements inside).

A: As hinted by @Johannes in the comments: The mess is caused by my traying to nest an -Tag in another -Tag. That's not part of the HTML spec, but the browser still tries to come up with something useable,


text:
Q: Multiply between 2 dataframe I have the following 2 dataframe i would like to multiply but I do not manage to do it. Any help would be appreciated.
1st dataframe:
created_at    2019-06-28    2019-06-29    2019-06-30    2019-07-01
currency
1WO         2.600000e+05  2.600000e+05  2.604320e+05  2.604320e+05
ABX         1.033400e+04  1.033400e+04  1.033400e+04  1.033400e+04
ADH         8.219730e+05  8.219730e+05  8.219730e+05  8.219730e+05
ALX         2.500000e+04  2.500000e+04  2.500000e+04  2.500000e+04
AMLT        4.874240e+05  7.510590e+05  7.510600e+05  7.510600e+05
BCH         2.690000e+02  2.360000e+02  2.390000e+02 -3.982000e+03

2nd dataframe:
          2019-06-28    2019-06-29    2019-06-30    2019-07-01
currency
1WO       5.108000e+00  5.533000e+00  5.305000e+00  4.745000e+00
ADH       1.600000e-01  1.807000e-01  1.587000e-01  1.470000e-01
ALX       3.877000e-01  4.564000e-01  4.751000e-01  3.773000e-01
AMLT      6.078000e-01  1.051000e+00  6.900000e-01  4.087000e-01
BCH       4.537659e+04  4.728048e+04  4.786292e+04  4.355922e+04

1st dataframe info:
<class 'pandas.core.frame.DataFrame'>
Index: 123 entries, 1WO to ZPR
Data columns (total 4 columns):
2019-06-28    123 non-null float64
2019-06-29    123 non-null float64
2019-06-30    123 non-null float64
2019-07-01    123 non-null float64
dtypes: float64(4)
memory usage: 4.8+ KB
None

2nd dataframe info:
<class 'pandas.core.frame.DataFrame'>
Index: 107 entries, 1WO to ZPR
Data columns (total 4 columns):
(2019-06-28 00:00:00,)    107 non-null float64
(2019-06-29 00:00:00,)    107 non-null float64
(2019-06-30 00:00:00,)    107 non-null float64
(2019-07-01 00:00:00,)    107 non-null float64
 dtypes: float64(4)
 memory usage: 4.2+ KB
 None

My code:
jpy_bal = pos_bal.mul(d_price, axis= 0)

The error:
File "inv_pos.py", line 321, in <module>
jpy_bal = pos_bal.mul(d_price, axis= 0)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pandas/core/ops.py", line 1550, in f
return self._combine_frame(other, na_op, fill_value, level)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pandas/core/frame.py", line 4727, in _combine_frame
this, other = self.align(other, join='outer', level=level, copy=False)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pandas/core/frame.py", line 3550, in align
broadcast_axis=broadcast_axis)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pandas/core/generic.py", line 7367, in align
fill_axis=fill_axis)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pandas/core/generic.py", line 7394, in _align_frame
other.columns, how=join, level=level, return_indexers=True)
 File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pandas/core/indexes/base.py", line 3735, in join
return_indexers=return_indexers)
 File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pandas/core/indexes/base.py", line 3830, in _join_multi
raise ValueError("cannot join with no level specified and no "
ValueError: cannot join with no level specified and no overlapping names

A: Ok I from you info , your second df2 columns type is datetime and multiple index which is wired , single columns but with multiple index type , so we convert then mul will work
df2.columns=df.columns.get_level_values(0)

df1.columns=pd.to_datetime(df1.columns)
df2.columns=pd.to_datetime(df2.columns)
df1.mul(df2)
            2019-06-28    2019-06-29    2019-06-30    2019-07-01
currency
1WO       1.328080e+06  1.438580e+06  1.381592e+06  1.235750e+06
ABX                NaN           NaN           NaN           NaN
ADH       1.315157e+05  1.485305e+05  1.304471e+05  1.208300e+05
ALX       9.692500e+03  1.141000e+04  1.187750e+04  9.432500e+03
AMLT      2.962563e+05  7.893630e+05  5.182314e+05  3.069582e+05
BCH       1.220630e+07  1.115819e+07  1.143924e+07 -1.734528e+08


text:
Q: Unable to reproduce example from python tutorial: match function gives SyntaxError I'm trying to reproduce an example that I've found here.
I guess the match function is not recognised:
def http_error(status):
    match status:
        case 400:
            return "Bad request"
        case 404:
            return "Not found"
        case 418:
            return "I'm a teapot"
        case _:
            return "Something's wrong with the internet"

  File "<ipython-input-151-1f275f95d012>", line 2
    match status:
          ^
SyntaxError: invalid syntax

I thought maybe the match function is missing, so I did import re and then replaced the match with re.match, but that also didn't work.
Any idea what's going wrong?


text:
Q: Different options to move synapse workspace across different environments What are the different options to export a workspace let's say from Development into another workspace in TEST, UAT OR Production Synapse Analytics. Most of the options I have come across has been around copying code and pasting it in the intended environment. But, I want it to be automated so there's less moving parts and seamlessly move pipelines, linked services & datasets into different environments and less prone to run into errors.

A: I suppose that you could follow this doc Source control in Synapse Studio to establish the integration. And also you need to check your role assignments in access control for the workspace.


text:
Q: How do I clear the whole contents of a file in C? I have a file with some of user1's data.  I want to use the same file for user2 by clearing the content of the file.
My idea is that when a new user comes, data of the previous user should be clear and the same file should be ready for the new user.

A: There are two ways:
1. fd=open(filename,O_RDONLY | O_WRONLY | O_TRUNC);

2. [cat /dev/null > filename] for BASH. It can be directly used in c program using [system()] system call.

   system("cat /dev/null > filename");

A: As @stefan said using fopen() with "w" mode will do the job for you. When you open a file with "w" flag it creates an empty file for writing. If a file with the same name already exists its contents are erased and the file is treated as an empty new file.
If the file is already open you can use freopen() function from stdio.h with "w" mode as it will first close the file and then reopen it for writing erasing whatever was in the file previously.

A: I am using:
fp=freopen(NULL,"w",fp);

A: fclose(fopen("file.txt", "w"));

Why this works:

write: Create an empty file for output operations. If a file with the same name already exists, its contents are discarded and the file is treated as a new empty file.

(quote from http://www.cplusplus.com/reference/cstdio/fopen/)

A: with fopen(filename, flag) just open it with flag= "w" or "wb" and it will be cleared

A: I prefer to use:-
system("echo "" > filename_with_complet_path");


text:
Q: FileUtils.readFileToString() from Apache Commons IO works incorrectly with Cyrillic I am using FileUtils.readFileToString to read contents of a text file with JSON at once. The file is UTF-8 encoded (w/o BOM). Yet, instead of cyrillic letters I get ?????? signs. Why?
public String getJSON() throws IOException
{
    File customersFile = new File(this.STORAGE_FILE_PATH);
    return FileUtils.readFileToString(customersFile, StandardCharsets.UTF_8);
}

A: FileUtils.readFileToString doesn't work with StandardCharsets.UTF_8.
Instead, try
FileUtils.readFileToString(customersFile, "UTF-8");
or
FileUtils.readFileToString(customersFile, StandardCharsets.UTF_8.name());

A: This is how I solved it back in 2015:
public String getJSON() throws IOException
{
//    File customersFile = new File(this.STORAGE_FILE_PATH);
//    return FileUtils.readFileToString(customersFile, StandardCharsets.UTF_8);
    String JSON = "";
    InputStream stream = new FileInputStream(this.STORAGE_FILE_PATH);
    String nextString = "";
    try {
        if (stream != null) {
            InputStreamReader streamReader = new InputStreamReader(stream, "UTF-8");
            BufferedReader reader = new BufferedReader(streamReader);
            while ((nextString = reader.readLine()) != null)
                JSON = new StringBuilder().append(JSON).append(nextString).toString();
        }
    }
    catch(Exception ex)
    {
        System.err.println(ex.getMessage());
    }
    return JSON;
}

A: I figured out that in logs all was fine, so I solved problem in rest controller:
 @GetMapping(value = "/getXmlByIin", produces = "application/json;charset=UTF-8")


text:
Q: Rewrite differential equation If $h(t+1) = g \cdot h(t) - dh(t)/dx$, then how can you rephrase it to $dh/dt = \dots$ ?
It's an advection equation describing the evolution of a fluid h over time.
Thanks

A: $$
\begin{align}
h(t+1) &= g\cdot h(t) + \frac{d h(t)}{dx} &\\
\frac{d h(t)}{dx} &= h(t+1) - g\cdot h(t) & \text{(reorder terms.)}\\
\frac{d h(t)}{dt}\cdot\frac{d t}{dx} &= h(t+1) - g\cdot h(t) & \text{(chain rule.)}\\
\frac{d h(t)}{dt} &= \dot{x}\cdot\left[ h(t+1) - g\cdot h(t)\right] & \frac{d x}{dt} = \dot{x}\\
\end{align}
$$
Disclaimer: I am assumming that you can apply chain rule here, of course.


text:
Q: Implementation help for Extended Euclidean Algorithm I'm not sure if this question is entirely on-topic here, please notify if not. I feel it is more a math related problem, than a programming problem.

Following the advice in this answer I'm trying to implement the Extended Euclidean Algorithm. The linked answer as well as one of the standard sources:
McEliece, Robert J.; Shearer, James B., A property of Euclid's algorithm and an application to Padé approximation, SIAM J. Appl. Math. 34, 611-615 (1978). ZBL0384.10006.
yield the same results, when I implement them. However, my results do not match the example given in McEliece and I have a hard time figuring out what I'm doing wrong.

The example given is:

My Code: using Matlab's quorem function:
syms a b x r t q s

a = x^7;
b = -x^6 + x^5 - x^3 + x^2 + x + 1;

s(-1+2) = 1;
t(-1+2) = 0;
r(-1+2) = a;
s(0+2) = 0;
t(0+2) = 1;
r(0+2) = b;

for k = 1:4
    [q(k+2), r(k+2)] = quorem(r(k-2+2),r(k-1+2),x);
    s(k+2) = s(k-2+2) - q(k+2)*s(k-1+2);
    t(k+2) = t(k-2+2) - q(k+2)*t(k-1+2);
end

disp( [ (1:5).'-2 r(:), q(:) ] )

(the +2 just shifts the index to a valid range)
yields to for $r_i$ and $q_i$:
[ -1,                             x^7,              q]
[  0, - x^6 + x^5 - x^3 + x^2 + x + 1,              0]
[  1,     x^5 - x^4 + 2*x^2 + 2*x + 1,        - x - 1]
[  2,           x^3 + 3*x^2 + 2*x + 1,             -x]
[  3,             - 21*x^2 - 14*x - 9, x^2 - 4*x + 10]
[  4,                            x/63,   - x/21 - 1/9]
[  5,                               0,              0]

Which is similar, but starting with line 3, not the same. I checked the code a dozen times, what am I doing wrong?

A: You did everything right except to understand the first sentence in the example:

Let $\Bbb F_3=\{-1,0,1\}$ be the field of integers modulo $3$ ...

This means that all integer computations are reduced to these numbers by adding or subtracting multiples of $3$. So that you get $1+1=-1$, as $2=-1+3$. In this sense,

*

*the computed $r_2=x^3 + 3*x^2 + 2*x + 1$ is then reduced to $x^3 + 0*x^2 - x + 1$ and

*in the next step, $r_3=- 21*x^2 - 14*x - 9$ gets reduced to $0*x^2+x-0$.

As the reduction to coefficients in $\Bbb F_3$ changes the degree of $r_3$, all the following computations have to be more different than just changes by multiples of $3$. This can be seen for instance in the next remainder where the division $r_4=x/63$ is a division by zero in $\Bbb F_3$.

A: In addition to the explaining answer of LutzL, here the corrected Matlab code, compared with Matlab's in-built function:
% Variable declaration:
syms a b x r t q s

% Example:
m = 4;
n = 3;
% Taylor expansion with minimum order of m+n
b = x^7 -x^6 + x^5 - x^3 + x^2 + x + 1;
% =>
a = x^(m+n+1);

% starting values
s(-1+2) = 1;
t(-1+2) = 0;
r(-1+2) = a;
s(0+2) = 0;
t(0+2) = 1;
r(0+2) = b;

% algortihm
poldeg = @(pol) feval(symengine, 'degree', pol, x);
k = 1;
while true
    [q(k+2), r(k+2)] = quorem(r(k-2+2),r(k-1+2),x);
    s(k+2) = s(k-2+2) - q(k+2)*s(k-1+2);
    t(k+2) = t(k-2+2) - q(k+2)*t(k-1+2);
    if poldeg(r(k)) == m; break; end
    k = k+1;
end

% Pade Approximant by Extended Euclidan Algorithm
PA = simplifyFraction(r(k)/t(k))

% Check with in-built function:
PA = pade(b,x,0,'Order',[m,n])

PA (this implementation) = (x^3 + 3*x^2 + 2*x + 1)/(x^2 + x + 1)
PA (Matlab in-built) = (x^3 + 3*x^2 + 2*x + 1)/(x^2 + x + 1)


text:
Q: How to add new pages (ROR) when my page of news is full? How to add new pages (ROR) when my page is full? I unload my application on Heroku. But I have no database. For example, I have this page: http://priroda-site.tk/mammal/index. I add new posts every day. What define in controller, that pages automatically created? I should have 6 posts on every page.
Stucture
post
post
post
post
post
post

1 2 3 4 5 6 7 8 9 10 ...

My post structure
html.erb

28 JULY 2014

            <%= image_tag "fakts/bee.jpg", :size=>"470x320" %>

A: What you're looking for is called pagination. There are a multitude of solutions for this in Rails, I tend to use will_paginate


text:
Q: What algorithm does Amazon ELB use to balance load? I found this in the official ELB documentation

By default, a load balancer routes each request independently to the
  application instance with the smallest load.

but an article on Newvem says that ELB supports only Round Robin algorithm

Algorithms supported by Amazon ELB - Currently Amazon ELB only supports Round Robin (RR) and Session Sticky Algorithms.

So which one is it?
[1] http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/US_StickySessions.html
[2] http://www.newvem.com/dissecting-amazon-elastic-load-balancer-elb-18-facts-you-should-know/?lead_source=popup_ebook&oid=00DD0000000lsYR&email=muneeb%40olacabs.com

A: It depends on the type of ELB used. AWS has over the time introduced Application ELB and Network ELB along with the Classic ELB.
Application Load Balancers applies listener rules and assigns the (HTTP/HTTPS) request to a target group. It selects a target from that target group using the round robin routing algorithm
Network Load Balancers node that receives the connection, selects a target from its target group using a flow hash routing algorithm
Classic Load Balancers uses round robin routing algorithm for TCP listeners and least outstanding requests routing algorithm for HTTP and HTTPS listeners
.
TLDR;

The modern ELBs use round robin routing algorithm for HTTP/HTTPS requests
  and flow hash routing algorithm for TCP requests.
Classic ELB used round robin routing algorithm for TCP requests and least outstanding requests routing algorithm for HTTP and HTTPS requests

Source / Further Reading : https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/how-elastic-load-balancing-works.html#routing-algorithm

A: It's request count based for HTTP(S), round robin for other.
http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/TerminologyandKeyConcepts.html#request-routing

Before a client sends a request to your load balancer, it first
  resolves the load balancer's domain name with the Domain Name System
  (DNS) servers. The DNS server uses DNS round robin to determine which
  load balancer node in a specific Availability Zone will receive the
  request.
The selected load balancer node then sends the request to healthy
  instances within the same Availability Zone. To determine the healthy
  instances, the load balancer node uses either the round robin (for TCP
  connections) or the least outstanding request (for HTTP/HTTPS
  connections) routing algorithm. The least outstanding request routing
  algorithm favors back-end instances with the fewest connections or
  outstanding requests.


text:
Q: Issue with click eventListener I found an example task to display an alert on a page when you click anywhere in a document. In the task you need to edit only the display() function, which has two parameters - myFunc and myObj, so that the name of the person object is displayed. I've come up with something like this, but the alert only comes up after the page refreshes, not after each click on the document.
function start() {
    var person = {
        name : "John"
    };
    function alertName() {
        alert(""+this.name.toUpperCase() + "");
    }
    document.addEventListener('click', display(alertName, person));
}
function display(myFunc, myObj) {
  name = myObj.name;
  myFunc();

}
start();

here is fiddle:

function start() {
    var person = {
        name : "John"
    };
    function alertName() {
        alert(""+this.name.toUpperCase() + "");
    }
    document.addEventListener('click', start(alertName, person));
}
function display(myFunc, myObj) {
  name = myObj.name;
  myFunc();

}
start();
body {
  background-color:yellow;
}
  <body>

  </body>

A: The issue here in that addEventListener second parameter need to be the function you want to invoke when the event is trigger.
In your exemple, you passed an instruction and not a function. What you can do is add the display() call inside a function body, and pass that function as the second parameter :
function start() {
    var person = {
        name : "John"
    };
    function alertName() {
        alert(""+this.name.toUpperCase() + "");
    }
    document.addEventListener('click', function() {
    display(alertName, person)
    });
}
function display(myFunc, myObj) {
  name = myObj.name;
  myFunc();

}
start();

A: You need to understand that display is a function and by display(alertName, person) you are calling it immediately, not as a event callback. However addEventListener needs function reference as the second parameter so it means that when called display(alertName, person) must return a new function that will call alertName (which is a reference) from inside.
Finally, this.name inside alertName implies that it needs to be invoked in context of myObj, use Function.prototype.call to do it.

function start() {
  var person = {
    name: "John"
  }

  function alertName() {
    alert("" + this.name.toUpperCase() + "");
  }

  document.addEventListener('click', display(alertName, person));
}

function display(myFunc, myObj) {
  return function () {
    myFunc.call(myObj)
  }
}
start();
Click somewhere.


text:
Q: Changed mpm-worker 2.4 config but with no effect I have changed the default configuration to:
<IfModule worker.c>
ServerLimit 20
StartServers            4
MaxRequestWorkers               600
MinSpareThreads         25
MaxSpareThreads         75
ThreadsPerChild         30
MaxConnectionsPerChild  0
</IfModule>

And when in peak, using server-status, when it reaches 400 sessions, it still doesn't seem to create new workers and remains at 400:
BusyWorkers: 400
IdleWorkers: 0
Scoreboard: KKKKCKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKRKCKKKKKKCKKRKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKRKKKKKCKKKCKKKKKRKKKCKKKKKKCKKKKKKKKKKKKRCKKCKKKCKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKCKKKRKKKKKKKRKKKKKKKKKKKKKCKCKKKKKCKKKCKCKKRCRKKKKKKKKKKKKRKKKKKKKKKKKKKKCKKKKCKKKKKRKCCKKKKKKKKKKKKKKCKKKKKKKRKKKKKKKKKKCKKKCKKRKKCRKKRKKKKKKKKKKKKKCKKKKRKKKKRKKKKCKKKKKRKKKKKKKKKKKKKKKKKKKKRKKKKKKKWKKKKKKKKKKKCKKKK

If I change the user to apache and issue an ulimit -u i get 1024
Any ideas?

A: I finally figured out why Apache was not able to create more than 400 workers. It was because of the configuration file format.
In our httpd.conf file the settings for worker and prefork modules are written just before the "LoadModule" section. It seems that apache does not like this format so it ignores our values for worker mode and falls back to the default values.
The fix is very simple, we have to delete the settings for worker and prefork modules from above "LoadModules" section and put them after this section.
These values are optimal for 1000 simultaneous connections:
# prefork MPM
# StartServers: number of server processes to start
# MinSpareServers: minimum number of server processes which are kept spare
# MaxSpareServers: maximum number of server processes which are kept spare
# ServerLimit: maximum value for MaxClients for the lifetime of the server
# MaxClients: maximum number of server processes allowed to start
# MaxRequestsPerChild: maximum number of requests a server process serves
<IfModule prefork.c>
    ServerLimit                                         40
    StartServers                                       5
    MinSpareThreads                           25
    MaxSpareServers                           75
    MaxRequestWorkers                   1000
    ThreadsPerChild                             25
    MaxConnectionsPerChild     0
</IfModule>
#
# worker MPM
# StartServers: initial number of -erver processes to start
# MaxClients: maximum number of simultaneous client connections
# MinSpareThreads: minimum number of worker threads which are kept spare
# MaxSpareThreads: maximum number of worker threads which are kept spare
# ThreadsPerChild: constant number of worker threads in each server process
# MaxRequestsPerChild: maximum number of requests a server process serves
<IfModule mpm_worker_module>
    ServerLimit                                         40
    StartServers                                       5
    MinSpareThreads                           25
    MaxSpareThreads                          75
    MaxRequestWorkers           1000
    ThreadsPerChild                             25
    MaxConnectionsPerChild     0
</IfModule>

After that just stop/start apache process.

A: You need to FULL stop/start for mpm changes to take effect, restart or graceful will still give you the previous settings.


text:
Q: Convert Web Page to PDF or Image I need to convert a web page [which has not public access] to PDF or Image [preferably to PNG].
Web page contains set of charts and image. Most of the charts are populated through Ajax calls so there is a delay between page load and chart load.
I am looking answer for any of these questions:
1- I found set of snapshot api's but none of them support accessing my internal page. Since the web page I am trying to export is not public I need to be authenticated. Biggest problem is I cannot send request headers [such as session-id, cookie or other variables] along with these API's. It seems they don't support this kind of functionality.
2- I am not sure if I can do following: Login to my web page with HTTP client, add http headers, send get call and get HTML string. Then use one of the converters to convert it to PDF. What I am not sure is if it's possible to get proper PDF from the HTML string I got from http client since resources [css, js and etc] will be missing. I want my pdf/image looks exactly as it on the web site.
I really appreciate if you can help.
Thanks in advance,
ED

A: You're probably best of using wkhtmltopdf, which is a server-side tool and is easily installed.
There are two parameters you can use to wait for your Ajax to finish, try:

*

*javascript-delay to influence the time the program waits for the JavaScript to finish

*window-status to wait for a certain return code for the window

See the extensive manual for this program here
wkhtmltopdf generates a PDF and wkhtmltoimg generates an image, which is PNG (as you requested) by default.

A: Authentication is difficult because it involves security. Because the operation you are describing is unusual it is likely to result in all kinds of alarm bells going off. It is entirely possible to do but it is fraught, easy to get wrong and fragile in the face of security updates and code changes.
As such I'm going to suggest an alternate method which is one we often recommend for ABCpdf (on which I work). Yes we support standard authentication methods but the beauty of this approach is that it is robust and is applicable to other solutions (eg Java based) and novel authentication methods.
Typically you just want a PDF of the current page. The easiest way to do this is snaffle the HTML. The way you do this rather depends on your environment. For example under ASP.NET you can obtain the HTML of the current page using the HttpResponse.Filter property or by overriding the Render method of the page. The way you do it will depend on what you're coding in.
Then you need to save this HTML to a file and present it to your solution via a 'file://' protocol URL. Now obviously at this point any relative links will be broken but this is easily fixed by dropping in a BASE tag that references the place they are located.
Generally the types of resources referenced by an server-side page are static. So if you can create a  tag that references the actual files rather than a web site, you will bypass any authentication for access to these resources.
That still leaves the AJAX based problems which are another can of worms. The render delay method is something we have supported for many years (from before AJAX was around) however it is not terribly reliable because you just don't know how long to wait.
Much better is a tighter link into the JavaScript via a callback you can use to determine if the page is loaded. I don't think ABCpdf is going to be appropriate for you since it is .NET but I would certainly encourage you to look for a Java based solution that uses this type of more sophisticated approach.


text:
Q: Hadoop MapReduce generates output containing only the last entry, on cluster I have a job for counting the hashtag-words from tweets and then display the 15 most frequent.
When testing it local from a test class is working perfectly, but on the cluster it gives as result only the last computed entry.
Mapper
public class HashtagMapper extends Mapper<LongWritable, Text, Text, IntWritable> {

private static final IntWritable ONE = new IntWritable(1);
private Text word = new Text();

@Override
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
    String cleanValue = value.toString().replaceAll("[^A-Za-z0-9#]", " ");
    cleanValue = cleanValue.replace("# ", " ");

    StringTokenizer itr = new StringTokenizer(cleanValue, " ");
    while (itr.hasMoreTokens()) {
        word.set(itr.nextToken().trim());
        if (word.find("#", 0) == 0) {
            context.write(new Text(word), ONE);
        }
    }
}

}

Reducer
public class HashtagReducer extends Reducer<Text, IntWritable, Text, DoubleWritable> {

private final HashMultimap<Text, Integer> hashtags = HashMultimap.create();

@Override
public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
    int sum = 0;
    for (IntWritable val : values) {
        sum += val.get();
    }
    hashtags.put(key, sum);
}

@Override
public void cleanup(Context context) throws IOException, InterruptedException {
    Map<Text, Collection<Integer>> sortedMap = sortByComparator(hashtags.asMap());
    Set<Text> keys = sortedMap.keySet();
    int index = 0;
    for (Text key : keys) {
        context.write(new Text(key), new DoubleWritable(sortedMap.get(key).iterator().next()));
        index++;
        if (index == Math.min(keys.size() -1, 15)) {
            break;
        }
    }
}

private static Map<Text, Collection<Integer>> sortByComparator(Map<Text, Collection<Integer>> unsortedMap) {

    List<Map.Entry<Text, Collection<Integer>>> list = new LinkedList<Map.Entry<Text, Collection<Integer>>>(unsortedMap.entrySet());

    Collections.sort(list, Collections.reverseOrder(new Comparator<Map.Entry<Text, Collection<Integer>>>() {
        public int compare(Map.Entry<Text, Collection<Integer>> o1,
                           Map.Entry<Text, Collection<Integer>> o2) {
            return (o1.getValue()).iterator().next().compareTo(o2.getValue().iterator().next());
        }
    }));

    Map<Text, Collection<Integer>> sortedMap = new LinkedHashMap<Text, Collection<Integer>>();

    for (Map.Entry<Text, Collection<Integer>> entry : list) {
        sortedMap.put(entry.getKey(), entry.getValue());
    }
    return sortedMap;
}
}

Driver
public class StubDriver {

public static void main(String[] args) throws Exception {

/*
 * Validate that two arguments were passed from the command line.
 */
if (args.length != 2) {
  System.out.printf("Usage: StubDriver <input dir> <output dir>\n");
  System.exit(-1);
}

/*
 * Instantiate a Job object for your job's configuration.
 */
Job job = Job.getInstance();

/*
 * Specify the jar file that contains your driver, mapper, and reducer.
 * Hadoop will transfer this jar file to nodes in your cluster running
 * mapper and reducer tasks.
 */
job.setJarByClass(StubDriver.class);

/*
 * Specify an easily-decipherable name for the job.
 * This job name will appear in reports and logs.
 */

job.setJobName("StubDriver");
job.setMapperClass(HashtagMapper.class);
job.setReducerClass(HashtagReducer.class);

FileInputFormat.setInputPaths(job, args[0]);
FileOutputFormat.setOutputPath(job, new Path(args[1]));

job.setInputFormatClass(TextInputFormat.class);
job.setOutputFormatClass(TextOutputFormat.class);

job.setOutputValueClass(IntWritable.class);
job.setOutputKeyClass(Text.class);

/*
 * Start the MapReduce job and wait for it to finish.
 * If it finishes successfully, return 0. If not, return 1.
 */
boolean success = job.waitForCompletion(true);
System.exit(success ? 0 : 1);
}
}

Test
public class HashtagTest {
MapDriver<LongWritable, Text, Text, IntWritable> mapDriver;
MapReduceDriver<LongWritable, Text, Text, IntWritable, Text, DoubleWritable> mapReduceDriver;

@Before
public void setUp() {
    HashtagMapper hashtagMapper = new HashtagMapper();
    HashtagReducer hashtagReducer = new HashtagReducer();

    mapDriver = new MapDriver<LongWritable, Text, Text, IntWritable>();
    mapDriver.setMapper(hashtagMapper);

    mapReduceDriver = new MapReduceDriver<LongWritable, Text, Text, IntWritable, Text, DoubleWritable>();
    mapReduceDriver.setMapper(hashtagMapper);
    mapReduceDriver.setReducer(hashtagReducer);
}

@Test
public void testMapReducer_3() {
    try {
        File file = new File("/home/paul/Documents/Studium/Master Bussines Informatics/3 Semester/Business Intelligence/Part 2/tweets/small.json");
        FileInputStream fileInputStream = new FileInputStream(file);
        byte[] data = new byte[(int) file.length()];
        fileInputStream.read(data);
        fileInputStream.close();

        String str = new String(data, "UTF-8");

        mapReduceDriver
                .withInput(new LongWritable(), new Text(str))
                .withOutput(new Text("#Like"), new DoubleWritable((77)))
                .withOutput(new Text("#Retweet"), new DoubleWritable(75))
                .withOutput(new Text("#Malerei"), new DoubleWritable(35))
                .withOutput(new Text("#N"), new DoubleWritable(35))
                .withOutput(new Text("#nagelstudio"), new DoubleWritable(35))
                .withOutput(new Text("#nailart"),new DoubleWritable(35))
                .withOutput(new Text("#Crystalnails"),new DoubleWritable(35))
                .withOutput(new Text("#babyboomer"),new DoubleWritable(35))
                .withOutput(new Text("#Geln"),new DoubleWritable(35))
                .withOutput(new Text("#GelN"),new DoubleWritable(35))
                .withOutput(new Text("#Muster"),new DoubleWritable(35))
                .withOutput(new Text("#NagelstudioWien"),new DoubleWritable(35))
                .withOutput(new Text("#GoodVibeTribe"),new DoubleWritable(24))
                .withOutput(new Text("#1DPL"),new DoubleWritable(24))
                .withOutput(new Text("#Przesz"),new DoubleWritable(22))
                .runTest();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}
does someone have a tip?

A: I solved the problem by changing following things in the Reducer:

*

*public void cleanup(Context context) => public void cleanup (Reducer.Context context)

*hashtag.put() => this.hashtag.put()

*sortedMap = sortByComparator(hashtag.asMap()) => sortedMap = sortByComparator(this.hashtag.asMap())


text:
Q: precision problem on decimal DbParameter In c#,
I use a decimal out DbParameter for a Sql Server stored procedure.
I create parameter like that

DbParameter prm = comm.CreateParameter();

prm.ParameterName = "@Price";

prm.DbType = DbType.Decimal;

prm.Direction = ParameterDirection.Output;

comm.Parameters.Add(prm);

//and set the value of comm.Parameters["@Price"] to a variable,

decimal.TryParse(comm.Parameters["@Price"].Value.ToString(),
  out this.ProdPrice);

But the value of the out parameter is allways rounded.
If i call the same stored procedure from Sql Server Management Studio, i can get this out
parameter properly with it's precision
There is not a precision or scale properties on DbParameter.
And i have to use DbParameter on System.Data.Common namespace for fetching the data
How can i being able to retieve decimal value with its full precision
Thanks in advance...

A: Adding to Marc's suggestion, you can change the code to

IDbDataParameter prm = comm.CreateParameter();

Rest of the code should work fine.
Precision and Scale properties are "explicit interface implementation" in DbParameter.

A: Have you tried setting Precision and Scale? Note you need to cast first.

A: First, you don't need to parse the string to get the Decimal, you should be able to cast directly to it:
this.ProdPrice = (Decimal) comm.Parameters["@Price"].Value;

That being said, what is the precision of the @Price parameter?  I believe that SQL Server allows for precision up to 35 places, while the Decimal class only provides precision up to 28 places, so if your parameter has more than 28 places, you won't be able to prevent the rounding.


text:
Q: Enable bitcode vs include bitcode before submitting app What's the difference between the "Enable Bitcode" setting in the app's target & project and the "Include Bitcode" checkbox that is present before submitting to App Store?
If I have "Enable Bitcode" FALSE and have "Include Bitcode" checked, what happens?
If I have "Enable Bitcode" TRUE and have "Include Bitcode" unchecked, what happens?
I saw other questions asking only what "Enable Bitcode" does, but mine ask the difference with this setting and the "Include Bitcode" setting just before submitting the app to the App Store.
Thanks

A: As you might imagine, you need both enabled in order to have your app support Bitcode recompilation in iTunes Connect. Just enabling it in Xcode simply means the Bitcode "architecture" is compiled, it doesn't necessarily mean that's sent to Apple.
Advance warning: I've done some tests on app submission with and without Bitcode, and for whatever reason submitting with Bitcode substantially slows down the time it takes for your binary to be processed so that it's ready for submission. Without Bitcode it can appear in a few minutes or up to maybe three hours; with Bitcode I've frequently had delays of 24 hours or more.

A: If bitcode is disabled for your target and all pods, the include bitcode checkbox will vanish from the dialog of upload to app store.


text:
Q: Adobe Flash and JSON I'm a newbie in adobe flash development.
I have form login, and I want to login with my api, which like this: /api/login and with user & pass.
And I don't know how to.
Which I have?

*

*IDE: Adobe Flash Professional CS6

*The form with username & password field

What I need?

*

*How to connect to API and get response

*How to send request to server with POST & GET

Thanks so much!

A: You can send GET/POST request with the URLLoader class:
import flash.net.URLLoader;
import flash.events.Event;
import flash.net.URLRequest;
import flash.net.URLLoaderDataFormat;
import flash.net.URLRequestMethod;

var urlRequest:URLRequest = new URLRequest("LINK_HERE");
urlRequest.method = URLRequestMethod.POST;
urlRequest.data = your_json_object;

var urlLoader:URLLoader = new URLLoader();
urlLoader.addEventListener(Event.COMPLETE, onComplete);
urlLoader.load(urlRequest);

function onComplete(e:Event):void
{
    trace(e.currentTarget.data); // the response from the server
}


text:
Q: Trying to Display Additional Image Thumbnails Below Main Featured Product Image Can't get files from Moltin API to display under main product image
Using this repo: https://github.com/moltin/gatsby-demo-store and updating
@moltin/gatsby-source-moltin to 1.3.1 I have tried expanding the product
node schema to include relationships as per Moltin API documentation then
referencing this in a new component but no additional images render.
Had a look at other implementations i.e. Gatsby Store example which uses
Thumbnails and could get a tiny clickable thin purple strip rendering but with no image. The store uses Shopify and localFile storage for image rendering so this use case is not applicable.
```
import React, { useContext, useEffect, useReducer, useState } from 'react'
import { graphql, withPrefix } from 'gatsby'

import SEO from '../components/SEO'
import Photo from '../components/Photo'
import Badge from '../components/Badge'
import AddToCart from '../components/AddToCart'
import { Shopkit } from '../shopkit'
import Img from 'gatsby-image'

  const {
    meta: { display_price }
  } = product

  return (
    <React.Fragment>
      <SEO
        type="product"
        title={product.meta_title || product.name}
        description={product.meta_description || product.description}
        image={withPrefix(product.mainImage.childImageSharp.fixed.src)}
      />

      <div className="flex flex-wrap md:bg-grey-light">
        <div className="py-2 md:py-5 md:px-5 w-full lg:w-1/2">
          <div className="sticky pin-t">
            <Photo
              src={product.mainImage}
              alt={product.main_image_alt_text || product.name}
            />
           <Img
             src={product.relationships.files.data.id}
             alt=""
           />
          </div>
        </div>
......
.....
....
    </React.Fragment>
  )
}

export const query = graphql`
  query($id: String!) {
    product: moltinProduct(id: { eq: $id }) {
      id
      slug
      name
      description
      sku
      mainImage {
        childImageSharp {
          fixed(width: 560) {
            ...GatsbyImageSharpFixed
          }
        }
        publicURL
      }
      meta {
        display_price {
          without_tax {
            formatted
          }
        }
      }
      manage_stock
      meta_title
      meta_description
      on_sale
      bulb
      bulb_qty
      material
      finish
      max_watt
      relationships {
             main_image {
              data {
                id
              }
            }
        files {
          data {
            type
            id
          }
    }
  }
`

export default ProductPage
```

Would like to get small thumbnail rending below main product image. Console
error message when using Img component: Uncaught TypeError: Cannot read
property 'src' of undefined.

A: gatsby-source-moltin adds a images field to the product schema which you can query like so:
images {
  childImageSharp {
    fluid(maxWidth: 300) {
      ...GatsbyImageSharpFluid
    }
  }
}

I put together an example on CodeSandbox.