text:
Q: How to prepare for magento certification? Currently i am working as Jr.Magneto developer since past 10 month and now i want decide to take exam of Magneto certified developer is it good idea to take exam ?Is there make difference during my next job interview? If yes then please provide some guidance about tutorial to learn and how much time require to preparation?please provide some guidance.
Thank you

A: First you need to go through Magento Video tutorials at least twice and then checkout below links
http://blog.belvg.com/tag/certification
http://blog.magestore.com/category/magento-certification
http://inchoo.net/ecommerce/magento/magento-mysql-database-structure/
http://www.ecomdev.org/blog
http://blog.magestore.com
http://ka.lpe.sh/2012/12/27/magento-certified-developer-exam/
http://quizlet.com/20443995/magento-certification-preparation-study-guide-answers-flash-cards/
http://ka.lpe.sh/2013/01/04/magento-certification-preparation-interview-questions-answers/

A: Even if this is really off topic,

*

*here, have my sword:
https://magento.stackexchange.com/questions/3374/magento-front-end-developer-certification

*and my bow: https://magento.stackexchange.com/questions/8268/are-there-any-document-or-ebook-for-magento-certification-exam

*and my axe Preparing for Magento Front End Certification

A: From the below image you can see all the certifications related to Magento or adobe commerce


text:
Q: Search for a valid ip address in a JSON file and grab it I want to look for an IP address in the file I receive. Can I just grab the IP address from the JSON just by removing everything else? What is the best method to grab this string?
Code:
if data['secret'] == "acoolsecret":
  print (data['ip'])
  for element in data['ip']:
        if element['ip'] == 'ip_addresss:':
            print 'there'
            break
    else:
        print 'IP NOT FOUND'
  return ("Secret Correct, continuing with program STATUS:200")

Sample JSON:
{"ip": "gateway: 1.1.0.0\\nip_address: 8.8.8.8\\nnetmask: 255.255.240.0\\ntype: public", "secret": "acoolsecret"}

Thanks in advance!

A: Perhaps I misunderstood your question, but if you do this
>>> d = {y[0].strip() : y[1].strip() for y in [x.split(':') for x in data['ip'].split('\\n')]}
>>> d.get('ip_address')
'8.8.8.8'

A: I ended up fixing it by modifying the code provided by @caverac. I'll paste the code here so that anyone can see the solution.
 datatmp=json.loads(request.data)
 datatmp=datatmp['ip']
 datatmp=datatmp.split('\n')
 datatmp=datatmp[1]
 ip=datatmp[12:]

Thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to hide/disable preprompt messages? When we boot a GNU/linux system it shows lots of messages on stdout. And then, immediately before the prompt it shows something like this:
Linux raspberrypi 4.19.66-v7+ #1253 SMP Thu Aug 15 11:49:46 BST 2019 armv7l

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.

I would like to hide that message. Which file do I need to edit to accomplish that?

A: The last two paragraphs are stored in /etc/motd; you just rename or delete it to get rid of them:
$ cd /etc
$ sudo mv motd motd.old

