text:
Q: Trouble setting application icon with JavaFX I am having trouble changing the application icon with JavaFX (code is below with my attempts commented out). I tried implementing several solutions from previous stack overflow answers but I'm not sure if those methods are now deprecated. I am using NetBeans 8.2 (and the icon is in a folder called images under the source package).
1st Attempt: Illegal start of expression. identifier expected: JavaFX Application Icon
2nd Attempt: No suitable method found for add(java.awt.Image): Changing the icon of my java application
3rd Attempt: Cannot find symbol. Cannot instantiate the type Image java?
5th Attempt: Image is abstract it cannot be instantiated. http://docs.oracle.com/javafx/2/deployment/self-contained-packaging.htm
package javafxapplication1;

import java.awt.Image;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

import javafx.event.EventHandler;
import javafx.scene.input.MouseEvent;
import javax.imageio.ImageIO;

public class JavaFXApplication1 extends Application {
    private double xOffset = 0;
    private double yOffset = 0;

    @Override
    public void start(Stage stage) throws Exception {

        //stage.getIcons().add(Image(<JavaFXApplication1>.class.getResourceAsStream( "/images/fiji.png" ));

        Image i = ImageIO.read(getClass().getResource("/images/fiji.png"));
        //setIconImage(i);
        //stage.getIcons().add(i);

        //stage.getIcons().add(Image("/images/fiji.png"));

        // stage.getIcons().add(ImageIO.read(getClass().getResource("/images/fiji.png")));

        //stage.getIcons().add(new Image(this.getClass().getResourceAsStream("/images/fiji.png")));

        Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
        //stage.initStyle(StageStyle.UNDECORATED);
        // makes it moveble
        // LOOK INTO!!!!!!!!!!!
         root.setOnMousePressed(new EventHandler<MouseEvent>() {
             @Override
             public void handle(MouseEvent event) {
                 xOffset = event.getSceneX();
                 yOffset = event.getSceneY();
             }
         });
         root.setOnMouseDragged(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
            stage.setX(event.getScreenX() - xOffset);
            stage.setY(event.getScreenY() - yOffset);
            }
         });
        Scene scene = new Scene(root);

        stage.setScene(scene);
        stage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

}

A: You need to load an Image and add it to the stage's icons.
import javafx.scene.image.Image;
Image icon = new Image(Controller.class.getResource("/game.png").toExternalForm(), false);
primaryStage.getIcons().add(icon);

However, on Ubuntu these icons do not get displayed. This JavaFX defect hasn't been solved for a long time.
It seems that your first attempt is missing the new keyword for the Image instantiation, and make sure it is a javafx.scene.image.Image, not a java.awt.Image image, which has a different constructor. Try this:
stage.getIcons().add(new Image(JavaFXApplication1.class.getResource( "/images/fiji.png" ).toExternalForm());

A: First, load an image and then add to the stage object. Please make sure to give path starting from the inside of the resource folder, not from the resource folder, or else use the whole project path.
Image favicon = new Image('URL_OF_THE_IMAGE');
stage.getIcons.add(favicon);


text:
Q: Disbale "lowercase_normalizer" normalizer while applying aggregation in Elasticsearch We have applied "lowercase_normalizer" normalizer to fields to achieve case insensitive search. However, we need to perform aggregation on certain fields without any text transformation. Is there any way of disabling the normalizer while aggregating through the records?

A: The data in the field has already been normalized before indexing, so it is stored in the index in lowercase. I suggest you make a separate field where you don't apply the lowercase_normalizer to be used for aggregations.

A: You can try my way.
Example your initial mapping is as follows:
"test_nor": {
    "type": "keyword",
    "normalizer": "lowerasciinormalizer"
}

Data
"test_nor": "Lê văn Lươn"
Aggregations look like this
{
 "size": 0,
 "aggs": {
     "by_name": {
         "terms": {
            "field": "test_nor",
             "size": 100
         },
         "aggs": {
             "by_email": {
                 "terms": {
                     "field": "email",
                     "size": 100
                 }
             }
         }
     }
 }
}

Result aggregations
"aggregations": {
    "by_name": {
        "doc_count_error_upper_bound": 0,
        "sum_other_doc_count": 0,
        "buckets": [
            {
                "key": "le van luon",
                "doc_count": 1,
                "by_email": {
                    "doc_count_error_upper_bound": 0,
                    "sum_other_doc_count": 0,
                    "buckets": [
                        {
                            "key": "email1@gmail.com",
                            "doc_count": 1
                        },
                        {
                            "key": "email2@gmail.com",
                            "doc_count": 1
                        }
                    ]
                }
            }
        ]
    }
}

You want result aggregations "key": "Lê văn Lươn" right.
1: Update mapping
PUT /my-index-000001/_mapping
{
     "properties": {
      "test_nor": {
          "type": "keyword",
          "normalizer": "lowerasciinormalizer",
          "fields": {
              "keyword": {
                  "type": "keyword"
              }
          }
      }
  }
}

2: Update a data field so that the data gets the new mapping
3: Update query aggregations
{
"size": 0,
"aggs": {
    "by_name": {
        "terms": {
            "field": "test_nor.keyword",
            "size": 100
        },
        "aggs": {
            "by_email": {
                "terms": {
                    "field": "email",
                    "size": 100
                }
            }
        }
    }
}
}

4: So now you got what you want
"aggregations": {
    "by_name": {
        "doc_count_error_upper_bound": 0,
        "sum_other_doc_count": 0,
        "buckets": [
            {
                "key": "Lê văn Lươn",
                "doc_count": 1,
                "by_email": {
                    "doc_count_error_upper_bound": 0,
                    "sum_other_doc_count": 0,
                    "buckets": [
                        {
                            "key": "email1@gmail.com",
                            "doc_count": 1
                        },
                        {
                            "key": "email2@gmail.com",
                            "doc_count": 1
                        }
                    ]
                }
            }
        ]
    }
}

Hope it helps you !

redpajama_set_name: RedPajamaStackExchange


text:
Q: Commit on top of a custom GO package I am using sha3 package inside a forked go project. I am using a special feature that does not exist in that package and I had to download a  file from gist, insert it into the sha3 package and compile it.
Everything is working fine. However, anyone who wants to run my code, they have to get that file and insert it into standard sha3 package first, install the package and run my project.
What is the best way that I can include the gist file and sha3 into my commit, so anyone can just clone and run it? Here is the file path:
workspace-
         |_src__
                |_github.com
                |          |_myproject
                |                     |_codes
                |                     |_.git
                |_golang.org
                           |_x
                             |_crypto
                                    |_sha3
                                         |_custom.go

A: Have a look at dep:

*

*Remove your golang.org folder, and go to your project folder.

*Then try dep ensure.

If you don't have go dep installed, type first:
go get -u github.com/golang/dep/cmd/dep

That will vendor your dependency: see "Understanding and using the vendor folder".

A: Since go 1.5, you can put a vendor folder at the root of your project (workspace/src/github.com/myproject/vendor). This folder is an import path. When building, go build will first look for packages inside your vendor folder and if not found, will look inside your $GOPATH.
You can copy your custom golang.org/x/crypto package inside your vendor folder and add it to your favorite VCS.
The other solution would be to make a fork of the golang.org/x/crypto repository like github.com/user/mycrypto and use the go get command to get the code like this:
go get github.com/user/mycrypto

That being said, VonC is right, it's a good practice to use a dependency manager as it will keep track of what version of libraries you have installed, and it allows better portability.


text:
Q: facebook api graph, get public photos I want to know if using the graph api there is a way to get all the public photo (or at least a limited list) stored in facebook, i know that you can get the public post using a keyword with:
https://graph.facebook.com/search?q=keyword&type=post

Is there a photo equivalent way?

A: You can use FQL to query for all the photos in the user's news feed. This post discusses this in some detail. Here is the FQL that you could use:
SELECT actor_id, created_time, likes, post_id, attachment
FROM stream WHERE filter_key IN (
    SELECT filter_key FROM stream_filter WHERE uid = me() AND (name = "Photos")
)


text:
Q: Construction of the completion of a measure space Let $(X,M, \mu)$ be a measure space. Let $\overline{M}$ be collection of $E \cup Z$ such that $E \in M$ and $Z \subset F$, where $F \in M,$ and $\mu(F) = 0.$ We also know $\bar{\mu}(E) = \mu(E).$
a) Show $\overline{M}$ is smallest sigma algebra containing $M$ and all subsets of elements of $M$ that have measure $0$.
Attempt: Notice if $E_{1} \subset \overline{M}$ then $E_{1} = E \cup Z.$ Since $E, Z \in M$ then $E_{1}^c = (E \cup F)^c \cup (F-Z)$ is in $M$ since $(E \cup F),(F-Z) \in M.$ Hence $\overline{M}$ is sigma algebra. If we let $Z = \emptyset$,then we see $M \subset \overline{M}.$ And since $\emptyset \in M,$ then let $E = \emptyset$, and then all subsets of $M$ with measure $0$ is in $M.$ Does this look okay? I am not sure how to show $\overline{M}$ is the smallest sigma algebra containing $M$
b) Show $\bar{\mu}$ is a measure of $\overline{M},$ and this measure is a completion.
Attempt: First check $\bar{\mu}$ is a measure of $\overline{M}.$ Notice $\bar{\mu}(\emptyset) = \mu(\emptyset) = 0.$ If $A_{1} \subset A_{2}$, and $A_{1} = B_{1} \cup C_{1}, A_{2} = B_{2} \cup C_{2},$ then $\bar{\mu}(A_1) = \mu(B_1) \le \mu(B_2) = \bar{\mu}(A_2).$ Lastly $\bar{\mu}(\cup_{i=1}^{n}A_{i}) = {\mu}(\cup_{i=1}^{n}B_{i}) \le \sum_{i=1}^{n}\mu(B_i).$ Next for completion, we need to show if $F \in \overline{M}$ and $\bar{\mu}(F) = 0,$ if $E\subset F$ then $E \in \overline{M}.$ I am not sure how to this.

A: Attempt of (a):
What you did here seems okay.  Make sure to realize $E_1 \in \overline{M}$, not $E_1 \subset \overline{M}$.
To show it's the smallest $\sigma$-algebra, you have to show $$\overline{M} = \bigcap N$$ where the intersection is over all complete $\sigma$-algebras on $X$ that contain $M$.
Your question on (b) follows from monotonicity, or write $E$ as $\emptyset \cup E$.

A: The argument "since $E, Z \in M$" is incorrect, since $Z$ needn't be in $M$. It is true, though, that $Z \subset F$ for some null measurable set $F$.
Here is a suggestion:
Without loss of generality, if $E \cup Z \in \overline{M}$, while $Z \subset F \in Null(M)$, one can assume that $E \cap F = \phi$. Indeed, otherwise one could write $E \cup Z = (E \setminus F) \cup [(F \cap E) \cup Z]$, and have $E \setminus F \in M, (F \cap E) \cup Z \subset F \in Null(M)$
So, $E^c = E^c \setminus F \cup F \in \overline{M}$, since $E^c \setminus F \in M, F \in Null(M)$


