text:
Q: how to call method from one adapter to current adapter activity Is it possible to call a method from one adapter activity to another adapter activity?
I have list view when I press item in list view I am getting popup window with check boxes by selecting check box and pressing ok. I have to disable item in the main list but the item is disabling in popup window list the main list loads in another adapter so I think by disable item there and attach to check box it may work. so please help me.
Main Activity:
listView1.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

                 @Override
                 public boolean onItemLongClick(AdapterView<?> parent, View view,
                 int position, long id) {
                 // TODO Auto-generated method stub
                     newListitems2.clear();
                  newListitems2.addAll(itemsList1);

                    // ArrayList newListitems2 = new ArrayList();
                     //newListitems2.add(itemsList1);
                     dialog = new Dialog(PendingOrdersActitvity.this);
                        dialog.setContentView(R.layout.itembumping);
                        dialog.show();

                        list1=(ListView )dialog.findViewById(R.id.list1);

                        ItemBumpingAdapter adapter2 = new ItemBumpingAdapter(PendingOrdersActitvity.this,newListitems2);
                        list1.setAdapter(adapter2);

                        Button okButton = (Button)dialog.findViewById(R.id.ok1);
                        okButton.setOnClickListener(new OnClickListener() {

                            @Override
                            public void onClick(View v) {

                                dialog.dismiss();

                            }
                 });
                            Button cancelButton = (Button)dialog.findViewById(R.id.Cancel1);
                    cancelButton.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            dialog.dismiss();
                        }

                        });
                        return true;

                 }
                            });

This is my main activity where on clicking item dialog appears.
dialog adapter:
 public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub

                        ViewHolder holder;
                        String item = null, qty = null;
                        if (convertView == null) {
                            holder = new ViewHolder();
                            convertView = inflator.inflate(R.layout.itembumpingadapter, null);
                            holder.qty = (TextView) convertView.findViewById(R.id.qty);
                            holder.name = (TextView) convertView.findViewById(R.id.item);
                            holder.childText = (TextView) convertView
                                    .findViewById(R.id.childitem);
                            holder.qtyChild = (TextView) convertView
                                    .findViewById(R.id.qtychild);
                             holder.checkbox = (CheckBox) convertView.findViewById(R.id.chckbox1);
                            convertView.setTag(holder);

                        } else {

                            holder = (ViewHolder) convertView.getTag();
                        }
                        parentobjid=newListitems.get(position).getParentobjectid();
                        if(!parentobjid.isEmpty())
                        {
                            holder.name.setText("   " +newListitems.get(position).getItemnNameDisplay());
                            holder.name.setTextColor(Color.parseColor("#CC0000"));
                            holder.qty.setText("      "+String.valueOf(newListitems.get(position)
                                    .getQuantityDisplay()));
                            holder.qty.setTextColor(Color.parseColor("#CC0000"));
                        }
                        else
                        {

                        holder.name.setText(newListitems.get(position).getItemnNameDisplay());
                        holder.qty.setText(String.valueOf(newListitems.get(position)
                                .getQuantityDisplay()));
                        holder.name.setTextColor(Color.parseColor("#FFFFFF"));
                        holder.qty.setTextColor(Color.parseColor("#FFFFFF"));
                        holder.checkbox.setChecked(false);

                        holder.checkbox.setTag(position);
                        holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener()
                            public void onCheckedChanged(CompoundButton buttonView,
                                    boolean isChecked) {

                                int position=(Integer)buttonView.getTag();

                                  newListitems.get(position).setChecked(!newListitems.get(position).isChecked());

                            }
                        });
                        if(newListitems.get(position).isChecked()){
                            holder.name.setEnabled(false);
                            holder.name.setBackgroundColor(Color.parseColor("#DCDBDB"));

                            }else{
                            holder.name.setEnabled(true);
                            }

This is adapter in which list along with check boxes is loaded.
List Adapter :
 public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub

                        ViewHolder holder;
                        String item = null, qty = null;
                        if (convertView == null) {
                            holder = new ViewHolder();
                            convertView = inflator.inflate(R.layout.itembumpingadapter, null);
                            holder.qty = (TextView) convertView.findViewById(R.id.qty);
                            holder.name = (TextView) convertView.findViewById(R.id.item);
                            holder.childText = (TextView) convertView
                                    .findViewById(R.id.childitem);
                            holder.qtyChild = (TextView) convertView
                                    .findViewById(R.id.qtychild);
                             holder.checkbox = (CheckBox) convertView.findViewById(R.id.chckbox1);
                            convertView.setTag(holder);

                        } else {

                            holder = (ViewHolder) convertView.getTag();
                        }
                        parentobjid=newListitems.get(position).getParentobjectid();
                        if(!parentobjid.isEmpty())
                        {
                            holder.name.setText("   " +newListitems.get(position).getItemnNameDisplay());
                            holder.name.setTextColor(Color.parseColor("#CC0000"));
                            holder.qty.setText("      "+String.valueOf(newListitems.get(position)
                                    .getQuantityDisplay()));
                            holder.qty.setTextColor(Color.parseColor("#CC0000"));
                        }
                        else
                        {

                        holder.name.setText(newListitems.get(position).getItemnNameDisplay());
                        holder.qty.setText(String.valueOf(newListitems.get(position)
                                .getQuantityDisplay()));
                        holder.name.setTextColor(Color.parseColor("#FFFFFF"));
                        holder.qty.setTextColor(Color.parseColor("#FFFFFF"));

This is my adapter in which main list is loaded. If I select the check box and press ok I want to disable or change color of item in main list but it is changing in dialog box list.
Please help me


text:
Q: Visual studio falls at a time when i'm debugging project My solution consists of several projects and every time I compile the project that I need to change. But lately every compiler eventually leads to the collapse of the visual studio.
Anybody know why?

A: I also had this problem, it is because every time you compile the LESS filesbuilds css. cancel this feature will override the options

redpajama_set_name: RedPajamaStackExchange


text:
Q: Javascript submit a form according to select option I plan to submit a form according to the option. But there is a javascript problem. I want to submit the form but I don't know the following code how to program. And the submit url is /dashboard/speed?speed=xxx Could someone help me ? Thanks a lot !

<form id="speed_form" class="form-inline pull-right">
<select name="population_speed">
  <option value="1">1 Rate</option>
  <option value="2">2 Rate</option>
  <option value="3">3 Rate</option>
</select>
</form>

A: You can submit the form with:
  $("#speed_form").submit();

A: You just need to submit the form, which you can do immediately after setting the action property (.attr() probably works too, but it's actually the property you should be setting):
$("#speed_form").prop("action", url).submit();

A: You can submit form with $("#speed_form").submit(); like;

<form id="speed_form" class="form-inline pull-right">
<select name="population_speed">
  <option value="1">1 Rate</option>
  <option value="2">2 Rate</option>
  <option value="3">3 Rate</option>
</select>
</form>

You can see working demo here: http://jsfiddle.net/4YmyL/

A: it would also help you in single line :
replace
$("#speed_form").attr("action", url);

to
$("#speed_form").attr("action", url).submit();

A: You just want to mimic the submit button with a select, there's no need to mimic all the native form functionality. So here's my approach:

<form id="speed_form" class="form-inline pull-right" action="/dashboard/speed" method="get">
<select name="speed">
  <option value="">Select your speed</option>
  <option value="1">1 Rate</option>
  <option value="2">2 Rate</option>
  <option value="3">3 Rate</option>
</select>
<input type="hidden" name="id" value="123456" />
</form>

Fiddle


text:
Q: Unable to initialize Mockito I am trying to set up Mockito 2.22 and have downloaded mockito-core-2.22.2.jar and byte-buddy-1.9.0.jar and, in the Netbeans 8.2 project, I have added those two jar files, JUnit 4.12 and Hamcrest 1.3 to the test libraries.
When I try to run the MCVE:
package com.stackoverflow.test;

import org.junit.Test;
import static org.mockito.Mockito.mock;

public class SimpleMockTest {
    public static class A{
        public String value(){ return "A"; }
    }
    @Test
    public void testASimpleMock()
    {
        A mocked = mock( A.class );
    }
}

When I try to run the test, I get the error:
Could not initialize plugin: interface org.mockito.plugins.InstantiatorProvider2 (alternate: interface org.mockito.plugins.InstantiatorProvider)
java.lang.IllegalStateException
    at org.mockito.internal.configuration.plugins.PluginLoader$1.invoke(PluginLoader.java:74)
    at com.sun.proxy.$Proxy12.getInstantiator(Unknown Source)
    at org.mockito.internal.creation.bytebuddy.SubclassByteBuddyMockMaker.createMock(SubclassByteBuddyMockMaker.java:44)
    at org.mockito.internal.creation.bytebuddy.ByteBuddyMockMaker.createMock(ByteBuddyMockMaker.java:25)
    at org.mockito.internal.util.MockUtil.createMock(MockUtil.java:35)
    at org.mockito.internal.MockitoCore.mock(MockitoCore.java:69)
    at org.mockito.Mockito.mock(Mockito.java:1895)
    at org.mockito.Mockito.mock(Mockito.java:1804)
    at com.stackoverflow.test.SimpleMockTest.testASimpleMock(SimpleMockTest.java:13)
    at org.mockito.internal.creation.instance.ObjenesisInstantiator.<init>(ObjenesisInstantiator.java:16)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:264)
    at org.mockito.internal.configuration.plugins.DefaultMockitoPlugins.create(DefaultMockitoPlugins.java:66)
    at org.mockito.internal.configuration.plugins.DefaultMockitoPlugins.getDefaultPlugin(DefaultMockitoPlugins.java:43)
    at org.mockito.internal.configuration.plugins.PluginLoader.loadPlugin(PluginLoader.java:67)
    at org.mockito.internal.configuration.plugins.PluginRegistry.<init>(PluginRegistry.java:32)
    at org.mockito.internal.util.MockCreationValidator.validateType(MockCreationValidator.java:22)
    at org.mockito.internal.creation.MockSettingsImpl.validatedSettings(MockSettingsImpl.java:238)
    at org.mockito.internal.creation.MockSettingsImpl.build(MockSettingsImpl.java:226)
    at org.mockito.internal.MockitoCore.mock(MockitoCore.java:68)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

Is there another dependency that I am missing? Or some other configuration/annotiation/setup that needs to be done to fix the error and allow the object to be mocked?

A: @JBNizet's suggestion to use Maven led me to Mockito's maven pom which lists the dependencies as:

*

*byte-buddy 1.9.0

*byte-buddy-agent 1.9.0

*objenesis 2.6

Downloading objenesis and adding it to the project fixed the issue.


text:
Q: Android Project Dependencies I need help with a project dependency issue in the Android SDK.
I have the following projects:
"Sync" (a Java only project)
"Agonis" (an Android Library project)
"Dragonis" (an Android application project)
Agonis has a project dependency on Sync, and Dragonis has a project dependency on Agonis, like so:
Dragonis->Agonis->Sync
I have correctly used the Properties->Android->Library dialog to add Agonis as an Android Library. I have exported the Sync project in the Agonis build path setup:
http://i.stack.imgur.com/GsQIR.png
In the Dragonis project, I see both Agonis and Sync in the "Android Dependencies" virtual folder:
http://i.stack.imgur.com/EhH8L.png
From here, I would expect everything to just work, but it doesn't.
I can start the app, but as soon as I instantiate a type from the Agonis project (com.mob.agonis.AgonisServer), I get a NoClassDefFoundError. If it matters, the Agonis type I am trying to instantiate extends a type that is in the Sync project (com.mob.sync.Server).
I tried cleaning all the projects, and using Android Tools->Fix Project Properties on both Agonis and Dragonis to no avail.
Am I overlooking something?

A: Put the jar library in the folder libs and add it to the java built path.
Right click on the file -> Build Path -> Add to Build Path
Hope it helps.

A: I figured it out.
The Sync Java-only library was compiling to 1.7 Java byte code. Android only supports converting Java 1.6 byte code to DEX.
Scroll to the top of the console, kids.

A: You can solve this through the command line tool. You could create/update the Dragonis and Agonis android projects - one as an application and other as library.  See http://developer.android.com/tools/projects/projects-cmdline.html
You can easily set up the dependency from D -> A using the command line tools as shown in section called referencing a library project. At this stage, a build of D automatically triggers a build of A.
Now modify the build.xml of A - to include a dependency on : build and copy Sync.jar at the pre-compile stage (look inside build.xml to find the placeholder).  The build and copy tasks can be done by starting a sub ant process using subant. See http://ant.apache.org/manual/Tasks/subant.html
At this stage all your dependency work properly on command line if you trigger ant build.   Now you can also use eclipse by importing the android project Dragonis from source.

A: From the project properties of "Sync" set the "Java Compiler"-> "JDK Complience" to 1.6. Rebuild and enjoy!


text:
Q: Order an array which contains OpenStructs by another array I have an array which contains OpenStruct elements.
I want to sort them by the id attribute, but not in a numeric order, which I can achieve by:
a.sort! { |x,y| x.id <=> y.id }

The order I need, as no logic, so I have an array, lets say:
order = ['4','32','1','3','5']

And I want to order my a array in that way.
All data contained in each a[x] is an OpenStruct which has an .id attribute.

A: Not clear whether you have numbers or strings as the attribute. If the former, then do
order.map!(&:to_i)

first. Then do:
a.sort_by!{|e| order.index(e.id)}

If there are no duplicates, do instead:
order & a.map(&:id)


text:
Q: strange overload = operator on some book, c-style? I find some books which this kind of code:

but if I try to compile somethings similar, it says that miss argument?
struct Test {
    double offsetDetected = 0.0;

    Test() {}
    Test &operator=() // removed here
};

what's wrong, and why books write this way those stuff? c-style?

A: This is C++, there's no "C style" for it. The book you're citing has a typo. That's all. I doubt that you find some "books". You found one book, I bet. The assignment operator requires an argument, since it's a binary operator.

A: It is a binary operator.As the other asnwere mentioned it might have a typing error.
#include <iostream>

struct Test {
    double offsetDetected = 0.0;

    Test() {}

    Test &operator=(const Test &obj); // removed here
};

int main() {

}


text:
Q: Find function in j2ee web application i'm developing a little market in a web application and i have to implement the search function. Now, i know i can use MATCH function in mysql or i can add some libraries (like apache lucene) but that's not the point of my doubt. I'm thinking about managing the set of results i get from the search function (a servlet will do this), cause not all the results should be send to client at one time, so i would like to separate them in some pages. I want to know what is more efficient to do, if i should prefer to do the search in db for every page the client calls or if i should save the result set in a managed bean and access them while the client request a new page of results. Thx (i hope my english is enough understandable)

A: The question you should be asking is "how many results can you store in memory"? If you have a small dataset, by all means, sure but you will have to define what "small dataset means". This will help as you call the database once and filter on your result in memory (which is faster).
Alternative approach, for larger/huge dataset, you will want to request to the database on every user page request. The problem here is that you call the database on each call, so you will have to have an optimised search query that will bring results in small chunks (SQL LIMIT clause). If you only want to hit the database once and filter the result in "memory", you will have to slot in a caching layer in between your application and your database. That way, the results are cached and you filter on the cached result. The cache will sit on a different JVM as not to share your memory heap space.
There is no silver bullet here. You can only answer this based on your non-functional requirements.
I hope this helps.


text:
Q: Type error when saving FormData when using Redux toolkit I've tried to save FormData(Javascript's standard API) using redux toolkit.
const initialState{
 myFile: FormData | null
}