The first line is specified in /etc/update-motd.d/10-uname; you can also delete it, or move it to another directory (making it hidden doesn't work).

A: It's Motd (Message of the Day) service. In Ubuntu you can just disable it
systemctl stop motd-news.timer
systemctl disable motd-news.timer

I do not have a lot of experience with Debian, but I bet it's the same or very similar.


text:
Q: Find control of repeater nested in datalist on repeater item command In my code repeater is nested in datalistdatalist contains checkboxes and radiobutton
i want to do database operation on checkchanged of checkboxes,so i had written this operation on repeater itemcomand. Here I am not able to find control of repeater.so please guide me how to find control of repeater.
My design is like this:
<asp:DataList ID="DatalistQues" runat="server" DataKeyField="QuestionID" OnSelectedIndexChanged="DataListText_SelectedIndexChanged"
Width="100%" OnItemCommand="Repeater1_ItemCommand">
<ItemTemplate>

<asp:LinkButton ID="LinkButton6" runat="server" CommandName="Select" CssClass="ppppp">
<asp:Image ID="Image1" runat="server" ImageUrl='<% #Eval("Image")%>' Height="60px"
Width="65px" />
</asp:LinkButton>

<asp:LinkButton ID="LinkButton7" runat="server" CommandName="Select" CssClass="ppppp">
<asp:Label ID="Label3" runat="server" Text='<% #Eval("name")%>'></asp:Label>
</asp:LinkButton>

            <asp:Label ID="TextBox2" runat="server" Text='<% #Eval("Question")%>'></asp:Label>

            <asp:Repeater ID="RepeaterQues" runat="server" OnItemCommand="Repeater1_ItemCommand">
                <HeaderTemplate>
                </HeaderTemplate>
                <ItemTemplate>

                                <asp:LinkButton ID="LinkButton23" runat="server" CommandName="radiob">
                                    <asp:RadioButton ID="RadioButton1" runat="server" onclick="fnCheckUnCheck(this.id);" /></asp:LinkButton><asp:LinkButton
                                        ID="LinkButton24" runat="server" CommandName="checkb">
                                        <asp:CheckBox ID="CheckBox1" runat="server" Text='<%#Eval("QOption") %>' /></asp:LinkButton>

                                <asp:Label ID="empname" Text='<%#Eval("QOption") %>' runat="server"></asp:Label>

                </ItemTemplate>
            </asp:Repeater>

</ItemTemplate>
</asp:DataList>

A: On Item command of Repeater you will have to first find the naming container of sender
it will return you datalist item.
then in returned list item you will have to find the repeater of that particular data list itme
once you will find the repeater you can easily find the controls of the item of repeater

A: Try this
((Repeater)e.Item.Parent).ID // this gives the ID as specified on the aspx page

If you need Unique ID, you have to use this
((Repeater)e.Item.Parent).ClientID


text:
Q: Azure ML webservice different datasets for learning & predicting I have created an experiment in Azure ML and published it as a webservice.  My dataset used for the training includes the result column, eg input columns are:
Team A
Team B
Stat 1
Stat 2
Result
When I publish it as a webservice to run new data against the model I dont know the result, so my inputs to the webservice will be:
Team A
Team B
Stat 1
Stat 2
But the webservice is expecting the columns to be the same so including result column, but as I am predicting the future I dont have any input for the result column.
How do I get the webservice to work when I dont have the result column ? (basically I need to remove the result column from the web service I think)
Cheers


text:
Q: How to filter out the same log, only keep the 1st one until value changed? I would like to keep the row first added, if CODE is same as in the previous row (filter out newest added). The code may not show only one time. Therefore, it seems that I can not simply use Qualify rank() over(partition by ...order by ...) to get the result.
Here is the raw data:
id  START_DATE  CODE
--- ---------- -----
 1  2008-02-03   A
 1  2010-04-22   A
 1  2013-01-29   C
 1  2013-12-22   C
 1  2016-05-25   B
 1  2017-07-13   A

and the final result I look forward to:
id  START_DATE  CODE
--- ---------- -----
 1  2008-02-03   A
 1  2013-01-29   C
 1  2016-05-25   B
 1  2017-07-13   A

Are there any ways to get the result with SQL?

A: Depending on which server you are on, you can use LAG() window function to test if the previous row has the same code, and if it does then flag it and keep only the one with the first date.
You can read more about LAG() window functions here. I think the syntax will be fairly alike for most servers supporting it.
Consider below script to get you the desired result (SQL Server):
select
    id
    ,START_DATE
    ,CODE
from
(
select
    id
    ,START_DATE
    ,CODE
    ,CASE WHEN CODE = LAG(CODE) over (order by id, START_DATE asc) THEN 0 else 1 END as flag
from
    YOURTABLE as T
) as T
where
    flag = 1

A: I think you can use a query like this:
select
    id, [START_DATE], CODE
from (
    select *
      --, lag(CODE) over (order by id, [START_DATE]) as prevCODE
      --  ^^^^ for non-supported languages use below code instead vvvv
        , (select top(1) tt.CODE -- if `top(1)` not supported may you need to add `limit 1` afyer order by
           from t tt
           where tt.id = t.id and tt.[START_DATE] > t.[START_DATE]
            order by tt.[START_DATE]
          ) prevCODE
    from t
    ) t1
where
    CODE <> coalesce(prevCODE, '');

[SQL Server Fiddle Demo]
[MySQL Fiddle Demo]


text:
Q: automated actions through xml files I managed to make the system send a message as a notification when some expiration date is close
BUT
I created a server action and an automatic action both in the GUI
I'd like to use xml files to create such actions
Otherwise I have to remember to create them every time I create a new db
I found something but for Odoo 15, I'm on Odoo 14

A: The creation of server actions and automated actions from XML are same in Odoo 14.0 or 15.0 and you can check the Odoo 14.0 Documentation
Example for server action:
<record id="act_hr_employee_holiday_request" model="ir.actions.server">
    <field name="name">Time off Analysis</field>
    <field name="model_id" ref="hr_holidays.model_hr_leave_report"/>
    <field name="binding_model_id" ref="hr.model_hr_employee"/>
    <field name="state">code</field>
    <field name="groups_id" eval="[(4, ref('base.group_user'))]"/>
    <field name="code">
    action = model.action_time_off_analysis()
    </field>
</record>

Examples for automated action.


text:
Q: Problems to control fan speed and keyboard lights in Asus TUF FX706HC I installed Ubuntu 22.04 in my Asus TUF FX706HC and so far, so good, except I can't control the fan speed or change the colors of the lights of keyboard even though I can change their intensity. The BIOS doesn't give any option
I already tried: Rogauracore, OpenRGB and faustus without results.
https://github.com/wroberts/rogauracore
http://openrgb.org/
https://github.com/hackbnw/faustus
I also tried:
sudo echo 1 > /sys/devices/platform/asus-nb-wmi/fan-boost-mode

but I get:
bash: /sys/devices/platform/asus-nb-wmi/fan-boost-mode: Permiso denegado

This doesn't work either (see: How to control fans on an asus laptop)
switch on = $ sudo echo 0 > /sys/devices/platform/asus-nb-wmi/hwmon/hwmon4/pwm1_enable
switch off = $ sudo echo 2 > /sys/devices/platform/asus-nb wmi/hwmon/hwmon4/pwm1_enable

¿Ideas?
Thanks in advance


text:
Q: Using a projection with xlim/ylim in R with the "maps" package results in a bigger map I'm using R with the maps/mapproject/maptools packages to plot some maps and noticed a behavior which seems counter-intuitive to me and actually limits what I can do.
Drawing a map of Europe (with the limits taken from the ETRS89 / ETRS-LCC, so without Iceland and also clipped in the East) without specifying any projection:
library(maps)
map("world",xlim=c(-10.67,34.5),ylim=c(31.55,71.05), interior = T)

The result is as expected, the limits are being used and the resulting map follows them.
The projection used by default by maps is, as per the help:
The default is to use a rectangular projection with the aspect ratio
chosen so that longitude and latitude scales are equivalent at the
center of the picture.

This is not a good projection for my needs, I will use an LCC projection with the parallels as indicated in the above spatialreference.org link:
library(maps)
map("world",xlim=c(-10.67,34.5),ylim=c(31.55,71.05), interior = T, projection="lambert", parameters = c(45,65))
box()

The result is unexpected in that it includes a much bigger area (going very far north and including Russia), essentially making the map unusable.
What's stranger is that when using a grid the original limits are clearly considered:
library(maps)
library(mapproj)
map("world",xlim=c(-10.67,34.5),ylim=c(31.55,71.05), interior = T, projection="lambert", parameters = c(45,65))
map.grid(cex=0.1 , col="grey30")
box()

What I would like to have (and what I assumed would be the result of the above code) was a rectangular crop that included the limits I specified (adjusted due to the projection used so having more area than the rectangular one above would be expected). Additionally there is a white space around the map and the border which is present whenever one uses a projection with map().
The question is: is there a way to have this result when using map/mapproj/maptools? I tried to artificially change xlim/ylim without good results since it seems to work in big intervals (i.e. changing them doesn't produce an effect until suddenly half of Europe disappears with the next decrement).

A: The basic behaviour of "map()" is to extract all the lines within xlim and ylim, but also lines that are partially in the domain are extracted from the database. When there is no projection, xlim and ylim are also used as limitations for the plot, but when the data is projected that would obviously not work. (You can not simply project the xlim and ylim, as this would not be a rectangular domain). The maps code is not sophisticated enough to find a nice solution and just sets the plot limits to the range of the data (which includes any unwanted lines). As (recent) maintainer of 'maps', this is actually something I may try to fix. Unfortunately, mapproj doesn't include inverse projections, which are required to do it correctly like you would expect. Limiting the map at the bottom (in stead of extending at the top) is much easier.
As a workaround, you could also try the following (using the output value of map):
mymap <- map("world",xlim=c(-10.6600,31.5500), ylim=c(34.5000,71.0500),  projection="lambert", parameters=c(10.44,52.775), plot=FALSE)

Now you can look at the range of mymap$x and mymap$y:
range(mymap$x, na.rm=TRUE)

or just plot(mymap) to see the range and decide which interval you need.
Then, finally, you can plot a map with exactly the limits you want, for instance
plot(mymap, type="l", asp=1,xaxt="n",yaxt="n",xlab="",ylab="", xlim=c(-0.2,0.15), ylim=c(-0.75,-0.35))

Not ideal, but hopefully good enough. The "asp=1" is to keep the aspect ratio on the map correct, even if you resize the plot window.

A: The bounds given on spatialreference.org are given as "bottom left, top right coordinate", which coincidentally comes very close to what you wrote. Correctly these coordinates would be:
xlim=c(-10.6700,31.5500), ylim=c(34.5000,71.0500)

But that does not seem to be the problem here.
Playing around with the second xlim parameter it appears that map() tries to include neighbouring lines, as long as some of those line's coordinates are within the limits. The country of Russia fits in there (which causes a huge jump around 29-31 on the 2nd xlim parameter), along with some African and eastern European countries. Turning on and off boundary somewhat confirms this, but this hides a lot of country's borders.
A workaround I found was to explicitly exclude neighbouring countries from being drawn at first. Then draw the map a second time using add=T. Use col="white" on the first drawing to not draw in the same place twice, it thickens the lines.
library(maps)
library(mapproj)
map("world",regions="(?!Russia|Morocco|Algeria|Tunisia|Turkey|Ukraine)",col="white",xlim=c(-10.6600,31.5500), ylim=c(34.5000,71.0500), interior=T, projection="lambert", parameters=c(10.44,52.775))
map("world",xlim=c(-10.6600,31.5500), ylim=c(34.5000,71.0500), interior=T, projection="lambert", parameters=c(10.44,52.775),add=T)
map.grid(cex=0.1, col="grey30")
box()

There seem to be some lines missing still due to xlim and ylim, removing that will again include Iceland and other countries and islands. Or maybe there's a better approach altogether.


text:
Q: Grouping data based on a field in R I am using R to complete the following task. I have a dataset that looks something like this:
Item Category Price
aaa      1    10.00
bbb      2    5.00
ccc      3    20.00
ddd      1    25.00
eee      3    5.00
fff      2    15.00

Is possible to group items by their categories and calculate some summary statistics (ex. average or total sum of the price)?
So essentially, I'm trying to create something like this:
Cateogry AveragePrice
    1    17.50
    2    10.00
    3    12.50

Thanks for your help!

A: Assuming that's a data.table (which will give you best performance and syntax):
library(data.table)
DT <- data.table(myDF) # where myDF is the original data.frame

DT[, list(AveragePrice = mean(Price),
          SumOfPrices = sum(Price)),
     by = Category]

A: To flesh out to @Roman Lustrik's suggestion, thus staying in base R for simplicity:
df1 <- data.frame(
 Category=c(1,2,3,1,3,2),
 Price= c(10,5,20,25,5,15)
 )
aggregate(df1,by=list(df1[,"Category"]),FUN=mean)

gives:
  Group.1 Category Price
1       1        1  17.5
2       2        2  10.0
3       3        3  12.5

or
tapply(df1[,"Price"], df1[,"Category"], mean)

gives:
   1    2    3
17.5  10.0 12.5

(Note df1[,"Price"]==df1$Price so either style can be used).
Personally I prefer the output from aggregate() and it's a bit faster, although on small datasets this is rather academic:
require(microbenchmark)
microbenchmark( aggregate(df1,by=list(df1[,"Category"]),FUN=mean) )
microbenchmark( tapply(df1[,"Price"], df1[,"Category"], mean) )

gives (simplified for clarity):
     min       lq    median       uq      max
2.233209 2.268719  2.311002 2.362932 4.018134
771.361 792.0915   807.2805 829.2435 1201.581

Finally, if you want output exactly like the example in your question:
a1 <- aggregate(df1,by=list(df1[,"Category"]),FUN=mean )
a1 <- a1[,-1] # remove 1st column
a1[,2] <- format(a1[,2],nsmall=2) # give 2 decimal places
colnames(a1)[2] <- "AveragePrice" # assign name to 2nd column

gives:
  Category AveragePrice
1        1        17.50
2        2        10.00
3        3        12.50


text:
Q: Is entropy maximized for steadily driven systems? Suppose we send an electric current through a piece of metal. If we knew only the average energy and current through the sample, it would seem natural to assume the state of the sample is described by a probability distribution (or density matrix) with the most entropy for the given current and energy. The density matrix of the system, satisfying such maximum entropy condition, can be shown to be equal to
$$
\hat{\rho}=\frac{1}{Z}e^{-\beta \hat{H}-\alpha \hat{I}},\quad (1)
$$
where $\hat{H}$ is the Hamiltonian of the system, $\hat{I}$ is the current, $\alpha$ and $\beta$ are coefficients to fix the mean energy and current.
Now, even though it may appear natural (at least to me) to pick the probability distribution as containing the least amount of information (i.e. the most entropy) for the given macroscopic variables, I do not see any other physical reasons to make such choice. We know that a piece of metal cannot have a constant current without generating heat, so something needs to take the heat away, which would make the state of the system depend on the model of the thermostat. In other words, it appears to be impossible to have a model-less steady distribution of the type (1).
Still, the concept of maximum entropy in steadily excited state looks extremely appealing, and I wonder if distributions of the type (1) have any physical significance?


text:
Q: How to set the value of any property in an object using a variable? I have an object with different levels of depth.

stdClass Object
(
    [1] => stdClass Object
        (
            [color] => green
        )
    [9] => stdClass Object
        (
            [optgroup] => stdClass Object
                (
                    [4] => stdClass Object
                        (
                            [OPTION] =>
                        )
                    [5] => stdClass Object
                        (
                            [OPTION] => stdClass Object
                                (
                                    [2] => stdClass Object
                                        (
                                            [DataSubtext] => SUBTEXT of
                                        )
                                    [3] => stdClass Object
                                        (
                                            [DataIcon] => glyphicon-heart
                                        )
                                )
                        )
                )
        )
)

I want to edit this object's data in a html page and need to access specific properties after they are clicked. But I don't know the depth in advance, i.e. 'color' is level 2 but 'THEOPT' is level 6.
When I create a string with the path (e.g. $string = ' {9} -> optgroup -> {2} -> OPTION -> {2} ->  THEOPT  ') and add it after
$var = $myobject -> $string ;
I would have to use eval to get and set the property but that should be avoided.
I thought about case ... for each level, i.e.
switch ($depth) ...
case 1...
case 2...

So how can I address any property with a variable in the best possible way?
I came up with this solution. It is a recursive function that returns the three properties I need. The array is the properties as array, i.e. 9, optgroup,2, etc.
I wonder that php does not provide an easy interface to edit an object precisely.
    function getObjectValue ( $object, $array ){
  if ( $array[1] == ''  )  {
     $f = new stdClass;
     $f -> POS  =  $array[0];
     foreach( $object -> {$array[0]} as $key  => $value ) {
         $f -> name = $key;
         $f -> value = $value;
    }
  return $f ;}
 if (  is_object(  $object -> {$array[0]} )   ){
     $next = array_shift($array) ;
     $result = getObjectValue(  $object -> {$next} ,  $array );
     }
  return $result;
 }

A: I don't know if this is can solve your problem, Anyway
$array = json_decode(json_encode($your_std_class_object), true);

this will get your object in an array format, so by using the array you can simply iterate, and check whether this has some child and, find out the depth of the array,.


text:
Q: Boolean Algebra Simplification Help, Need AND's, OR's, NOT's only I'm having a very hard time simplifying this:
A!B!C+ABC+!A!BC+!AB!C
The objective here is to simplify the equation until it can be expressed in "AND"'s "OR"'s and "NOT"'s. I have to create an integrated circuit for the simplified expression using only those 3 gates in Logisim.
This is as far as I've gone:
A(!B!C+BC)+!A!BC+!AB!C
A+!A!BC+!AB!C
A+!BC+B!C
I'm not sure if this is right

A: If $!X$ means $1+X$ in the Boolean algebra then your expression simplifies to $A+B+C$.  Check this by replacing the $!$ operators as indicated and distributing the multiplications.  This expression can be written as
$$
(A \operatorname{AND} \operatorname{NOT} (B \operatorname{OR} C)) \operatorname{OR}\\
(B \operatorname{AND} \operatorname{NOT} (A \operatorname{OR} C)) \operatorname{OR}\\
(C \operatorname{AND} \operatorname{NOT} (A \operatorname{OR} B)) \operatorname{OR}\\
(A \operatorname{AND} B \operatorname{AND} C).
$$
Note that $X+Y$ can be written as $(X \operatorname{OR} Y) \operatorname{AND} \operatorname{NOT} (X \operatorname{AND} Y)$.


text:
Q: If any match found in the stream set data to innerobject of the first object in a list GroupNode Class:
@Data
public class GroupNode {
    private String groupName;
    private List<PolicyNode> policies;
    private String eventId;
}

PolicyNode Class:
@Data
public class PolicyNode {
    private String policyName;
    private String eventTime;
    private String eventId;
}

Here i want is if eventId of groupNode matches with the eventId of policyNode then i want to set the policyNode details in groupNode.
the code i've tried.
List<GroupNode> groupWithPolicy = groupWithoutPolicy.stream()
    .filter(gwp->groupPolicyNodeList.stream().anyMatch(gwop->gwop.getEventId().equals(gwp.getEventId())))
                .collect(Collectors.toList());

I know that i'm not setting any property here but I'm not getting any idea how to set those properties to a group node:/
this is the sample response i want:
"groups": [
            {
                "groupName": "My group",
                "policies": [
                    {
                        "policyName": "Inno-Test-Cust-Man-Policy",
                        "eventId": "67e3426e-fd42-483f-9d90-8f7d15646f6a",
                    },
                    {
                        "policyName": "Inno-Test-Cust-Man-Policy",
                        "eventId": "67e3426e-fd42-483f-9d90-8f7d15646f6a",
                    }
                ],
                "eventId": "2d72752d-8f28-4549-9c0c-986ac98873cf"
            }
        ]
    }

I removed lot of data from above output here the eventId's are not matching. so i've all groups list without policies attached to it. and all policies list. now based on eventId i want to add policies to the group.

A: You can do it for example so:
public static void main(String[] args) {
    List<GroupNode> groupWithPolicy = groupWithoutPolicy.stream()
            .map(s -> setPolicyNodeList(s, externalPolicyList))
            .collect(Collectors.toList());

}

private static GroupNode setPolicyNodeList(GroupNode groupNode, List<PolicyNode> policyNodeList) {
    groupNode.setPolicyNode (
            policyNodeList.stream()
            .filter(s-> s.getEventId.equals(groupNode.getEventId))
            .collect(Collectors.toList())
    );

    return groupNode;
}

it's easy to read and understanding.
Also, you can do grouping and escape from O(n*n):
    Map<String, List<PolicyNode>> collect = policyNodeList.stream()
            .collect(groupingBy(s -> s.getEventId));
    List<GroupNode> groupWithPolicy = groupWithoutPolicy.stream()
            .peek(s -> s.setPolicies(collect.get(s.getEventId())))
            .collect(Collectors.toList());

A: It seems that you need to update existing groups without policies, which can be done as follows:
List<PolicyNode> policies = buildPolicyList(); // aka groupNodePolicyList
List<GroupNode> groups = buildInitialGroupList(); // aka groupWithoutPolicy

groups.forEach(group ->
     group.setPolicies(
         policies.stream()
                 .filter(p -> group.getEventId().equals(p.getEventId()))
                 .collect(Collectors.toList())
));

Ater that, the groups with empty policy list can be filtered out:
List<GroupNode> groupsWithoutPolicy = groups
        .stream()
        .filter(g -> g.getPolicies().isEmpty())
        .collect(Collectors.toList());

Another approach could be to prepare a map of <String, List<PolicyNode>> from policies to reuse it as a cache when setting the policy list in group nodes:
Map<String, List<PolicyNode>> mapEventPolicy = policies
        .stream()
        .collect(Collectors.groupingBy(Policy::getEventId));

Then the list of groups with policies may be built by filtering and re-collecting without affecting initial list of groups:
List<GroupNode> groupsWithPolicy = groups
        .stream()
        .filter(group -> mapEventPolicy.containsKey(group.getEventId()))
        .map(group -> new GroupNode( // use/add appropriate all-args constructor
            group.getGroupName(),
            new ArrayList<>(mapEventPolicy.get(group.getEventId())),
            group.getEventId()
        ))
        .collect(Collectors.toList());

Note: a copy of policy list should be provided per group.


text:
Q: Applying GraduatedColorsRenderer based on classification field values in ArcPy import arcpy
import pandas as pd
data = arcpy.ListFields(r"C:\Users\Administrator\Documents\ArcGIS\Projects\Oakville\Oakville.gdb\Etobicoke")
path = r"C:\Users\Administrator\Documents\ArcGIS\Projects\Oakville\Oakville.gdb\Etobicoke"
p = arcpy.mp.ArcGISProject("CURRENT")
m = p.listMaps("Map2")[0]
lyr = m.listLayers('SampleTestingData')[0]
sym = lyr.symbology
flag = True

CSDNames = []
CSDName_minlst = []
CSDName_maxlst = []

# create a list of unique names
with arcpy.da.SearchCursor(path, ['EtobicokeDA2_CSDNAME']) as cursor:
    for row in cursor:
        if row[0] not in CSDNames:
            CSDNames.append(row[0])
# create a list of maximum values for each name
for i in CSDNames:
    maxList = []
    where = """{} = '{}'""".format("EtobicokeDA2_CSDNAME", i)
    with arcpy.da.SearchCursor(path, ["EtobicokeData_AVG_Home_Values"], where) as cur2:
        for row2 in cur2:
            if row2[0] not in maxList:
                maxList.append(row2[0])
    maxList.sort()
    CSDName_maxlst.append(int(maxList[-1]))
# create list of minimum values for each name
for i in CSDNames:
    minList = []
    where = """{} = '{}'""".format("EtobicokeDA2_CSDNAME", i)
    with arcpy.da.SearchCursor(path, ["EtobicokeData_AVG_Home_Values"], where) as cur2:
        for row2 in cur2:
            if row2[0] not in minList:
                minList.append(row2[0])
    minList.sort()
    minList = [i for i in minList if i != 0]
    CSDName_minlst.append(int(minList[0]))

CSD_ranges = []
# create ranges for each name
for items in range(len(CSDName_minlst)):
    CSD_bin = int((CSDName_maxlst[items]- CSDName_minlst[items])/8)
    bin_1 = CSDName_minlst[items] + CSD_bin
    bin_2 = CSDName_minlst[items] + CSD_bin*2
    bin_3 = CSDName_minlst[items] + CSD_bin*3
    bin_4 = CSDName_minlst[items] + CSD_bin*4
    bin_5 = CSDName_minlst[items] + CSD_bin*5
    bin_6 = CSDName_minlst[items] + CSD_bin*6
    bin_7 = CSDName_minlst[items] + CSD_bin*7
    bin_8 = CSDName_minlst[items] + CSD_bin*8
    CSD_ranges.append([bin_1, bin_2,bin_3, bin_4, bin_5, bin_6, bin_7, bin_8])

So I have basically created two lists: one which contains all the unique names and the other contains class break Values for each name.  I was wondering if there is a way to apply symbology based on what the field value is, using a conditional statement. My end goal is to basically use this symbology in the web app and once I filter it to the field value, it would only show me the symbology for that specific field value


text:
Q: How to pass tag id to to onClick function in react? I want to pass id of th tag  to on click function. Suppose i want to print the id of  in click() function console.log.
here is the code-

    Name
    Phone number
    Email

the click() function-
click(){
console.log('the clicked id is:') //here i want the id
}

A: Bind takes arguments
this.click.bind(this, 'phone')

click(phone) {
  // ...
}

or use es6 arrow functions
onClick={() => this.click('phone')}

A: You can do something like this:
const headers = [
  { id: 'name', label: 'Name' },
  { id: 'phone', label: 'Phone' },
  { id: 'Email', label: 'Name' },
]

const ab = (

      {headers.map(doc => (
         { this.click(doc.id) }}>{doc.label}
      ))}

)