text:
Q: Polymorphism and inheritance using class reference (part 2)? The console application below gives "Runtime error"...
Why would this happen ? Many thanks !
PS: Related SO post
program Project2;

{$APPTYPE CONSOLE}

type
  TParent = class;
  TParentClass = class of TParent;

  TParent = class
  public
    procedure Work; virtual; abstract;
  end;

  TChild1 = class(TParent)
  public
    procedure Work; override;
  end;

  TChild2 = class(TParent)
  public
    procedure Work; override;
  end;

procedure TChild1.Work;
begin
  WriteLn('Child1 Work');
end;

procedure TChild2.Work;
begin
  WriteLn('Child2 Work');
end;

procedure Test(ImplClass: TParentClass);
var
  ImplInstance: TParent;
begin
  ImplInstance := ImplClass.Create;
  ImplInstance.Work;
  ImplInstance.Free;
end;

begin
  Test(TParent);
  Test(TChild1);
  Test(TChild2);
  Readln;
end.

A: The TParent.Work method is declared as abstract. The documentation says:

You can call an abstract method only in a class or instance of a class in which the method has been overridden.

When you call TParent.Work you break that rule and so encounter a runtime error.


text:
Q: how to setup constraint for 2 labels and one image view in Tableview Cell using storyboard? I am new to swift development. I am stuck at one point. I want to add 2 labels and one image view side by side like shown below in the image. I have tried many combination but unable to achieve the desired result. I even tried placing both labels in one container view and image view in another container view and set the constraints to it but no success. Below is the output which I want to achieve.

Any help will be highly appreciated.

A: Apply Constraints like below:
Label 1:

Label 2:

Imageview :

hope,it's help to you.

A: You can use horizontal stack view. In that you can place your labels and image horizontally.

A: I think, a picture can represent it in a better way. Please follow below steps to apply the constraints to your view:
1) Apply trailing, width and height to your image view. Still absence of y-position will throw error. Will handle in next image.

2) Align the image view, vertically centre to superview.

3) Do the same as step 1 and step 2 for you time label as well. Just give the leading constraint rather than trailing.

4) Give the leading and trailing constraints to name label and align it vertically centre to superview. Because you have given the widths to time label and image view to it will cover rest of the available width with 3 px padding from front and back.

5) Now, you will see a warning for this view, It is because you have fixed the time label's width and what happen if text will be larger for this label?. You can handle this situation by 2 methods
*First, change the autoshrink property from Fixed Font Size to Minimum Font Scale with factor 0.5. But it will just handle the case and will not remove warning. *

Second, update width constraint of time label with >=. But it will again create error because updating constraint to >= will conflict with name label's automatic width detection. To solve this follow next image

6) Decrease Horizontal Content Hugging Property of name label.


text:
Q: Why the is the set operator "includes" equivalent to the logical operator "implies"? Let's say we have a superset called "People" (P). In that superset we have two subsets, "Men" (M) and "Women" (W). We can say that:
$P  \supset M$
$P  \supset W$
In logical language, this is equivalent to:

*

*$P   \Rightarrow  M$

*$P   \Rightarrow  W$
But translated to human language, (1) means that being a Person implies being a Man, and (2) means that being a Person implies being a Woman, which does not make any logical sense.
Shouldn't the equivalence between sets and logic be the other way round?

*

*$P   \Leftarrow  M$

*$P   \Leftarrow  W$
Now, being a man, obviously implies being a Person, and being a woman obviously
 implies being a Person.

A: We have that $M \subset H$, that reads : the set of Males is a subset of the set of Humans", is defined by the formula :

$\forall x (\text Mx \to \text H (x))$,

that reads : "every Male is Human".
The relationship between the symbol $\subset$ for set inclusion and $\supset$ for the conditional connective ("if…, then…") is historical; see the post Why is there this strange contradiction between the language of logic and that of set theory? as well as the post Is there any connection between the symbol $\supset$ when it means implication and its meaning as superset?
In a nutshell :

Ernst Schröder, into Vorlesungen uber die Algebra der Logik, Vol. I (Leipzig, 1890), used $\subset$ for "is included in" (untergeordnet) and $\supset$ for "includes" (ubergeordnet).
Giuseppe Peano expressed the relations and operations of logic in Volume I of his Formulaire de mathematiques (1895) by the signs $\in$, c, ɔ, [...] the meanings of which are, respectively, "is" (i.e., is a member of), "contains," "is contained in," [...].

Peano "inverted c" becomes $\supset$ :

On pourrait indiquer la relation $p \supset q$ par le signe $q \text C p$ qu'on lira "$q$ est conséquence de $p$".

The diffusion of the use of $\supset$ to deonte the conditional is due to Whitehead & Russell's Principia Mathematica (1910-1913).


text:
Q: Creating macro for Boost path My team and I all use Boost with C++. We all have installed Boost at different directory paths on our respective machines. This has now become a problem because we would all like to add the project settings file (.vcxproj) to Git repo. One way to do this is to force everyone to install Boost at the same directory path and then add that path to the project properties.
But, I was wondering if there was a better way. Can I define a Boost path macro such that each user can simply define the macro as per the Boost installation path on his computer. I see such macros when I expand the macros list in Include Additional Directories dialog box.
How can I create such a macro in Visual STudio to assign boost path? I did not see a button to create a macro in the macros box.

A: Custom user macros are handled using the Property Sheets. Here is explained how to add a new property sheet to a project. Here is how to edit the property sheet. The property sheet edit dialog has the Common Properties->User Macros tab. Using it is necessary to create a new macro, for instance, Name is BOOST_ROOT and Value is C:\boost_1_57_0\.
After that the $(BOOST_ROOT) macro will be present in the macros list of the Additional Include Directories dialog. This macro is possible to user across of the project properties.
Also is possible to add this macro to the Additional Include Directories of the property sheet. In this case it is not necessary even to add the $(BOOST_ROOT) macro in the Additional Include Directories of the project.


text:
Q: Hyper-V 2019 Core Server can't install windows defender update KB4052623? I am having a problem with installing the "Update for Microsoft Defender Antivirus antimalware platform - KB4052623 (Version 4.18.2205.7)" Update on my Microsoft Hyper-V Server 2019 Core Server. Using sconfig it always says installation failed. I also tried to download the update file from update-katalog. You will find 3x .cab files and 3x .exe files on the microsoft update-katalog site for this update. I tried all of them. The cab files return an error, if i run them using dism:

dism /online /add-package /packagepath:"C:\37049705_04c96011b32d783314a49ed52845bfe05357f68f.cab

If I run the .exe files nothing happens.
I also found on this site https://support.microsoft.com/en-us/topic/update-for-microsoft-defender-antimalware-platform-kb4052623-92e21611-8cf1-8e0e-56d6-561a07d144cc
that Applocker could lead to this problem, if activated. But on my hyper-v server applocker isn't activated.
In the log file i found the following entries:
2022-07-01 09:53:57, Error                 DISM   DISM Package Manager: PID=3808 TID=856 Failed to get the Update through CBS. - CDISMPackage::Internal_OpenFeature(hr:0x800f080c)
2022-07-01 09:53:57, Error                 DISM   DISM Package Manager: PID=3808 TID=856 Failed to get the underlying CBS Feature - CDISMPackage::OpenFeature(hr:0x800f080c)
2022-07-01 09:53:57, Error                 DISM   API: PID=2376 TID=1640 Failed to open feature Windows-Defender-Default-Definitions - CDisableFeatureCommandObject::InternalExecute(hr:0x800f080c)
2022-07-01 09:53:57, Error                 DISM   API: PID=2376 TID=1640 InternalExecute failed - CBaseCommandObject::Execute(hr:0x800f080c)
2022-07-01 09:53:57, Error                 DISM   API: PID=2376 TID=1584 CDisableFeatureCommandObject internal execution failed - DismDisableFeatureInternal(hr:0x800f080c)

I already tried the DISM /Online /Cleanup-Image /RestoreHealth scan and sfc /scannow. Still got the problem. Also tried to delete the distribution file as well.
Could you help me find out what the problem is and how to install this update ?

A: Confirmed on 10/3/22 that KB4052623 install continues to fail:

*

*Did a clean install of  "Microsoft Hyper-V Server 2019 (updated Sept 2019)"

*Used sconfig to install all updates, all installed okay. Restarted as prompted.

*Used sconfig to install all updates, all installed okay except "Update for Microsoft Defender Antivirus antimalware platform - KB4052623 (Version 4.18.2207.7)"

Note: If you then use WAC, Update, and attempt to install "KB4052623 (Version 4.18.2207.7)", it fails and goes into a loop of a failed attempts every ten minutes.  A server restart does not stop the issue and updates like  "Security Intelligence Update for Microsoft Defender Antivirus - KB2267602 (Version 1.375.1506.0)" are aborted unless you manually install then individually.  With sparce log information to examine, all I know for sure is that the server crashes every other day.
I have many servers running Hyper-V Server 2019 (Mainstream End Date is 1/9/2024). This unresolved problem is now in its third month.

A: The latest KB4052623 (version 4.18.2209.7) successfully installs on Hyper-V Server 2019 now [2022-10-13].
The patch notes for this version state Fixed Defender Platform update failure on Server Core 2019 SKUs although there was never acknowledgement that it has been an issue for the past few months.

A: I am seeing the same issue...reinstalled a server, etc. attempting to resolve this issue and never could get it to update. Hope they release a working update soon.

A: After installing the updates in the screenshot from 19.10.2022, the KB4052623 update was installed too.
Or rather, as said above, Willie, his version is 4.18.2209.7
enter image description here


text:
Q: Настройки Magento Создал блок. Нужно сделать в админке настройку (checkbox) например Show Images
И использовать настройку в блоке.
Magento 1.9
Я только 2 день как пробую magento! Никак не разберусь как добавить пункт в Система > Конфигурация. и как потом с ним работать!

A: Чтобы добавить поле в админку в системные настройки например нужно:

*

*Добавить в модуль system.xml

*В него добавить секцию/группу/поле например каталог/моя настройка/название настроки

*Получить значение Mage::getStoreConfig('секция/группа/поле',Mage::app()->getStore()->getId())

Вот неплохой ресурс с подробным объяснением.
Еще совет всегда смотреть в ядро системы, там много всего интересного)

Нашел еще новый способ(пока не испробовал) для поля можно указывать frontend_model и она наследует класс Varien_Data_Form_Element_Renderer_Interface и там есть уже много реализованных классов http://joxi.ru/Vrw3goguOJzW0r так что я думаю вполне можно и чекбокс и все что угодно добавить используя это метод.

A: Магента не позволяет в system / configuration юзать чекбоксы (если об этом идет речь). Сделайте через yes/no (гляньте по аналогии как делается)