const controllerSlice = createSlice({
  name: 'controller',
  initialState,
  reducers: {
    test: (state, action) => ({
      ...state,
    }),
//...

It complains
Types of property 'myFile' are incompatible. Type 'WritableDraft<FormData> | null' is not assignable to type 'FormData | null'
I don't know why it complains exactly, but redux toolkit uses immerjs inside of it so seems it wraps FormData with WritableDraft.
The only solution what I've found is changing FormData | null to any
const initialState{
 myFile: any
}

But I want to use FormData | null as a type of myFile. Any ideas?


text:
Q: Single file queue with people as blockers In a single-file queue of $n$ people with distinct heights, define a blocker to be someone who is either taller than the person standing immediately behind them, or the last person in the queue. For example, suppose that Ashanti has height $a,$ Blaine has height $b,$ Charlie has height $c,$ Dakota has height $d,$ and Elia has height $e,$ and that $a<b<c<d<e.$ If these five people lined up in the order Ashanti, Elia, Charlie, Blaine, Dakota (from front to back), then there would be three blockers: Elia, Charlie, and Dakota. For integers $n \ge 1$ and $k \ge 0,$ let $Q(n,k)$ be the number of ways that $n$ people can queue up such that there are exactly $k$ blockers.

*

*Show that $$Q(3,2)= 2 \cdot Q(2,2)+ 2 \cdot Q(2,1).$$

*Show that for $n \ge 2$ and $k \ge 1,$
$$Q(n,k)=k \cdot Q(n-1,k)+(n-k+1) \cdot Q(n-1,k-1).$$
Assume that $Q(1,1)=1,$ and that $Q(n,0)=0$ for all $n.$
For the first part of the problem, can we just bash certain values as our proof? (e.g. $Q(3, 2)$)
Part $2$ so far: For every queue of $n-1$ people with $k$ blockers, there are $k$ corresponding queues with $n$ people and $k$ blockers. For every queue of $n-1$ people with $k-1$ blockers, there are $n-k+1$ corresponding queues with $n$ people and $k$ blockers; and that these queues together make up all queues with $n$ people and $k$ blockers.

A: For every sequence of $n$ people with $k$ blockers, consider what happens when you remove the tallest person from the line, while keeping everyone else in the same order. How many blockers will new lineup have? It turns out it depends on where the tallest person was removed from. Let $n$ be the tallest person, and suppose they are behind person $a$ and in front of person $b$:
$$
\dots a\gets n \gets b \dots
$$
There are two cases:

*

*If $a$ is shorter than $b$, then removing $n$ reduces the number of blockers by $1$, since $n$ is a blocker.

*If $a$ is taller than $b$, then removing $n$ does not change the number of blockers, since the blocker $n$ is removed, but $a$ becomes a blocker.
You also have to consider what happens when $n$ is at the beginning or end of the line.
With these observations in mind, here is a big hint towards a proof. Every lineup of $n$ people can be obtained by inserting a person with height $n$ into a lineup of people with heights $1$ to $n-1$. In order to create a lineup of $n$ people with $k$ blockers, you have to either

*

*start with a lineup of $n-1$ with $k-1$ blockers, and insert $n$ in a place which causes the number of blockers to increase, or

*start with a lineup of $n-1$ with $k$ blockers, and insert $n$ in a place which causes the number of blockers to stay the same.
In each of these cases, count the number of places where you can insert $n$.


text:
Q: Model theory for intuitionistic predicate logic: a non-empty domain? In classical logic we tend to make the assumption that the domain of quantification is non-empty. This isn't (too) problematic because classical mathematicians assume a language/mind/proof independent existence of mathematical objects.
My question is this:

Does the model theory for intuitionistic logic make a similar assumption of a non-empty domain?

Since Intuitionists view mathematical statements as having no truth value until proven, we can say that mathematical statements are indexed with a time, $t_0 \dots t_n$.
If we take $t_0$ to be the starting point at which no proofs have been given, my question is must the domain at $t_0$ be taken to be non-empty, even though no mathematical objects have been constructed at that point?

A: The quantifier rules for standard intuitionist logic are the same as for standard classical logic, and the inference $\forall xFx \vdash \exists xFx$ (which presupposes a non-empty domain) is valid in both standard systems.
We can tinker in the same way with the rules in both the classical and the intuitionist case to allow for empty domains (this is particularly neatly done in the case of 'tree' systems).
The intuitionist and classic cases are, in this respect, quite parallel.
It is a further question whether the intuitionist has a special reason, over and above those available to the classical logician, to drop the standard assumption of non-empty domains. The classicist, after all, could also argue that the presumption that there are some objects to quantify over (in a given case) is not in general a logical assumption.


text:
Q: Conditional Seasonal Averaging Time-Series Data Introduction
Summary:

*

*Trying to average data by season (when necessary) when certain conditions are met.

Hello everyone.
I am currently working with numerous large data sets (>200 sets with >5000 rows each) of long-term time series data collection for multiple variables across different locations.  So far, I've extracted data into separate CSV files per site and per station.
For the most part, the data reported per parameter is one instance per season.
Season here is defined ecologically as DJF, MAM, JJA, SON for months corresponding to Winter, Spring, Summer, and Fall respectively.
However, there are some cases where there were multiple readings during a seasonal event. Here, the parameter values and dates have to be averaged; this is before further analysis can take place on these data sets.
To complicate things even further, some of the data is marked by a Greater Than or Less Than (GTLT) symbol).  In these cases, values and dates are not averaged unless the recorded value is the same.

Data Example
Summary:

*

*Code and Tables show requested changes in data-set

So, for a data-driven example...
Here's a few rows from a data set.
Data.Example<-structure(list(
    Station.ID = c(13402, 13402, 13402, 13402, 13402, 13402),
    End.Date = structure(c(2L, 3L, 4L, 2L, 3L, 1L), .Label = c("10/13/2016", "7/13/2016", "8/13/2016", "8/15/2016"), class = "factor"),
    Parameter.Name = structure(c(2L, 2L, 2L, 1L, 1L, 1L), .Label = c("Alkalinity", "Enterococci"), class = "factor"),
    GTLT = structure(c(2L, 2L, 2L, 1L, 1L, 1L), .Label = c("", "<"), class = "factor"),
    Value = c(10, 10, 20, 30, 15, 10)),
    .Names = c("Station.ID", "End.Date", "Parameter.Name","GTLT", "Value"), row.names = c(NA, -6L), class = "data.frame")

This is ideally what I would like as output
Data.Example.New<-structure(list(
    Station.ID.new = c(13402, 13402, 13402, 13402),
    End.Date.new = structure(c(2L, 3L, 2L, 1L), .Label = c("10/13/2016", "7/28/2016", "8/15/2016"), class = "factor"),
    Parameter.Name.new = structure(c(2L, 2L, 1L, 1L), .Label = c("Alkalinity", "Enterococci"), class = "factor"),
    GTLT.new = structure(c(2L, 2L, 1L, 1L), .Label = c("", "<"), class = "factor"),
    Value.new = c(10, 20, 22.5, 10)),
    .Names = c("Station.ID.new", "End.Date.new", "Parameter.Name.new", "GTLT.new", "Value.new"), row.names = c(NA, -4L), class = "data.frame")

Here, the following things are occurring:

*

*For Enterococci measured in July and Aug 13, there is a GTLT symbol, but Value for both == 10. So average dates.  New row is 7/28/2016 and Value 10.

*While Enterococci on Aug 15 is within same season as other values, since GTLT value is different, it would only be averaged in same season of same year with other values of 20.  In this case, since it is only one where Value==20, that row does not change and is repeated in final data frame.

*Alkalinity in July and August are same season, so average dates (7/28/16) and Value (22.5) in new row.

*Alkalinity in October is different season, so keep row.

*All other data (such as Station.ID and Parameter.Name) should just be copied since they shouldn't differ here.

If for some reason you have a GTLT and non-GTLT for same parameter:
End.Date    GTLT    Value    Parameter
7/13/2015     <      10         Alk
7/13/2016     <      10         Alk
8/13/2016            10         Alk
8/15/2016            20         Alk

Then final result would be
End.Date    GTLT    Value    Parameter
7/13/2015     <      10         Alk
7/13/2016     <      10         Alk
8/14/2016            15         Alk

Approach
Summary:

*

*Define seasons and then aggregate using package like dplyr?

*Create loop function to read row by row (after sort by Parameter.Name then Date?)

As one might expect, this is where I'm stuck.
I know seasons can be defined in R from prior Stack Q's:
New vector of seasons based on dates
And I know that average/aggregation packages such as dplyr (and possibly zoo?) can do chaining commands.
My issue is putting this thought process into code that can be repeated for each data set.
I'm not sure if that's the best approach (define seasons and then set conditions for averaging data), or if some sort of loop function would work here by going through row by row of the data set post-sort by Parameter.Name then End.Date.
I quickly sketched my thoughts on what some sort of loop function would have to include:
Rough idea of flow diagram
Note, you can't just average starting row [i] and [i+1] because [i+2], etc. might need averaged as well.  Hence finding row [i+n] that breaks loop before last step, averaging all prior rows [i+n-1], and moving on to next new row [i+n].
Further, as clarification, the season would have to be within season of that annual cycle.  So 7/13/2016 == 8/13/2016 for same season.  12/12/2015 == 01/01/2016 for same season.  But 4/13/2016! == 4/13/2015 in regards to averaging.

Conclusion and Summary
In short, I need help designing code to average individual parameter time-series values by annual season with specific exceptions for multiple large data sets.
I'm not sure of the best approach in designing code to do this, whether it's a large loop function or a combination of code and specialized chaining-enabled packages.
Thank you for your time in advance.
Cheers,
soccernamlak

A: Using dplyr and lubridate I was able to come up with a solution. My output matches your example output, except I did not keep the exact dates, which I felt were misleading in the final result.
Data.Example<-structure(list(
  Station.ID = c(13402, 13402, 13402, 13402, 13402, 13402),
  End.Date = structure(c(2L, 3L, 4L, 2L, 3L, 1L), .Label = c("10/13/2016", "7/13/2016", "8/13/2016", "8/15/2016"), class = "factor"),
  Parameter.Name = structure(c(2L, 2L, 2L, 1L, 1L, 1L), .Label = c("Alkalinity", "Enterococci"), class = "factor"),
  GTLT = structure(c(2L, 2L, 2L, 1L, 1L, 1L), .Label = c("", "<"), class = "factor"),
  Value = c(10, 10, 20, 30, 15, 10)),
  .Names = c("Station.ID", "End.Date", "Parameter.Name","GTLT", "Value"), row.names = c(NA, -6L), class = "data.frame")

# Create season key
seasons <- data.frame(month = 1:12, season = c(rep("DJF",2), rep("MAM", 3), rep("JJA", 3), rep("SON",3), "DJF"))

# Isolate Month and Year, create Season column
Data.Example$Month <- lubridate::month(as.Date((Data.Example$End.Date), "%m/%d/%Y"))
Data.Example$Year <- lubridate::year(as.Date((Data.Example$End.Date), "%m/%d/%Y"))
Data.Example$Season <- seasons$season[Data.Example$Month]

# Update 'year' where month = December so that it is grouped with Jan and Feb of following year
Data.Example$Year[Data.Example$Month == 12] <- Data.Example$Year[Data.Example$Month == 12]+1

# Find out which station/year/season/paramaters have at least one record with a GTLT
GTLT.Test<- Data.Example %>%
  group_by(Station.ID, Year, Season, Parameter.Name) %>%
  summarize(has_GTLT = max(nchar(as.character(GTLT))))

# First only calculate averages for groups without any GTLT
Data.Example.New1 <- Data.Example %>%
  anti_join(GTLT.Test[GTLT_test$has_GTLT == 1,],
            by = c("Station.ID", "Year", "Season", "Parameter.Name")) %>%
  group_by(Station.ID, Year, Season, Parameter.Name, GTLT) %>%
  summarize(Value.new = mean(Value))

# Now do the same for groups with GTLT, only combining when values and GTLT symbols match.
Data.Example.New2 <- Data.Example %>%
  anti_join(GTLT.Test[GTLT_test$has_GTLT == 0,],
            by = c("Station.ID", "Year", "Season", "Parameter.Name")) %>%
  group_by(Station.ID, Year, Season, Parameter.Name, GTLT, Value) %>%
  summarize(Value.new = mean(Value)) %>%
  select(-Value)

# Combine both
Data.Example.New <- rbind(Data.Example.New1, Data.Example.New2)

EDIT: I just noticed you linked to another SO question for converting dates to seasons. Mine simply converts by month, not date, and does not use actual seasons. I did this because in your example, Dec. 12 matches with Jan. 1. December 12 is technically fall, so I assumed you weren't using actual seasons, but were instead using four three-month groupings.


text:
Q: Xtext - how to constrain a value to be in specific range? I develop simple DSL language in Xtext, similar to JSON or markup language. I want to automatically validate entered integer values range while editing my custom language project. For example, I have attribute "timeout", and I want to give constraints from 100 to 1000. I know terminal rules, but it allows only to validate single number characters: from 0 to 9. Actually, I can write something like that:
terminal RANGE :
    ('0'..'9')('0'..'9')('0'..'9') | ('0'..'9')('0'..'9')('0'..'9')('0'..'9')

to express a certain amount of digits' numbers, but I don't think it is a clever solution.
Is there any possibility to make rules for such ranges?

A: You can either registering a custom IValueConverter for your RANGE terminal rule through a binding IValueConverterService in guice.
Or you implement semantic validations at all places that use RANGE as attribute.


text:
Q: Functional JavaScript: Closure & Recursion. Why does this fail? desired functionality:
mult(3);
 //(x) => 3 * mult(x)
mult(3)(4);
 //(x) => 3 * (4 * mult(x))
mult(3)(4)();
//12

attempt:
function mult(x){
    if(x === undefined){
        return 1;
    }else{
        return (y => x * mult(y));
    }
}

result:
mult(3)
//y => x * mult(y)
//looks pretty good

mult(3)()
//3
//exactly what I want so far.

mult(3)(4)()
//Uncaught TypeError: mult(...)(...) is not a function

sure enough,
mult(3)(4)
//NaN

Yet mult(3) looks good and typeof mult(3) === "function".
What gives?
Can I not be this fancy in JS? Any why not?

A: In
mult(3)(4)

mult(3) yields y => 3 * mult(y).
Thus
(y => 3 * mult(y))(4)

becomes
3 * mult(4)

mult(4) yields y => 4 * mult(y).
3 * (y => 4 * mult(y))

is nonsense because you're trying to multiply 3 by a function. This is why you're getting NaN here, and NaN can't itself be further applied.

Possible solution:

function mkmult(acc) {
    return x =>
        x === undefined
            ? acc
            : mkmult(acc * x);
}

const mult = mkmult(1);

console.log(mult(3)());
console.log(mult(3)(4)());
console.log(mult(3)(4)(5)());

A: If you think about it, the mult should never be passed undefined since it represents the "current" or left side of the multiplication. The inner function receiving y is the one that should handle providing the result.

function mult(x){
    return y => {
        if (y === undefined) return x;
        else return mult(x * y);
    };
}

console.log(mult(3))
console.log(mult(3)())
console.log(mult(3)(4)())

A: Here's another way that uses a secondary parameter with a default value

*

*base case – x is undefined, return the accumulator acc

*inductive case - x is not undefined – return a new lambda that asks for the next input y and recur using y and acc * x

const mult = (x, acc = 1) =>
  x === undefined
    ? acc
    : y => mult (y, acc * x)

console.log (mult ())             // 1
console.log (mult (2) ())         // 2
console.log (mult (2) (3) ())     // 6
console.log (mult (2) (3) (4) ()) // 24

Personally, I would use a known (explicit) empty value rather than relying upon the implicit undefined

const Empty =
  Symbol ()

const mult = (x = Empty, acc = 1) =>
  x === Empty
    ? acc
    : y => mult (y, acc * x)

console.log (mult ())             // 1
console.log (mult (2) ())         // 2
console.log (mult (2) (3) ())     // 6
console.log (mult (2) (3) (4) ()) // 24

Really though, mult as it is defined above is a toy. A more practical implementation would use variadic interface instead of the weirder currying with () used to signal a return value

// fixed arity
const mult = (x, y) =>
  x * y

// variadic interface
const multiply = (x = 1, ...xs) =>
  xs.reduce (mult, x)

console.log (multiply ())        // 1
console.log (multiply (2))       // 2
console.log (multiply (2, 3))    // 6
console.log (multiply (2, 3, 4)) // 24


text:
Q: How to implement maintenance mode in custom php cms? Ello,
I would like to make maintenance mode for my website, because i daily update files from development to production and website in that time website slows down or errors occurring for user at that time.
What the procedure for this kind of work. I would also like to allow users with right permissions to still login in website and use it normally (for testing purposes of implemented new features).
Thanks.

A: The answer really depends on the architecture of your cms. If there were no users needing a login during maintenance, you could use .htaccess to redirect browsers to a static page showing that maintenance is in progress. But if you need to be able to show some of the updated content, you have to make decision whether or not you want to show it to a specific visitor at cms level.


text:
Q: how to define variable in yaml symfony2 I'm not really familiar with YAML so I open parameters.yml and config.yml files to see example how to use parameters or variable in YAML.
parameters.yml:
parameters:
   database_driver: pdo_mysql
   database_host: 127.0.0.1
   database_port: 3306
   database_name: homlist

config.yml:
doctrine:
  dbal:
    driver:   "%database_driver%"
    host:     "%database_host%"
    port:     "%database_port%"
    dbname:   "%database_name%"

But when I tried it with doctrine mapping yaml file like this:
parameters:
   table_name: test

Mockizart\Bundle\BlogBundle\Entity\MockblogTag:
type: entity
table: "%table_name%"

it's error like this:

An exception occurred while executing 'SELECT count(DISTINCT %0_.id) AS sclr0 FROM %table_name% %0_':

this is my mapping file Resources\Config\Entity\MockblogTag
Mockizart\Bundle\BlogBundle\Entity\MockblogTag:
type: entity
table: mockblog_tag
indexes:
    user_id:
        columns:
            - user_id
    name:
        columns:
            - name
    slug:
        columns:
            - slug
id:
    id:
        type: integer
        nullable: false
        unsigned: false
        comment: ''
        id: true
        generator:
            strategy: IDENTITY
fields:
    dateCreated:
        type: integer
        nullable: false
        unsigned: false
        comment: ''
        column: date_created
    name:
        type: string
        nullable: false
        length: 60
        fixed: false
        comment: ''
    slug:
        type: string
        nullable: false
        length: 100
        fixed: false
        comment: ''
    totalPost:
        type: integer
        nullable: false
        unsigned: false
        comment: ''
        column: total_post
manyToOne:
    user:
        targetEntity: ORD\UserBundle\Entity\User
        joinColumn:
          referencedColumnName: id
        type: integer
        nullable: false
        unsigned: false
lifecycleCallbacks:

How to define variable in yaml symfony2 ?

A: The way of defining parameters it's correct, however I see from comments that your purpose is to configure the class used for User object:
As Cerad said you can't do that. But if you want to configure the class you use for the User, you can have a manager service class.
<?php

namespace YourNamespace\UserBundle\Manager;

use Doctrine\Common\Persistence\ObjectManager;

class UserManager
{

    /**
     * @var ObjectManager
     */
    protected $em;

    /**
     * Your user class
     *
     * @var string
     */
    protected $className;

    public function __construct(ObjectManager $em, $class)
    {
        $this->em = $em;
        $this->className = $class;
    }

    public function createInstance()
    {
        return new $this->className;
    }

    public function getRepository()
    {
        return $this->em->getRepository($this->className);
    }

}

And the services definitions will be like this:
services:
    your_user.manager:
        class: YourNamespace\UserBundle\Manager\UserManager
        arguments: ['@doctrine.orm.entity_manager', 'YourNamespace\UserBundle\Entity\User']

In your controller you can use this manager class like this:
$userManager = $this->get('your_user.manager');

$user = $userManager->createInstance();

I think this is a good way to have a central point when dealing with user object. And if someday for whatever reason you decide to use a different class for user you just modify the argument 'YourNamespace\UserBundle\Entity\User'.
Also in this way you can use 'YourNamespace\UserBundle\Entity\User' argument as parameter, so the definition will change to:
services:
    your_user.manager:
        class: Moneytablet\UserBundle\Manager\UserManager
        arguments: ['@doctrine.orm.entity_manager', '%user_class%']

and in you parameters.yml you can have:
parameters:
    user_class: YouNamespace\UserBundle\Entity\User

I really like working this way, you can create save(), remove() methods on manager class and so on. Also later on when creating new services you can inject this manager like a regular service if it's a dependency.
And if you want a new manager for a different entity, you can create a new service definition with different construct arguments, but with the same service class.


text:
Q: Can I have both iAds and Admob on my app? I recently added iAd on my app, then I realized that iAds isn't available in my country. Most  of my users are in my country, so iAds is useless for me.
I'm wondering If I can put Admob in my app once the didFailToReceiveAdWithError: method is being called? Will this cause any problems?

A: Yes.
I've done it in one of my apps, which I shall refrain from linking to here. What I did was exactly what you're thinking of, showing a different ad provider (AdMob) in place of iAd when an iAd wasn't available. I've been doing this for months, several updates, and no problem.
If you want to be safe, just make sure that iAd has supremacy over the other providers - that way, there's no reason for Apple to complain.


text:
Q: Call Ghostscript in Windows by its invocation name? What should I do to be able to call Ghostscript in Windows by its invocation name?
I added Ghostscript bin folder to Windows PATH and Path variables but it doesn't work,
neither does 'gswin32c.exe' nor 'gswin32c'. Logging out and then logging back in also didn't help.
How do I solve this issue? Maybe I'm using the wrong invocation name?

A: I've finaly got what i want after rebooting. Weird. Thanks all of you for your help.

A: In my case the easiest option that actually made it work was renaming the main exe to gs.exe and with the path configured it works like a charm.

A: There are several possibilities. To list the two most frequent ones:

*

*c:\full\path\to\gswin32c.exe should always work.
 For 64bit systems, use c:\full\path\to\gswin64c.exe.

*After a fresh installation using a standard windows installer, you may need to reboot before the updated %path% environment variable is used.

*Open a cmd window and (assuming your Ghostscript installation ended up in c:\path\to\gs...) then type set path=c:\path\to\gs\gs9.02\bin;%path%. From this same cmd window you can now simply use gswin32c to start Ghostscript (use gswin64c on 64 bit Windows)...


text:
Q: How to get the uploaded file path in FilePicker Currently we are able to drag and drop the folders and we are able to get all the files in the folder.
but we are not able to get the path of that files.
How can we get the file path of the files which are uploaded, so that we can maintain the same folder structure ?

A: In response from filepicker you receive list of objects.
Each object looks like this:
{
     "url":"https://www.filepicker.io/api/file/0SIihoHPT8ORvwQ3EOPx",
     "filename":"filepicker_test.png",
     "mimetype":"image/png",
     "size":4607,
     "id":4,
     "path":"/2/folder/filepicker_test.png",
     "isWriteable":true
}

So you can restore directories structure using "path" key from filepicker answer.


text:
Q: Viewing all Products that a Customer has purchased on Stripe How can I view all Products that a Customer has purchased using the Stripe API? Is there a specific event that is sent out when a purchase occurs? I'm seeing that there is an Orders item as well, but am not sure that Products can only be purchased as part of Orders.
Sample query for getting all Orders by a Customer:
from stripe import Order

Order.list(customer=customer_1['data'][0].id)

Basically I want to get all non-subscription-based items that the user has purchased -- will querying the API for Orders this way give me all non-subscription-based items, since a Product must necessarily each be tied to an Order, or is there a different/better way of doing this?

A: You can retrieve all orders for a customer with the list all orders method and the customer parameter.
You can then go through the order's items attribute to find the SKUs included in the order.
Finally, you can use a SKU's product attribute to retrieve the product associated to the SKU.
In Python, you could do something like this:
customer_id = "cus_..."
products = []  # list of products ordered at least once by the customer

orders = stripe.Order.list(customer=customer_id)
for order in orders.auto_paging_iter():
    for item in order.items.auto_paging_iter():
        if item.type == "sku":
            sku = stripe.SKU.retrieve(item.parent)
            if sku.product not in products:
                products.append(product)

The above code is not very efficient as it would send a SKU retrieve request for every item of type "sku". In practice, you'd likely want to cache the results and only retrieve each SKU once.


text:
Q: Minimum tls configuration not working in docker private repository Using below configuration to set minimum tls version in Docker private registry.
http:
  addr: 0.0.0.0:5000
  net: tcp
  relativeurls: false
  draintimeout: 60s
  host: https://example.com:443
  tls:
    certificate: /certs/domain.crt
    key: /certs/domain.key
    minimumtls: tls1.3
    ciphersuites:
      - TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
      - TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384

But when u run below command. It is showing tlsv1 is enabled.
openssl s_client -connect example.com:443 -tls1
********
Expansion: NONE
No ALPN negotiated
SSL-Session:
    Protocol  : TLSv1
    Cipher    : ECDHE-RSA-AES128-SHA
    Session-ID: A611949FBC6ED8ED322D4360C7B32887C75BE6HJFU5BA9B536C3721924A103F3E
********


text:
Q: Where are the connection files for IIS Manager for Remote Administration? I have IIS Manager for Remote Administration installed on one PC and now I have a new PC and want to move the connections I setup on my old PC. But I don't know where are the connection files are saved. I tried to look into my Profile but don't have a clue on where they are.
I have the 32bit on the old PC and 64bit on the new PC. I also wonder if the connection files can be shared among them at all?

A: I found the file. It's located at
c:\Users\{user_name}\AppData\Roaming\Microsoft\WebManagement\7.0.0.0\InetMgr.preferences

then you can just create the necessary folders and copy the file from old PC to new.


text:
Q: Rails, Select2 and Ransack return emprty array I have a City Model:
    class Geo::City < Smth
      self.table_name = 'cities_table'
      has_many :streets, class_name: "Geo::Street", primary_key: :geo_code, foreign_key: :geo_code

The aim is, to search all streets in the city and print them as a search result. In my controller I have a filter method as follows:
    def filter
      @city_list = city_list
      params[:q] ||= {}
      params[:q][:ags8_id_eq] = @city_list[0][1]
      if params[:q].present? && params[:q][:geo_code_eq].present?
        @city = Geo::City.find_by(geo_code: params[:q][:geo_code_eq])
        @collection = [["#{@city}", "#{params[:q][:geo_code_eq]}"]]
      end
      @streets = @city.streets.limit(15)
      @q = @streets.ransack(params[:q])
    end

I also have a search_city method as follows:
  def search_city
    render json: city_list.select {|city| city.first.include?(params[:q][:geo_code_eq])}
  end

And a private method city_list which I am calling in methods above:
  def city_list
    all_cities = Geo::City.order('city_name').reduce([]) {|cities, c| cities << [c.name, c.geo_code]}

I had to change all the method names,cause it's for work, so the_city list is kind of an example and it also works fine, I assume, this is not the problem. I also have a js-file for select 2.
    (function() {
      $(function() {
        return $('.city-select2').select2({
          ajax: {
            url: "/filter/search_city",
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return {
            q: {
              geo_code_eq: params.term
            }
          };
            },
            processResults: function(data) {
              return {
                results: $.map(data, function(obj) {
                  return {
                    id: obj[1],
                    text: obj[0]
                  };
                })
              };
            },
            cache: true
          },
          minimumInputLength: 2,
          placeholder: "City",
          tags: false,
          tokenSeparators: [","],
          selectOnClose: true,
          allowClear: true
        });
      });

    }).call(this);

It seems to be working, cause when I type city name it finds the city with the letters I typed. What happens after I submit select form is that I just get an empty array, so basically like this:

The url looks the following:
http://localhost:3000/filter/search_city?q%5Bgeo_code_eq%5D=16071003&commit=Search

My view does this:
= search_form_for @q, url: search_city_path do |f|
    .columns.is-centered{style: 'padding-top: 100px;'}
        .column.is-half
            = f.select(:geo_code_eq, options_for_select(collection: @collection.present? ? @collection : [], input_html: { class: "city-select2 select-input" })
            = f.submit "Search"

What is wrong? How do I get streets in the cities printed? There might be some spelling mistakes in the code, as I had to replace names, this won't be the reason for my empty array. Also, in the url there is only B selected, maybe that the reason? But it also finds the geo_code, so it should be capable of giving the streets back linked to geo_code, as geo_code is also the part of streets_table..

A: Main reason for the array was the path in the view. Should have been filter_path ans not the search_city_path, as it was the same path my select2 was getting data from, redirection there on submit made no sence.


text:
Q: A more efficient way of creating an NxM array in Python In Python, I need to create an NxM matrix in which the ij entry has value of i^2 + j^2.
I'm currently constructing it using two for loops, but the array is quite big and the computation time  is long and I need to perform it several times. Is there a more efficient way of constructing such matrix using maybe Numpy ?

A: You can use broadcasting in numpy. You may refer to the official documentation. For example,
import numpy as np
N = 3; M = 4   #whatever values you'd like

a = (np.arange(N)**2).reshape((-1,1))   #make it to column vector
b = np.arange(M)**2

print(a+b)  #broadcasting applied

Instead of using np.arange(), you can use np.array([...some array...]) for customizing it.


text:
Q: php SoapClient and recurring XML What is the recommended method to create a recurring tag using SoapClient?  I'm assuming it's via an array but where does it get the recurring tag name from?  And is there any weirdness for a single vs. multiple items?
I'm trying to utilize the Soap layer for Authorize.Net and it seems to break if I use an array for CustomerPaymentProfileType when there's only one CustomerPaymentProfile in the array.
treii28


text:
Q: Signal/Method for every executed sql statement According to this 12 years old issue, django does not support a signal for every executed sql statement: https://code.djangoproject.com/ticket/5415
I need this in a production environment where debug=False.
This means overwriting connection.queries does not work.
Is there a way to run some custom code after each sql statement (even if debug=False)?

A: I do believe that the interesting solution posted by @Louis should be flagged as the the correct one.
Having said this, if your need is that of logging and analyzing all executed queries, you might consider installing django-debug-toolbar and configuring it to be optionally available in production for the superuser or a specific administration user.
For example, put this in myproject/settings.py:
def show_toolbar(request):
    from constance import config
    if not config.DEBUG_SHOW_TOOLBAR:
        return False
    return request.user.is_superuser

DEBUG_TOOLBAR_CONFIG = {
    'SHOW_TOOLBAR_CALLBACK': 'myproject.settings.show_toolbar',
    'INTERCEPT_REDIRECTS': False,
}

django-debug-toolbar has a specific panel with very detailed informations about all database activity.

A: I've taken a look at how Django populates connection.queries. When DEBUG = True, the base database backend code that is used by all backend wraps the database-specific cursors with CursorDebugWrapper. Otherwise, it uses CursorWrapper. It would be in theory possible to force Django to populate it even when DEBUG = False by overriding the queries_logged property or setting the flag force_debug_cursor on the database connection object. Either method would force Django to use CursorDebugWrapper even when DEBUG is False. However, I don't recommend this approach because CursorDebugWrapper is not particularly efficient for cases where the only thing you want is to know that a query was executed. For instance, besides populating connection.queries it logs the queries to a logger. If you do not need this logging, then it is just a waste.
So taking inspiration from how CursorDebugWrapper works, I've come up with a custom way to know when a SQL query has been made.
I created an app called first whose __init__.py is:
from django.db.backends import utils
from contextlib import contextmanager

# This is inspired by Django's stock CursorDebugWrapper class.
class Mixin(object):

    def execute(self, sql, params=None):
        with self.notify(sql, params, use_last_executed_query=True):
            return super().execute(sql, params)

    def executemany(self, sql, param_list):
        with self.notify(sql, param_list):
            return super().executemany(sql, param_list)

    @contextmanager
    def notify(self, sql=None, params=None, use_last_executed_query=False):
        try:
            yield
        finally:
            if use_last_executed_query:
                sql = self.db.ops.last_executed_query(self.cursor, sql, params)
            # I've used print for this proof-of-concept, replace with whatever
            # mechanism suits you.
            print("Executed: ", sql)

class CustomWrapper(Mixin, utils.CursorWrapper):
    pass

class CustomDebugWrapper(Mixin, utils.CursorDebugWrapper):
    pass

utils.CursorWrapper = CustomWrapper
utils.CursorDebugWrapper = CustomDebugWrapper

Then in my settings.py file, I've put the first app first INSTALLED_APPS. This makes it so that the __init__.py file for it executes before anything that accesses the database.
What this is doing is essentially replacing the stock CursorWrapper and CursorDebugWrapper classes with custom ones that allow knowing when an SQL query has occurred. This change takes effect for all the backends that are shipped with Django.
I don't know of another way to add this capability in one fell swoop like I'm doing above. I first looked to see if I could derive a new backend from an existing one. I'm sure it is doable but it requires a lot of boilerplate. Also, projects that use multiple backends at once would have to derive a new backend for each stock backend that was originally used.

A: Maybe you could add a logger to your db backends:
import logging
logger = logging.getLogger('django.db.backends')
logger.setLevel(logging.DEBUG) #set the log level you want
logger.addHandler(logging.StreamHandler())

This will track all database transactions.
I remember seeing this some years ago, but I think it should work, since the logging system is pretty much the same.
It is not a signal, but I think it would do what you want.


text:
Q: Constructor not recognizing attribute member I have the following constructor for my Dbconn class:
def __init__(self):
    self.host     = "localhost"
    self.database = "my_database"
    self.username = "username"
    self.password = "password"

    try:
        self.db = MySQLdb.connect(
            self.host,
            self.username,
            self.password,
            self.database
        )
        self.cursor = self.db.cursor()
    except:
        print "There was an error while connecting to the database"
        self.db.rollback()

however, when I execute the program, I get:
  File "database.py", line 39, in __init__
    self.db.rollback()
AttributeError: Dbconn instance has no attribute 'db'

Any clues why I'm getting that?

A: When MySQLdb.connect() fails, self.db is not set at all. There is no point in rolling back at that point.
Start by setting it to None, then test for that in the except handler:
db = None

def __init__(self):
    self.host     = "localhost"
    self.database = "my_database"
    self.username = "username"
    self.password = "password"

    try:
        self.db = MySQLdb.connect(
            self.host,
            self.username,
            self.password,
            self.database
        )
        self.cursor = self.db.cursor()
    except MySQLdb.Error:
        print "There was an error while connecting to the database"
        if self.db is not None:
            self.db.rollback()

I also made the exception handler more specific; blanket except handlers are rarely a good idea.

A: Nothing gets assigned to self.db if MySQLdb.connect throws an exception.

A: If MySQLdb.connect fails, the db attribute won't be assigned. Also, what do you want to rollback if a connect to the DB failed?


text:
Q: Multiplication of leptonic - hadronic tensor I am about to proof
$$ L_{\mu\nu}T^{\mu\nu}=8\Big(2(k \cdot p)(k' \cdot p) + \frac{q^2}{2 M^2} \Big). $$
from leptonic tensor:
$$ L_{\mu\nu} = 2(k'_\mu k_\nu + k'_\nu k_\mu + \frac{1}{2}q^2g_{\mu\nu}) ,$$
and hadronic tensor
$$T^{\mu\nu}=(p+p')^\mu(p+p')^\nu,$$
I have tried to expand the $T^{\mu\nu}$
$$T^{\mu\nu}=(p^\mu p^\nu + p^\mu p'^\nu + p'^\mu p^\mu + p'^\mu p'^\nu),$$
but then I can't get the pattern. Here, we use framework of rest particle target, e.g. $p^\mu=(M,\textbf{0})$, the final hadron $p=(E',\textbf{p'})$, with lepton initial $k=(\omega,\textbf{k})$ and final $k'=(\omega',\textbf{k}')$.


text:
Q: Why cannot my app create fitness.runs for test users? My web app can successfully create fitness.runs for myself and friends, but not for test users (created in the Test Users view of the Roles tab of the App's Dashboard). So I have a problem getting the app approved in the review, required for explicit sharing.
The app makes the following HTTP request to create (line breaks in content for readability):
POST /me/fitness.runs HTTP/1.1
Content-Type: application/x-www-form-urlencoded

course=https%3A%2F%2Fbroker-web.appspot.com%2Fpub%2Fcourse%2FagxzfmJyb2tlci13ZWJyLAsSDERQYXJ0aWNpcGFudBiAgICA_fCfCgwLEgZEU3BsaXQYgICAgICAgAoM
&start_time=2014-04-30T13%3A43%3A46
&expires_in=86400
&object=%7B%22app_id%22%3A%22255653361131262%22%2C%22title%22%3A%22Demo+410m%22%7D
&access_token=ACCESS_TOKEN

The successful response contains the action id (for myself and friends), and for test users the following error message is returned:
HTTP 500 OK

{error={message=An unexpected error has occurred. Please retry your request later., type=OAuthException, code=2}}

The crawler was successful visiting the object:
89.236.16.14 - - [30/Apr/2014:06:45:13 -0700] "GET /pub/course/agxzfmJyb2tlci13ZWJyLAsSDERQYXJ0aWNpcGFudBiAgICA_fCfCgwLEgZEU3BsaXQYgICAgICAgAoM HTTP/1.1" 200 6211 -
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36"
"broker-web.appspot.com" ms=135 cpu_ms=41 cpm_usd=0.000694 app_engine_release=1.9.4 instance=00c61b117ce48a0349d573d3cd16b02587ffe00b

A: My app was using the wrong FB app ID when creating the action. That is an issue only for Test Users, as they exist for the correct FB App only.


text:
Q: Using volatile to avoid race conditions I'm learning about java.util.concurrent. I wrote some code like this:
import java.util.concurrent.ArrayBlockingQueue;

public class JUCArrayBlockingQueue {

private static ArrayBlockingQueue<String> abq = new ArrayBlockingQueue<String>(1);
private static volatile int i = 0;
private static volatile int j = 0;

public static void main(String[] args) {
    new Pop("t1").start();
    new Pop("t2").start();
    new Push("p1").start();
    new Push("p2").start();
}

static class Pop extends Thread {
    public Pop(String name) {
        super(name);
    }

    @Override
    public void run() {

        String str;
        try {

            while (++j < 500) {
                str = abq.take();
                System.out.println(j + ">>"
                        + Thread.currentThread().getName() + " take: "
                        + str);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

static class Push extends Thread {
    public Push(String name) {
        super(name);
    }

    @Override
    public void run() {

        while (i < 500) {
            if (abq.offer(Thread.currentThread().getName() + " t" + i
                    + "  ~")) {
                i++;
            }
            ;
        }
    }
}
}

And the result is like this:
488>>t1 take: p2 t486  ~
489>>t2 take: p2 t487  ~
490>>t2 take: p1 t488  ~
491>>t1 take: p1 t489  ~
492>>t1 take: p2 t490  ~
493>>t1 take: p1 t490  ~
494>>t2 take: p1 t492  ~
495>>t2 take: p1 t493  ~
496>>t1 take: p1 t494  ~
497>>t2 take: p1 t495  ~
498>>t1 take: p1 t496  ~
499>>t2 take: p1 t497  ~
500>>t1 take: p2 t498  ~

I am puzzled by this output because the left size is expected, but not the right size. I was not expecting duplicate values to be shown on the right side. How can I fix it? Anyone help?

A: Let's take a look at the code snippet that prints the right hand side of your output :
if (abq.offer(Thread.currentThread().getName() + " t" + i
                    + "  ~")) {
       i++;
 }

Let's zoom into the condition in the if statement :
abq.offer(Thread.currentThread().getName() + " t" + i
                        + "  ~")

So you are using the offer method. Let's take a look at the java doc for the offer method :

public boolean offer(E e)
Inserts the specified element at the tail of
  this queue if it is possible to do so immediately without exceeding
  the queue's capacity, returning true upon success and false if this
  queue is full. This method is generally preferable to method add(E),
  which can fail to insert an element only by throwing an exception.

Call to offer does not seem to be a blocking call. This means that multiple threads can call the offer method at the same time. This is what is most likely the problem :

*

*t1 offers an element to the ArrayBlockingQueue. i = 0

*p2 immediately takes the element from the queue. i = 0

*t2 offers an element to the ArrayBlockingQueue even before t1 gets a chance to call i++. i=0.

*p2 immediately takes the element from the queue. i = 0.

You can see from 2) and 4) that there is a possibility that two threads read the value of i even before i++ is called and thus see the same value of i.
So how do you fix this problem? As others have suggested, you can use AtomicInteger as explained below :
The volatile keyword will ensure that when a read or a write on a variable (memory location) shared across multiple threads is done, it is guaranteed that each Thread will see the latest value of the variable. Notice the emphasis on or. When you say i++ or j++, you are doing a read and a write together. This is not an atomic operation and the volatile keyword will not stop threads from seeing inconsistent values.
Change
private static volatile int i = 0;

To :
private static final AtomicInteger i = new AtomicInteger();

AtomicInteger provides the atomic increment operations incrementAndGet() (=++i) and getAndIncrement() (=i++) which can be used in this case:
int nr=0; // local holder for message number
while ((nr = i.getAndIncrement()) < 500) {
    abq.put(Thread.currentThread().getName() + " t" + nr + "  ~");
}

(1) Note the usage of the local variable nr! It ensures that the result of the increment operation is used as the message number in put(...). If we used i directly instead of nr, other threads could have incremented i in the meantime and we would have a different message number or a duplicate message number as well!
(2) Also note that offer(...) is replaced by put(...). As your queue is bounded (to 1 element only), the insert operation should block if it runs out of capacity. (offer(...) will immediately return false in that case.)
(3) Note that this code does NOT ensure correct insertion order according to the message number. It only ensures that there are no duplicates! If correct insertion order is required, you will have to use a completely different approach without AtomicInteger and ArrayBlockingQueue. Instead use a non-thread-safe queue and use good old synchronized to make increment and insertion atomic:
while (true) {
    synchronized(queue) {
        if (i++ >= 500) break;
        queue.put(... + i + ...);
    }
}

The above code is not efficient. Almost the entire code is synchronized. There is no real parallel execution and concurrency is useless.
You can change j in a similar fashion.

A: Making a variable volatile does not protect it from race conditions,  it just indicates that the object to which the variable is bound may mutate to prevent compiler optimizations, it is not needed in your case because I & j are modified in the same thread (the loop thread).  To overcome the race condition you need to make the i++and j++ action atomic by synchronization,  like defining them as atomic integer and using incrementAndGet().


text:
Q: ArrayList reflection
Possible Duplicate:
How do I find out what type each object is in a ArrayList<Object>?
Knowing type of generic in Java

How can I retrieve the Type Foo from my ArrayList using the reflection in Java?
ArrayList<Foo> myList = new ArrayList<Foo>();

A: You can't get this type from the value, but you can get it from the Field information.
public class Main {
    interface Foo { }
    class A {
        List<Foo> myList = new ArrayList<Foo>();
    }
    public static void main(String... args) throws NoSuchFieldException {
        ParameterizedType myListType = ((ParameterizedType)
                                A.class.getDeclaredField("myList").getGenericType());
        System.out.println(myListType.getActualTypeArguments()[0]);
    }
}

prints
interface Main$Foo

Fields, method arguments, return types and extended classes/interfaces can be inspected, but not local variables or values
These produce the same result.
List<Foo> myList = new ArrayList();
List<Foo> myList = (List) new ArrayList<String>();

You cannot obtain a generic type for
List myList = new ArrayList<Foo>();


text:
Q: Is it possible to store a list or a python dictionary in a sqlalchemy database column? I'm doing a grocery shop website and I'm still new to web dev. I'd like to add in my Users table a column that stores a list with all the user's purchase date or a dictionary with all the user's purchase date as keys and items as values. I'm using Flask-SQLAlchemy for my database. Is there a way to do this?
Here is my code:
class Users(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    first_name = db.Column(db.String(100), nullable=False)
    last_name = db.Column(db.String(120), nullable=False)
    email = db.Column(db.String(120), index=True, unique=True, nullable=False)
    email_confirmed = db.Column(db.Boolean, nullable=False, default=False)
    email_confirmed_on = db.Column(db.DateTime(timezone=True), nullable=True)
    purchase_history = db.Column(??)
    password_hash = db.Column(db.String(120))

Thank you in advance!

A: There actually IS a way to store a list in database (as a JSON field), but it is strongly not recommended to do this (at least you really really need to) and you probably will be cursed by your colleagues. jk.
it is better to store such entities in a separate table.
not only because it's more read-usable (allowing you to filter purchases that will be displayed, for example), but also because it's easier to maintain. in fact, you already gave a good example yourself.
say, at the moment dates is all that's enough for you to store purchase history. so you store it as a list.
but then you decide you want to store items also.
and display them.
but you already store purchase history as a list, and it will be a huge headache to adjust it, especially if you have a lot of data already stored there.
I hope you get the idea. I'd create a Purchase table and a relationship for User.


text:
Q: window.onbeforeunload allow submit button? I have the following javascript to show a confirm box when a user leaves the page.
My problem is, it is showing even when user clicks the submit button inside a form in my page. I don't want this to be triggered on form submit and on a span click.
How can I allow form submit and span click in the function below?
window.onbeforeunload = function (e) {
    e = e || window.event;

    return '';
};

EDIT-------------------------------
sorry, it is now a form, it is simple button and a href:
I have one page that uses only a button:
<input type="button" value="Save" id="btn-crop" />

and a link:
Save

A: You should be able to check what object dispatched the event using e.currentTarget property and then show the prompt if necessary.

A: You could call [Event].stopPropagation in an callback of submit event for each button in the page.
This function would stop the callback function of the beforeunload event when would go submit the button.
You can read more about the [Event].stopPropagation
here.
Like so: Button.addEventListener("submit",function(Event){Event.stopPropagation()})


text:
Q: Asp.net MVC4 Dropwdownlist Retain Selected Value after Get I have a drop down list that is included in the _layout view of my application.
What i am trying to do is populate the list with Data from a sql server and then based on the value selected redirect the user to another view.
All is working fine except that when the user click Enter/Search the value of dropdownlist gets defaulted to the first value. As i am currently transitioning from Web Forms it's quite difficult and frustrating.
Here is the code for my Model
                 public class DomainNameViewModel
{
    private static readonly string ConStr = WebConfigurationManager.ConnectionStrings["App"].ConnectionString.ToString();

    public string SelectedDomainId { get; set; }

    public IEnumerable<SelectListItem> domains
    {
        get
        {

            List<SelectListItem> l = new List<SelectListItem>();
            using (SqlConnection con = new SqlConnection(ConStr))
            {
                SqlCommand com = new SqlCommand("spDomainList", con);
                con.Open();
                SqlDataReader sdr = com.ExecuteReader();
                while (sdr.Read())
                {
                    l.Add(new SelectListItem() { Text = sdr[0].ToString(), Value = sdr[1].ToString() });
                }

                return l;
            }

        }

The Code for controller.
     [ChildActionOnly]
    public ActionResult Index()
    {

        return PartialView(new DomainNameViewModel());
    }

The DomainName View
            @model app.Models.DomainNameViewModel

          @{
  Layout = null;
   }

          @Html.DropDownListFor(x => x.SelectedDomainId, Model.domains, new { @id   = "e1",@class = "bannerlist" })

And the code for _Layout view
                   @using (Html.BeginForm("Search","DomainSearch",FormMethod.Get))
    {
    @Html.TextBox("txtDomain", null, new { @class = "bannertextbox" , placeholder="Search for a Perfect Domain!" })
 @Html.Action("index","DomainName")
    <input type="submit" class="bannerbutton" value="Search" />
    }

Any help would be appreciated.
EDIT: Added the DomainSearchController code.
    public class DomainSearchController : Controller
{
    //
    // GET: /DomainSearch/

    public ActionResult Search(string txtDomain,string SelectedDomainId)
    {
        DomainNameViewModel Domain = new DomainNameViewModel();
        Domain.SelectedDomainId = SelectedDomainId;
       string check = Domain.ParseDomain(HttpUtility.HtmlEncode(txtDomain), HttpUtility.HtmlEncode(SelectedDomainId));

        string s = Domain.CheckDomains(check);
        ViewBag.Domain = Domain.DomainCheckResult(s);
        return View();
    }

}

A: You haven't quite shown/explained how exactly are you performing the redirect. But you will need to either pass the selected value in the query string to the target page or store in in a cookie or somewhere on the server like in the ASP.NET Session (beurk).
The reason you need to do this is because in ASP.NET MVC, contrary to classic WebForms there's no ViewState and you cannot retrieve the selected value on subsequent PostBack (there's neither such notion as PostBack in ASP.NET MVC).
Then in your child controller action you will need to retrieve the selected value from the query string or from the cookie or from the ASP.NET session (beurk) and set the SelectedDomainId property on your view model to this value.
For example:
[ChildActionOnly]
public ActionResult Index()
{
    var model = new DomainNameViewModel();
    // here you need to set the SelectedDomainId property on your view model
    // to which the dropdown is bound to the selected value
    model.SelectedDomainId = Request["domain_id"];
    return PartialView(model);
}

Assuming you decide to pass this value as query string parameter when redirecting you will need to keep this parameter on subsequent redirects in order to keep the state.


text:
Q: split array into two equal subarray where index is selected I need to return an index of the element where the sum of the elements on the left is equal to the sum of the elements on the right. e.g for the array [-3, 8, 3, 1, 1, 3], the return value is index 2 since the sum of the elements to the left of the first 3 ([-3, 8]) is the same as the sum of elements to its right ([1, 1, 3]).
So I started by doing a liner-search function to find the intended index,
then after that i attempted to split the array left and right of the selected index but had no success doing so
I haven't had much success getting it to work
//linear-search portion,x is the index selected to be split point
public static int findindex(int arr[], int x) {
//if array is null
if (arr == null) {
        return -1;
    }
//find array length
int len = arr.length;
int i = 0;
//traverse the array
while (i < len) {
//if the i-th element is is x then return the index
    if (arr[i] == x) {
        return i;
    } else {
        i = i + 1;
    }
}
//splint array portion,returns index if not possible
int leftsum = 0;
//treverse array elements
for (int i = 0; i < x; i++) {
//adds current elements to left
    leftsum += arr[i];
//find sum of remader the array elements to rightsum
    int rightsum = 0;
    for (int j = i + 1; j < x; J++)
        rightsum += arr[j];
//split pint index
    if (leftsum == rightsum)
        return i + 1;
}
//if not possible return
return -1;
}

// driver code
public static void main(String[] args) {
    int[] array1 = { -3, 8, 3, 1, 1, 3 };
    System.out.println(findindex(array1));
}

A: Your code has two problems. One is that the variable i is defined two times in the same method. Another problem is that you only provide one input parameter and not two. I don't even know what parameter x should be and therefore also removed it from my improved version. I also removed the while loop as I don't understand what you tried to do there. Anyways here is my version of the code:
public static int findindex(int arr[]) {
    if (arr == null) {
        return -1;
    }

    int len = arr.length;
    int leftsum = 0;
    for(int i = 0; i < len; i++)
    {
        leftsum += arr[i];
        int rightsum = 0;
        for(int j = i+2; j < len; j++)
            rightsum += arr[j];
        if(leftsum == rightsum)
            return i+1;
    }
    return -1;
}

public static void main(String[] args) {
    int[] array1 = {-3, 8, 3, 1, 1, 3};
    System.out.println(findindex(array1));
}

When I removed everything unneccessary from your code the only bug was that you should have initialized j with i+2, because you don't want to include the element at the index itself and only the right side, if I understood the requirements of your code correctly.

A: You can use the below code for solve the problem
static void Main(string[] args)
        {
            int[] array1 = {-3, 8, 3, 1, 1, 3}; // { -3, 8, 3, 1, 1, 3, 6, 1, 19 };
            int indexPosition = GetIndex(array1);
            if (indexPosition != -1)
            {
                Console.WriteLine(indexPosition);
            }
        }

        static int GetIndex(int[] param)
        {
            if (param.Length < 0) return -1;
            int leftSum = 0, rightSum = 0; int rightIndex = param.Length - 1;
            for (int i = 0; i < param.Length; i++)
            {
                if (i < rightIndex)
                {
                    if (leftSum > rightSum)
                    {
                        rightSum += param[rightIndex];
                        rightIndex -= 1;
                    }
                    else
                    {
                        if (i < rightIndex)
                        {
                            leftSum += param[i];
                        }
                    }
                }
                else
                {
                    rightSum += param[rightIndex]; // if you are looking for only index position you can comment this line,
                    //variable rightSum and leftSum will give you the sum of left and right side of the array
                    rightIndex -= 1;
                    break;
                }
            }

            return rightIndex;
        }

Hope this helps .


text:
Q: Maven - AbsoluteLayout dependency I am trying to revive my old project. I want to use maven for it and I want to add AbsoluteLayout dependency. I am kinda new in maven so I have no idea what is  wrong. I have found that this should work:
<dependency>
<groupId>org.netbeans.external</groupId>
<artifactId>AbsoluteLayout</artifactId>
<version>RELEASE802</version>
</dependency>

but I only get this error:
Failed to execute goal on project XXX: Could not resolve dependencies for project xx.xxxx:XXX:jar:1.0-SNAPSHOT: Failure to find org.netbeans.external:AbsoluteLayout:jar:RELEASE802 in http://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced -> [Help 1]

After this I manually added this dependency from my netbeans folder in my computer. And it is working. Is there another way how to add this dependency? I would like to include it in my pom file. Any ideas?

A: You need to add a Netbeans repository to your POM:
<repositories>
    <repository>
      <id>netbeans</id>
      <name>Netbeans rep</name>
      <url>http://bits.netbeans.org/maven2/</url>
    </repository>
</repositories>

A: I added the below dependency block to my POM and after updating my maven indices it worked just fine.
<!-- https://mvnrepository.com/artifact/org.netbeans.external/AbsoluteLayout -->
<dependency>
    <groupId>org.netbeans.external</groupId>
    <artifactId>AbsoluteLayout</artifactId>
    <version>RELEASE802</version>
</dependency>

So you might want to try updating your maven indices and see if that does it for you. This dependency block came directly from mvnrepository.com/, and worked without me needing to add any special repo as far as I'm aware.

A: Look like that dependency is not exists in the public repository, you can register an account and upload it, or, from my view point is better, you can setup your own private maven repository server, there many software support to do this, for example JFrog Artifactory, it is easy to install and manipulate.


text:
Q: Подвисает цикл while в скрипте при выполнении условий - не могу понять причину Есть блок с календарем, где внутри тега

April 2019

выводится месяц  и год (подтягивается с объекта Date) начиная с текущего.
Кнопка с классом .dopbsp-next-btn сдвигает календарь на месяц вперед (May 2019, June 2019), все стандартно.
Я хочу настроить чекбокс id autumn-check таким образом, чтобы сдвиг был на осенний месяц.
Условие if выполняется, но while почему-то подвисает, в консоли выводится зацикленный текущий месяц, а кнопка .dopbsp-next-btn не работает.
В чем проблема и как исправить?
Код:

$("#autumn-check").click(function() {
  if ($(this).is(':checked')) {
    var month = $(".dopbsp-month-year").text().split(' ')[0];
    if (month !== "September" || month !== "October" || month !== "November") {
      while (month !== "September" || month !== "October" || month !== "November") {
        $(".dopbsp-next-btn").click();
        month = $(".dopbsp-month-year").text().split(' ')[0];
        console.log(month); // April
      }
    } else {
      console.log("Not Autumn");
    }
  }
});

<input type="checkbox" id="autumn-check" name="autumn">Autumn

April 2019

Next month

Обработчик $(".dopbsp-next-btn").click();
function() {
  methods_calendar.init(methods_calendar.vars.startYear,
    methods_calendar.vars.currMonth + 1);
  $('.DOPBSPCalendar-navigation .dopbsp-previous-btn', Container).css('display', 'block');
}

UPD Пробую сделать через setInterval(), но после первой итерации сразу выходит
var checkAutumn = setInterval(function() {
  if (month !== "September" || month !== "October" || month !== "November") {
    $(".dopbsp-next-btn").click();
    month = $(".dopbsp-month-year").text().split(' ')[0];
    console.log(month);
    clearInterval(checkAutumn);
  }
}, 100);

A: while выполняется синхронно - поэтому, если значение в условии выхода из цикла изменяется асинхронно, то нет шансов на то что это изменение данных произойдет: в таком случае, цикл будет крутиться бесконечно (или, до тех пор пока интерпретатор не прибьет скрипт).
Под спойлером пример асинхронного цикла с проверкой.

$('#autumn-check-async').click(function () {
  console.clear();
  if (!this.checked) return;
  const months = ['September', 'October', 'November'],
        dateEl = $('.dopbsp-month-year').first(),
        btnEls = $('.dopbsp-next-btn');
  const getMonth = () => dateEl.text().split(/\s+/)[0];
  let month = getMonth();
  if (months.includes(month)) {
    console.log('Autumn');
    return;
  }
  console.log('Not Autumn...');
  btnEls.click();
  const interval = setInterval(() => {
    const nextMonth = getMonth();
    if (nextMonth === month) return;
    if (months.includes(nextMonth)) {
      clearInterval(interval);
      console.log('Autumn');
      return;
    }
    month = nextMonth;
    btnEls.click();
  }, 0);
});

$('.dopbsp-next-btn').click(function (e) {
  const date = new Date($('.dopbsp-month-year').first().text());
  date.setMonth(date.getMonth() + 1);
  $('.dopbsp-month-year').text(
    date.toLocaleString('en-us', { month: 'long', year: 'numeric' })
  );
});

  <input type="checkbox" id="autumn-check-async">
  Autumn (async)

April 2019

    Next month

Но гораздо проще будет использовать общий обработчик события, и выполнять изменение данных до их вывода в DOM (то есть, сначала считаем, и только затем выводим).
Это хорошая практика не только в простейших случаях, как здесь с датой, а в общем и целом - ведь чем сложнее и больше становится скрипт/веб-приложение, тем значительнее задержки из-за "лишних" промежуточных обращений к DOM.
Короче, вот пример:

$('#autumn-check, .dopbsp-next-btn').click(nextMonth);

function nextMonth(e) {
  const date = new Date($('.dopbsp-month-year').first().text());
  let month = incMonth(date);
  if (e.target.id === 'autumn-check') {
    while ((month < 8) || (month > 10))
      month = incMonth(date);
  }
  $('.dopbsp-month-year').text(
    date.toLocaleString('en-us', { month: 'long', year: 'numeric' })
  );
}

function incMonth(date) {
  let month = date.getMonth() + 1;
  date.setMonth(month);
  return month;
}

  <input type="checkbox" id="autumn-check" name="autumn">
  Autumn

April 2019

    Next month

Во втором примере, проверка состояния чекбокса для демонстрации принципа не требуется (и думаю что с добавлением такой проверки, сложностей не возникнет).

A: А ни кто не заметил условия цикла, да?
while (month !== "September" || month !== "October" || month !== "November")

Ну, я тоже хорош.
while (month !== "September" && month !== "October" && month !== "November")

А это вообще убрать можно
if (month !== "September" || month !== "October" || month !== "November") {


text:
Q: Adding multiple character count with multiple limits on same page There is an issue adding multiple character counts on a single page. How would I allow for multiple limits without using multiple lines of the same script?
https://jsfiddle.net/r7c3754j/1/
var text_max = 80;
$('#character_count').html(text_max + ' remaining');

$('#text_area').keyup(function() {
  var text_length = $('#text_area').val().length;
  var text_remaining = text_max - text_length;

  $('#character_count').html(text_remaining + ' remaining');
});


text:
Q: Antlr backtrack option not working I am not sure but I think the Antlr backtrack option is not working properly or something...
Here is my grammar:
grammar Test;
options {
  backtrack=true;
  memoize=true;
}

prog:   (code)+;

code
    :   ABC {System.out.println("ABC");}
    |   OTHER {System.out.println("OTHER");}
    ;

ABC : 'ABC';
OTHER : .;

If the input stream is "ABC" then I'll see ABC printed.
If the input stream is "ACD" then I'll see 3 times OTHER printed.
But if the input stream is "ABD" then I'll see
line 1:2 mismatched character 'D' expecting 'C'
line 1:3 required (...)+ loop did not match anything at input ''
but I expect to see three times OTHER, since the input should match the second rule if the first rule fails.
That doesn't make any sense. Why the parser didn't backtrack when it sees that the last character was not 'C'? However, it was ok with "ACD."
Could someone please help me solve this issue???
Thanks for your time!!!

A: The option backtrack=true applies to parser rules only, not lexer rules.
EDIT
The only work-around I am aware of, is by letting "AB" followed by some other char other than "C" be matched in the same ABC rule and then manually emitting other tokens.
A demo:
grammar Test;

@lexer::members {
  List<Token> tokens = new ArrayList<Token>();

  public void emit(int type, String text) {
    state.token = new CommonToken(type, text);
    tokens.add(state.token);
  }

  public Token nextToken() {
    super.nextToken();
    if(tokens.size() == 0) {
      return Token.EOF_TOKEN;
    }
    return tokens.remove(0);
  }
}

prog
  :  code+
  ;

code
  :   ABC   {System.out.println("ABC");}
  |   OTHER {System.out.println("OTHER");}
  ;

ABC
  :  'ABC'
  |  'AB' t=~'C'
     {
       emit(OTHER, "A");
       emit(OTHER, "B");
       emit(OTHER, String.valueOf((char)$t));
     }
  ;

OTHER
  :  .
  ;

A: Another solution. this might be a simpler solution though. i made use of "syntactic predicates".
grammar ABC;

@lexer::header {package org.inanme.antlr;}
@parser::header {package org.inanme.antlr;}

prog: (code)+ EOF;
code: ABC {System.out.println($ABC.text);}
    | OTHER {System.out.println($OTHER.text);};

ABC : ('ABC') => 'ABC' | 'A';
OTHER : .;


text:
Q: Oracle: Split html string into multiple rows/columns? I have a table in Oracle where some rows have a column with embedded HTML string. I'd like to know the SQL required so that I can split the string into multiple fields/rows. The table example looks like this:

ID
HTML_Content

1

Where would you like to go today?

Customer Service

Technical Service

Human Resources

I'd like the output to look like:

ID
Data_Jump
Content

1
1234567
Customer Service

1
2134583
Technical Service

1
8881234
Human Resources

Thank you!

A: If you can guarantee that the HTMl can be parsed as XML ( all enclosing tags have and end tag), then you can do something like this:
with test_data as
( select
xmltype('
Where would you like to go today?

Customer Service

Technical Service

Human Resources

') vals
from dual)
select x.* from test_data,
 XMLTABLE ('//li'
                    PASSING vals
                    COLUMNS
                      data_jump VARCHAR2(30) PATH 'a/@data-jump',
                      content   varchar2(500) PATH '*'
                    ) x


text:
Q: Flask Arabic Translation using Babel not working I am using Flask-Babel to provide i18n to my flask app.
The 2 languages used are Arabic and French, French being the default one.
I tried testing some translations before starting the work and I noticed this issue:
Here is how I'm getting my locale:
@babel.localeselector
def getLocale():
    return 'fr' # hardcoding it just for testing, after this I'll use babel best_match function

This is my test:
dt = datetime(2022, 8, 22, 12, 33)
tr_date = format_date(dt)

When the getLocale is in French, it works fine and prints: 22 août 2022
When the getLocale is in English, it works fine and prints: Aug 22, 2022
But,
When the getLocale is in Arabic, it prints this: 22/08/2022 instead of something like:
2022, أغسطس  ,22


text:
Q: UWP Calendar Date Picker and Time Picker binding to one date time I am trying to get a calender date picker and time picker binded (MVVM Light x:Bind) to one datetime object but im just getting frustrated as nothing I try is working.  I've tried using converters which convert the datetime to datetimeoffset for the calender date property (This works) but the time picker seems to infinitly keep calling its converter which returns the timespan on the datetime?
I know it will be something stupid and really simple but im just getting frustrated with UWP and how the simplest of things takes an age to work out because lack of documentation.
Is there a simple sample of this type of control or nuget package i can be pointed to so I can view it and get my head around?

A: Looks like x:Bind is the source of my problems, changing to Binding seems to fix all my issues


text:
Q: How to Send custom google Analytics event when user kills the application in Android I need to send google Analytics custom even when the user kills the application.

*

*I tried Service.onTaskRemoved() but could not preserve Analytics object till this is called

*I tried to send the event when the app goes to the background on pressing the back button, but this does not really solve the problem because I cannot track when the application goes to the background on pressing the home button.


text:
Q: Forensic Incident Response, How-To Guide/Process I'm searching for a really good source and/or book on how one responds to a computer intrusion.  I've come across many books that touch on the subject, illustrating tools and techniques to acquire forensic artifacts, but I'm searching for a how-to guide/process.
For instance, you read ... first verify that an incident has actually occurred before beginning the IR response.  What exactly do I do in this circumstance?  I'm left w/lots of choices.  Do I conduct a netstat to see if an offending IP address is presently on the box, do I evaluate the file system to see if I can find suspicious files, etc.  And of course each of these decisions has a residual effect of the data, which you'd have to explain later.  Secondarily, how do you address circumstances where many computers in a large network are affected.  If you clean one, the others may still be out there and will re-infect.  I'm searching for a source that will answer these sorts of questions.
Could someone suggest a good source of info. for this?

A: The second part of your question asked about IR for identifying all hacked computers on a large network, to prevent reinfection.  FYI, here's a paper on that topic.  It's one of the earliest IR papers, but may be helpful:
"Intrusion-detection for incident-response, using a military battlefield-intelligence process"
http://seclab.cs.ucdavis.edu/papers/science.pdf

A: It sounds like you may be looking for standard-operating procedures (SOPs) for incident-response (IR), i.e., an IR cookbook.  From my experience, IR processes and techniques can vary a lot among organizations due to variations in assets protected, resources available, technical skill-level, etc.  Also, individual investigations can vary quite a bit due to types of attack, technology involved (e.g., systems and networking), security resources available, security monitoring (logs), etc.  All of this variation limits the opportunities for creating SOPs for IR.
For example, there's a great book on security monitoring from two Cisco authors.  I'd highly recommend it in general, but you may not have all the security resources and skills that they have.  What works well for them, may not be appropriate in your setting.
"Security Monitoring: Proven Methods for Incident Detection on Enterprise Networks"
http://www.amazon.com/Security-Monitoring-Incident-Detection-Enterprise/dp/0596518161
Anyway, all this to say, you if you're looking for an IR cookbook solution, it may be helpful to consider these limitations for IR SOPs.


text:
Q: html ignoring a required mat-select I have this mat-select and I need it to be required in order to enable the submit button. Problem is, the form ignores the select and enables even if nothing is selected. How can I solve this?
<mat-select required [(ngModel)]="serverEvent.categoria" name="categoria" [disabled]="this.isnew == false">
      <mat-option  *ngFor="let categoria of categoriaEvento" [value]="categoria.id">
        {{categoria.descrizione}}
      </mat-option>
    </mat-select>

This is the button (calendarEventForm states for the whole form):
 <button type="submit" class="btn btn-success" [disabled]="!calendarEventForm.valid"> Conferma </button>


text:
Q: Why is ReferenceError being thrown? I simply cannot see how eventCards is not initialized. Can someone show me?
ReferenceError: Cannot access uninitialized variable. Line 7:26
var eventCards = [
    'Do1',
    'Do2',
    'Do3',
    'Do4'
];
var eventDeck = new Deck(eventCards);

class Deck {
    constructor(cards) {
        this.cards = cards;
        this.deck = shuffle(cards);
    }

    shuffle(array) {
        ...
    }

    drawTopCard() {
        ...
    }
}

A: For class variables, you need to define the class before it's used. Just hoist the class definition to the top and it should be ok:
class Deck {
    constructor(cards) {
        this.cards = cards;
        this.deck = shuffle(cards);
    }

    shuffle(array) {
        ...
    }

    drawTopCard() {
        ...
    }
}

var eventCards = [
    'Do1',
    'Do2',
    'Do3',
    'Do4'
];
var eventDeck = new Deck(eventCards);

see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes


text:
Q: Parsing a ZonedDateTime around the Daylight saving transition fails I was testing the edge cases for my code and I ran into an unexpected effect with regards to parsing a ZonedDateTime in Java.
This parsing does not behave as I expect it in the Daylight savings transition from Summertime to Wintertime. This is the period where the clock moves back and in Europe this means that the LocalDateTime for that day has the 02:00-02:59 period twice.
Assume it is 02:30 that day then the distinction between the two local time occurrences of that time is the timezone: one is according to the "Summer time" and one is according to the "Winter time". The difference between these two Instants should be 1 hour.
So I parse these two distinct instances and then format them again to a String using the same DateTimeFormatter.
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS z");
System.out.println(fmt.format(ZonedDateTime.parse("2021-10-31 02:30:00.000 CET", fmt)));
System.out.println(fmt.format(ZonedDateTime.parse("2021-10-31 02:30:00.000 CEST", fmt)));

I expected to get the two input strings back but I get this instead:
2021-10-31 02:30:00.000 CEST
2021-10-31 02:30:00.000 CEST

So both are mapped to the same instant, which to me seems incorrect; they should be 1 hour apart.
To check I have done the same for the New York timezone and this gives the exact same effect:
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS z");
System.out.println(fmt.format(ZonedDateTime.parse("2021-11-07 01:30:00.000 EDT", fmt)));
System.out.println(fmt.format(ZonedDateTime.parse("2021-11-07 01:30:00.000 EST", fmt)));

gives
2021-11-07 01:30:00.000 EDT
2021-11-07 01:30:00.000 EDT

I have tried this on OpenJDK Java 1.8.0_292, 11.0.11 and 17.0.1 and all give the same output.
What am I doing wrong? What do I misunderstand?
Or have I stumbled upon a bug in Java?

Additional:
I ran into this problem when looping over epoch values and testing this round trip.
Instant instant = Instant.ofEpochMilli(1635643800000L);
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(instant, ZoneId.of("Europe/Amsterdam"));

DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS z");
String instantString =  fmt.format(zonedDateTime);

System.out.println(instantString);      // --> "2021-10-31 02:30:00.000 CET"
ZonedDateTime parsed = ZonedDateTime.parse(instantString, fmt);
System.out.println(fmt.format(parsed)); // --> "2021-10-31 02:30:00.000 CEST"
System.out.println(parsed.toInstant().toEpochMilli()); // --> 1635640200000 != 1635643800000

Te bug report I submitted was accepted and can be found here:
https://bugs.java.com/bugdatabase/view_bug.do?bug_id=JDK-8277049


text:
Q: C - array of pointers to struct, syntax I've got a struct A and an array of pointers to instances of that struct
I'm trying to access a member directly from the array but I don't know what's the right syntax to do it :
struct A
{
  int a;
  void** b;
}

A* p = (A*) malloc(sizeof(A));
p->b = (A**) malloc(sizeof(A*) * 3);

//
// something is done
//

int c;

A* test = p->b[0];
c = test->a;

Basically what I'm asking is how do I get rid of the intermediate A* test so I can assign the value of c in one line ?

A: Just do
int c = ((struct A*) (p->b[0]))->a;

Defining
struct A
{
  int a;
  struct A ** b;
}

this would do
int c = p->b[0]->a;

A: You can do :
c = ((A*) (p->b[0]))->a;