A: This should work:

  Name
  Phone number
  Email

The onclick function
   foo=(e)=> {
     console.log(e.target.id);
   }


text:
Q: SSIS created in Visual Studio 2019 not working from an application created in Visual studio 2010 I have an application created in Visual Studio 2010 which use to run SSIS(created in 2008 BIDs) and many different process. We have upgraded to Visual studio 2019 and creating the SSIS in VS 2019. The new SSIS created in 2019 are not loading from application created in Visual Studio 2010.
-****- Error: - Ex Message:The package failed to load due to error 0xC0010014 "One or more error occurred. There should be more specific errors preceding this one that explains the details of the errors. This message is used as a return value from functions that encounter errors.". This occurs when CPackage::LoadFromXML fails.
I am getting this error message.
Thanks in Advance.


text:
Q: Is it possible to use route 53 to redirect http to https for the same link? I need to redirect my link from HTTP to HTTPS using route 53. I am running my app on heroku and using the domain from route 53.
Is there a way to redirect all HTTP links to HTTPS without meddling with the server-side code?
For example, using example.com, when going to http://example.com, I would want it to redirect to https://example.com. There is no need to redirect it to https://www.example.com.

A: Route53 isn't involved in serving the request, it's just involved in the DNS resolution, so no it's not possible.

A: Route 53 is a DNS service only for mapping domains to resolvable records, redirects are not part of the service provided here.
If you're interested in performing a HTTP to HTTPS redirect without having to apply any configurations or code changes within your application there a couple of services that can perform the redirect for you. However, as you're using Heroku an Application Load Balancer would not be applicable.
CloudFront is AWS managed CDN service, by adding this in front of your application you can enable HTTP to HTTPS redirect in the distribution configuration. You would then use an Alias record in Route 53 to resolve your domain to the CloudFront CNAME you're provided.
In addition for general context the below option can also be used when the host is in AWS, or the ALB can communicate to it via a private IP address.
For AWS based hosts (or IP based hosts) AWS can also perform redirects via a Application Load Balancer which supports any complex redirect rules, including the ability to redirect HTTP to HTTPS. Application hosts would be added to the ALB via a target group and would become private to avoid any direct communication.


text:
Q: How to mock axios with cookieJarSupport with jest Here is my code that works fine
const axios = require('axios')
const axiosCookieJarSupport = require('axios-cookiejar-support').default
const tough = require('tough-cookie')

axiosCookieJarSupport(axios)

async function getData() {
  let cookieJar = new tough.CookieJar()

  try {
    await axios.post({ jar: cookieJar, withCredentials: true, url: '/user' })
    const data = await axios.post({ jar: cookieJar, withCredentials: true, url: '/token' })

    return data
  } catch (error) {
    console.error(error)
    return error
  }
}

module.exports.getData = getData

And here is my Jest test:
const axios = require('axios');
const getData = require('../getData');

jest.mock("axios");

test('test axios and return data', async () => {
  axios.post.mockImplementation((options) => {
    switch (options.url) {
      case '/user':
        return Promise.resolve({ user: 'John' });
        break;
      case ORMB_URL:
        return Promise.resolve({ token: 'testtoken' });
        break;
      default:
        return Promise.reject(new Error('not found'))
    }
  });

  const data = await getData.getData();
  console.log(data);
})