text:
Q: URL decode in Razor .NET file (cshtml) I'm POSTing url encoded data to a cshtml file.
How can I decode the variables customerEmail and customerRequest before I email it?
@{
    var customerEmail = Request["customerEmail"];
    var customerRequest = Request["customerRequest"];

    var errorMessage = "";
    var debuggingFlag = false;
    try {
        // Initialize WebMail helper
        WebMail.SmtpServer = "your-SMTP-host";
        WebMail.SmtpPort = 25;
        WebMail.UserName = "your-user-name-here";
        WebMail.Password = "your-account-password";
        WebMail.From = "your-email-address-here";

        // Send email
        WebMail.Send(to: customerEmail,
            subject: "Dashboard Feedback from - " + customerEmail,
            body: customerRequest
        );
    }
    catch (Exception ex ) {
        errorMessage = ex.Message;
    }
}

A: Using System.Web.dll you can decode information: HttpUtility.UrlDecode.
Example:
String foo = "foo%40bar.com";
String bar = HttpUtility.UrlDecode(foo);
// bar = "foo@bar.com"

But I should mention, incoming information should already be decoded through the Request object.

A: You don't.
The Request object decodes everything for you already.


text:
Q: Passing data into Task Continuation I have the following method :
private void GetHistoricalRawDataFromTextFiles(MessageHeader header, HistoricalRawDataFromTextFileSubscriptionDto dto)
{
    var computeInstance = GetComputeInstance(dto.SubscriberId, dto.ComputeInstanceId);
    var task = computeInstance.GetHistoricalRawDataFromTextFiles(dto, progress => SendProgress(header.Sender, progress));

    task.ContinueWith(myTask =>
    {
        dto.TimeSeries = myTask.Result;
        Messenger.SendTo(SubscriberId, header.Sender, MessageType.Reply, MessageTopic.HistoricalRawDataFromTextFiles, dto);
    });
}

Method computeInstance.GetHistoricalRawDataFromTextFiles returns a Task<List<string>> and my question is

*

*whether this is the correct way to pass header and dto into the lambda expression and task continuations. It is important that the header and dto instance values are captured within the lambda expression and task continuation at the time the outer method is called. The same method may be called again before the task from the previous call completes.

A:
It is important that the header and dto instance values are captured
  within the lambda expression and task continuation at the time the
  outer method is called.

When using lambda expressions, what gets closed over is the variable, and not the value of that variable.
As long as header and dto aren't global variables which you modify each time before making the method call, you should be fine. If they are global variables, then you'll need to find a way to create a local copy for each of them. If they're reference types, you'll need to clone them, and if they're value types, you'll need to copy them to a local variable inside the lambda.

A: I think that your question boils down to : "Is my method thread safe?"
I don't think it's related to your captured variable here.
Your method doesn't seem to access a shared/global source ( static/global variables or fields).(otherwise you'd need synchronization)
Even if this method was called by a multiple threads simultaneously then it still be thread safe and each call to GetHistoricalRawDataFromTextFiles would deal with a separate "realm" - This is because each thread has its own stack.
So whether or not you use captured variable (refers to the same memory location)  - you still get unique dto and header for each iteration realm.
I don't see here any same shared memory location issue since each invocation (even if threaded) - gets its own space.
Again. this is assuming you're not using any global state.


text:
Q: SQL: Searching X table and returning rows from Y based on X data
*

*Search goals for rows where userid = 1.

*Using returned rows, search checkin where biometricid's match, along with the userid, and filter out rows that are older than the goal date.

Note: Both the userid and biometricid are foreign tables.
How may I do this with one query?
checkin
id  | userid    | date                  | biometricid   | value
1   | 1         | 2015-01-10 00:00:00   | 1             | 9
2   | 1         | 2000-05-11 00:00:00   | 1             | 7
3   | 2         | 2015-01-10 00:00:00   | 1             | 9
4   | 1         | 2015-01-10 00:00:00   | 2             | 1
5   | 1         | 2017-01-11 00:00:00   | 1             | 4

goals
id  | userid | date                 | biometricid   | value
1   | 1      | 2000-01-05 00:00:00  | 1             | 3
2   | 1      | 2015-01-01 00:00:00  | 2             | 2
3   | 2      | 2015-01-01 00:00:00  | 1             | 2

desired result
id  | date                  | biometricid   | value
1   | 2015-01-10 00:00:00   | 1             | 9
2   | 2017-01-11 00:00:00   | 1             | 4

A: Due to the way you worded the question, and the fact that it seems many other questions I've answer recently used them, I was tempted to show a subselect in a WHERE; but I realize your question can be answered much more simply:
SELECT c.*
FROM goals AS g
   INNER JOIN checkin AS c ON g.userid = c.userid
      AND g.biometricid = c.biometricid
      AND c.`date` >= g.`date`
WHERE g.user_id = 1
;


text:
Q: How to make game a draw with existing code I've created functions with all winning combinations for player one and player two but need to create one for a draw and don't want to write out all possible draw combinations. What would be the best way to attempt this?
I was thinking if I could make the playerOneWin and playerTwoWin function true if they run I could have a draw function() that says if both are false then the match is a draw, or if all boxes are fille and playerOne and playerTwo haven't won then it is a draw.

var box1 = document.querySelector(".box1");
var box2 = document.querySelector(".box2");
var box3 = document.querySelector(".box3");
var box4 = document.querySelector(".box4");
var box5 = document.querySelector(".box5");
var box6 = document.querySelector(".box6");
var box7 = document.querySelector(".box7");
var box8 = document.querySelector(".box8");
var box9 = document.querySelector(".box9");

var activePlayer;

var playerOne = "X";
var playerTwo = "O";

activePlayer = playerOne;

function clickBoxPlayer(event) {
  if (activePlayer === playerOne) {
    var boxClicked = event.target;

    if (
      boxClicked.innerHTML === playerOne ||
      boxClicked.innerHTML === playerTwo
    ) {
      console.log("noturturn");
    } else if (boxClicked.innerHTML === "") {
      boxClicked.innerHTML = activePlayer;
      activePlayer = playerTwo;
    }
    console.log("one");
    //tie && winning function

    function playerOneWin() {
      if (
        box1.innerHTML === playerOne &&
        box2.innerHTML === playerOne &&
        box3.innerHTML === playerOne
      ) {
        console.log("playeronewins");
      } else if (
        box1.innerHTML === playerOne &&
        box4.innerHTML === playerOne &&
        box7.innerHTML === playerOne
      ) {
        console.log("playeronewins");
      } else if (
        box1.innerHTML === playerOne &&
        box5.innerHTML === playerOne &&
        box9.innerHTML === playerOne
      ) {
        console.log("playeronewins");
      } else if (
        box2.innerHTML === playerOne &&
        box5.innerHTML === playerOne &&
        box8.innerHTML === playerOne
      ) {
        console.log("playeronewins");
      } else if (
        box3.innerHTML === playerOne &&
        box6.innerHTML === playerOne &&
        box9.innerHTML === playerOne
      ) {
        console.log("playeronewins");
      } else if (
        box3.innerHTML === playerOne &&
        box5.innerHTML === playerOne &&
        box7.innerHTML === playerOne
      ) {
        console.log("playeronewins");
      } else if (
        box4.innerHTML === playerOne &&
        box5.innerHTML === playerOne &&
        box6.innerHTML === playerOne
      ) {
        console.log("playeronewins");
      } else if (
        box7.innerHTML === playerOne &&
        box8.innerHTML === playerOne &&
        box9.innerHTML === playerOne
      ) {
        console.log("playeronewins");
      }
    }
    playerOneWin();
  } else if (activePlayer === playerTwo) {
    var boxClicked = event.target;

    if (
      boxClicked.innerHTML === playerOne ||
      boxClicked.innerHTML === playerTwo
    ) {
      console.log("noturturn");
    } else if (boxClicked.innerHTML === "") {
      boxClicked.innerHTML = activePlayer;
      activePlayer = playerOne;
    }

    console.log("two");
  }
  //player two winning combinations
  function playerTwoWin() {
    if (
      box1.innerHTML === playerTwo &&
      box2.innerHTML === playerTwo &&
      box3.innerHTML === playerTwo
    ) {
      console.log("playertwowins");
    } else if (
      box1.innerHTML === playerTwo &&
      box4.innerHTML === playerTwo &&
      box7.innerHTML === playerTwo
    ) {
      console.log("playertwowins");
    } else if (
      box1.innerHTML === playerTwo &&
      box5.innerHTML === playerTwo &&
      box9.innerHTML === playerTwo
    ) {
      console.log("playertwowins");
    } else if (
      box2.innerHTML === playerTwo &&
      box5.innerHTML === playerTwo &&
      box8.innerHTML === playerTwo
    ) {
      console.log("playertwowins");
    } else if (
      box3.innerHTML === playerTwo &&
      box6.innerHTML === playerTwo &&
      box9.innerHTML === playerTwo
    ) {
      console.log("playertwowins");
    } else if (
      box3.innerHTML === playerTwo &&
      box5.innerHTML === playerTwo &&
      box7.innerHTML === playerTwo
    ) {
      console.log("playertwowins");
    } else if (
      box4.innerHTML === playerTwo &&
      box5.innerHTML === playerTwo &&
      box6.innerHTML === playerTwo
    ) {
      console.log("playertwowins");
    } else if (
      box7.innerHTML === playerTwo &&
      box8.innerHTML === playerTwo &&
      box9.innerHTML === playerTwo
    ) {
      console.log("playertwowins");
    }
  }
  playerTwoWin();
}

var allBoxes = document.querySelector(".allBoxes");
allBoxes.addEventListener("click", clickBoxPlayer);
.allBoxes div {
  display     : block;
  float       : left;
  width       : 2em;
  height      : 2em;
  margin      : .3em;
  background  : lightgrey;
  text-align  : center;
  line-height : 1.8em;
  cursor      : pointer;
  }
.allBoxes div:nth-of-type(4),
.allBoxes div:nth-of-type(7) {
  clear : left;
  }

A: You are correct, if you changed your playerOneWin and playerTwoWin functions to return true or false based on the checks that you are already doing and if you also add a function that returns true if all boxes are filled (and false otherwise), then you can use them to check for the winning and the draw conditions like this
    if (playerOneWin()) {
        console.log("playeronewins");
    }

    // your other code

    if (playerTwoWin()) {
        console.log("playertwowins");
    }
    else if (allBoxesFilled() && !playerOneWin()) {
        console.log("draw");
    }

EDIT: to check all of the boxes you can put all of them (box1 - box9) into an array
// you could also do this by selecting all boxes
// with a document.querySelectorAll(...)
const boxes = [box1, box2, box3, box4, box5, box6, box7, box8, box9]

and then call .every on the boxes array with a predicate function. The predicate function has to return true, when the condition you are interested in is met, and false when the condition is not met. The condition you are interested in is that each box has to be filled, so it must not be empty, so the condition is innerHTML !== "". With such predicate function .every will return true only if the condition is true for all the items in the array (every means every item meets the condition in the predicate function). Which gives us the following code
const allBoxesFilled = boxes.every(box => box.innerHTML !== "")

You can use it like this in your code (instead of the function call), or put it into a function
function allBoxesFilled() {
  const boxes = [box1, box2, box3, box4, box5, box6, box7, box8, box9]
  return boxes.every(box => box.innerHTML !== "")
}

A: the way to do that:

const
  Boxes    = Array.from(document.querySelectorAll('#allBoxes > div'))