Now, Jest fails in line:
axios.post.mockImplementation((options) => {

with error:
TypeError: axios.post.mockImplementation is not a function

It seems working if I comment this line in source:
axiosCookieJarSupport(axios)

But this is now what I need.. All other calls will fail with this line commented.. What am I doing wrong?

A: axios.post = jest.fn().mockImplementation((options) => {
    switch (options.url) {
      case '/user':
        return Promise.resolve({ user: 'John' });
        break;
      case ORMB_URL:
        return Promise.resolve({ token: 'testtoken' });
        break;
      default:
        return Promise.reject(new Error('not found'))
    }
  });

A: axiosCookieJarSupport(axios) mutates the argument axios by creating a new instance of axios after jest as mocked all the functions on the default export. This is essentially overwriting the jest mock functions. You could either mock the implementation of axios-cookiejar-support to return the instance passed, or you should create a new instance of axios and pass it to axiosCookieJar support to avoid side effects.


text:
Q: density shaded bars in ggplot2 Does anyone know of a way to produce a density shaded bar plot in ggplot2? Are there any packages that directly support this? I saw an example (extract below) as part of The Washington Post's coverage of the last US election. The bars of interest are the shaded ones on the right:

with a link to the full image here. The eventual application would to be help explain Bayesian and other output.


text:
Q: CMake 3.8.0 generates wrong link command in makefiles Problem:
After I run cmake to generate a project with a STATIC library, which completes successfully, both ninja and mingw32-make fail to make their targets at linking. For SHARED libraries or executables this same setup worked fine. I've tried this both for "Ninja" and "MinGW Makefiles" generators:
ninja output:
[2/2] Linking CXX static library hello_wsl.lib
FAILED: hello_wsl.lib
cmd.exe /C "cd . && "C:\Program Files\CMake\bin\cmake.exe" -E remove hello_wsl.lib && "" qc hello_wsl.lib  CMakeFiles/hello_wsl.dir/lib_hello_world.cpp.obj && cd ."
"""" no se reconoce como un comando interno o externo,
programa o archivo por lotes ejecutable.
ninja: build stopped: subcommand failed.

mingw32-make output:
Scanning dependencies of target hello_wsl
[ 50%] Building CXX object CMakeFiles/hello_wsl.dir/lib_hello_world.cpp.obj
[100%] Linking CXX static library hello_wsl.lib
Error running link command: El parámetro no es correcto
CMakeFiles\hello_wsl.dir\build.make:93: recipe for target 'hello_wsl.lib' failed
mingw32-make.exe[2]: *** [hello_wsl.lib] Error 2
CMakeFiles\Makefile2:66: recipe for target 'CMakeFiles/hello_wsl.dir/all' failed
mingw32-make.exe[1]: *** [CMakeFiles/hello_wsl.dir/all] Error 2
Makefile:82: recipe for target 'all' failed
mingw32-make.exe: *** [all] Error 2

Also take a look at "project_root\build\CMakeFiles\hello_wsl.dir\link.txt" generated by "MinGW Makefiles":
"" qc hello_wsl.lib  CMakeFiles/hello_wsl.dir/lib_hello_world.cpp.obj

Sample project, in steps, to reproduce the problem for "MinGW Makefiles":

*

*Install CMake 3.8.0

*Install MinGWx64 6.3 windows binaries (I've downloaded them from here)

*Create a root folder for this project, I'll call it project_root in this sample.

*Create these subfolders inside:

*

*project_root\build

*project_root\include

*project_root\include\lib_hello_world

*Create these files:

*

*project_root\include\lib_hello_world\lib_hello_world.cpp:
#include <iostream>

class HelloWorldClass{
    HelloWorldClass(){
        std::cout << "Hello, world!" << std::endl;
    }
};

*project_root\include\lib_hello_world\CMakeLists.txt:
cmake_minimum_required(VERSION 3.8.0)
project(lib_hello_world)

add_library(lib_hello_world STATIC lib_hello_world.cpp)

*project_root\toolchain.cmake:
# Target system (cross compile)
set(CMAKE_SYSTEM_NAME WindowsStore)
set(CMAKE_SYSTEM_VERSION 10.0)

# BIN utils
SET(CMAKE_AR      "$ENV{MINGW_W64_BIN_DIR}/ar.exe")
SET(CMAKE_OBJCOPY "$ENV{MINGW_W64_BIN_DIR}/objcopy.exe")
SET(CMAKE_OBJDUMP "$ENV{MINGW_W64_BIN_DIR}/objdump.exe")
SET(CMAKE_RANLIB  "$ENV{MINGW_W64_BIN_DIR}/ranlib.exe")
SET(CMAKE_NM      "$ENV{MINGW_W64_BIN_DIR}/nm.exe")
SET(CMAKE_STRIP   "$ENV{MINGW_W64_BIN_DIR}/strip.exe")

# C compiler
SET(CMAKE_C_COMPILER "$ENV{MINGW_W64_BIN_DIR}/gcc.exe")

# CXX compiler
SET(CMAKE_CXX_COMPILER "$ENV{MINGW_W64_BIN_DIR}/g++.exe")

# LINKER
SET(CMAKE_LINKER "$ENV{MINGW_W64_BIN_DIR}/ld.bfd.exe")

*project_root\configure.bat:
@ECHO OFF
SETLOCAL
@ECHO OFF
REM Change these variables to the corresponding paths on your own system
SET "CMAKE_EXECUTABLE=C:\Program Files\CMake\bin\cmake.exe"
SET "MINGW_W64_BIN_DIR=C:/Program Files/MinGWx64/bin"
CD "%~dp0\build"
CALL "%CMAKE_EXECUTABLE%" "-DCMAKE_EXPORT_COMPILE_COMMANDS=ON" "-DCMAKE_BUILD_TYPE=Debug" -G "MinGW Makefiles" "-DCMAKE_MAKE_PROGRAM='%MINGW_W64_BIN_DIR%/mingw32-make.exe'" "-DCMAKE_TOOLCHAIN_FILE='%~dp0/toolchain.cmake'" "%~dp0/include/lib_hello_world"
ENDLOCAL

*project_root\build.bat:
@ECHO OFF
SETLOCAL
@ECHO OFF
REM Change this variable to the corresponding path on your own system
SET "MINGW_W64_BIN_DIR=C:/Program Files/MinGWx64/bin"
CD "%~dp0\build"
CALL "%MINGW_W64_BIN_DIR%/mingw32-make.exe"
ENDLOCAL

*Finally, open CMD and run the commands:
project_root\configure.bat
project_root\build.bat

This is a sketchy fix/workaround that I found:

*

*Create this file:
project_root\fix.bat:
@ECHO OFF
SETLOCAL
@ECHO OFF

MOVE "%~dp0\build\CMakeCache.txt" ".\"
RMDIR "%~dp0\build" /S /Q
MKDIR "%~dp0\build"
MOVE "%~dp0\CMakeCache.txt" ".\build\"

ENDLOCAL

*After reproducing the error, open CMD and run:
project_root\fix.bat
project_root\configure.bat
project_root\build.bat

*ninja output after fix (successfully linked):
[2/2] Linking CXX static library hello_wsl.lib

*mingw32-make after fix (successfully linked):
Scanning dependencies of target hello_wsl
[ 50%] Building CXX object CMakeFiles/hello_wsl.dir/lib_hello_world.cpp.obj
[100%] Linking CXX static library hello_wsl.lib
[100%] Built target hello_wsl

A few things I did to try to figure this out:

*

*I made a backup of CMakeCache.txt (CMakeCache.txt.before_fix) before applying the fix and reruning configure and build. There was no diference between the CMakeCache.txt.before_fix and CMakeCache.txt files after reconfiguring and successfully building the project.

*I also made a backup of "rules.ninja" and then compared them with FC. This is the output of FC "project_root\rules.ninja.before_fix" "project_root\build\rules.ninja":
Comparando archivos .\rules.ninja.before_fix y .\BUILD\RULES.NINJA
***** .\rules.ninja.before_fix
rule CXX_STATIC_LIBRARY_LINKER__lib_hello_world
command = cmd.exe /C "$PRE_LINK && "C:\Program Files\CMake\bin\cmake.exe" -E remove $TARGET_FILE && "" qc $TARGET_FILE $LINK_
FLAGS $in && $POST_BUILD"
description = Linking CXX static library $TARGET_FILE
***** .\BUILD\RULES.NINJA
rule CXX_STATIC_LIBRARY_LINKER__lib_hello_world
command = cmd.exe /C "$PRE_LINK && "C:\Program Files\CMake\bin\cmake.exe" -E remove $TARGET_FILE && C:\PROGRA~1\MinGWx64\bin\
ar.exe qc $TARGET_FILE $LINK_FLAGS $in && C:\PROGRA~1\MinGWx64\bin\ranlib.exe $TARGET_FILE && $POST_BUILD"
description = Linking CXX static library $TARGET_FILE
*****

*And did the same for "MinGW Makefiles". This is the output of FC "project_root\link.txt.before_fix" "project_root\build\CMakeFiles\lib_hello_world.dir\link.txt":
Comparando archivos .\link.txt.before_fix y .\BUILD\CMAKEFILES\LIB_HELLO_WORLD.DIR\LINK.TXT
***** .\link.txt.before_fix
"" qc hello_wsl.lib  CMakeFiles/hello_wsl.dir/lib_hello_world.cpp.obj
***** .\BUILD\CMAKEFILES\LIB_HELLO_WORLD.DIR\LINK.TXT
C:\PROGRA~1\MinGWx64\bin\ar.exe qc lib_hello_world.lib  CMakeFiles/lib_hello_world.dir/lib_hello_world.cpp.obj
C:\PROGRA~1\MinGWx64\bin\ranlib.exe lib_hello_world.lib
*****

A: There is some specific about CMAKE_AR and CMAKE_RUNLIB variables: according to that bugreport they should be declared as CACHED:
SET(CMAKE_AR      "$ENV{MINGW_W64_BIN_DIR}/ar.exe" CACHE FILEPATH "Arhiver")
SET(CMAKE_RANLIB  "$ENV{MINGW_W64_BIN_DIR}/ranlib.exe" CACHE FILEPATH "Runlib")


text:
Q: gcc ODBC on Linux is not linking I am attempting to get up and running with some simple C odbc code (with a fairly simple utility in mind that I need for a larger application).  The problem is, I am so far unable to get my simple test case to compile and link into a binary that I can actually execute.
This code is from the easysoft website, and is about the simplest example they have available:
#include <stdio.h>
#include <sql.h>
#include <sqlext.h>

main() {
  SQLHENV env;
  char driver[256];
  char attr[256];
  SQLSMALLINT driver_ret;
  SQLSMALLINT attr_ret;
  SQLUSMALLINT direction;
  SQLRETURN ret;

  SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env);
  SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (void *) SQL_OV_ODBC3, 0);

  direction = SQL_FETCH_FIRST;
  while(SQL_SUCCEEDED(ret = SQLDrivers(env, direction,
                       driver, sizeof(driver), &driver_ret,
                       attr, sizeof(attr), &attr_ret))) {
    direction = SQL_FETCH_NEXT;
    printf("%s - %s\n", driver, attr);
    if (ret == SQL_SUCCESS_WITH_INFO) printf("\tdata truncation\n");
  }
}

My compile statement is: gcc -lodbc listdrivers.c -o listdrivers
Output from gcc:
/tmp/cchgAMyC.o: In function `main':
listdrivers.c:(.text+0x2f): undefined reference to `SQLAllocHandle'
listdrivers.c:(.text+0x4d): undefined reference to `SQLSetEnvAttr'
listdrivers.c:(.text+0xd8): undefined reference to `SQLDrivers'
collect2: error: ld returned 1 exit status

I thought maybe it wasn't actually finding the library, so I specified the path on the command line:
gcc -lodbc -L/usr/lib/x86_64-linux-gnu listdrivers.c -o listdrivers
Still no luck.  I also verified that the driver is installed and configured for use.
ldconfig -p | grep odbc
libodbcinstQ4.so.1 (libc6,x86-64) => /usr/lib/x86_64-linux-gnu/libodbcinstQ4.so.1
libodbcinst.so.2 (libc6,x86-64) => /usr/lib/x86_64-linux-gnu/libodbcinst.so.2
libodbcinst.so (libc6,x86-64) => /usr/lib/x86_64-linux-gnu/libodbcinst.so
libodbccr.so.2 (libc6,x86-64) => /usr/lib/x86_64-linux-gnu/libodbccr.so.2
libodbccr.so (libc6,x86-64) => /usr/lib/x86_64-linux-gnu/libodbccr.so
libodbc.so.2 (libc6,x86-64) => /usr/lib/x86_64-linux-gnu/libodbc.so.2
libodbc.so (libc6,x86-64) => /usr/lib/x86_64-linux-gnu/libodbc.so
libiodbcinst.so.2 (libc6,x86-64) => /usr/lib/x86_64-linux-gnu/libiodbcinst.so.2
libiodbcadm.so.2 (libc6,x86-64) => /usr/lib/x86_64-linux-gnu/libiodbcadm.so.2
libiodbc.so.2 (libc6,x86-64) => /usr/lib/x86_64-linux-gnu/libiodbc.so.2

Then I thought maybe the library itself is corrupt, but that also looks fine:
readelf -Ws /usr/lib/x86_64-linux-gnu/libodbc.so | grep Alloc
   113: 0000000000007870    21 FUNC    GLOBAL DEFAULT   11 SQLAllocStmt
   148: 0000000000007820    67 FUNC    GLOBAL DEFAULT   11 SQLAllocHandleStd
   164: 0000000000007810    10 FUNC    GLOBAL DEFAULT   11 SQLAllocHandle
   196: 0000000000006720    21 FUNC    GLOBAL DEFAULT   11 SQLAllocConnect
   213: 0000000000006740    20 FUNC    GLOBAL DEFAULT   11 SQLAllocEnv

The function is clearly listed in the library, and I see no reason why that library would not be getting included, but at this point, I am stuck...
I have also tried removing and reinstalling the unixodbc and unixodbc-dev packages to no avail.  Any help would be greatly appreciated as this is now driving me crazy.

A: So it turns out that on Ubuntu, the -lodbc needs to come after the c file.  So the following appears to work fine:
gcc listdrivers.c -o listdrivers -lodbc
I didn't realize the order would make any difference in this case, and on Fedora the order doesn't matter (possibly a different version of gcc, but I didn't check specifically)


text:
Q: Prisma: Finding users in the same chat room model Chatroom {
  room_id     Int           @id @default(autoincrement())
  Participant Participant[]
  Message     Message[]
}

model Participant {
  participant_id Int @id @default(autoincrement())

  roomId          Chatroom @relation(fields: [chatroomRoom_id], references: [room_id])
  chatroomRoom_id Int

  user_id User @relation(fields: [userId], references: [id])
  userId  Int
}

Is there a way to find if two target participants have a chatroom together in the Prisma client?
I've tried querying both users rooms and filtering it where I can find the room the two users are in exist but I want to know if there's a way to do this in prisma findFirst.


text:
Q: JavaScript sometimes behave differently This code is an answer for a question. So I would like to know why JS behave differently in some situations
The below code is functioned to remove the last one digit when clicking the delete button.
for example if i type 777887328758 or some long number with repeated digits and click on delete button fast and repeatedly , it remove first digit or intermediate digit or sometimes last digit. Why this happens?

function del(){
  var num=document.getElementById('num').value;
  num=num.replace(num[num.length-1],'');
  document.getElementById('num').value=num;
}
function isValid(a){
  if(!(/^[0-9]+$/.test(a.value))){
    a.focus();
    console.clear();
    console.log("Please enter number");
  }
}
<input type="tel" onblur="isValid(this);" id="num" /><button onclick="del();">Del</button>

A: Because it's got a bug. See this line in del():
num=num.replace(num[num.length-1],'');

What does it do? It takes the last character of num, and replaces, that's the bug, the first occurrence of that character.
Fixed version:
num = num.substr(0, num.length - 1);

A: use this to remove numbers

function del() {
    var num = document.getElementById('num').value;
    num = num.slice(0, num.length-1);
    document.getElementById('num').value = num;
}


text:
Q: Unbounded sequence and its reciprocal. Let $a_n$ and $b_n$ be 2 positive and increasing sequence. Then is it true that either the sequence  $a_n/b_n $ or sequence $ b_n/a_n $ is bounded ?
At first i thought, if $a_n/b_n $ is unbounded, then $b_n/a_n $ is bounded and vice versa. This is very intuitive to me since it's like saying: if $a_n$ grows faster than $b_n$ then $b_n $ grows slower then $ a_n$, then $b_n/a_n$ should be bounded given that they are all positive.
But then, i think the above is wrong, $a_n/b_n$ is unbounded then the limit law $lim \frac {a_n} {b_n}\times lim \frac{b_n}{a_n} $ doesn't apply and $b_n/a_n$ can also be unbounded.
Can someone give me an example that both $a_n/b_n$ and $b_n/a_n$ are unbounded and explain why they can both grow unbounded ?

A: Let $$a_n=\begin{cases}
(2n)^{2n},&\text{if }n\text{ is even}\\
(2n+1)^{2n+1},&\text{if }n\text{ is odd}\;,
\end{cases}$$
and let $$b_n=\begin{cases}
(2n+1)^{2n+1},&\text{if }n\text{ is even}\\
(2n)^{2n},&\text{if }n\text{ is odd}\;.
\end{cases}$$
It's easy to check that both sequences are increasing, and since
$$\frac{(2n+1)^{2n+1}}{(2n)^{2n}}=(2n+1)\left(1+\frac1{2n}\right)^{2n}>2n+1\;,$$
$\dfrac{a_n}{b_n}>2n+1$ when $n$ is even, and $\dfrac{b_n}{a_n}>2n+1$ when $n$ is odd, so both ratio sequences are unbounded.

A: The answer is yes, the example can be constructed as follows:
Take $c_{2n-1}=n$, $c_{2n}=1/n$, and let $a_n=(n!)^2\cdot c_n$, $b_n=(n!)^2$, then we have $a_{2n-1}/b_{2n-1}=n$, and $a_{2n}/b_{2n}=1/n$. Thus both $a_n/b_n$ and $b_n/a_n$ diverge.
We may check that $a_{2n+1}/a_{2n}= (2n+1)^2\cdot n(n+1)>1$, $a_{2n}/a_{2n-1}=(2n)^2/n^2=4>1$, so $a_n$ is increasing, and $b_n=(n!)^2$ is also increasing.

A: Hmm how about this: $a_{4k} = b_{4k} = (2k)!$, $a_{4k+1} = a_{4k}+1, a_{4k+2} = a_{4k+1}k, a_{4k+3}=a_{4k+2}k$, $b_{4k+1} = b_{4k}k, b_{4k+2} = b_{4k+1} + 1, b_{4k+3}=b_{4k+2}+1$. Here $a_n/b_n$ goes to 1 for the subsequences with n = 4k and n = 4k+2, but it is unbounded for the subsequence with n = 4k+3, while its inverse is unbounded for the sbsequence with n = 4k+1.


text:
Q: AWK- string expression I have an example of a regular expression:
seq 20 | awk 'NR!~/^2$|^12$|^15$/'

The same, but with the chain expression:
seq 20 | awk 'NR != "2" && NR != "12" && NR != "15"'

Is it possible to write shorter string expression?
seq 20 | awk 'NR != "2" | "12" | "15" '

Thank you for the explanation.

A: Not to my knowledge. And like you have hinted at, you will need to use a regular expression if you would like to perform equality testing (or inequality testing, in this case) in this way.
If you have multiple values to ignore, consider using an array in the BEGIN block. This will make the expression shorter (i.e. the expression is now simply: !(NR in array)) when awk iterates through each line:
seq 20 | awk 'BEGIN { array[2]++; array[12]++; array[15]++ } !(NR in array)'

Results:
1
3
4
5
6
7
8
9
10
11
13
14
16
17
18
19
20

If you there is some sort of pattern to the lines your trying to ignore, consider using a for loop in the BEGIN block:
seq 20 | awk 'BEGIN { for (i=1; i<=15; i++) array[i]++ } !(NR in array)'

16
17
18
19
20

A: The first one is probably the shortest, it would be shorter if you left the anchors outside a group ():
seq 20 | awk 'NR !~ /^(2|12|15)$/'


text:
Q: Working with multiple related django modelforms I'm trying to get two forms derived from related models to display on the same page and save together.
This is my models.py:
class userinfo(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, primary_key= True,
on_delete=models.CASCADE)
    name = models.CharField(max_length = 200, blank = True)
    email = models.EmailField(max_length= 300, default = 'Null')
    phone = models.CharField(max_length= 10, default = 'Null')

    def __unicode__(self):
        return self.user

class seller_event(models.Model):
    event_id = models.AutoField(primary_key=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE)
    title = models.CharField(max_length = 300, default = 'Null')
    description = models.CharField(max_length = 300, default = 'Null')
    location = models.CharField(max_length= 300, default = 'Null')
    cash_payment = models.BooleanField(default=False)
    paytm_payment = models.BooleanField(default=False)

    def __unicode__(self):
        return str(self.event_id) + str(self.title)

As you can see, the user (saved as user_id in my sqlite3 db) is the foreign key from the userinfo table. I'm trying to get multiple events listed for each seller.
forms.py:
class Userinfo(forms.ModelForm):

    class Meta:
        model = userinfo
        exclude = {'user'}

class Seller_event(forms.ModelForm):

    class Meta:
        model = seller_event
        exclude = {'user'}

views.py:
def newlist(request):
    if request.user.is_authenticated():
        user = request.user
        print user
        if request.method == 'POST':
            userinfo_form = Userinfo(request.POST, instance = user.userinfo)
            seller_event_form = Seller_event(request.POST, instance =
user.seller_event)
            if userinfo_form.is_valid() and seller_event_form.is_valid():
                userinfo_form.save()
                seller_event_form.save()
                return redirect('/home')
        else:
            userinfo_form = Userinfo()
            seller_event_form = Seller_event()

        return render(request, 'home/newlist.html', {'userinfo_form':
userinfo_form, 'seller_event_form': seller_event_form })

html:
{% load static %}

<form action="/home/newlist/" method="post">

{% csrf_token %}
{{ userinfo_form.as_p }}
{{ seller_event_form.as_p }}

<input type="submit">

</form>

I suspect the problem is that while for userinfo, the user pk is a onetoone, there is no issue with identifying the model. However, this is not the case for seller_event. Here it is a fk. So, how do I get it to accept the user as an fk?
Thanks in advance!

A: After form validation, save your form without committing, then set your foreign key and save.
if userinfo_form.is_valid() and seller_event_form.is_valid():
    userinfo_form.save()

    new_seller_event = seller_event_form.save(commit=False)
    new_seller_event.user = user
    new_seller_event.save()

    return redirect('/home')


text:
Q: how do we handle white spaces in Website name My requirement is to add a web application to Default website and enable the directory browsing for the same.
I am using following command line to create the application.
 C:\Windows\System32\inetsrv> .\appcmd.exe add app /site.name:"mytest" /Path=/test4 /PhysicalPath:"c:\test

This is working fine.But if i try to put website name as following:
C:\Windows\System32\inetsrv> .\appcmd.exe add app /site.name:"Default Web Site" /Path=/test4 /PhysicalPath:"c:\test

It gives errors.Please help :)

A: As this question has been tagged with Powershell, here's a powershell solution using the WebAdministration module:
Import-Module webadministration

# Create the Web Application
New-WebApplication -Name testApp -Site 'Default Web Site' -PhysicalPath c:\test -ApplicationPool DefaultAppPool

# Set directory browsing enabled
Set-WebConfigurationProperty -filter /system.webServer/directoryBrowse -name enabled -PSPath 'IIS:\Sites\Default Web Site' -Value $true


text:
Q: How can I print the Jsonarray in json-Glib? I am using json-glib library. I have created one json array using that. I want to print that json array to see how it looks like. I mean that square brackets, commas and all, how they are included in json array. I have searched whole API but no function I have. I am using C++. Please help.

A: You need json_generator_new and json_generator_to_data.
void print_array (JsonArray *a)
{
    /* Setup root node and JSON generator */
    JsonNode *n = json_node_alloc();
    json_node_init_array(n, a);
    JsonGenerator *g = json_generator_new();
    json_generator_set_root(g, n);
    char *d = json_generator_to_data(g);

    /* Print JSON string */
    g_print("%s\n", d);

    /* Cleanup */
    g_free(d);
    g_unref(g);
    json_node_free(n);
}


text:
Q: Can I use the noun "tenure" to refer to the length of time someone has worked for a company? I am in the situation where I would like to be able to concisely refer to the length of time an employee has been with the company. Can I use the word tenure in this case?
For example:

The median tenure at this company is less than two years.

The dictionary definitions I've read of the word tenure are a bit too vague to tell me whether it can be used this way.
If it cannot, is there another term that would serve well in the given example?


text:
Q: Characterization of functors whose right adjoint is monadic? Let $F: \mathcal A^\to_\leftarrow \mathcal B: U$ be an adjunction, and suppose we want to know whether the comparision functor $\mathcal B \to Alg^{UF}$ is an equivalence, where $Alg^{UF}$ is the category of algebras for the monad $UF$. The Beck monadicity theorem gives a necessary and sufficient condition for this to be the case, which can be verified by looking just at $U$. That is, all we need to know about $F$ in order to apply Beck's theorem is that $F$ exists; the condition "$U$ creates coequalizers of $U$-split pairs" refers only to $U$ and not to $F$. I wonder if there is dually some necessary and sufficient criterion for monadicity which can be checked by looking at $F$ only (so that all we need to know about $U$ is that it exists)?
Question: Given a functor $F$ which is known to have a right adjoint $U$, is there some way to check whether $U$ is monadic by looking just at $F$ (and $\mathcal A, \mathcal B$), so that all we need to know about $U$ is that it exists?
For my purposes, I'm not at all averse to making strong assumptions about $\mathcal A, \mathcal B$, like (co)completeness assumptions, exactess assumptions, etc. Just so long as I don't have to explicitly consider $U$.
To put a finer point on it, if the hypotheses of the adjoint functor theorem hold, then Beck's theorem can be used to show that $U$ is monadic without referring to $F$ at all -- $F$ can be verified to exist by verifying that $U$ preserves limits and satisfies the solution set condition, and then the other condition for the monadicity theorem likewise refers only to $U$. So dually, I'm looking for a criterion which would give monadicity of the right adjoint of $F$ which, in the presence of the adjoint functor theorem, might never require me to explicitly refer to that right adjoint at all.

A: Let $F: C \to D$ be a left adjoint functor. I hope I'm not saying anything stupid, but I think you can just rephrase the two conditions of Beck Monadicity theorem in terms of the left adjoint:
The condition that $U$ is conservative translate as:

*

*The $Hom(F(x),\_)$ are jointly conservatives.

It can also be replaced by the apparently stronger condition but more familiar:

*

*The essential image of $F$ is dense,

As this condition is known to holds for monadic functors and implies the previous one.
The other condition is a bit harder. But I think we can manage if we assume that the domain of $F$ is Cauchy complete using the following lemma.
Lemma: Let $C$ be a Cauchy complete category. Then a pair $X \rightrightarrows Y$ admit a split coequalizer if and and only if $Hom(A,X) \rightrightarrows Hom(A,Y)$ admits a split coequalizer for each object $A \in C$ functorially in $A$.
I suspect one can remove the "functorially in $A$", but that was anoying to check, if someone has the motivation to do it, let me know !
In any case, the functoriality makes the proof very simple: this provides a split hence absolute coequalizer in the category of presheaves on $C$, but as $C$ is Cauchy complete any absolute colimits of representables is representable, hence the split coequalizer is already in $C$.
So assuming $C$ is Cauchy complete the second condition can be rephrased as:

*

*Every pair $X \rightrightarrows Y$ in $D$ such that $Hom(F(A),X) \rightrightarrows Hom(F(A),Y)$ admit (functorially in $A$) a split coequalizer for each $A \in C$, admits a coequalizer in $D$ that is preserved by $Hom(F(A),\_)$ for each $A \in C$.

Of course if you can remove the functoriality in the lemma, then you can remove it here as well.


text:
Q: Change Facebook Customer Chat Plugin Icon to a Custom One Any ideas on how to change Facebook Customer Chat Plugin icon to a custom one?
The whole Facebook customer chat is loaded over iframe, so it seems there is not much to do there, I've tried placing my own icon on top of it and use "pointer-events: none;" so the original Facebook icon would be clicked, but the problem is that my icon has transparent parts and you can see the original icon underneath.
Has anyone tried this and has any ideas on what could work?


text:
Q: Determine the largest size n of a problem that can be solved in time t , assuming that the algorithm to solve the problem takes f(n) microseconds. For each function f(n) and time t in the
following table, determine the largest size n of a problem that can be solved in time t ,
assuming that the algorithm to solve the problem takes f(n) microseconds.

A: I will do the first two as an example to help you do the rest. Since a second is $10^6$ microseconds. By solving an equation which relates $f(n)$ to the time we are plotting for $f(n)$ to run we can solve for the largest input $n$ that $f$ can run on within the time limit.
$1$ second:
$log(n^2) = 1,000,000 \implies n^2 = e^{1,000,000} \implies n = e^{500,000}$
$1$ minute:
$log(n^2) = 60,000,000 \implies n^2 = e^{60,000,000} \implies n = e^{30,000,000}$
the rest can be similarly done.
P.S. make sure to floor the values of n you get from these equations because n is an integer length input.


text:
Q: Question for GCC equation.com for building the using static I like windows gcc equation.com because it like ran natively just like windows compiler. However :

*

*I will need some dll's that not included on distributed package. if i compiled a windows equation.com gfortran program like using Openblas, it will need libgcc_s_seh-1.dll libgfortran-5.dll  libquadmath-0.dll libwinpthread-1.dll.
I could find it on web. But how to make it statically linked, i saw libgcc.a libgfortran.a libquadmath.a libpthread.a so i dont have to copy the dll from other. It is possible ?

*For several c source code it need include <sys/resource.h> that not included. It's compatible with resource.h from where. After just copied from others, and recompile.
I got error :
c:\gcc\x86_64-w64-mingw32\include\sys\resource.h:74:29: error: unknown type name 'id_t'; did you mean 'pid_t'?

*Is there any forum for this type gcc? Is there any debugger for windows gcc that friendly like VisualStudio Community for Intel Fortran.
Regards.


text:
Q: PHP Search bar causing page load error I had a page loading data from my mysql database working and showing the data correctly, but after attempting to implement a search function there is now an error attempting to load the page.
Below is my html code I added for the search bar (this is in the file PhysicianSearch.php):
<form action="PhysicianSearch.php" method="post">
  <input type="text" placeholder="Search.." name="ValueToSearch">
  <input type="submit" name="search" value="Filter">

</form>

below is the php code I added for the search bar (this is in the file PhysicianSearch.php):
<?php
  if(isset($_POST['search'])) {
      $valueToSearch = $_POST['valueToSearch'];
      $query = "SELECT * FROM Physician WHERE CONCAT('physicianID', 'firstName', 'lastName', 'yearNum', 'yearNum', 'position', 'isAttending', 'highRiskTrained') LIKE '%" . $valueToSearch ."%'";
      $search_result = filterTable($query);

  } else {
    $query = "select * from Physician";
    $search_result = filterTable($query);

  }

  function filterTable($query) {
    $connect = mysqli_connect("localhost", "root", "password", "dbName");
    $filter_results = mysqli_query($connect, $query);
    return $filter_results

  }
?>

A: Your input name is ValueToSearch where the PHP code is checking for valueToSearch
Make sure they have the same case


text:
Q: Dagger 2.10 - ContributesAndroidInjector annotation I've just implemented dagger.android as per documentation. First incorrect thing written there is existence of HasActivityInjector that was easily replaced with HasDispatchingActivityInjector.
Another thing mentioned there is usage of @ContributesAndroidInjector annotation that should simplify source creation a bit... But I cannot find such annotation neither via Android studio autocomplete nor in their JavaDoc and link in the documentation redirects me to 404 site. How can i use the annotation? Or can I?
Edit: I'm using
compile "com.google.dagger:dagger:$rootProject.daggerVersion"
compile "com.google.dagger:dagger-android:$rootProject.daggerVersion"
annotationProcessor "com.google.dagger:dagger-compiler:$rootProject.daggerVersion"
annotationProcessor "com.google.dagger:dagger-android-processor:$rootProject.daggerVersion"

where daggerVersion = '2.10'

A: @ContributesAndroidInjector is in HEAD, added ten days ago. It is not yet in a numbered release in Maven, but I'd imagine it will be shortly. Until then, you can download or clone the repository directly from Github (click the green button).
Edit: @ContributesAndroidInjector was released in Maven under version 2.11-rc1. Also HasDispatchingActivityInjector interface is now called HasActivityInjector as per documentation


text:
Q: Best way to store images in sql server on a network server I'm developing an application that needs to store large images
and about 100 image a day
about 3 people work on the same application DB (desktop application connected to same db)
any one of theme can view , edit, delete other work
which means all of theme can access certain image at once
now the question is what is the best way to store images this big
(currently I'm storing the images in a table but i know this eventually will suck)
I'm using sql server 2008

A: You could use the new in v2008 FILESTREAM data type to store your images. This is a hybrid approach that means the data can be queried from SQL, but the data itself is stored  in the filesystem rather than in the database.


text:
Q: A subspace contains the zero vector; intersection of subspaces is a subspace I have a simple question I have to answer but I am not sure where to start with this due to my lack of experience regarding subspaces. Can anybody help me?

*

*Assume $V \subset \Bbb R^n$ is a linear subspace. Show that $0 ∈ V$.

*Assume that $V, W \subset \Bbb R^n$ are linear subspaces. Show that $V \cap W$ is a linear subspace of $\Bbb R^n$ as well.

A: I'll help you with the first one. First, we suppose that the only element of $V$ is a zero vector. Everything is ok, we can check the axioms of vector space, $V$ is indeed a vector space. Then, suppose we have $x\in V$, $x\ne 0$, $V$ - vector space. By axioms of vector space, we can can multiply $x$ by any scalar number and the result will still be in $V$; let's say that we chose $-1$; therefore, $-x\in V$. On the other hand, if two vectors are in a vector space, then their sum is in this vector space, too (it's also an axiom of vector space). We take the sum: $x+ (-x) = 0$. We conclude that $0\in V$.
Another way to conclude the same thing is to chose a scalar equal to zero.

A: You need to use the definition/criteria of what it means to be a linear subspace, and the definition of the intersection of two sets (here, the intersection of two subspaces).
For the first: One of the criteria of a subspace is that it contains the zero vector. So by definition, if we assume $V$ is a subspace of $\mathbb R^n$, then it must follow that $0 \in V$.
For the second, again, use the definition of linear subspace. We assume $V, W \subset R^n$ are linear subspaces. By definition, $0 \in V$ and $0 \in W$. So what can you conclude about $0 \in V \cap W$?   Similarly, show that $V \cap W$ satisfies the criteria of a subspace of $R^n$. Informally, the intersection of two subspaces keeps all and only those vectors that are in both of the subspaces. So if two vectors are in $V\cap W$, then those vectors are in each subspace $V$ and $W$, thus their sum is in each subspace, so their sum is in the intersection, $V\cap W$.


text:
Q: Any way to determine if adjustsFontSizeToFitWidth has triggered? Is there anyway to determine if adjustsFontSizeToFitWidth has been triggered?  My app has a UILabel that takes up the entire view.  By using the UIPinchGestureRecognizer you can pinch in and out to change the font size.  Works great.  However, when the font reaches the max size for the UILabel, it displays bizarre behaviour.  The text in the UILabel moves down the UILabel.  Without adding bannerLabel.adjustsFontSizeToFitWidth = true the text gets clipped.  I would like to know when the font is at the maximum size for the UILabel, and i will stop trying to increase the font size.
import UIKit

class ViewController: UIViewController, UIGestureRecognizerDelegate {

    @IBOutlet weak var bannerLabel: UILabel!

    var perviousScale:CGFloat = 0
    var fontSize:CGFloat          = 0
    var originalFontSize: CGFloat = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        let pinchGesture = UIPinchGestureRecognizer(target: self, action: Selector("pinch:"))
        view.addGestureRecognizer(pinchGesture)
        perviousScale = pinchGesture.scale

        bannerLabel.adjustsFontSizeToFitWidth = true

        originalFontSize = bannerLabel.font.pointSize
        fontSize         = originalFontSize

    }

    func pinch(sender:UIPinchGestureRecognizer) {

        println("font size \(bannerLabel.font.pointSize)")

        if perviousScale >= sender.scale  //Zoom In
        {
            decreaseFontSize()

        }
        else if perviousScale < sender.scale  //Zoom Out
        {
            increaseFontSize()
        }

    }

    func threeFingers(sender:UIPanGestureRecognizer) {

        println("threeFingers")

    }

    override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {

        bannerLabel.font = UIFont(name: bannerLabel.font.fontName, size: fontSize)

    }

    func increaseFontSize(){

        bannerLabel.font = UIFont(name: bannerLabel.font.fontName, size: fontSize)

        fontSize = fontSize + 2.5

    }

    func decreaseFontSize(){

        bannerLabel.font = UIFont(name: bannerLabel.font.fontName, size: fontSize)

        if fontSize >= originalFontSize {

            fontSize = fontSize - 2.5
        }
    }
}

A: Yup, you can add an observer:
1) Add the dynamic modifier to the property you would like to observe:
dynamic UILabel bannerLabel = UILabel()

2) Create a global context variable
private var myContext = 0

3) Add an observer for the key-path
bannerLabel.addObserver(self, forKeyPath: "adjustsFontSizeToFitWidth", options:.New, context:&myContext)

4) Override observeValueForKeyPath and remove observer in deinit
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject: AnyObject], context: UnsafeMutablePointer<Void>) {
        if context == &myContext {
            println("Font size adjusted to fit width: \(change[NSKeyValueChangeNewKey])")
        } else {
            super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
        }
    }

 deinit {
        bannerLabel .removeObserver(self, forKeyPath: "adjustsFontSizeToFitWidth", context: &myContext)
    }


text:
Q: ¿Cómo recibir un array en un procedimiento de forma correcta en oracle? Tengo un problema con una función que recibe un array, he buscado por todas partes pero no he podido encontrar una respuesta concreta...
El código para obtener el array es el siguiente:
CREATE TYPE arreglo IS VARRAY(3) OF INT;
/
CREATE OR REPLACE FUNCTION array_example
RETURN arreglo
AS
    variable_arreglo arreglo;
BEGIN
    variable_arreglo := arreglo(0,0,0);
    variable_arreglo(1) := ROUND(dbms_random.VALUE() * 19) + 1;
    variable_arreglo(2) := ROUND(dbms_random.VALUE() * 19) + 1;
    variable_arreglo(3) := ROUND(dbms_random.VALUE() * 19) + 1;
    dbms_output.put_line('Valores en arreglo:');
    -- recorriendo arreglo
    FOR i IN variable_arreglo.first..variable_arreglo.last LOOP
        dbms_output.put_line('Posicion '||i||': '||variable_arreglo(i));
    END LOOP;
    RETURN variable_arreglo;
END;
/

El código del procedimiento es el siguinte
CREATE OR REPLACE PROCEDURE seleccion(ingreso VARRAY)
IS
DECLARE variable_arreglo VARRAY;
BEGIN
    UPDATE AEROPUERTO
    SET id_principal = NULL;

    UPDATE AEROPUERTO
    SET id_principal = ingreso;

    --select * from aeropuerto;
    FOR X IN (SELECT * FROM AEROPUERTO)
    LOOP
        IF AEROPUERTO.id_principal = AEROPUERTO.id THEN
            BEGIN
            UPDATE aeropuerto
            SET id_principal = NULL;
            END;
        END IF;
    END LOOP;
END;
/

El procedimiento debería recibir el array y asignar un valor aleatorio de él en una columna de una tabla, pero estoy teniendo problemas para poder hacerlo
Alguien me podría explicar que estoy haciendo mal? :(
El error que obtengo con ese código para el procedimiento es el siguiente:
3/1       PLS-00103: Se ha encontrado el símbolo "DECLARE" cuando se esperaba uno de los siguientes:     begin function pragma procedure subtype type      current cursor delete    exists prior external language
Errores: comprobar log de compilador


text:
Q: How order Percentage field in SQLite I was wondering when I order by DESC the percentage value it give me not correct:
Before Order
10%
70%
99%
90%
100%
After Order
99%
90%
70%
100%
10%
Actually it's should be 100% is up.
Any body can help me on that?
My order Code:
public Cursor queue_FRUIT()
{
    String[] columns = new String[]{KEY_ID, KEY_LEVEL, KEY_CORRECT, KEY_INCORRECT, KEY_DATE, KEY_PERCENTAGE, KEY_RESULT};
    Cursor cursor = sqLiteDatabase.query(TABLE_FRUIT, columns, null, null, null, null, KEY_DATE+" DESC, " + KEY_PERCENTAGE+" DESC", "10");
    return cursor;
}

A: This query result is because the column ordering is handled as String. The KEY_PERCENTAGE column shall be defined as INTEGER type instead of TEXT.
In this case you must store just the value without '%' character.


text:
Q: Date ranges using recursion I have a query that returns results that look like the create table query below
create table #testresults
(
  pat_id int,
  fill_date date,
  script_end_date date,
  drug_class char(3),
  distinctDrugs int
)

There are seven different categories of drugs that a pat_id can be given.  The distinctDrugs column is the number of different drugs that a pat_id can be given within the time frame of fill_date and script_end_date.  The results of running the query look like:

Each pat_id has many different fill_date and script_end_date time periods.  These different time periods have a different drug_class and distinctDrugs per row.  The right two columns on this example are indicative of what I need: I need on each row, for each fill_date and script_end_date the drug_class anddistinctDrugs for each drug_class.  I used this query to add the two right-most columns to my base view
select distinct
 t.pat_id
,t.fill_date
,t.script_end_date
,t.drug_class
,t.distinctDrugs
,h3a.drug_class as h3aDrugClass
,h3a.distinctDrugs
from #temp as t
left join
(
    select
     pat_id
    ,fill_date
    ,script_end_date
    ,drug_class
    ,distinctDrugs
    from #temp
    where drug_class='h3a'
) as h3a on h3a.pat_id=t.pat_id and h3a.fill_date between t.fill_date and t.script_end_date and t.drug_class !=h3a.drug_class
where h3a.drug_class is not null

It would be easy enough to do this for the rest of the drug_class columns, but this isn't remotely efficient.  Is there a way to do this much more simply using recursion (or any other manner for that matter)?
EDIT:
Here is the final product of what I was looking for:
select distinct
 f.pat_id
,f.fill_date
,f.script_end_date
,case when h3a.drug_class is null then 'H3A' else 'H3A' end as H3A
,isnull(h3a.distinctDrugs,0) as h3aCounts
,case when h4b.drug_class is null then 'H4B' else 'H4B' end as H4B
,isnull(h4b.distinctDrugs,0) as h4bCounts
,case when h6h.drug_class is null then 'H6H' else 'H6H' end  as H6H
,isnull(h6h.distinctDrugs,0) as h6hCounts
,case when h2s.drug_class is null then 'H2S' else 'H2S' end as H2S
,isnull(h2s.distinctDrugs,0) as h2sCounts
,case when h2e.drug_class is null then 'H2E' else 'H2E' end  as H2E
,isnull(h2e.distinctDrugs,0) as h2eCounts
,case when h2f.drug_class is null then 'H2F' else 'H2F' end as H2F
,isnull(h2f.distinctDrugs,0) as h2fCounts
,case when j7c.drug_class is null then 'J7C' else 'J7C' end  as J7C
,isnull(j7c.distinctDrugs,0) as j7cCounts
from familyStrata as f
left join
(
    select
     pat_id
    ,drug_class
    ,distinctDrugs
    ,fill_date
    from familyStrata
    where drug_class='h3a'
) as h3a on h3a.pat_id=f.pat_id and h3a.fill_date between f.fill_date and f.script_end_date
left join
(
    select
     pat_id
    ,drug_class
    ,fill_date
    ,distinctDrugs
    from familyStrata
    where drug_class='h4b'
) as h4b on h4b.pat_id=f.pat_id and h4b.fill_date between f.fill_date and f.script_end_date
left join
(
    select
     pat_id
    ,drug_class
    ,fill_date
    ,distinctDrugs
    from familyStrata
    where drug_class='h6h'
) as h6h on h6h.pat_id=f.pat_id and h6h.fill_date between f.fill_date and f.script_end_date
left join
(
    select
     pat_id
    ,drug_class
    ,fill_date
    ,distinctDrugs
    from familyStrata
    where drug_class='h2f'
) as h2f on h2f.pat_id=f.pat_id and h2f.fill_date between f.fill_date and f.script_end_date
left join
(
    select
     pat_id
    ,drug_class
    ,fill_date
    ,distinctDrugs
    from familyStrata
    where drug_class='h2s'
) as h2s on h2s.pat_id=f.pat_id and h2s.fill_date between f.fill_date and f.script_end_date
left join
(
    select
     pat_id
    ,drug_class
    ,fill_date
    ,distinctDrugs
    from familyStrata
    where drug_class='h2e'
) as h2e on h2e.pat_id=f.pat_id and h2e.fill_date between f.fill_date and f.script_end_date
left join
(
    select
     pat_id
    ,drug_class
    ,fill_date
    ,distinctDrugs
    from familyStrata
    where drug_class='j7c'
) as j7c on j7c.pat_id=f.pat_id and j7c.fill_date between f.fill_date and f.script_end_date

This is actually rather fast, but is in no way remotely elegeant/extensible.  Here is what the result set should look like:

You can see the number the drug_class and the distinctDrugs for each different drug, for each time period.  Now, is there a much more elegant solution to this problem than this?

A: In SQL server you do recursive queries using common table expressions (CTEs). Here's how:
http://msdn.microsoft.com/en-gb/library/ms186243(v=sql.105).aspx

A: So, recursion isn't the best method for doing this.  I settled with
select
 pat_id
,fill_date
,script_end_date
,'h3a' as h3a, coalesce(sum(case when drug_class='h3a' then distinctDrugs end),0) as h3aCounts
,'h4b' as h4b, coalesce(sum(case when drug_class='h4b' then distinctDrugs end),0) as h4bCounts
,'h6h' as h6h, coalesce(sum(case when drug_class='h6h' then distinctDrugs end),0) as h6hCounts
,'h2e' as h2e, coalesce(sum(case when drug_class='h2e' then distinctDrugs end),0) as h2eCounts
,'h3a' as h2f, coalesce(sum(case when drug_class='h2f' then distinctDrugs end),0) as h2fCounts
,'h3a' as h2s, coalesce(sum(case when drug_class='h2s' then distinctDrugs end),0) as h2sCounts
,'h3a' as j7c, coalesce(sum(case when drug_class='j7c' then distinctDrugs end),0) as j7cCounts
,row_number() over(order by pat_id) as rn
from x
group by pat_id,fill_date,script_end_date
)


text:
Q: Process behaviour after receiving a SIGSEGV signal? We recently learned about signals in UNIX our OS class. We use C to access the unix API.
A class mate was fooling around with dereferencing invalid pointers (to unallocated memory or null pointers) and then handling the resulting SIGSEGV signal. He had a code block that went something like this:
int* p;
int i = 0;
for (; i < 10; i++){
    printf("Iteration %d\n", i);
    p = i;
    int n = *p;
}

Then he had a simple signal handler that would simply print the signal number. What ended up happening was that the program would repeatedly print out that it had received a signal with the number 11 - a SIGSEGV signal and wouldn't ever exit the loop. Our professor found this behaviour to be odd and said he'd look into it.
From a search I did on the internet the behaviour does not seem to be at all odd, as the program is supposed to perform the offending instruction again after the signal it receives is handled in the case of a SIGSEGV. However this behaviour seems not to be documented anywhere in any of the official UNIX or LINUX documentation. Can any of you point me in the general direction of documentation regarding this type of behaviour?
EDIT:
The signal handler went something like this:
void signal_handler(int signo)
{
printf("%d\n", signo);
}

Redirecting console output to a file generated something like this:
Iteration 0
11
11
11
11
11
... (only stopped if we sent it a SIGINT)

A: As the documentation you found says the response of the OS on returning from a SIGSEGV is undefined. Specifically for this instance it means that the relevant library standards don't define where it should resume but leave it to the exact details of the machine it's running on.
From memory X86 derived machines will restart the faulting instruction. However, Other processors skip that instruction an continue with the next. In general neither method is that useful as they both can create very weird behaviours.
As you might guess from this exactly what is done usually depends on the processor you're running on. For a particular processor the page fault response (and other faults) are all defined precisely this includes exactly what will happen if you do an 'Return' instruction on the fault stack frame.
In general, for a portable program, the only safe thing to do in a SIGSEGV handler is to exit the program. It is, however, possibly to use setjmp/longjmp if you're very, very careful about not trapping the signal during library calls or similar.


text:
Q: C# Threading Performance, One Thread 99% Of The Time I have a multi-threaded C# application.  There is one dictionary that is accessed from N different threads at the same time.  99% of the calls are from thread A and the rest are from B, C, ...
Right now, I'm just locking the dictionary on each access.  But it seems wasteful because 99% of the time that I'm calling lock, thread A already has the lock.
What would a more efficient way of doing this be?
Maybe some type of .Begin and .End calls could be required for threads B, C, ... and then Thread A would only have to check one bit on each call to see if any of the other threads are using the dictionary.  Does anyone have a code sample of something like this implemented in a thread safe way?

A: You need to carefully examine your profiler data.
Both Monitor and RWLSlim won't actually "hard-lock" (as in drop down to the OS primitives) unless there's an actual contention; the will use Interlocked in all other cases, and perf implications of that are relatively minimal (aside from the cache flushes).
Performance wise, RWLockSlim is relatively expensive to create and a little more expensive than Monitor to enter. Its virtue is to allow muliple readers and a single writer.
If you are seeing hard locks showing up, then you have actual contention, in which case the 99%/1%/1%/1%/... ratio you stated probably doesn't reflect reality.
As previous posters noted, you should exmaine tha patten of use - in most cases you have occasional writes and massive reads, otherwise the system's consistency a somewhat difficult to enforfce. If that is the case, the RWlockSlim should remove unnecessary contention.
Bottomline : it all depends on what you are trying to do - as in what this dictionary is for and how is accessed. Sometimes it make sense to widen locks to prevent taking too many of those, and in some - very rare  - cases you might want to play with lock-free-style primitives like Interlocked before you even try to hit the "real" lock.
Perhaps if you told us more about the scenario, we'd be able to help better.

A: How do you perform the lock. For reading you don't need to lock out the other threads in the same "hard" way as if you are also updating. Either way you can be a bit more loose around the read operations. I would suggest looking into the ReaderWriterLockSlim (unless you are already using it):
class DictionaryHolder
{
    private IDictionary<int, string> _data = new Dictionary<int, string>();
    private ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
    public void Update(int key, string value)
    {
        _lock.EnterWriteLock();
        try
        {
            _data[key] = value;
        }
        finally
        {
            _lock.ExitWriteLock();
        }
    }

    public string GetValue(int key)
    {
        _lock.EnterReadLock();
        try
        {
            if (_data.ContainsKey(key))
            {
                return _data[key];
        }
        finally
        {
            _lock.ExitReadLock();
        }
    }
}

This will allow several threads to read from the dictionary "at the same time", while blocking access from other threads when updating it.

A: You shouldn't worry about this unless a profiler tells you you are spending a lot of time in Monitor.Enter and company - in general, acquiring an uncontended lock or a lock you already hold is a very fast operation and should be similar in performance to the bit check that you propose. A lock operation is usually only slow when it has to block due to contention.

A: ReaderWriterLockSlim does help when there are many readers and few writers.  However, individual operation performance of ReaderWriterLockSlim seemed to be worse than that of Monitor according to the following link: A Performance Comparison of ReaderWriterLockSlim with ReaderWriterLock.
One option you may try is to play with Interlocked operations together with Event objects to synchronize threads.  But, again, you should measure the performance of this approach as well.

A: Try using System.Collections.Concurrent.ConcurrentDictionary in .NET 4.0
It's thread safe by design


text:
Q: Calling method in Node js from browser (Using Express) I defined these three routes in app.js
app.use('/', require('./routes/index'));
app.use('/LEDon', require('./routes/LEDon'));
app.use('/LEDoff', require('./routes/LEDoff'));

In my route file I have the following:
var express = require('express');
var router = express.Router();
var Gpio = require('onoff').Gpio,
    led = new Gpio(17, 'out');

router.get('/', function(req, res, next) {
  led.writeSync(1);
});

module.exports = router;

So when I go to the /LEDon page the method runs and everything works. Is it possible though to run a method without using a get request? My main goal is to just click a hyperlink which then runs the method..

A: Essentially you are asking your client side script to directly call a function on your Node server script. The only other choice other than an Ajax POST AFAIK is Socket.io
This similar stackoverflow question should help you out.

edit: I made a simple example spanning multiple files:
/test/app.js:
var express = require('express');
var app = express();

app.post('/LEDon', function(req, res) {
    console.log('LEDon button pressed!');
    // Run your LED toggling code here
});

app.listen(1337);

/test/clientside.js
$('#ledon-button').click(function() {
    $.ajax({
        type: 'POST',
        url: 'http://localhost:1337/LEDon'
    });
});

/test/view.html
<!DOCTYPE html>

    <button id='ledon-button'>LED on</button>

To run it: node app.js in terminal, and open view.html on your browser. Try pressing the button and check out your terminal. Hope this helps.

A: For resolve your problem you can use ajax request, for example:

    LED On
    LED Off

A: Old question - I know. But as time flies, new ways appear.
Can I suggest trying api-mount. It basically allows calling API as simple functions without having to think about AJAX requests, fetch, express, etc. Basically in server you do:
const ApiMount = apiMountFactory()
ApiMount.exposeApi(api)

"api" is basically an object of methods/functions that you are willing to call from your web application.
On the web application you then do this:
const api = mountApi({baseUrl: 'http://your-server.com:3000'})

Having done that you can call your API simply like this:
const result = await api.yourApiMethod()

Try it out. Hope it helps.


text:
Q: Submitting form in Sencha Touch I have created a form and am trying to send its contents to a server. I used the forms example from sensa.com as a template.  The form sends a message to my server, but only with my the disable caching value and not any of the form values, for example  [url]/register?_dc=1829384859324  .  I also modified the example to use my server url and my server received the same type of request with only _dc=... from the example.
Is there some explicit way I have to list the fields I want sent to the server?
My form code is listed below.  When I call submit, I use form.submit({method: 'get'});
var formBase = {
        scroll: 'vertical',
        url   : 'MYURL/register',
        standardSubmit : false,
        items: [{
            xtype: 'fieldset',
            title: 'Personal Info',
            instructions: 'Please enter the information above.',
            defaults: {required: true,labelAlign: 'left',labelWidth: '40%'},
            items: [
            { xtype: 'textfield',name : 'first',label: 'First Name',useClearIcon: true,autoCapitalize : false
            }, { xtype: 'textfield',name : 'last',label: 'Last Name',useClearIcon: true,autoCapitalize : false
            }, { xtype: 'passwordfield',name : 'password',label: 'Password',useClearIcon: false
            }, {xtype: 'textfield',name : 'phone',label: 'Phone Number',
            }, {xtype: 'emailfield', name : 'email',label: 'Email',placeHolder: 'you@email.com',useClearIcon: true
            }]
        }],
    listeners : {
        submit : function(form, result){
                console.log('success',Ext.toArray(arguments));
        },
        exception : function(form, result){
                console.log('failure', Ext.toArray(arguments));
        }
}

A: I've just started using Sencha Touch myself, but I'm posting my form a bit different. I've created a submit button, and given that button a handler. The code that gets executed is the following:
    this.loginView.submit({
        method: 'POST',
        waitTitle: 'Connecting',
        waitMsg: 'Sending data...',
        success: function(form, result) {
            Ext.Msg.alert('Login succeeded!', result.response.reason);
        },
        failure: function(form, result){
            Ext.Msg.alert('Login Failed!', result.response.reason);
        }
    });

In which this.loginView refers to an Ext.form.FormPanel object (I'm separating controller-code and view-code, which I highly recommend!). Another method you could try is create your own AJAX request (using Ext.Ajax.request) and retrieve your form params using the getValues(); method from the FormPanel object.
I hope it helps!

A: You have to set the form property standardSubmit to true.

A: This post is quite old, but there might be others having similar issues with form submitting.
If you are new to Sencha and you have a form which is submitting nothing, you probably followed this tutorial Building your first app
It has a problem. Form items MUST HAVE NAME which is missing in the example.
Items should look something like the following:
    items: [
    {
        xtype: 'textfield',
        name: 'name',
        label: 'Name'
    },
    {
        xtype: 'emailfield',
        name: 'email',
        label: 'Email'
    },
    {
        xtype: 'textareafield',
        name: 'message',
        label: 'Message'
    }
]


text:
Q: I'm trying to make a snake with opengl but some vertices seem to go off, what can I do? I've been trying to make a Snake in c++ with Opengl, the main components work and quite everything is fine, but somehow when the Snake's tail gets bigger, it glitches.
Program's exact behaviour:

Basically, I already "made" this but without batch rendering, and this problem didn't appear at all and now i'm just confused about what's happening
EDIT : The glitch only appears after taking when tail's size is an even number

*

*Code compiled with Visual Studio Community 2019 in Debug x32,

*Processor: AMD Ryzen 5 3400G with Radeon Vega Graphics 3.70 GHz

*Ram:  6Go

Code:
App.cpp (Where the problem most likely is)
#include <glm/glm.h>
#include <glad/glad.h>
#include <glfw/glfw3.h>

int main(){
// Snake Head

// n_Height is 770 and n_Width is 1090
    glm::mat4 proj = glm::ortho(0.0f, float(n_Height), 0.0f, float(n_Height), -1.0f, 1.0f);

Snake::snakeTail = {
        n_Width / 2 - 5, n_Height / 2 - 5, 0.0f,
        n_Width / 2 - 5, n_Height / 2 + 5, 0.0f,
        n_Width / 2 + 5, n_Height / 2 + 5, 0.0f,
        n_Width / 2 + 5, n_Height / 2 - 5, 0.0f
};

/*
  Each snake tail parts is 12 vertices
*/

// Snake tail

for (int i = 1; i < Snake::tailSize+1; i++) {
        Snake::snakeTail.push_back(Snake::snakeTail[0] - i * 10);
        Snake::snakeTail.push_back(Snake::snakeTail[1]);
        Snake::snakeTail.push_back(0.0f);

        Snake::snakeTail.push_back(Snake::snakeTail[3] - i * 10);
        Snake::snakeTail.push_back(Snake::snakeTail[4]);
        Snake::snakeTail.push_back(0.0f);

        Snake::snakeTail.push_back(Snake::snakeTail[6] - i * 10);
        Snake::snakeTail.push_back(Snake::snakeTail[7]);
        Snake::snakeTail.push_back(0.0f);

        Snake::snakeTail.push_back(Snake::snakeTail[9]  - i * 10);
        Snake::snakeTail.push_back(Snake::snakeTail[10]);
        Snake::snakeTail.push_back(0.0f);
}

for (int i = 0; i < n_Height/10*n_Width/10; i++) {
        Snake::indices.push_back(i * 4);

        Snake::indices.push_back(i * 4 + 1);

        Snake::indices.push_back(i * 4 + 2);

        Snake::indices.push_back(i * 4 + 2);

        Snake::indices.push_back(i * 4 + 3);

        Snake::indices.push_back(i * 4);
}
}

//Creates vertex array, index buffer, shader program, vertex buffer and renders
// sets uniform mat4 with proj matrix

Snake.cpp (What happens on collision with apple and when snake moves):
 // When snake hits apple
            tailSize++;
            Snake::snakeTail.push_back(Snake::snakeTail[0] - tailSize * 10);
            Snake::snakeTail.push_back(Snake::snakeTail[1]);
            Snake::snakeTail.push_back(0.0f);

            Snake::snakeTail.push_back(Snake::snakeTail[3] - tailSize * 10);
            Snake::snakeTail.push_back(Snake::snakeTail[4]);
            Snake::snakeTail.push_back(0.0f);

            Snake::snakeTail.push_back(Snake::snakeTail[6] - tailSize * 10);
            Snake::snakeTail.push_back(Snake::snakeTail[7]);
            Snake::snakeTail.push_back(0.0f);

            Snake::snakeTail.push_back(Snake::snakeTail[9] - tailSize * 10);
            Snake::snakeTail.push_back(Snake::snakeTail[10]);
            Snake::snakeTail.push_back(0.0f);

// On render

for (int i = tailSize; i > 0; i--) {
            snakeTail[i * 12] = snakeTail[(i - 1) * 12];
            snakeTail[i * 12 + 1] = snakeTail[(i - 1) * 12 + 1];
            snakeTail[i * 12 + 3] = snakeTail[(i - 1) * 12 + 3];
            snakeTail[i * 12 + 4] = snakeTail[(i - 1) * 12 + 4];
            snakeTail[i * 12 + 6] = snakeTail[(i - 1) * 12 + 6];
            snakeTail[i * 12 + 7] = snakeTail[(i - 1) * 12 + 7];
            snakeTail[i * 12 + 9] = snakeTail[(i - 1) * 12 + 9];
            snakeTail[i * 12 + 10] = snakeTail[(i - 1) * 12 + 10];
}
 // Movement
        snakeTail[0] += addX;
        snakeTail[1] += addY;
        snakeTail[3] += addX;
        snakeTail[4] += addY;
        snakeTail[6] += addX;
        snakeTail[7] += addY;
        snakeTail[9] += addX;
        snakeTail[10] += addY;
// Sets buffer data to the new array
glBufferData(&Snake::snakeTail[0], snakeTail.size());
}

A: So hi, basically the answer was that I did an error that took me hours to find, it was such a simple error and yet it made opengl all act wrong,
I was setting up the buffer by using this :
    glBufferData(GL_ARRAY_BUFFER, size, data, GL_STATIC_DRAW);

while I had to do this :
    glBufferDara(GL_ARRAY_BUFFER, size*sizeof(float), data, GL_STATIC_DRAW);

so yeh that question was useless, sorry for disturbing everything :3


text:
Q: Magento remove reindex bar in admin I have an API script that updates the prices in Magento and does a reindex. This occurs every minute. So when this happens you can see the "One or more of the Indexes are not up to date" in the backend.
Is there a way that I can easily remove this bar from the backend?
Thanks

A: You could probably do that via CSS, but I honestly have to question the motivation of updating prices once per minute.  That is going to be incredibly costly in terms of bandwidth and CPU time, unless you have like 5 products.


text:
Q: Jasmine SpecRunner style page for Karma I am trying to show Jasmine SpecRunner style page using karma-jasmine, karma and gulp plugins but not able to see all the specs listing all of the test that passed on failed. I used karma-jasmine-reporter node module to get a report of the tests that ran but how can I rerun an individual test. I am looking to generate a page like this where I can see the result and rerun individual tests.

A: I've found that https://www.npmjs.com/package/karma-jasmine-html-reporter the karma-jasmine-html-reporter is the best UI reporter that gets close to the default jasmine html file look.
Your question is old, but it's what I was trying to find myself.
If you found a better solution since posting I'd like to know. One thing that this HTML reporter doesn't do is refresh if you updated the tests.
So if you run 'karma start' then it will run the tests, open your browser then you have to click on the debug button to show the UI reporting of your tests.
Then if you update the tests, the cmd window will refresh to reflect your new tests but the browser window will not.  You must refresh it manually.  Would be awesome to not have to do that.