, players  = ['x','o']
, winCases = [[0,1,2],[3,4,5],[6,7,8],[0,4,8],[2,4,6],[0,3,6],[1,4,7],[2,5,8]]
  ;
var
  playerNum = 0
, winnerIs  = ''
  ;
document.querySelector('#allBoxes').onclick = ({target}) =>
  {
  if (!target.matches('#allBoxes div')
    || winnerIs != ''
    ) return

  if (target.textContent ==='')
    {
    target.textContent = players[playerNum]
    checkWinner(players[playerNum])
    playerNum = ++playerNum % 2
  } }
function checkWinner(player)
  {
  if (winCases.some(suite=>suite.every(x=>Boxes[x].textContent === player )))
    {
    winnerIs = player
    console.log(' winner is:',player)

    for (let [a,b,c] of winCases)
      {
      if ( Boxes[a].textContent === player
        && Boxes[b].textContent === player
        && Boxes[c].textContent === player
        ){
        Boxes[a].className = Boxes[b].className = Boxes[c].className = 'win'
        break;
  } } } }
#allBoxes div {
  display     : block;
  float       : left;
  width       : 2em;
  height      : 2em;
  margin      : .3em;
  background  : lightgrey;
  text-align  : center;
  line-height : 1.8em;
  cursor      : pointer;
  }
#allBoxes div:nth-of-type(4),
#allBoxes div:nth-of-type(7) {
  clear : left;
  }
#allBoxes div.win {
  background : yellow;
  }


text:
Q: Call WebApi action with a list of parameters Web API code
[HttpGet]
public string GetMore([FromUri] Int32[] dd)
{
   return "";
}

I need to be able to call this web api passing in an array of integers
The route at the WebApiconfig is as follows
config.EnableCors();

// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

// Web API routes
config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
config.Routes.MapHttpRoute(
                name: "ActionApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

I try to access the method with the URL

*

*http://localhost/testApplication/api/questionnaire/GetMore/dd=1
Calls the method but the dd array list is empty that is no data is present in the dd array.

*http://localhost/testApplication/api/questionnaire/GetMore/?dd=1&dd=2&dd=3 i get an error

{"Message":"The request is invalid.","MessageDetail":"The parameters
  dictionary contains a null entry for parameter 'id' of non-nullable
  type 'System.Int32' for method
  'WebAPI.Services.Controllers.Questionnaire Get(Int32)' in
  'WebAPI.Services.Controllers.QuestionnaireController'. An optional
  parameter must be a reference type, a nullable type, or be declared as
  an optional parameter."}

None of them seem to work . I am sure im doing something wrong. Just not sure what that is ?


text:
Q: best pratice to compile all templates files in a unique file with backbone/marionette I have a huge application built with Backbone, Marionette, Require.js and this is an example of the view that I'm using:
define([
 'backbone',
 'text!templates/oauth.html'
], function (Backbone, Template) {
var OAuthView = Backbone.View.extend({

    template: _.template(Template),
    render: function() {

        var type = this.options.error;
        this.$el.html(this.template({ error: type }));

        return this;
    }

});

return OAuthView;

});
I would like to have in production (only in production because in development I like that all template files are separated) a single file html and use this
https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.templatecache.md to improve the performance.
Any hints/idea? How can you solve this problem?
Thanks.

A: Not sure what your workflow is, I offer this as a solution that works for me.
I use grunt as my automation tool, and the
grunt jst plugin to automate
the pre-compilation of all my templates.
This creates a single javascript file will all the compiled templates.
Once include this file in your html document you can reference all
templates through the window.JST[...] object.

I keep all my templates in src/templates/views/* and src/templates/layouts/*.
My jst config looks likes this:
jst: {
  compile: {
    options: {
      prettify: false,
      amdWrapper: false,
      processName: function (filename) {
        var key = 'templates/';
        // src/templates/views/viewName.js -> views/viewName
        return filename.slice(filename.indexOf(key) + key.length, filename.lastIndexOf('.'));
      }
    },
    files: {
      "<%= app.src %>/scripts/templates.js": ["<%= app.src %>/**/*.tpl"]
    }
  }
},

This gives me a src/scripts/templates.js file looking like this:
this["JST"] = this["JST"] || {};

this["JST"]["views/modal"] = function(obj) {
    // compiled template here...
};
...

And finally my views look like this:
var ModalView = Backbone.View.extend({
    template: window.JST['views/modal'],
    ...
});

You can easily wrap window.JST['views/modal'] in a helper, much like Marionette.TemplateCache. Perhaps this is where you could handle dev/production differences, dynamically requiring the template if in dev, loading the pre-compiled version for production.

Ideally you want to abstract the logic for getting a template into a function.
In development you could have something like this where you require all your
templates and based on the input name you return the correct template. You'll have to adjust this depending upon how your app/workflow is designed.
define([
    'text!templates/oauth.html',
    'text!templates/otherTemplate.html',
    ...
], function () {
    App.getTemplate = function (name) {
        return require('text!templates/' + name + '.html');
    };
});

Then in production you would include this alternate version of the getTemplate
function that access the precompiled templates
App.getTemplate = function (name) {
    return window.JST[name];
};

A: Solved using https://github.com/guybedford/require-is – any feedback?
define([
    'jquery',
    'app',
    'marionette',
    'is!dev?text!templates/about.html'
], function ($, app, Marionette, template) {
    var AboutView = Marionette.ItemView.extend({

        getTemplate: function () {
            if(template){
                return template;
            }else{
                return window.JST['about']();
            }
        },

        render: function() {
            this.$el.html(_.template(this.getTemplate()));
            return this;
        }

    });

    return AboutView;
});

It could be cool to add getTemplate directly on the base backbone or marionette view.


text:
Q: MacBook Pro mouse pauses every 1.5 seconds with external monitors I have two Samsung QHD 27" monitors plugged into my 2019 MacBook Pro 16", but noticed that when moving the mouse, the mouse cursor gets stuck around every 1.5 seconds. This is extremely frustrating while working.
I initially had the screens plugged into the two left USB-C ports via two USB-C to Startech HDMI cables. I tried plugging into different ports, for example both screens on the right 2 USB ports, one on the left, one on the right, but to no avail.
Yesterday afternoon the mouse pausing stopped for a couple of hours, but today, it's all happening again. I turned off Spotlight by disallowing Spotlight to index my harddrive, tried changing to different screen resolutions and refresh rates, but nothing helps. Tried closing every application I could, this even happens right from initial startup.
Recently, I purchased two USB-C to DisplayPort cables rated good enough for 8k, but that too didn't help.
Tried booting into Windows 10, no problem there, so it's definitely something in macOS.
I'm using macOS Big Sur version 11.5.2. No USB dock, screens are plugged into the ports directly.
Has anyone had this issue before?


text:
Q: Выполнение команды в оболочке Kali Nethunter Я хочу запустить команду metasploit в оболочку терминала  кали, что-то типа такого su -c "bootkali && msfconsole" но проблема в том, что команда bootkali завершается только после закрытия терминала а мне надо выполнить команду внутри него. Как мне это реализовать?

A: в общем решением было то, что я подредактировал bootkali, там была строка с custom_command и я в ней custom_command заменил на msfconsole и теперь можно запускать так su -c "bootkali msfconsole"


text:
Q: Problem with Time zone configuration Rails 3 I've been having some problems with the configuration of timezone.
So I've seen some posts/questions about this topic and some say I should add the following configuration in the "application.rb".
config.time_zone = "Brasilia"

I've done that, but even after configuring this, if a run the following code in rails console I get (GMT+00:00) UTC
Time.zone

The same happens when a do
Time.now.in_time_zone

It responds in GMT 0.
Another problem that I think relates to this, is when choosing a datetime with the datetime_select tag. It seems as it's showing the right time but when the field is saved to the db is also on the UTC +00.

A: have you checked your {environments}.rb file (e.g. environments/development.rb)? The config values in application.rb are overridden by the same values in the environment .rb files. Perhaps you have GMT set in development.rb?
When I added config.time_zone = "Brasilia" to my development.rb file and ran rails c, I get:
ruby-1.9.2-p290 :001 > Time.zone
 => (GMT-03:00) Brasilia


text:
Q: OpenCV Circle Recognition in android devices I am new to android app development. I need to develop a very simple app that could detect coloured circles.Can someone please tell me in detail how to use openCV Circle Recognition code in developing a simple android app that can detect coloured circles. I am currently using openCV+ Eclipcs but it does not allow me to compile the source code in to .apk file
I have already done what u are saying...I have done the following

*

*I download the full NVidia tegra-devpack-2.0-windows-2013-02-06-14961502 and installed It contains both android ADT for eclipse and eclipse also. It also contains the open CV and it automatically configures everything.

*Everything works fine when I make a new android app like "my first HELLO WORLD app" and I can even install it to my android phone that means everything is working fine and everything is configured correctly.

*The problem arises when I try to import the source code of the "CVCamera" an common app for detecting circles in android devices

*When I import it in the eclipse as an android project from existing code it gives me following 2 errors
(a) Project 'CVCamera' is missing required Java project: 'OpenCV'
(b) The project cannot be built until build path errors are resolved.

*I have tried lots of things I even tried to link the open CV library to the project but of no use

*I have a simple objective I want to develop an android application for detection of coloured circles by using the already available code on the web. Please help me in achieving the following
I am using openCV4android . I can even create new apps but the problem arises when i try develop the application by using already made source code. I am using the sources code of the CV camera app which has been already developed by so many developers Following is the link of the error I am getting in the eclipse.
  Please see the image
 Following is the link of the CV camera application which I am trying to import
stanford.edu/class/ee368/Android/OpenCV/CVCamera_Canny.zip
Here is the link for another error "Build path entry is missing: OpenCV"
image
building workspace problim image

A: Use opencv4android in eclipse.
Before that you should deploy android ADT for eclipse, or download bundle for android dev.
Then follow the tutorial at opencv official site to start your way to android.
Use hough transform for circle detection.

A: You must link JavaCV lib into your project rather than OpenCV.
Android app cannot use OpenCV(C++) unless you use JNI, which is far beyond the scope of this question.
So please follow the tutorial for using JavaCV on Android rather than doing the import stuff on your own. Please make some JavaCV examples compile and run on your phone before you try to adapt the code.
Besides I strongly recommend you use openCV4android, which is sure to work, rather than JavaCV + Android, which takes your considerable time coping with configuration and integration.


text:
Q: Choco-Solver: Is there a way to know how many times a constraint is broken during the solving process? My models is inefficient and taking too long to find valid solutions so I think knowing how many times the constraints are being broken would be useful for testing.
Thank you

A: Since Choco-solver-4.10.8, it is possible to have insights on the propagation.
//...
Solver s = m.getSolver();
PropagationProfiler profiler = s.profilePropagation();
s.findSolution();
profiler.writeTo(new File("profiling.txt"));

You can have an idea of what is being collected in the following discussion.


text:
Q: Convenient way to delegate function calls I have a series of similar functions that all need to extract some values from a data frame. Something like this:
foo_1 <- function(data, ...) {
  x <- data$x
  y <- data$y

  # some preparatory code common to all foo_X functions

  # .. do some boring stuff with x and y

  # pack and process the result into 'ret'
  return(ret)
}

These functions are then provided as arguments to some other function (let us call it "the master function". I cannot modify the master function).
However, I wish I could avoid re-writing the same preparatory code in each of these functions. For example, I don't want to use data$x instead of assigning it to x and using x because it makes the boring stuff hard to read. Presently, I need to write x <- data$x (etc.) in all of the foo_1, foo_2... functions. Which is annoying and clutters the code. Also, packing and processing is common for all the foo_N functions. Other preparatory code includes scaling of variables or regularization of IDs.
What would be an elegant and terse way of doing this?
One possibility is to attach() the data frame (or use with(), as Hong suggested in the answer below), but I don't know what other variables would then be in my name space: attaching data can mask other variables I use in fun_1. Also, preferably the foo_N functions should be called with explicit parameters, so it is easier to see what they need and what they are doing.
Next possibility I was thinking of was a construction like this:
foo_generator <- function(number) {

  tocall <- switch(1=foo_1, 2=foo_2, 3=foo_3) # etc.

  function(data, ...) {
    x <- data$x
    y <- data$y
    tocall(x, y, ...)
    # process and pack into ret
    return(ret)
}

foo_1 <- function(x, y, ...) {
  # do some boring stuff
}

Then I can use foo_generator(1) instead of foo_1 as the argument for the master function.
Is there a better or more elegant way? I feel like I am overlooking something obvious here.

A: You might be overthinking it. You say that the code dealing with preparation and packing are common to all foo_n functions. I assume, then, that # .. do some boring stuff with x and y is where each function differs. If that's the case then just create a single prep_and_pack function which takes a function name as a parameter, and then pass in foo_1, foo_2, etc. For example:
prep_and_pack <- function(data, func){
    x <- data$x
    y <- data$y

    # preparatory code here

    xy_output <- func(x, y) # do stuff with x and y

    # code to pack and process into "ret"

    return(ret)
}

Now you can create your foo_n functions that do different things with x and y:
foo_1 <- function(x, y) {
    # .. do some boring stuff with x and y
}

foo_2 <- function(x, y) {
    # .. do some boring stuff with x and y
}

foo_3 <- function(x, y) {
    # .. do some boring stuff with x and y
}

Finally, you can pass multiple calls to prep_and_pack into your master function, where foo_1 etc. are passed in via the func argument:
master_func(prep_and_pack(data = df, func = foo_1),
            prep_and_pack(data = df, func = foo_2),
            prep_and_pack(data = df, func = foo_3)
            )

You could also use switch in prep_and_pack and/or forgo the foo_n functions completely in favor of if-else conditionals to deal with the various cases, but I think the above keeps things nice a clean.

A: The requirements still seem a bit vague to me,
but if your code is so similar that you can simply wrap it around a helper function like tocall in your example,
and your input is in a list-like structure
(like a data frame which is just a list of columns),
then just write all your foo_* functions to take the "spliced" parameters like in your proposed solution,
and then use do.call:
foo_1 <- function(x, y) {
  x + y
}

foo_2 <- function(x, y) {
  x - y
}

data <- list(x = 1:2, y = 3:4)

do.call(foo_1, data)
# [1] 4 6

do.call(foo_2, data)
# [1] -2 -2

A: I'm not sure the following is a good idea. It reminds me a bit of programming with macros. I don't think I would do this. You'd need to carefully document because it is unexpected, confusing and not self-explanatory.
If you want to reuse the same code in different functions, it might be an option to create it as an unevaluated call and evaluate that call in the different functions:
prepcode <- quote({
  x <- data$x
  y <- data$y
  }
)

foo_1 <- function(data, ...) {
  eval(prepcode)
  # some preparatory code common to all foo_X functions

  # .. do some boring stuff with x and y

  # pack and process the result into 'ret'
  return(list(x, y))
}

L <- list(x = 1, y = "a")
foo_1(L)
#[[1]]
#[1] 1
#
#[[2]]
#[1] "a"

It might be better, to then have prepcode as an argument to foo_1 to make sure there won't be any scoping issues.

A: Use with inside the function:
foo_1 <- function(data, ...) {
  with(data, {
    # .. in here, x and y refer to data$x and data$y
  }
}

A: I'm not sure I understand fully, but can't you simply use a function for all common stuff, and then unpack that into the foo_N functions using list2env? For example:
prepFun <- function(data, ...) {
    x <- data$x
    y <- data$y
    tocall(x, y, ...)
    # process and pack into a named list called ret
    # so you know specifically what the elements of ret are called
    return(ret)
}

foo_1 <- function(data, ...) {

  # Get prepFun to do the prepping, then use list2env to get the result in foo_1
  # You know which are the named elements, so there should be no confusion about
  # what does or does not get masked.
  prepResult <- prepFun(data, ...)
  list2env(prepResult)

  # .. do some boring stuff with x and y

  # pack and process the result into 'ret'
  return(ret)

}

Hope this is what you're looking for!

A: I think defining a function factory for this task is a bit overkill and confusing. You can define a general function and use purrr::partial() on it when passing it to your master function.
Something like :
foo <- function(data, ..., number, foo_funs) {
  tocall <- foo_funs[[number]])
  with(data[c("x", "y")], tocall(x, y, ...))
    # process and pack into ret
   return(ret)
}

foo_1 <- function(x, y, ...) {
  # do some boring stuff
}

foo_funs <- list(foo_1, foo_2, ...)

Then call master_fun(fun = purrr::partial(foo, number =1) , ...)

A: another possibility is to use list2env which saves the components of a list in to a specified environment:
foo_1 <- function(data){
  list2env(data, envir = environment())
  x + y
}

foo_1(data.frame(x = 1:2, y = 3:4))

See also this question.


text:
Q: Could not create SSL/TLS secure channel only on Windows Server 2012 I have a peculiar problem where a c# app works on all other machines and other client machines I have tested. But does not establish a connection on my clients Windows Server 2012 hosted by his ISP. This app have been working up to about 2 days ago on this machine according to my client and uses .Net4.5.2. I have no idea what changed the last couple of days unfortunately.
What I have tested on this machine:

*

*Using Chrome the url works

*Using Edge the url works

*hitting the URL with curl works

*Using IE11 the url does not work

*Using our app does not work

*Using a quick test app does not work

This is the same no matter what settings I change on the server or in the app.
Error from my app:
AuthResponse is null: False
AuthResponse ErrorException: System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel.
   at System.Net.HttpWebRequest.GetRequestStream(TransportContext& context)
   at System.Net.HttpWebRequest.GetRequestStream()
   at RestSharp.Http.WriteRequestBody(HttpWebRequest webRequest)
   at RestSharp.Http.PostPutInternal(String method)
   at RestSharp.Http.AsPost(String httpMethod)
   at RestSharp.RestClient.DoExecuteAsPost(IHttp http, String method)
   at RestSharp.RestClient.Execute(IRestRequest request, String httpMethod, Func`3 getResponse)
AuthResponse ErrorMessage: The request was aborted: Could not create SSL/TLS secure channel.

Error from IE11:
Turn on TLS 1.0, TLS 1.1, and TLS 1.2 in Advanced settings and try connecting to  again. If this error persists, it is possible that this site uses an unsupported protocol or cipher suite such as RC4 (link for the details), which is not considered secure. Please contact your site administrator.

Errors From Event Viewer:
A fatal alert was received from the remote endpoint. The TLS protocol defined fatal alert code is 40.
A fatal alert was generated and sent to the remote endpoint. This may result in termination of the connection. The TLS protocol defined fatal error code is 40. The Windows SChannel error state is 1205.
A fatal error occurred while creating an SSL client credential. The internal error state is 10013.

There are a lot of these errors in event viewer, I just copied three of them in case they are actually relevant.
What I have tried:
I used IISCrypto to change and configure all manner of settings and testing in between. All with the same results. I have modified my app with quite a few changes I have found by searching all with the same results as well. Some of the code changes I made below:
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
ServicePointManager.Expect100Continue = true;
System.Net.ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

This is not all the changes I tried. I tried all kinds of different variations as well such as only tls1.2. I have used my little test app as well to connect to other https sites like google and my other rest service and no error is reported on this machine.
Our Auth server uses Lets Encrypts certificates and uses OAth and only accepts tls2.1. I have hit another REST Api that we use that also use Lets Encrypt and that is working. I don't know if I need to update the certificate store (if that is possible), or if there is a setting I'm missing. I'm honestly at a loss here.
Test app source if that helps at all:
static async Task test(string url)
{
    // Call asynchronous network methods in a try/catch block to handle exceptions.
    try
    {
        HttpClient httpClient = new HttpClient();
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

        ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

        var result = await httpClient.GetAsync(url);
        MessageBox.Show(result.StatusCode.ToString());
    }
    catch (HttpRequestException e)
    {
        MessageBox.Show(e.ToString());
    }
}

A: We had the same problem today.
Some unsafe cipher suites were removed at our webserver yesterday.
Though vulnerable, adding these cipher suites fixed the problem.
https://learn.microsoft.com/en-us/windows-server/security/tls/manage-tls
Here is list of cipher suites:
https://support.microsoft.com/en-us/help/2929781/update-adds-new-tls-cipher-suites-and-changes-cipher-suite-priorities
Listing supported cipher suites:
https://learn.microsoft.com/nl-nl/windows/win32/secauthn/prioritizing-schannel-cipher-suites?redirectedfrom=MSDN#listing-supported-cipher-suites

A: I also have the same issue like this, after searching for a while, there's a few things you need to do:

*

*First you check the url you need to access/query, which type "Connection Encrypted" that Url uses? The easy way is open the url via Mozila or Chrome then check the "Connection Encrypted"
this example for my case

*Then try search available TLS cipher that's available for Windows Server 2012 at https://learn.microsoft.com/en-us/windows/win32/secauthn/tls-cipher-suites-in-windows-8-1. Find the "Connection Encrypted" from first step, for this step no.2, if you can't find it "Cipher suite string", so it means your server can't call that url via C# code.
Even if you set this in your code.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Because Windows Server 2012 can't support that "Connection Encrypted"
Hope it can help you.

A: You have probably resolved the issue, but I just came across this same issue where an external api call failed due to the same error of "Could not create SSL/TLS Secure Channel".
I spent two days on it and the fix was first checking what TLS version and cipher is supported on the endpoint by using https://www.ssllabs.com/ssltest/
After that, I used IIS Crypto to enable the proper ciphers accordingly, rearrange the ciphers in the order provided by SSLLabs and that resolved the issue.

A: Maybe this will help someone.
I just had this very problem with Windows Server 2019 Datacenter.
The X.509 certificate I was using to secure my self-hosted service on the server was old and weak, RSA 1024, MD5 hash.
Event Viewer was no help in tracking down the cause.
On a hunch, I replaced the old X.509 with a newer X.509, RSA 4096, SHA256 and the error went away.


text:
Q: Turning a closed-form generating function back to ordinary power series If I know the formal power series, I know how to find the closed form:
$$\displaystyle F = \sum_{n=0}^{\infty} {X^n} = 1 + X^1 + X^2 + X^3 + ...$$
$$\displaystyle F \cdot X = X \cdot \sum_{n=0}^{\infty} {X^n} = X^1 + X^2 + X^3 + X^4 + ...$$
$$\displaystyle F - F \cdot X = 1 $$
$$\displaystyle F = \frac 1 {1 - X} $$
But if I only know the closed form $\frac 1 {1 - X}$, how do I turn it back into the series $1 + X^1 + ...$? In other words, how do I do extract the coefficients if I only know the closed form and I do not know that $\frac 1 {1 - X}$ corresponds to $1 + X^1 + ...$.
My textbook and everywhere I looked at seems to avoid talking about this, and somehow magically transform things back and forth with a set of known formulas. Is there a better way to do this, or is formula matching the best we can do?
Edit: This is the type of questions I need to solve:

Find the coefficient of $X^8$ in the formal power series $(1 - 3X^4)^{-6}$

A: The quickest way to transform your generating function to a power series is to have a table of formulae handy. For a given rational function, you would use partial fraction expansion if necessary and switch back to the power series by looking at the appropriate entry in the table for each term. If you look at Herbert Wilf's book http://www.math.upenn.edu/~wilf/gfologyLinked2.pdf , in section 2.5, he has a list of such formulae.
You have
\begin{equation}
\frac{1}{(1-x)^{k+1}} = \sum_n \binom{n+k}{n} x^n
\end{equation}
So, for your case, we have
\begin{equation}
\frac{1}{(1-3x^4)^6} = \sum_n \binom{n+5}{n} 3^n x^{4n}
\end{equation}
The coefficient of $x^8$ in this expansion is $3^2 \times \binom{7}{2} = 189$.
It is actually not difficult to derive the identity. You start with
\begin{equation}
\frac{1}{1-x} = 1+x+x^2 +\ldots
\end{equation}
Take derivative on both sides k times and you will get
\begin{equation}
\frac{k!}{(1-x)^{k+1}} = \sum_n [(n+k)(n+k-1) \ldots n]x^n
\end{equation}
this simplifies to
\begin{equation}
\frac{1}{(1-x)^{k+1}} = \sum_n \binom{n+k}{n} x^n
\end{equation}

A: Differentiation $n$ times, setting the variable to 0, multiplying by $n!$ gets you the $n$th coefficient of the ogf of a function $f$. That is, if $F(x)$ is the ogf of $f(n)$ then
$$f(n) = [(D^nf)(0)]\cdot n!$$.
But you want the closed form of $f$ from the ogf. For the most part, that is an ad hoc process (svenkatr's answer gives a particular method for $\frac{1}{(1-x)^k}$).
A general method is to use the above differentiation trick (essentially computing the Taylor series), but finding a pattern from it. For a simple example, if $F(x)= \log \frac{1}{1-x}$, differentiating numerous times, you'll see the pattern 1, 1/2, 1/3, 1/4,..., so you'll notice and be able to prove) that $f(n) = 1/n$.


text:
Q: WPF - How to write a trigger for mouse over of grid? I see that Button object has a IsMouseOVer property.
But how do create an effect for the mouse over of a grid or other
element that does not have IsMouseOver??
Thanks
Malcolm
Edit: i figured it out. I was using the wrong method for setting the trigger.

A: I realize that I am responding to a dead thread but since I came across it, and since the thread is not answered, I am going to answer it.
The WPF Grid has an "IsMouseOver" property.
I think this question was asked because the "IsMouseOver" property only changes if the mouse is over a "hit-testable" control (ie a Button, or ComboBox) within the Grid itself.
Therefore, it may appear that the "IsMouseOver" property doesn't work (especially if you are using it in a trigger to set the Grid's Visible property).
For example:
<Grid>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="25" />
    <ColumnDefinition />
  </Grid.ColumnDefinitions>

  <Button Grid.Column="1">A Button</Button>

  <Grid.Style>
    <Style TargetType="{x:Type Grid}">
      <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="False">
          <Setter Property="Opacity" Value="0.5"></Setter>
        </Trigger>
        <Trigger Property="IsMouseOver" Value="True">
          <Setter Property="Opacity" Value="1"></Setter>
        </Trigger>
      </Style.Triggers>
    </Style>
  </Grid.Style>
</Grid>

The above Grid and it's contents will be displayed in half opacity.
You will notice that the opacity will not be set to full if you hover over the first column (which doesn't contain anything); however the opacity will be set to full if you hover over the button in the second column. This is because the first column, with nothing in it, is not hit-testable; whereas, the button within the second column is hit-testable and so the event is triggered.
If you want the Grid's IsMouseOver property to detect when the mouse is anywhere over the Grid itself all you have to do is set the Background property of the Grid to something that is not Null (set it to Transparent for example). Setting the Background property will make the Grid "hit-testable".
The following code will fix the problem:
<Grid Background="Transparent">
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="25" />
    <ColumnDefinition />
  </Grid.ColumnDefinitions>

  <Button Grid.Column="1">A Button</Button>

  <Grid.Style>
    <Style TargetType="{x:Type Grid}">
      <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="False">
          <Setter Property="Opacity" Value="0"></Setter>
        </Trigger>
        <Trigger Property="IsMouseOver" Value="True">
          <Setter Property="Opacity" Value="1"></Setter>
        </Trigger>
      </Style.Triggers>
    </Style>
  </Grid.Style>
</Grid>

-Frinny

A: One can also use the MouseEnter/MouseLeave events as such:
<Grid Name="grid">
    <Grid.Triggers>
        <EventTrigger RoutedEvent="MouseEnter">
            <BeginStoryboard>
                <Storyboard>
                    <ThicknessAnimation Storyboard.TargetProperty="Margin" From="0,0,-300,0" To="0,0,0,0" DecelerationRatio=".9" Duration="0:0:1" />
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
        <EventTrigger RoutedEvent="MouseLeave">
            <BeginStoryboard>
                <Storyboard>
                    <ThicknessAnimation Storyboard.TargetProperty="Margin" From="0,0,0,0" To="0,0,-300,0" AccelerationRatio=".9" Duration="0:0:1" />
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Grid.Triggers>
</Grid>

A: That would be the "MouseEnter" and "MouseLeave" actions on the WPF object.


text:
Q: MailKit does not find message ID I am currently migrating from OpenPop to MailKit.
I have a unit test that loads a string into a MimeMessage like this:
var emailText = @"
X-MDAV-Processed: mx1.footechnology.com.au, Mon, 30 Mar 2015 12:54:30 +1100
Return-path: <do-not-reply@baz.com.au>
Received: from mail2.baz.com.au (mail2.baz.com.au [220.157.74.146])
    by mx1.footechnology.com.au (mx1.footechnology.com.au)
    (MDaemon PRO v11.0.3)
    with ESMTP id md50005410292.msg
    for <faxes@foobar.com.au>; Mon, 30 Mar 2015 12:54:29 +1100
Authentication-Results: mx1.footechnology.com.au
    spf=neutral smtp.mail=do-not-reply@baz.com.au;
    x-ip-ptr=pass dns.ptr=mail2.baz.com.au (ip=220.157.74.146);
    x-ip-helo=pass smtp.helo=mail2.baz.com.au (ip=220.157.74.146);
    x-ip-mail=pass smtp.mail=do-not-reply@baz.com.au (ip=220.157.74.146)
Received-SPF: none (mx1.footechnology.com.au: do-not-reply@baz.com.au does not
    designate permitted sender hosts)
    x-spf-client=MDaemon.PRO.v11.0.3
    receiver=mx1.footechnology.com.au
    client-ip=220.157.74.146
    envelope-from=<do-not-reply@baz.com.au>
    helo=mail2.baz.com.au
X-Spam-Processed: mx1.footechnology.com.au, Mon, 30 Mar 2015 12:54:29 +1100
    (not processed: sender do-not-reply@baz.com.au in exclude file)
X-MDPtrLookup-Result: pass dns.ptr=mail2.baz.com.au (ip=220.157.74.146) (mx1.footechnology.com.au)
X-MDHeloLookup-Result: pass smtp.helo=mail2.baz.com.au (ip=220.157.74.146) (mx1.footechnology.com.au)
X-MDMailLookup-Result: pass smtp.mail=do-not-reply@baz.com.au (ip=220.157.74.146) (mx1.footechnology.com.au)
X-MDDK-Result: neutral (mx1.footechnology.com.au)
X-MDDKIM-Result: neutral (mx1.footechnology.com.au)
X-MDSPF-Result: none (mx1.footechnology.com.au)
X-Rcpt-To: faxes@foobar.com.au
X-MDRcpt-To: faxes@foobar.com.au
X-MDRemoteIP: 220.157.74.146
X-Return-Path: do-not-reply@baz.com.au
X-Envelope-From: do-not-reply@baz.com.au
X-MDaemon-Deliver-To: faxes@foobar.com.au
Received: from melbourne.baz.com.au (melbourne.baz.com.au [118.88.188.238])
    by mail2.baz.com.au (Postfix) with ESMTP id 3E100437181
    for <faxes@foobar.com.au>; Mon, 30 Mar 2015 11:54:17 +1000 (EST)
Received: from baz.com.au (localhost [127.0.0.1])
    by melbourne.baz.com.au (Postfix) with ESMTP id 6BA057C07C
    for <faxes@foobar.com.au>; Mon, 30 Mar 2015 12:54:16 +1100 (EST)
Content-Transfer-Encoding: binary
Message-ID : <syd1_did11-1403160784-288657210-5-21314.1403160831@medora2.syd1.colo.j2noc.com>
Content-Type: multipart/mixed; boundary=""_----------=_1301450056175850""
MIME-Version: 1.0
X-Mailer: MIME::Lite 3.01 (F2.72; B3.04; Q3.03)
Date: Mon, 30 Mar 2015 01:54:16 UT
From: ""Baz"" <do-not-reply@baz.com.au>
To: ""Foo Bar"" <fax@foobar.com.au>

This is a multi-part message in MIME format.

--_----------=_1301450056175850
Content-Disposition: inline
Content-Length: 1133
Content-Transfer-Encoding: binary
Content-Type: text/plain

This is the content of the message.

--_----------=_1301450056175850
Content-Disposition: attachment; filename=""fax-20110330125416.pdf""
Content-Transfer-Encoding: base64
Content-Type: application/pdf; name=""fax-20110330125416.pdf""

JVBERi0xLjEgDSXi48/TDQoxIDAgb2JqDTw8IA0vVHlwZSAvQ2F0YWxvZyAN

--_----------=_1301450056175850--
";

            var stream = new MemoryStream(Encoding.UTF8.GetBytes(emailText));
            var message = MimeMessage.Load(stream);

            Console.WriteLine("Text body:" + message.TextBody);
            Console.WriteLine("Html body:" + message.HtmlBody);
            Console.WriteLine("Date:" + message.Date);
            Console.WriteLine("MessageId:" + message.MessageId);
            Console.WriteLine("From:" + message.From.Mailboxes.First().Address);
            Console.WriteLine("To:" + message.To.Mailboxes.First().Address);

Whilst the message is successfully parsed, the MessageId header is not found. OpenPop could find the MessageId in the email. Why does MailKit fail? Is the message id header somehow considered invalid and thrown away?

A: The problem is the extra space before the ':' char:
Message-ID : <syd1_did11-1403160784-288657210-5-21314.1403160831@medora2.syd1.colo.j2noc.com>


text:
Q: Combining Multiple sheets from one work book into a single sheet on another work book with a macro I am just attempting this to help speed up cost comparisons, except my programming skills are laughable at this point. This is what I have so far...
Sub CommandButton1_Click()

'Last cell in column
Dim WS As Worksheet
Dim LastCell As Range
Dim LastCellRowNumber As Long

Set WS = Worksheets("Asphalt")
With WS
    Set LastCell = .Cells(.Rows.Count, "C").End(xlUp)
    LastCellRowNumber = LastCell.Row + 1
End With

Dim wb As Workbook, wb2 As Workbook
Dim vFile As Variant

'Set source workbook
Set wb = ActiveWorkbook

'Open the target workbook
vFile = Application.GetOpenFilename("Excel-files,*.xlsx", _
    1, "Select One File To Open", , False)

'if the user didn't select a file, exit sub
If TypeName(vFile) = "Boolean" Then Exit Sub
Workbooks.Open vFile

'Set selectedworkbook
Set wb2 = ActiveWorkbook

'Select cells to copy
wb2.Worksheets("Asphalt").Range("J3:R3").Copy

'Go back to original workbook you want to paste into
wb.Activate

'Paste starting at the last empty row
wb.Worksheets("Asphalt").Range("C" & LastCellRowNumber).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Application.CutCopyMode = False
Application.ScreenUpdating = True

'Close and save the workbook you copied from
wb2.Save
wb2.Close

End Sub

Now first thing I can't seem to open another .xls workbook for whatever reason. Secondly I get a message saying my subscript is out of range.
Ultimately what I want to happen is to hit a button, open the work book I want to have as my initial costs and it will populate not only pricing but also line items and quantities. Then hit another button to open another workbook and import the costs from that workbook but only if the line items match.
Now I know this is a tall tall order and I will continue on my trek to get my goal of having this all powerful spreadsheet, but I would greatly appreciate any and all help that I can get.
Here is a picture of roughly what I would like the final project to look like http://imgur.com/3EnYEcP just minus manually inputting all the numbers in like a caveman ;)

A: Remove the part that says, including the quotation marks "Excel-files,*.xlsx" to allow it to open all file types.  The code should be
vFile = Application.GetOpenFilename(, _
    1, "Select One File To Open", , False)
As for subscript out of range that could be for a variety of reasons...so you would need to expand more on which part of the code is getting the subscript error.
Hope this helps
H


text:
Q: What mean that Itô integral is not pathwise defined? Let $(X_t)$ a stochastic process and denote $I(t)=\int_0^t X_sdB_s$. In a book I'm reading it's written : Not that we cannot say that at $\omega $, the integral depend only on the path $t\mapsto B_t(\omega )$ and $t\mapsto X_t(\omega )$ since the integral is not pathwise defined.
What mean "the integral is not pathwise defined" ?

A: For almost all  $\omega$ the function $s \to B_s(\omega)$ is of unbounded variation so we cannot consider the integral as an ordinary Riemann Stieltjes integral.


text:
Q: Empty cart on Payment cancle or failure in Magento 1.9 When I place order on my store then I choose third party payment option like payumoney or paytm. Then I cancle or failure order then redirect to my cart page but cart is empty.
I want to products in the cart which i added before payment.
Please give me solution.
Thanks in advance.
class Mage_Payment_Model_Observer
{
    /**
     * Set forced canCreditmemo flag
     *
     * @param Varien_Event_Observer $observer
     * @return Mage_Payment_Model_Observer
     */
    public function salesOrderBeforeSave($observer)
    {
        $order = $observer->getEvent()->getOrder();

        if ($order->getPayment()->getMethodInstance()->getCode() != 'free') {
            return $this;
        }

        if ($order->canUnhold()) {
            return $this;
        }

        if ($order->isCanceled() || $order->getState() === Mage_Sales_Model_Order::STATE_CLOSED) {
            return $this;
        }
        /**
         * Allow forced creditmemo just in case if it wasn't defined before
         */
        if (!$order->hasForcedCanCreditmemo()) {
            $order->setForcedCanCreditmemo(true);
        }
        return $this;
    }

    /**
     * Collect buy request and set it as custom option
     *
     * Also sets the collected information and schedule as informational static options
     *
     * @param Varien_Event_Observer $observer
     */
    public function prepareProductRecurringProfileOptions($observer)
    {
        $product = $observer->getEvent()->getProduct();
        $buyRequest = $observer->getEvent()->getBuyRequest();

        if (!$product->isRecurring()) {
            return;
        }

        $profile = Mage::getModel('payment/recurring_profile')
            ->setLocale(Mage::app()->getLocale())
            ->setStore(Mage::app()->getStore())
            ->importBuyRequest($buyRequest)
            ->importProduct($product);
        if (!$profile) {
            return;
        }

        // add the start datetime as product custom option
        $product->addCustomOption(Mage_Payment_Model_Recurring_Profile::PRODUCT_OPTIONS_KEY,
            serialize(array('start_datetime' => $profile->getStartDatetime()))
        );

        // duplicate as 'additional_options' to render with the product statically
        $infoOptions = array(array(
            'label' => $profile->getFieldLabel('start_datetime'),
            'value' => $profile->exportStartDatetime(true),
        ));

        foreach ($profile->exportScheduleInfo() as $info) {
            $infoOptions[] = array(
                'label' => $info->getTitle(),
                'value' => $info->getSchedule(),
            );
        }
        $product->addCustomOption('additional_options', serialize($infoOptions));
    }

    /**
     * Sets current instructions for bank transfer account
     *
     * @param Varien_Event_Observer $observer
     * @return void
     */
    public function beforeOrderPaymentSave(Varien_Event_Observer $observer)
    {
        /** @var Mage_Sales_Model_Order_Payment $payment */
        $payment = $observer->getEvent()->getPayment();
        if ($payment->getMethod() === Mage_Payment_Model_Method_Banktransfer::PAYMENT_METHOD_BANKTRANSFER_CODE) {
            $payment->setAdditionalInformation('instructions',
                $payment->getMethodInstance()->getInstructions());
        }
    }

    /**
     * Will veto the unassignment of the order status if it is currently configured in any of the payment method
     * configurations.
     *
     * @param Varien_Event_Observer $observer
     * @throws Mage_Core_Exception
     */
    public function beforeSalesOrderStatusUnassign($observer)
    {
        $state = $observer->getEvent()->getState();
        if ($state == Mage_Sales_Model_Order::STATE_NEW) {
            $statusModel = $observer->getEvent()->getStatus();
            $status      = $statusModel->getStatus();
            $used        = 0;
            $titles      = array();
            foreach (Mage::app()->getWebsites(true) as $website) {
                $store = current($website->getStores()); // just need one store from each website
                if (!$store) {
                    continue; // no store is associated with the website
                }
                foreach (Mage::helper('payment')->getPaymentMethods($store) as $value) {
                    if (isset($value['order_status']) && $value['order_status'] == $status && $value['active']) {
                        ++$used;

                        // Remember the payment's information
                        $title       = $value['title'];
                        $websiteName = $website->getName();
                        if (array_key_exists($title, $titles)) {
                            $titles[$title][] = $websiteName;
                        } else {
                            $titles[$title]   = array($websiteName);
                        }
                    }
                }
            }
            if ($used > 0) {
                // build the error message, and throw it
                $methods = '';
                $spacer  = '';
                foreach ($titles as $key => $values) {
                    $methods = $methods . $spacer . $key . ' [' . join(', ', $values) . ']';
                    $spacer = ', ';
                }
                throw new Mage_Core_Exception(Mage::helper('sales')->__('Status "%s" cannot be unassigned. It is in used in %d payment method configuration(s): %s',
                    $statusModel->getLabel(), $used, $methods));
            }
        }
    }
}

A: Since Magento version 1.6.0.0 (juli 2011) you can enable "Persistent Shopping Cart"
under
System > Configuration > Customers > Persistent Shopping Cart

This should solve this problem.
Use these settings to make it work
Enable Persistence = Yes
Persistence Lifetime (seconds) = 31536000
Enable "Remember Me" = Yes
"Remember Me" Default Value = Yes
Clear Persistence on Log Out = No
Persist Shopping Cart = Yes


text:
Q: How to ask for only Date in Google Assistant actionSdk I am using DateTime intent to get DOB of user and my Google Assistant actionSdk code is as below
// Actions SDK
const app = actionssdk()

app.intent('actions.intent.MAIN', conv => {
  conv.ask(new DateTime({
    prompts: {
      initial: 'When do you want to come in?',
      date: 'What is your Birth Date?',
      time: 'What time of day works best for you?',
    }
  }))
})

app.intent('actions.intent.DATETIME', (conv, input, datetime) => {
  const { month, day } = datetime.date
  const { hours, minutes } = datetime.time
  conv.close(new SimpleResponse({
    speech: 'Great see you at your appointment!',
    text: `Great, we will see you on ${month}/${day} at ${hours} ${minutes || ''}`
  }))
})

Its working fine and able to get Date but its force to get time as well. but as my requirement i have ask only for Date. if i remove time or initial key them its giving error.


text:
Q: Getting the string from the server side and separating the code fragment from the string in Kotlin I made an Android application where the users ask questions, but they may use programming codes in their questions. How can I separate the programming codes from the normal texts in Kotlin? If you can explain, I want to change the background of the codes. Like this
enter image description here

A: just use something just like stackoverflow i.e. put code between "```" and you can easily parse it from string.
More info: to parse string you can use Regex
here's some sample code that detects "```" and changes inner text to red:
...
onCreate(){
textView.setText(formatString("alo ```alo```"));
}
...
SpannableStringBuilder formatString(String message) {
        Pattern p = Pattern.compile("(```)(.*?)(```)");// detects the pattern ```*``` in the string
        Matcher matcher = p.matcher(message);

        SpannableStringBuilder spannable = new SpannableStringBuilder(message);
        //for changing color of text
        while (matcher.find()) {
            ForegroundColorSpan span = new ForegroundColorSpan(Color.RED);
            spannable.setSpan(span, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

            spannable.replace(spannable.getSpanStart(span), spannable.getSpanStart(span) + 3, "");
            spannable.replace(spannable.getSpanEnd(span) - 3, spannable.getSpanEnd(span), ""); //to remove ``` from string

        }
        return spannable;
    }


text:
Q: Select multiple polygons or points from WFS or WMS GetFeatureInfo Is there a way to select multiple polygons and/or points from a WFS or WMS service and then get the feature information for each selected item? There are numerous examples on the OpenLayers website but none of them show how to multi-select AND get the attributes for the selected items.
For instance I can get the feature info for a single selected item by using the GetFeatureInfo option for a WMS service but this does not allow me to select multiple items. I absolutely have to have the ability to select multiple items!
Also, I can select multiple items by drawing a box, a freehand polygon, or multi-selecting individual features using a number of different methods but none of those methods have the ability to get the feature info. What good is being able to select multiple items but not be able to get the attributes for the features? Am I missing something really obvious?
My goal is to be able to select multiple features and then extract my unique identifier (point number or polygon number) from each of the features info in order to query data from a SQLServer database. I don't need to do anything fancy to the spatial data all I want to do is select multiple items and take the unique id from each of them so I can query my database for info that relates to the selected items.
I am using OpenLayers to build my map interface and GeoServer to serve my WMS/WFS services. I can connect to my point and polygon shapefiles using either WMS or WFS but I can not find a way to select multiple items and then get the attribute info for the items.
Is there a way in OpenLayers to select multiple items and then loop through the list of items?
I have been stuck on this problem for four very long and frustrating days and if anyone has any ideas on how to do this I would be eternally grateful!!
10/11/2012 - HERE IS THE CODE I ENDED UP USING
//THIS FUNCTION UPDATES THE TEXT BOX WITH THE LIST OF SELECTED ATTRIBUES WHEN THE USER SELECTS A NEW POLYGON OR MULTIPLE POLYGONS
var update = function(feature) {
     names.push(feature.attributes['yourLayersAttributeNameHere']);
    showStatus(names.join(", "));
};

//THIS FUNCTION UPDATES THE TEXT BOX WITH THE LIST OF SELECTED ATTRIBUTES WHEN THE USER UNSELECTS A POLYGON
var clear = function(feature) {
  name=feature.attributes['yourLayersAttributeNameHere'];
    for(var y in names){
       if (name === names[y]){
         names.splice(y,1);
        }
    }
    showStatus(names.join(", "));
};

//INSTANTIATE A NEW CONTROL THAT ALLOWS THE USER TO SELECT FROM THE AVAILABLE WFS FEATURE
// var control = new OpenLayers.Control.SelectFeature(
               nameOfyourLayerHere,
              /{
                clickout: true,
       toggle: true,
                multiple: true,
       hover: false, //if hover is set to true it takes away the selection functionality.
        toggleKey: "ctrlKey", // ctrl key removes from selection
               /multipleKey: "shiftKey", // shift key adds to selection
               /onSelect: update, //ON SELECT CALL THE UPDATE FUNCTION
                onUnselect: clear, //ON UNSELECT CALL THE CLEAR FUNCTION
     //
              // }
          // );

//ADD THE CONTROL TO THE MAP CONTROLS COLLECTION
// map.addControl(control);
//ACTIVATE THE NEW CONTROL
//control.activate();

A: The easiest way would be to use a WFS - try something like http://ian01.geog.psu.edu/geoserver/www/wfs/wfs-sld2.html and then instead of updating the div make a query.
Also you can create a WFS query that takes your box or polygon and carries out one query to return all the features that are contained or that intersect with the object. One way to get a feel for what's possible is to play with the GeoServer demos (use http://ian01.geog.psu.edu/geoserver/web/?wicket:bookmarkablePage=:org.geoserver.web.demo.DemoRequestsPage if you don't have a local install handy) - scroll down the request list to the WFS_GetFeatureXXXX ones.

A: Here is the code I ended up using. Thanks again to iant for providing his generous assistance!!
//INSTANTIATE A NEW CONTROL THAT ALLOWS THE USER TO SELECT FROM THE AVAILABLE WFS   FEATURE
var control = new OpenLayers.Control.SelectFeature(
                lyrstands, //THE NAME OF THE LAYER THAT IS BEING SELECTED FROM
               {
               clickout: true, //WHEN THEY CLICK OUTSIDE OF THE POLYGON LAYER ALL SELECTED ITEMS ARE DESELECTED
       toggle: true, //SELECTED ITEMS CAN BE DESELECTED AND VICE VERSA
               multiple: true, //USER CAN SELECTED MULTIPLE FEATURES
       hover: false, //IF HOVER IS SET TO TRUE IT TAKES AWAY THE SELECTION FUNCTIONALITY
      highlightOnly: false,
       toggleKey: "ctrlKey", // CTRL KEY REMOVES FROM SELECTION
               multipleKey: "shiftKey", // SHIFT KEY ADDS TO SELECTION
               onSelect: update, //ON SELECT CALL THE UPDATE FUNCTION
               onUnselect: clear, //ON UNSELECT CALL THE CLEAR FUNCTION

               }
          );

//ADD THE CONTROL TO THE MAP CONTROLS COLLECTION
map.addControl(control);
//ACTIVATE THE NEW CONTROL
control.activate();

//THIS FUNCTION UPDATES THE TEXT BOX WITH THE LIST OF SELECTED STANDS WHEN THE USER SELECTS A NEW STAND
var update = function(feature) {
     names.push(feature.attributes['yourAttributeName']); //THE SELECT FEATURE IN THIS FUNCTION IS HARD CODED TO A SPECIFIC ATTRIBUTE FROM THE LAYER
    showStatus(names.join(", "));
};

//THIS FUNCTION UPDATES THE TEXT BOX WITH THE LIST OF SELECTED FEATURE ATTRIBUTES WHEN THE USER UNSELECTS A FEATURE
var clear = function(feature) {
  name=feature.attributes['yourAttributeName']; //THE UNSELECT FEATURE IN THIS FUNCTIONS IS HARD CODED TO A SPECIFIC ATTRIBUTE FROM THE LAYER
    for(var y in names){
       if (name === names[y]){
         names.splice(y,1);
        }
    }
    showStatus(names.join(", "));
};

var names = [];
//CREATE THE SHOWSTATUS FUNCTION THAT IS CALLED BY UPDATE AND CLEAR FUNCTIONS
//THE NAME OF THE TEXTBOX THAT DISPLAYS THE SELECTED ITEMS IS 'responseText'.
//THIS FUNCTION CALLS FOR THE VALUE 'text' (WHICH IS A STRING) FROM THE UPDATE AND    CLEAR FUNCTIONS AND THEN POPULATES THE TEXT BOX WITH THE VALUES
function showStatus(text) {
    document.getElementById("responseText").innerHTML = text;
}


text:
Q: jQuery get text include single quote using text() doesn't show properly So I want to show div's text to input value if button clicked. But if the text includes single quote, It doesn't show properly.

It's Yours!

<button id="btn_comment_edit">Edit</button>

// jQuery
$('.btn_comment_edit').click(function(){
    $('#content_comment').replaceWith("<form method='post'><input type=text value='"+$('#content_comment').text()+"'></form>")
});

// result
// It'  (doesn't show after single quotes)

It should be It's Yours! in input value. How can I display whole statement with single quotes?

A: You can do something like this
 $('#content_comment').replaceWith("<form method='post'><input type=text value='\'' +$('#content_comment').text()+'\'></form>")

A: The problem is with the usages of single and double quotes. You are also using .btn_comment_edit instead of #btn_comment_edit. Try like following.

$('#btn_comment_edit').click(function () {
    $('#content_comment').replaceWith('<form method=post><input type=text value="' + $('#content_comment').text() + '"></form>');
});

It's Yours!

<button id="btn_comment_edit">Edit</button>

A: This is how you can do the encoding.
$('.btn_comment_edit').click(function(){
    var a = $('#content_comment').text();
    a = addslash(a);
    $('#content_comment').replaceWith("<form method='post'><input type=text value='"+a+"'></form>")
});

function addslash(iid){
    str=iid.replace(/"/g,'\"');
    str=iid.replace(/'/g,'\'');
    return str;
}


text:
Q: How to get Community Url in a Visualforce email template Background
I would like to display the Community Url within a visualforce email template.
Standard templates use:
{!Community_Url}

But I cannot find an equivalent field for visualforce email templates.
Here is a simplified version of the email template:
<messaging:emailTemplate subject="Forgot Password"
    recipientType="User" relatedToType="Community">
    <messaging:htmlemailbody >

                Dear {!recipient.Firstname },

            Your password has been reset for {!relatedTo.Name}.

            Go to: {!$Network.NetworkUrlForUserEmails}

    </messaging:htmlemailbody>
</messaging:emailTemplate>

Question

*

*What merge field can I use to create a link to the community?

A: I was working on a similar requirement some time back, where we had to send the reset password url for a community user.
If the Visualforce Email template you want to use, is defined under the Community Settings-->Adminstration, then using just {!$Network.NetworkUrlForUserEmails} should be good enough. If this doesn't helps you, then elaborate more on how exactly do you plan to use this template and what results do you see on using {!$Network.NetworkUrlForUserEmails}
<messaging:emailTemplate subject="forgotNew"
    recipientType="Contact"
    relatedToType="User"
    language="{!recipient.LanguageLocaleUser__c}"
    >
<messaging:htmlEmailBody >

     Hereeee

</messaging:htmlEmailBody>
</messaging:emailTemplate>


text:
Q: Read host process packet size I want to know the number of packets and the packet size for each packet sent by every process in the host computer.
I have tried using psutil the library:
         p=psutil.Process(pid)
         process_connection=p.connections()

But it shows the address and port but no information about the packet.
         psutil.net_io_counters()

This shows the bytes sent and received by the host.
How can I get this information using Python 2.7 and Windows 7?

A: Conceptually, you need to apply a packet sniffer for that. The process statistics do not collect (meta-)information about each and every packet sent by a process, that would be very inefficient with respect to both processing power and memory footprint.
Scapy is one of the popular packages providing packet sniffing from Python for unixes, but I don't know about its support for windows or other packages which support windows.


text:
Q: Fast calculation of dominators It is said that when converting intermediate code to static single assignment form,

*

*It is necessary to calculate the dominators of basic blocks

*The somewhat obvious way to do this as a fixed point of equations is slow

*To do it fast, you need to use the fairly complicated Lengauer-Tarjan algorithm
I can see the first two points, but I'm not clear about the reasoning behind the third. In particular, is there any reason why you can't do it just in the process of calculating the preorder dominator tree? I've implemented a version of that in JavaScript and it seems to work:
var domPreorder = [];

function doms(b) {
    b.children = [];
    for (var c of b[b.length - 1].targets)
        if (c.i == null) {
            c.i = domPreorder.length
            domPreorder.push(c)
            b.children.push(c)
            c.parent = b
            doms(c)
        }
}

f[0].i = 0
domPreorder.push(f[0])
doms(f[0])

Is there some disadvantage to this method that I'm not seeing?

A: While calculating dominators quickly and correctly is indeed not trivial, there are much simpler algorithms than Lengauer-Tarjan that are as fast or faster in practice (i.e. on the kinds of control flow graphs that occur in most programs), even though the worst-case complexity sounds scary. See: Cooper, Keith D.; Harvey, Timothy J; and Kennedy, Ken (2001). "A Simple, Fast Dominance Algorithm"

A: Ah, I see now, simple techniques don't correctly handle control flow graphs that have arbitrarily many forks and rejoins. You need to be able to find bypassing paths, and if you want the code for doing that to be fast, you need to calculate and remember semidominators, and then it looks like you end up with Lengauer-Tarjan or something along similar lines anyway.