text:
Q: Why is firebase not receiving any data? I followed the instructions from the Firebase assistant for Realtime Database, but no data is sent. I connected the app to Firebase and the dependencies are set up correctly.
This is my code:
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

public class MainActivity extends AppCompatActivity {

    TextView text;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FirebaseDatabase database = FirebaseDatabase.getInstance();
        DatabaseReference myRef = database.getReference("message");

        myRef.setValue("Hello!");
        text = (TextView)findViewById(R.id.text);

        myRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // This method is called once with the initial value and again
                // whenever data at this location is updated.
                String value = dataSnapshot.getValue(String.class);
                Log.d("TAG", "Value is: " + value);
                text.setText(value);
            }

            @Override
            public void onCancelled(DatabaseError error) {
                // Failed to read value
                Log.w("TAG", "Failed to read value.", error.toException());
            }
        });
    }
}

The log works and in the console I get a "D/TAG: Value is: Hello!" but when I look in Firebase the database is empty. database
Those are the rules:
{
  "rules": {
    ".read": true,
    ".write": true
  }
}


text:
Q: EXC_BAD_ACCESS KERN_INVALID_ADDRESS for class method I am seeing EXC_BAD_ACCESS KERN_INVALID_ADDRESS for class method.
From what I understand, I should not be seeing this for class/static methods.
Am I missing something?
Stack Trace:

Thread : Crashed: com.apple.root.user-initiated-qos
0  libobjc.A.dylib                0x0000000196eac0b4 objc_retain + 20
1  $APP_NAME                     0x00000001002611a8 +[$CLASS_NAME $METHOD_NAME:] ($CLASS_NAME.m:590)
2  libdispatch.dylib              0x0000000197511994 _dispatch_call_block_and_release + 24
3  libdispatch.dylib              0x0000000197511954 _dispatch_client_callout + 16
4  libdispatch.dylib              0x000000019751e780 _dispatch_root_queue_drain + 1848
5  libdispatch.dylib              0x000000019751fc4c _dispatch_worker_thread3 + 108
6  libsystem_pthread.dylib        0x00000001976f121c _pthread_wqthread + 816
7  libsystem_pthread.dylib        0x00000001976f0ee0 start_wqthread + 4

A: I have seen this crash a few times (with very similar, if not identical stack traces), and found that it had to do with a nonatomic property being set with a new object, while simultaneously being read.
That objc_retain +20 instruction turned out to be a call on the isa property of the object being read-- but at that point the object is already released and the isa pointer is changed to a bad address
I was able to debug my issue by following this blog post by Mike Ash:
https://www.mikeash.com/pyblog/tales-from-the-crash-mines-issue-1.html
I would highly recommend reading the entire thing through-- it involves using the disassembler to debug, but it was definitely a lifesaver for us on multiple occasions
EDIT: Note that I am definitely not even 50% sure that this is your issue, but I hope that my anecdotal experience could save you some time.  I know that I've spent many work weeks debugging issues that looked like this, but I still was never 100%

A: This crash happen because of dangling pointer.
For example, when variables or objects is trying to access an object that's already been de-allocated.
P.S: Most people might be confused about "memory leak" and "dangling pointer"
Dangling pointer occurs when a pointer references memory that has been de-allocated.
Memory Leak occurs when memory is still allocated but nothing references it.

A: EXC_BAD_ACCESS generally means that you are sending a objective C message to an invalid memory address.
It may cause:
1. An object that you want to use which has been deallocated.
2. When any variable or object is trying to access restricted memory. That means such crash occurs due to memory leak.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Create a small table for each dataframe in a list I have a list containing 20 datasets.
Each dataset is basically:
library(lubridate)

Date <- c("2010-01-28", "2010-01-28", "2010-02-28",
           "2010-02-28", "2010-02-28", "2010-02-28",
           "2010-01-28", "2010-01-28", "2010-02-28",
           "2010-02-28")

Date <- as_date(Date)

Country <- rep("Bolivia", 10)

Value_A <- 1:10

df <- data.frame(Date, Country, Value_A)

So I made a small table containing the last value, the last - 1, and last - 7.
Time <- c("Today", "Yesterday", "One week ago")
Value <- c(df$Value_A[nrow(df)], df$Value_A[nrow(df)-1], df$Value_A[nrow(df)-7])

table <- data.frame(Time, Value)

tibble(table)

   Time         Value
  <chr>        <int>
1 Today           10
2 Yesterday        9
3 One week ago     3

What I want is: do this same process, but automatically to each dataset in the list and store into another list.
Ps: All datasets have the same variables, only changing the country.

A: You could use lapply over your list (here called lst) of data frames and use a separate named function (or anonymous function as here):
lapply(lst, function(x) {
  nr <- nrow(x)
  data.frame(
    Time = c("Today", "Yesterday", "One week ago"),
    Value = c(x[["Value_A"]][nr], x[["Value_A"]][nr-1], x[["Value_A"]][nr-7])
  )
})

The result should be a list of data frames similar to what you have in your example. The Country is ignored as desired in the comments.


text:
Q: Django task to created objects in database systematically failed on the first record I use Django (2.2.5), Docker, celery and Postgresql database.
I have write a celery task that query database first, create a dataframe with results of the query and update_or_create objects in databases based on this dataframe.
code simplified
# load queries definition
    queries = dcf_queries_definitions() # this line query the database
    # print(queries)
    if not queries.empty:
        for index, row in queries.iterrows():
            # multiple call to api of another app to look for missing data
            # return **df** dataframe that will be used to create objects in database
        records = df.to_dict(orient='records')
        for record in records:
            try:
                DataCorrectionForm.objects.create(
                    dcf_ide=record['dcf_ide'],
                    category=record['category'],
                    crf=record['crf'],
                    crf_ide=record['crf_ide'],
                    patient=record['patient'],
                    record_date=record['record_date'],
                    field_name=record['field_name'],
                    field_label=record['field_label'],
                    message=record['message'],
                    field_value=record['field_value'],
                    dcf_status=record['dcf_status'],
                    query_id=record['query_id'],
                    deactivated=record['deactivated'],
                    comments=record['comments']
                )
            except Exception as e:
                print(record)
                print('Exception raised when trying to update object',e)
                continue

But I have a OperationalError that systematically raised on the first objects to be created or updated. The message in not very explicit for me.

OperationalError('server closed the connection unexpectedly\n\tThis
probably means the server terminated abnormally\n\tbefore or while
processing the request.\n')

I controlled data I try to insert in the model and there is no problem.
If I upload the same datas from a csv file to insert in my database, there is no problem.
I suspect problem with transaction between querying database and trying to insert in database in the same task.
If I try to create object with the create method (not update_or_create method) and captur the error, the error is connection already closed.
I initially open a post here but got no answer but analysis of the issue is now quite different.
I would appreciate some help and advice.


text:
Q: How do you append 2 subnames to a variable in R? It has to be possible but I can't find an answer (or think of the proper search terms).
Basically I'm stuck in a double loop and need to append 2 different subnames (1 for each separate iteration) to a variable.
Basic example:
var <- list()
i1 <- 0
i2 <- 0

while (i1 < 3) {
i1 <- i1 - 1

while (i2 < 3) {
i2 <- i2 - 1

var[[i1]][[i2]] <- c(1, 5, 8)
}
}

However, stringing two subnames together like that doesn't seem to work.  I'd like to get 9 results (based on 3x3 iterations) names as var11, var12, var13, var21, etc.
Thanks!

A: Seems like you need to initialize properly your i1 and i2 variables and increase them rather than decrease. Then, in the inner loop you initialize a sublist and assign that sublist to your var list. Try this:
    var <- list()
    i1 <- 0
    while (i1 < 3) {
      i2<-0
      i1 <- i1 + 1
      var2<-list()
      while (i2 < 3) {
        i2 <- i2 + 1
        var2[[i2]] <- sample(1:10,3)
      }
    var[[i1]]<-var2
    }

Another approach could be initialize your principal list and all the sublists:
    var<-vector("list",3)
    for (i in 1:3) var[[i]]<-vector("list",3)

At this point, you can assign values with the double subscript:
    var[[i]][[j]]<-c(1,5,8)

Assuming that both i and j ranging from 1 to 3,

A: In R, you can do this in a simple one liner, but I'll initialize some variables to be explicit about it.
i1start<-1
i1end<-3
i2start<-1
i2end<-3
result<-lapply(i1start:i1end, function(i1) lapply(i2start:i2end, function(i2) c(1,5,8)))

Which should return a list of lists, where each entry at position (i1,i2) is the vector (1,5,8).
Let's break this down.  It'd be useful if you look up lapply (via the command ?lapply) to brush up on the function.
If we were to just run the inner lapply, what would happen?
 lapply(i2start:i2end, function(i2) c(1,5,8))

#[[1]]
#[1] 1 5 8
#
#[[2]]
#[1] 1 5 8
#
#[[3]]
#[1] 1 5 8

lapply "applies" the vector 1,2,3 (i2start:i2end) to the function, which is essentially the following
#lapply does this
function(1) c(1,5,8)
function(2) c(1,5,8)
function(3) c(1,5,8)

and then stores all these results in a list (since it is l-apply)
We then use the same concept in the outer lapply call, except our function has changed.  It is no longer
 function(i) c(1,5,8)

but actually
 #substituting 1:3 for i2start:i2end
 function(i) lapply(1:3, function(i2) c(1,5,8))

so now we are calling
 lapply(1:3, function(i1) lapply(1:3, function(i2) c(1,5,8)))

which essentially calls
 function(1) lapply(1:3, function(i2) c(1,5,8))
 function(2) lapply(1:3, function(i2) c(1,5,8))
 function(3) lapply(1:3, function(i2) c(1,5,8))

and stores the results of those functions in a list.  Each of those function calls then run the inner function, which I explained just prior, and when you put it all together, it leads to your result!  A lot going on in one line


text:
Q: How to create users and store them in a database and link them to windows authentication logins What I want:
An intranet application where only people who are logged in can see the application... and an Admin and Member role.
1:
I have created an MVC 5.0 web application (for intranet).
It has a Home view with a home controller...
I have an Admin view with an admin controller.
The home page has a link (well it's not a link yet but whatever) on it that is conditional:
@if(User.IsInRole("Admin")){

Admin
 @*Will be link to admin controller action*@
}

I would like to create 1 user with role of "Admin" and allow him/her to then create new users (assigning them to Windows authentication logins) with a username and a new role of either "Admin" or "Member"...
2:
Next, I want to make it so that the users with Admin role can do all of the stuff denoted in my SQL database with the roles that be-fit them.
For example,
John only has read and write access to some of the tables ("Member")
But Jack and Jill have read and write access to all of the tables ("Admin").
John cannot see the Admin link on the Home view, but Jill can.
The Admin controller action is locked down to only allow users with "Admin" as the role, not "Member"...
The Core question (with 1 and 2 in mind):
I realise that there are two sets of authentication here, one for windows authentication for the application itself, and then one for the database, but I have a funny feeling they should be linked in some way. I have read quite a bit of material but am consistently confused with it, coming from a Web Form authentication skill set, It's my first intranet application... bit confused.
What I've done so far:
I have currently got Windows Authentication enabled, and I can successfully use the application and call upon:
@User.Identity.Name

to find out who I am...
Side Notes:
I would like to understand in what context the Authorize parameters are to be used eg.
[Authorize(Roles="Admin")]


text:
Q: How to inject code into Magento admin template I have to add a snippet of code to each of the following adminhtml templates:
shipment/create/form.phtml
shipment/view/form.phtml
creditmemo/create/form.phtml
creditmemo/view/form.phtml
invoice/create/form.phtml
invoice/view/form.phtml

So there are 6 templates in total and all will require a associated layout code to replace the template from default magento to my custom template.
All for the sake of adding a single line of code to echo something out.
Now, I cannot see it, but is there a way for me to add my code somehow to these templates but not have to replace the default magento templates with my customized version?

A: There is no need to change templates necessarily. Adminhtml rendering is the same as frontend rendering, including fallback. Specify a custom theme for the admin store in your module's config:
<config>
    <!-- ... -->
    <stores>
        <admin>
            <design>
                <theme>
                    <template>your_theme</template>
                    <!-- or <default>your_theme</default> -->
                </theme>
            </design>
        </admin>
    </stores>
</config>

You'll need a different approach if this will be a distributed module, or you'll need to advise customers using your extension of the custom template. This approach doesn't work prior to CE1.6.1.0 due to the Find_Feed module.
In that case, you can use layout update XML to change the templates which are used as you've described. This isn't ideal if a user is already using custom templates for these blocks - unlikely but possible. If worse comes to worse, you can always observe the core_block_abstract_to_html_after event as a last resort.


text:
Q: Angular momentum of a rolling cylinder about the point of contact
A cylinder of mass 5 kg and radius 10 cm is moving on a horizontal surface with velocity of centre of mass 5 m/s towards right and angular speed 10 rad/s (clockwise) . Find the angular momentum of the cylinder about the point of contact.

My approach: The angular velocity of the body about the point of contact will be 10 rad/s and the moment of inertia about the point will be 1.5 MR^2 . So angular momentum should be (moment of inertia)*(angular velocity)= 10 * 1.5 (5)(0.1)(0.1) giving 0.75 but the answer is 2.75 . I don't know where I have gone wrong.

A: You forgot to include angular momentum of center of mass.
Thus add $MR^2\omega$ to your answer By the way angular momentum is not $I\omega$, it is $\vec{l_{com}}+I_{com}\vec{\omega}$ It is $I_{contact}\omega$ only for cases when point of contact is the point of instantaneous or fixed axis of rotation.

A: There are a few things in your question that do not add up, a cylinder of radius $R = 0.1 \mathrm m$ rolling, I assume without slipping, at a velocity $v_{\mathrm C}= 5 \mathrm{ms^{-1}}$ has an angular velocity $$\omega = \frac{v_{\mathrm C}}{R} = \frac{5}{0.1}\mathrm{\frac{rad}{s}} = 50\mathrm{\frac{rad}{s}} \neq 10\mathrm{\frac{rad}{s}}$$
Let's assume that the velocity is correct and $\omega = 50\mathrm{\frac{rad}{s}}$. We know that the moment of inertia about the center $\mathrm C$ is:
 $$I_\mathrm{C}=\int_M r^2 \mathrm dm = \int_0^R r^2 \left(\frac{M}{R^2}((r+\mathrm dr)^2 - r^2)\right) = \frac{2M}{R^2}\int_0^Rr^3\mathrm dr=\frac{1}{2}MR^2$$
The Parallel Axis Theorem states that the moment of inertia about a parallel axis passing through $\mathrm P$ (point of contact) would be:
$$I_{\mathrm P} = I_{\mathrm C} + Md^2 = \frac{1}{2}MR^2 + MR^2 = \frac{3}{2}MR^2$$
This makes the angular momentum $L_{\mathrm P} = I_{\mathrm P}\omega =\frac{3}{2}MR^2\omega = 3.75$.


text:
Q: java.lang.IllegalStateException: No bean class specified on bean definition Trying to run a simple spring based program. I'm using spring-framework-3.0.5.
Not sure what is causing this error!!
spring.xml
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="user" name="com.spsam.UserPOJO">
        <property name="id" value="1351231"/>
        <property name="name" value="Ninam"/>
    </bean>
</beans>

Sample class:
public class Sample1 {
    public static void main(String[] args){
        ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        UserPOJO user = (UserPOJO) context.getBean("user");
        user.getUserDetails();
    }
}

Exception got :
Dec 12, 2013 6:59:08 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@744607b5: startup date [Thu Dec 12 18:59:08 IST 2013]; root of context hierarchy
Dec 12, 2013 6:59:08 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Dec 12, 2013 6:59:08 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@6e58f809: defining beans [user]; root of factory hierarchy
Dec 12, 2013 6:59:08 PM org.springframework.beans.factory.support.DefaultListableBeanFactory destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@6e58f809: defining beans [user]; root of factory hierarchy
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'user' defined in class path resource [spring.xml]: Instantiation of bean failed; nested exception is java.lang.IllegalStateException: No bean class specified on bean definition
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:965)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:911)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at com.spsam.Sample1.main(Sample1.java:18)
Caused by: java.lang.IllegalStateException: No bean class specified on bean definition
    at org.springframework.beans.factory.support.AbstractBeanDefinition.getBeanClass(AbstractBeanDefinition.java:372)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:52)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:958)
    ... 13 more
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

A: The documentation explains

A bean definition essentially is a recipe for creating one or more
  objects. The container looks at the recipe for a named bean when
  asked, and uses the configuration metadata encapsulated by that bean
  definition to create (or acquire) an actual object.
If you use XML-based configuration metadata, you specify the type (or
  class) of object that is to be instantiated in the class attribute of
  the  element. This class attribute, which internally is a
  Class property on a BeanDefinition instance, is usually mandatory.

Your bean definition is missing the class attribute. Add it
<bean id="user" name="com.spsam.UserPOJO" class="com.spsam.UserPOJO">
    <property name="id" value="1351231"/>
    <property name="name" value="Ninam"/>
</bean>

A: If you're using Spring MVC ResourceBundleViewResolver, and your view beans are not written right in view.properties you will get this error.
See this link to help verify your view beans are correct.
https://www.mkyong.com/spring-mvc/spring-mvc-resourcebundleviewresolver-example/


text:
Q: If else statement on ForegroundColor SwiftUI I wanted to do a simple if-else statement on a button
Button(action: {self.theSoal = nomor.id}) {
            Circle()
                .frame(width:80,height: 80, alignment:.center)
                .foregroundColor(.blue)
                .overlay(
                    Text("99")
                        .font(.title)
                        .fontWeight(.bold)
                        .foregroundColor(.white)

                )
        }

see that .blue, so I wanted to a conditional statement of if the button is clicked then the color change from .blue to .yellow
how do I do it?? well so far my options are using a state?
state color = "blue"

if the button is pushed then color = "yellow"

shortish, but it's not good and I need to add the color to my self
so is there a way to deal with it??
This is how the button looks like

A: Persist Color
If you want to change the color and you want it to continue with that color,

*

*First you need to define a State for the button

*Then you need to toggle the state inside the button's action

*And lastly, You make the color of the button conditional
struct ContentView: View {

    @State var isActive = false // <- Check this out

    var body: some View {

        Button {
            theSoal = nomor.id
            isActive.toggle() // <- Check this out
        } label: {
            Circle()
                .frame(width: 80, height: 80, alignment:.center)
                .foregroundColor(isActive ? .blue : .yellow) // <- Check this out
                .overlay(
                    Text("99")
                        .font(.title)
                        .fontWeight(.bold)
                        .foregroundColor(.white)
                )
        }
    }
}

Touch down color
If you want it to change color on touch-down and revert the color on touch-up then you need to define a custom style:
struct CustomButton: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .frame(width: 80, height: 80, alignment:.center)
            .font(Font.title.weight(.bold))
            .foregroundColor(.white)
            .background(configuration.isPressed ? Color.yellow : .blue) // <- Check this out
            .clipShape(Circle())
    }
}

And the usage code would be like:
struct ContentView: View {

    var body: some View {
        Button("99") { theSoal = nomor.id }
        .buttonStyle(CustomButton())
    }
}

Note that you can encapsulate your configuration inside the style


text:
Q: How to sort an Elasticsearch query result by a nested calculated field We are using Elasticsearch 7.9
Our index, called method_info_tree, contains two-level nested fields:

*

*The top level described a java method,

*the nested level below it describes a thread that ran the method,  and

*the third nested level within a thread describes the states of that thread over time.

Below is the mapping of the index in Elasticsearch:
{
  "mappings": {
    "properties": {
      "method_id" : {
        "type" : "long"
      },
      "threads": {
        "type": "nested",
        "properties": {
          "thread_id": {
            "type": "long"
          },
          "states": {
            "type": "nested",
            "properties": {
              "collect_time": {
                "type": "date"
              },
              "state": {
                "type": "keyword"
              },
              "elapsed_time": {
                "type" : "integer"
              }
            }
          }

        }
      }
    }
  }
}

Here is a sample document in the index:
{
  "took" : 13,
  "timed_out" : false,
  "_shards" : {
    "total" : 2,
    "successful" : 2,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 5198,
      "relation" : "eq"
    },
    "max_score" : 0.0,
    "hits" : [
      {
        "_index" : "method_info_tree-000001",
        "_type" : "_doc",
        "_id" : "WiHCCYQBhPdvF01n3kp1",
        "_score" : 0.0,
        "_routing" : "86163-d5c064d0-55a3-44b9-88fb-c44b7233cfa4",
        "_source" : {
          "timestamp" : 1666610993800,
          "method_id" : 140280075031760,

          "threads" : [
            {
              "thread_id" : 1,

              "states_hit" : [
                {
                  "state" : "RUNNABLE",
                  "collect_time" : 1666610994750,
                  "elapsed_time" : 50
                },
                {
                  "state" : "IO",
                  "collect_time" : 1666610994800,
                  "elapsed_time" : 50
                },
                {
                  "state" : "IO",
                  "collect_time" : 1666610994850,
                  "elapsed_time" : 50
                },
                {
                  "state" : "IO",
                  "collect_time" : 1666610994900,
                  "elapsed_time" : 50
                },
                {
                  "state" : "IO",
                  "collect_time" : 1666610994950,
                  "elapsed_time" : 50
                },
                {
                  "state" : "IO",
                  "collect_time" : 1666610995000,
                  "elapsed_time" : 50
                },
                {
                  "state" : "IO",
                  "collect_time" : 1666610995050,
                  "elapsed_time" : 50
                },
                {
                  "state" : "IO",
                  "collect_time" : 1666610995100,
                  "elapsed_time" : 50
                },
                {
                  "state" : "IO",
                  "collect_time" : 1666610995150,
                  "elapsed_time" : 50
                }
              ]

            }
          ]
        }
      }
    ]
  }
}

Note that for each method_id we have many documents for various thread_ids.
I would like, for each method_id, to calculate the sum of elapsed_time field per state (for all threads), something like:
method_id ->
    [
      {
        "state" : "IO",
        "elapsed_time" : 566622.0
      },
      {
        "state" : "RUNNABLE",
        "elapsed_time" : 566572.0
      },
      {
        "state" : "BLOCKED",
        "elapsed_time" : 50.0
      }
    ]

Below is my Elasticsearch query:
GET method_info_tree/_search
{
  "from": 0,
  "size": 0,
  "track_total_hits": true,
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "session_id": "86163-d5c064d0-55a3-44b9-88fb-c44b7233cfa4"
          }
        },
        {
          "nested": {
            "path": "threads.states_hit",
            "query": {
              "bool": {
                "filter": [
                  {
                    "range": {
                      "threads.states_hit.collect_time": {
                        "gte": 0,
                        "lte": 2000000000000
                      }
                    }
                  }
                ]
              }
            }
          }
        }
      ]
    }
  },
  "aggs": {
    "top_methods_agg": {
      "terms": {
        "field": "method_id",
        "size": 20
      },
      "aggs": {
        "elapsed_time_agg": {
          "nested": {
            "path": "threads.states_hit"
          },
          "aggs": {
            "states_range": {
              "range": {
                "field": "threads.states_hit.collect_time",
                "ranges": [
                  {
                    "from": 0,
                    "to": 2000000000001
                  }
                ]
              },
              "aggs": {
                "elapsed_time_per_state_agg": {
                  "terms": {
                    "field": "threads.states_hit.state",
                    "size": 10
                  },
                  "aggs": {
                    "elapsed_time": {
                      "sum": {
                        "field": "threads.states_hit.elapsed_time"
                      }
                    }
                  }
                },
                "total_self_elapsed_time": {
                  "sum": {
                    "field": "threads.states_hit.elapsed_time"
                  }
                },
                "wasted_elapsed_time": {
                  "filter": {
                    "terms": {
                      "threads.states_hit.state": [
                        "BLOCKED",
                        "IO"
                      ]
                    }
                  },
                  "aggs": {
                    "total_wasted": {
                      "sum": {
                        "field": "threads.states_hit.elapsed_time"
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

A sample result would be:
{
  "took" : 218,
  "timed_out" : false,
  "_shards" : {
    "total" : 2,
    "successful" : 2,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 5727,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [ ]
  },
  "aggregations" : {
    "top_methods_agg" : {
      "doc_count_error_upper_bound" : 1,
      "sum_other_doc_count" : 73,
      "buckets" : [
        {
          "key" : 140280074341584,
          "doc_count" : 728,
          "elapsed_time_agg" : {
            "doc_count" : 21838,
            "states_range" : {
              "buckets" : [
                {
                  "key" : "1970-01-01T00:00:00.000Z-2033-05-18T03:33:20.001Z",
                  "from" : 0.0,
                  "from_as_string" : "1970-01-01T00:00:00.000Z",
                  "to" : 2.000000000001E12,
                  "to_as_string" : "2033-05-18T03:33:20.001Z",
                  "doc_count" : 21838,
                  "total_self_elapsed_time" : {
                    "value" : 1133244.0
                  },
                  "wasted_elapsed_time" : {
                    "doc_count" : 1,
                    "total_wasted" : {
                      "value" : 50.0
                    }
                  },
                  "elapsed_time_per_state_agg" : {
                    "doc_count_error_upper_bound" : 0,
                    "sum_other_doc_count" : 0,
                    "buckets" : [
                      {
                        "key" : "IO",
                        "doc_count" : 10919,
                        "elapsed_time" : {
                          "value" : 566622.0
                        }
                      },
                      {
                        "key" : "RUNNABLE",
                        "doc_count" : 10918,
                        "elapsed_time" : {
                          "value" : 566572.0
                        }
                      },
                      {
                        "key" : "BLOCKED",
                        "doc_count" : 1,
                        "elapsed_time" : {
                          "value" : 50.0
                        }
                      }
                    ]
                  }
                }
              ]
            }
          }
        },
        {
          "key" : 140282650318928,
          "doc_count" : 3,
          "elapsed_time_agg" : {
            "doc_count" : 3,
            "states_range" : {
              "buckets" : [
                {
                  "key" : "1970-01-01T00:00:00.000Z-2033-05-18T03:33:20.001Z",
                  "from" : 0.0,
                  "from_as_string" : "1970-01-01T00:00:00.000Z",
                  "to" : 2.000000000001E12,
                  "to_as_string" : "2033-05-18T03:33:20.001Z",
                  "doc_count" : 3,
                  "total_self_elapsed_time" : {
                    "value" : 150.0
                  },
                  "wasted_elapsed_time" : {
                    "doc_count" : 0,
                    "total_wasted" : {
                      "value" : 0.0
                    }
                  },
                  "elapsed_time_per_state_agg" : {
                    "doc_count_error_upper_bound" : 0,
                    "sum_other_doc_count" : 0,
                    "buckets" : [
                      {
                        "key" : "RUNNABLE",
                        "doc_count" : 3,
                        "elapsed_time" : {
                          "value" : 150.0
                        }
                      }
                    ]
                  }
                }
              ]
            }
          }
        }
      ]
    }
  }
}

Note that I deleted some of the result buckets for better coherence of the example.
My problem:
I need to sort the results by 'total_self_elapsed_time'   and return only the top 5 results.
Since the result is nested, I cannot access the calculated field 'total_self_elapsed_time'.
Can you please direct me to how I can add to my query sorting by this aggregated field?

A: I have replaced states_range range aggregation with filter aggregation.
Range aggregation will generate buckets for each ranges specified. So you cannot sort terms based on sub multi buckets.
To sort I have used  "order" in terms aggregation.
Query
  "aggs": {
    "top_methods_agg": {
      "terms": {
        "field": "method_id",
        "size": 20,
        "order": {
          "elapsed_time_agg>states_range>total_self_elapsed_time": "asc"
        }
      },
      "aggs": {
        "elapsed_time_agg": {
          "nested": {
            "path": "threads.states_hit"
          },
          "aggs": {
            "states_range": {
              "filter": {
                "range": {
                  "threads.states_hit.collect_time": {
                    "gte": 0,
                    "lte": 2000000000000
                  }
                }
              },
              "aggs": {
                "elapsed_time_per_state_agg": {
                  "terms": {
                    "field": "threads.states_hit.state",
                    "size": 10
                  },
                  "aggs": {
                    "elapsed_time": {
                      "sum": {
                        "field": "threads.states_hit.elapsed_time"
                      }
                    }
                  }
                },
                "total_self_elapsed_time": {
                  "sum": {
                    "field": "threads.states_hit.elapsed_time"
                  }
                },
                "wasted_elapsed_time": {
                  "filter": {
                    "terms": {
                      "threads.states_hit.state": [
                        "BLOCKED",
                        "IO"
                      ]
                    }
                  },
                  "aggs": {
                    "total_wasted": {
                      "sum": {
                        "field": "threads.states_hit.elapsed_time"
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }

Try above , see if it works out for you.

A: For completeness sake, here's the query that works:
  "aggs": {
    "top_methods_agg": {
      "terms": {
        "field": "method_id",
        "size": 20
      },
      "aggs": {
        "elapsed_time_agg": {
          "nested": {
            "path": "threads.states_hit"
          },
          "aggs": {
            "states_range": {
              "filter": {
                "range": {
                  "threads.states_hit.collect_time": {
                    "gte": 0,
                    "lte": 2000000000000
                  }
                }
              },
              "aggs": {
                "elapsed_time_per_state_agg": {
                  "terms": {
                    "field": "threads.states_hit.state",
                    "size": 10
                  },
                  "aggs": {
                    "elapsed_time": {
                      "sum": {
                        "field": "threads.states_hit.elapsed_time"
                      }
                    }
                  }
                },
                "total_self_elapsed_time": {
                  "sum": {
                    "field": "threads.states_hit.elapsed_time"
                  }
                },
                "wasted_elapsed_time": {
                  "filter": {
                    "terms": {
                      "threads.states_hit.state": [
                        "BLOCKED",
                        "IO"
                      ]
                    }
                  },
                  "aggs": {
                    "total_wasted": {
                      "sum": {
                        "field": "threads.states_hit.elapsed_time"
                      }
                    }
                  }
                }
              }
            }
          }
        },
        "top_methods_sort": {
          "bucket_sort": {
            "sort": [
              {
                "elapsed_time_agg>states_range>total_self_elapsed_time": {
                  "order": "desc"
                }
              }
            ],
            "size": 5
          }
        }
      }
    }
  }

Many thanks!


text:
Q: Computer randomly loggin-out on ubuntu 13.04 This happens really randomly, usually while I am typing something. Any idea what it could be?
In case that can help, here's my logs from pastebinit ~/.xsession-errors http://paste.ubuntu.com/6144800/
EDIT happened again. Logs from System Logs/Xorg.0.log just after relogging :
http://paste.ubuntu.com/6155272/

A: Turns out installing the drivers from my builtin Intel graphic chip solved the problem. Instructions for installation can be found here : https://01.org/linuxgraphics/downloads/2013/intelr-linux-graphics-installer-version-1.0.2


text:
Q: Using variable from controller in an if statement I have a variable that is passed from the controller. It works fine when I just have it rendered as HTML however I am trying to use it in a PHP if statement and in this case it is saying that it doesn't exist.
@if ([[private_count]] != 0)

Content

@endif

I think it has to do with calling the [[]] shorthand within PHP but how else would  I be able to use it to compare?

A: Blades @if directive is just a wrapper around PHPs native if:
@if($private_count != 0)

Content

@endif

A: you can use simple php code also.
 <?php if(condition ){ ... }?>

It also works with .blade template


text:
Q: How to finish this job in emacs? The original string is like this:
  # chrom,name,strand,txStart

And the result should looks like this:
 # $1: chrom
 # $2: name
 # $3: strand
 # $4: txStart

Does anyone have idea of a quick way to do that?

A: Lots of ways.
You could use a search and replace making use of the \# counter in the replacement. That's zero-based, so you'd either need to add a dummy replacement at the front to use up the zero, or else use the elisp replacement expression \,(1+ \#) instead.
You could use a keyboard macro, and insert a counter with C-xC-kTAB or <f3>. You can seed that counter by supplying a prefix argument when you start recording.
On Emacs 24 you can number the lines of a marked region using a custom format string with C-uC-xrN, so your format string could be # $%1d:

A: Evaluate following code and execute foo function on input line.
(require 'cl)

(defun foo ()
  (interactive)
  (let* ((str (buffer-substring-no-properties
               (line-beginning-position) (line-end-position)))
         (words-str (and (string-match "# \\(.+\\)$" str)
                         (match-string 1 str)))
         (buf (get-buffer-create "*tmp*")))
    (unless words-str
      (error "Line should be '# word1,word2,...'"))
    (with-current-buffer buf
      (erase-buffer)
      (loop with index = 1
            for word in (split-string words-str ",")
            do
            (progn
              (insert (format "# $%d: %s\n" index word))
              (incf index)))
      (pop-to-buffer buf))))


text:
Q: Why I am getting `Endpoint request timed out` error when AWS SecretsManager is implemented? I am developing a REST API with AWS Lambda, API Gateway, RDS (MySQL). I am using Node.js.
This is my normal AWS Lambda code, calling database table to get the data and send it over the REST API.
const mysql = require('mysql');
const con = mysql.createConnection({
  host     : "****.****.****.rds.amazonaws.com",
  user     : "****",
  password : "****",
  port     : 3306,
  database : "****"
});

exports.getAllRoles = (event, context, callback) => {
  // allows for using callbacks as finish/error-handlers
  context.callbackWaitsForEmptyEventLoop = false;
  const sql = "select * from role";
  con.query(sql, function (err, result) {
    if (err) throw err;

    var response = {
        "statusCode": 200,
        "headers": {
            "Content-Type": "application/json"
        },
        "body": JSON.stringify(result),
        "isBase64Encoded": false
    };
    callback(null, response)
  });
};

This is the same code, but now with AWS SecretsManager
const mysql = require('mysql');

// Load the AWS SDK
var AWS = require('aws-sdk'),
    region = "us-east-1",
    secretName = "test-secret",
    secret,
    decodedBinarySecret;

// Create a Secrets Manager client
var client = new AWS.SecretsManager({
    region: region
});

exports.getAllRoles = (event, context, callback) => {

    client.getSecretValue({
        SecretId: secretName
    }, function (err, data) {
        if (err) {
            throw err;
        } else {
            // Decrypts secret using the associated KMS CMK.
            // Depending on whether the secret is a string or binary, one of these fields will be populated.
            if ('SecretString' in data) {
                secret = data.SecretString;
            } else {
                let buff = new Buffer(data.SecretBinary, 'base64');
                decodedBinarySecret = buff.toString('ascii');
            }
        }
        // Your code goes here.
        const secretObj = JSON.parse(secret);

        //Create MySQL Connection
        const con = mysql.createConnection({
            host     : secretObj.host,
            user     : secretObj.user,
            password : secretObj.password,
            port     : secretObj.port,
            database : secretObj.database
          });

        // allows for using callbacks as finish/error-handlers
        context.callbackWaitsForEmptyEventLoop = false;
        const sql = "select * from role";
        con.query(sql, function (err, result) {
            if (err) throw err;

            var response = {
                "statusCode": 200,
                "headers": {
                    "Content-Type": "application/json"
                },
                "body": JSON.stringify(result),
                "isBase64Encoded": false
            };
            callback(null, response)
        });
    });

};

This is my cloud formation file
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  aaaa-restapi

  Sample SAM Template for aaaa-restapi

# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
  Function:
    Timeout: 100
    VpcConfig:
        SecurityGroupIds:
          - sg-4424242424
        SubnetIds:
          - subnet-424242424242

Resources:

  GetAllRolesFunction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: aaaa-restapi/
      Handler: role-getall.getAllRoles
      Runtime: nodejs14.x
      Events:
        HelloWorld:
          Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
          Properties:
            Path: /role/getall
            Method: get

  LambdaRole:
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - 'sts:AssumeRole'
      Path: /
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
      Policies:
        - PolicyName: root
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action:
                  - ec2:DescribeNetworkInterfaces
                  - ec2:CreateNetworkInterface
                  - ec2:DeleteNetworkInterface
                  - ec2:DescribeInstances
                  - ec2:AttachNetworkInterface
                Resource: '*'

My code without the AWS SecretsManager is working fine when deployed.
However the code with AWS SecretsManager is giving timeout error when deployed and tested the API Call with POSTMAN. I just call
https://*****.****-api.****-1.amazonaws.com/Prod/role/getall
I just see "message": "Endpoint request timed out" and nothing else, even in the console. The same code is working fine when executed with sam invoke local GetAllRolesFunction. Also fine when tested with sam local start-api. The issue only arises when uploaded to AWS and the API Call is made.
What is happening here?

A: The error message "Endpoint request timed out" from API Gateway suggests that your API-invoked Lambda function  took longer than 29 seconds to complete.
I am going to guess that your Lambda function is running in a VPC and you have correctly set up network routing to your (private) RDS database but you don't have a network route to the Secrets Manager service endpoint, hence that request times out. If so, you'd need a VPC Endpoint for Secrets Manager or a NAT (or NAT Gateway) with routing to the public internet.


text:
Q: Change li class in jquery I want to change the class of the current li(list) which is selected
 $('li.doBlokkeer').click(function(e) {
 $(this).addClass('doDEBlokkeer').removeClass('doBlokkeer');
 });

 $('li.doDEBlokkeer').click(function(e) {
 $(this).addClass('doBlokkeer').removeClass('doDEBlokkeer');
 });

so if a current li is selected its class need to be changed (it needs to have doDEBlokkeer). The above code works..
The problem is that this only works once for each LI item..
when I click on li.doBlokkeer the class changes which is good, but when I press the same current li again, it calls the same function li.doBlokkeer instead of li.doDEBlokkeer function (despite the css class) . I tried so much stuff but i really can't find any solution. can you guys help me out? I have been searching for a solution for more then 14 hours, so frustrated right now...

A: Issue is that you are binding the event on the class selector (for the element existed in DOM at that time ) which gets changed dynamically so your binding is lost. You can consider using event delegation syntax or bind it to a different class/selector which doesn't change.
Using Event delegation (jq >=1.7) you can try:
$('ul').on('click', 'li.doBlokkeer', function(e) {
     $(this).addClass('doDEBlokkeer').removeClass('doBlokkeer');
 });

 $('ul').on('click', 'li.doDEBlokkeer', function(e) {
    $(this).addClass('doBlokkeer').removeClass('doDEBlokkeer');
 });

Another shortcut:
$('.cls').click(function (e) { // add a common class to all lis and bind the click event to that.
    var flg = $(this).is('.doBlokkeer'); //check if it is a specific class
    $(this).addClass(function () {
        return flg ? 'doDEBlokkeer' : 'doBlokkeer'; //based on flag return the other class
    }).removeClass(function () {
        return flg ? 'doBlokkeer' : 'doDEBlokkeer'; //based on flag return the other class
    });
});

or just:
$('.cls').click(function (e) {
    $(this).toggleClass('doDEBlokkeer').toggleClass('doBlokkeer');
});

Fiddle
Fiddle

A: Also, please consider this:
$('li').click(function()
{
    var $this = $(this),
        one = 'doBlokkeer',
        two = 'doDEBlokkeer';

    if ( $this.hasClass(one) ) {
        $this.removeClass(one).addClass(two);
    } else {
        $this.removeClass(two).addClass(one);
    }
});

A: Use .toggleClass
$('li.doBlokkeer').click(function(e) {
    $(this).toggleClass('doDEBlokkeer');
});

There is no need for the second click event

A: The issue is as explained earlier, that you bind the event to an element with the given class name, then, on click you change the class name, so the handler doesn't listen to it any more...
I would recommend to stick with event delegation because it's lighter and you can also nest elements in your lis (like a link or a div etc.):
First add the class 'cls'to your
, so
. Your HTML could the look like:

Click on me

Click on me

Click on me

Click on me

All you need for your javaScript is now:
$('.cls').on('click', '.doDEBlokkeer, .doBlokkeer', function (e) {
    $(this).toggleClass('doDEBlokkeer doBlokkeer');
});

...which requires jQuery 1.7. If you have only jQuery 1.4.2 and up you can use '.delegate()`
$('.cls').delegate('.doDEBlokkeer, .doBlokkeer', 'click', function (e) {
    $(this).toggleClass('doDEBlokkeer doBlokkeer');
});

The event (and only one) is now on the ul and the .on() pickes out the right elements defined by the class names you passed through.
I updated the fiddle from PSL


text:
Q: Replace span tag and &nbsp from html string I have a HTML code like this:
This is HTML.  This is    paragraph.

And I want to replace the span tag along with  .
My output would be like this:
This is HTML.This is    paragraph.

This is what I've tried:
myvar = "This is HTML.  This is    paragraph.";
newContent = myvar.replace(/<\/?span[^>]*>/g,"");

A: Just use replace several times. Since, unless you use a regex, it only replaces the first occurrence of something, you won't lose the extra  .

let initialString = 'This is HTML.  This is    paragraph.';
let finalString = initialString.replace('', '').replace('', '').replace(' ', '');


text:
Q: Weird GIT Issue : push Failing with HTTP error 502 I have been running into a very strange issue with a git repo where I am able to edit and update an existing file (css, html, js, xml) and do a normal push BUT if I add new files to the repo or REPLACE existing files, I get the following error when I would usually input my credentials on a successful push:
error: RPC failed; result=22, HTTP code = 502
fatal: The remote end hung up unexpectedly
fatal: The remote end hung up unexpectedly

I have read over the many posts on this issue and have run:
git config http.postBuffer 524288000

from the clone directory.
I am running: git version 1.8.3.2
$ git remote -v  outputs the following
origin http://[redacted]/git/TestProgram.git (fetch)
origin http://[redacted]/git/TestProgram.git (push)

On the server log, I see a Bad Gateway error but I KNOW that the git repo exists and is correct being that I'm able to clone it and update files - just not add or replace files in the clone.  I'm leaning towards this being a disk write permissions issue.  Has anyone run into anything similar - does this assessment sound valid?
Any ideas would be welcome, as I've been bashing my face off of this all week.

A: Even before getting to the end of your post, I was thinking "Disk permission issues".  In fact I'm fairly certain that your error message is precisely the message I received when faced withthe same issue, although it's been a long time since I've used git over http.


text:
Q: Angular generated filenames too long I'm building an Angular 10 enterprise app. When building with --prod we generate extremely long filenames containing tildes, such as
default~device-overview-device-overview-module~group-overview-group-overview-module~rule-overview-ru~1e39f90e.a0c2aafc27b60aa57fc0.js

This messes up our deployment system. Is there a way to get Angular to use shorter filenames?
(I'm not concerned about the cache-busting hashes - I need those).

A: Check the angular.json file, which configures the build process.
You can use the output hashing to configure the desired filename.
"production": {
  "outputHashing": "...",
  ...
}

*

*e.g. "media", will just give them incremental numbers, and results in the shortest names.

*e.g. "all" will give each file a unique hash code based on their content.

*e.g. You can also put it on "none" if you want them unmodified.

Alternatively, you can also enforce this from the CLI, but it's more convenient to just configure it once.


text:
Q: How to do a completely quiet 'make' , outputting only a log file? I have the following steps in a Docker build stage:
make shared > clbuild.log
export CRYPTLIB_BUILD_EXIT_CODE=$?
if [ ${CRYPTLIB_BUILD_EXIT_CODE} -ge 0 ]; then exit 1 ;fi

The warnings will still go to output with:
make shared > clbuild.log

How might i get make to log everything to 'clbuild.log' file, and not show any output at all, warnings or errors?
I wish to rather simply rely on exit code to indicate success or fail. (And abort and display the log only upon failure to build)

A: Programs always output to two streams, stdout and stderr, with IDs 1 and 2 respectively. You must tell you shell to dump stderr into stdout, with > ... 2>&1, or less verbosely, &>.
Anyway I think trying to mess with the build process is a loss of time


text:
Q: kafka connect distributed NOT_ENOUGH_REPLICAS error I'm setting up kafka s3 sink connector and everything works when I tried with connect-standalone.sh
Now I switched to connect-distributed.sh I ran into the following error:
WARN [Producer clientId=producer-3] Got error produce response with correlation id 40 on topic-partition connect-configs-0, retrying (2147483611 attempts le
ft). Error: NOT_ENOUGH_REPLICAS (org.apache.kafka.clients.producer.internals.Sender:637)

I tried to change
offset.storage.replication.factor=5
config.storage.replication.factor=5
status.storage.replication.factor=5

which is the actual number of replicas however this error does not go away.
I also tried to change all values to match the min.insync.replicas, it still does not work.
Topic: myTopic    PartitionCount: 12      ReplicationFactor: 5    Configs: compression.type=producer,***min.insync.replicas=2***,segment.bytes=1073741824,max.me
ssage.bytes=2097152,index.interval.bytes=4096,retention.bytes=-1,segment.index.bytes=10485760
        Topic: myTopic        Partition: 0    Leader: 43      Replicas: 43,11,9,42,10 Isr: 10,42,9,11,43
        Topic: myTopic        Partition: 1    Leader: 11      Replicas: 11,42,10,43,9 Isr: 10,42,9,11,43
        Topic: myTopic        Partition: 2    Leader: 9       Replicas: 9,42,10,43,11 Isr: 10,42,9,11,43
        Topic: myTopic        Partition: 3    Leader: 42      Replicas: 42,10,43,11,9 Isr: 10,42,9,11,43
        Topic: myTopic        Partition: 4    Leader: 10      Replicas: 10,43,11,9,42 Isr: 10,42,9,11,43
        Topic: myTopic        Partition: 5    Leader: 43      Replicas: 43,10,11,9,42 Isr: 10,42,9,11,43
        Topic: myTopic        Partition: 6    Leader: 11      Replicas: 11,43,9,42,10 Isr: 10,42,9,11,43
        Topic: myTopic        Partition: 7    Leader: 9       Replicas: 9,43,11,42,10 Isr: 10,42,9,11,43
        Topic: myTopic        Partition: 8    Leader: 42      Replicas: 42,11,9,10,43 Isr: 10,42,9,11,43
        Topic: myTopic        Partition: 9    Leader: 10      Replicas: 10,42,43,11,9 Isr: 10,42,9,11,43
        Topic: myTopic        Partition: 10   Leader: 43      Replicas: 43,11,9,42,10 Isr: 10,42,9,11,43
        Topic: myTopic        Partition: 11   Leader: 11      Replicas: 11,42,10,43,9 Isr: 10,42,9,11,43

root@9c4c4d97dcd6:/opt/bitnami/kafka/bin# grep replication.factor= /plugins/worker.properties
offset.storage.replication.factor=2
config.storage.replication.factor=2
status.storage.replication.factor=2

Is there anything I mis-configured?  Thanks

A: It seems that I simply need to recreate the following topics in kafka:
offset.storage.topic=connect-offsets-distriuted
config.storage.topic=connect-configs-distributed
status.storage.topic=connect-status-distributed

Please note that I added -distributed suffix.
I used to have
offset.storage.topic=connect-offsets
config.storage.topic=connect-configs
status.storage.topic=connect-status

which are left over from running connector-standalone.sh
These left over topics do not work with connector-distributed.
Also it needs to match with replicationfactor on server side.
Topic: connect-status-distributed       PartitionCount: 5       ReplicationFactor: 2    Configs: compression.type=producer,min.insync.replicas=2,cleanup.policy=compact,segment.bytes=10
73741824,max.message.bytes=2097152,index.interval.bytes=4096,retention.bytes=-1,segment.index.bytes=10485760
        Topic: connect-status-distributed       Partition: 0    Leader: 43      Replicas: 43,11 Isr: 43,11
        Topic: connect-status-distributed       Partition: 1    Leader: 11      Replicas: 11,42 Isr: 11,42
        Topic: connect-status-distributed       Partition: 2    Leader: 9       Replicas: 9,42  Isr: 9,42
        Topic: connect-status-distributed       Partition: 3    Leader: 42      Replicas: 42,10 Isr: 42,10
        Topic: connect-status-distributed       Partition: 4    Leader: 10      Replicas: 10,43 Isr: 10,43
Topic: connect-configs-distributed      PartitionCount: 1       ReplicationFactor: 2    Configs: compression.type=producer,min.insync.replicas=2,cleanup.policy=compact,segment.bytes=10
73741824,max.message.bytes=2097152,index.interval.bytes=4096,retention.bytes=-1,segment.index.bytes=10485760
        Topic: connect-configs-distributed      Partition: 0    Leader: 11      Replicas: 11,43 Isr: 11,43

A: In response to your answer / question

left over from running connector-standalone.sh

Standalone mode does not use those 3 topics, or properties. Therefore, it would never throw this error

tried to change all values to match the min.insync.replicas

Replication factor should ideally be greater than min ISR, at all times, for any topic. You can make it equal, but it's not necessary strictly to fix this error.

match with replicationfactor on server side

Unclear what this means. If the topics already exist, Distributed Connect will simply use them, as is, not try to recreate or validate the replication config matches the actual topics
I'd recommend at least a replication factor of 3 since you have more than 2 brokers


text:
Q: Java HTTPS Server: Mutual SSL Authentication I have developed a Java 7 HTTPS server (I use com.sun.net.httpserver.HttpsServer) for a SOAP web service (mostly influenced by this SO answer) with the difference that the server is set to need client authentication. This is the server's configuration code I use:
final InetSocketAddress address = new InetSocketAddress( localhost, 8888 );
this.httpsServer = HttpsServer.create( address, 0 );

// ... KeyStore configuration ...

// configure the HTTPS server
this.httpsServer.setHttpsConfigurator( new HttpsConfigurator( sslContext )
{
   @Override
   public void configure(final HttpsParameters params)
   {
      try
      {
         // initialize the SSL context
         final SSLContext c = SSLContext.getDefault();
         final SSLEngine engine = c.createSSLEngine();
         params.setNeedClientAuth( true );
         params.setCipherSuites( engine.getEnabledCipherSuites() );
         params.setProtocols( engine.getEnabledProtocols() );

         // get the default parameters
         final SSLParameters defaultSSLParameters = c.getDefaultSSLParameters();
         params.setSSLParameters( defaultSSLParameters );
      }
      catch ( final Exception e )
      {
         LOG.error( ExceptionUtils.getStackTrace( e ) );
      }
   }
} );

However, upon connections from clients I notice that client authentication is not enforced! I'm currently testing on localhost with self-signed certificates but it seems that any client is able to connect. I tested with SoapUI (which I have not configured to send any certificates to my knowlegde) as well as openssl in client mode with and without a certificate.
openssl s_client -cert client.pem -connect localhost:8888 -debug
openssl s_client -connect localhost:8888 -debug

I have already started the server with the java option -Djavax.net.debug=all but didn't see any relevant parts which indicate a client authentication or a request that the client shall present its certificate.
I see that clients validate the server's certificate indeed!
I want to reject any clients which do not present a valid certificate. How can I do this?

A: After very long searching I noticed that the configure(..) method of the HttpsConfigurator is wrong. I didn't set the SSLParameters correctly!
It should look like this:
@Override
public void configure(final HttpsParameters params)
{
   try
   {
      final SSLParameters sslParams = getSSLContext().getDefaultSSLParameters();
      final SSLEngine sslEngine = getSSLContext().createSSLEngine();
      sslParams.setNeedClientAuth( true );
      sslParams.setCipherSuites( sslEngine.getEnabledCipherSuites() );
      sslParams.setProtocols( sslEngine.getEnabledProtocols() );
      params.setSSLParameters( sslParams );
   }
   catch ( final Exception e )
   {
      LOG.error( ExceptionUtils.getStackTrace( e ) );
   }
}


text:
Q: Why weierstrass equation should not be used for elliptic curves over the field char=2? According to my source, this is because 'Weierstrass equation is singular', and it shows singularity by the point $(x_0,y_0)$, where $x_0$ is the root of $-3x^2-A$(maybe on a field extension), and $y_0$ satisfies $y_0^2=x_0^3+Ax+B$. He claims the derivatives $f_x(x_0,y_0)=f_y(x_0,y_0)=0$ by using char=2. \
But this still does not make sense to me, why we care about a derivate of point on a field extension? \
For derivates, my guess is that zero derivatives implies multiple roots, which weierstrass equation not allowed(but I also dont know why not). But as I said above, $(x_0,y_0)$ may be a point out of our initial field, why we care?

A: Actually, the problem is the discriminant. By definition, an elliptic curve
must have non-zero discriminant, otherwise it is degenerate. A clear
explanation of this with examples of finite fields by John D. Cook is at
All elliptic curves over fields of order 2 and 3. With the short Weierstrass form
$\,y^2 = x^3 + Ax + B\,$ there are no curves with non-zero discriminant
in a field of characteristic $2$.
The article by Cook makes an important point:

The two curves in the example of Lendstra and Pila are the only ones
over GF(2) with five points. So the two curves of order 5 over GF(2) are
$$y^2 + y = x^3 + x^2$$
$$y^2 + y = x^3 + x.$$
They determine the same set of points but are algebraically different.

He explains what this means with

Both determine the same set of points, but the two curves are algebraically different because $(0,0) + (0,0)$ equals $(1,1)$ on the first curve and $(1,0)$ on the second.

If the curve is degenerate, then you can't even define the addition of
points on the curve.


text:
Q: Angular JS img tag not working if I use scope Does anyone know why my code stops working in IE 11 when using  tag like this:
<img blabla ng-src="{{test.bla.path }}">

I printed out the test.bla.path and did this:
<img blabla ng-src=" and I copied the text that top scope returned in here ">

and it worked. O.O
The image displays but I do things with this image after it loads but this just seems to not work on IE 11 if I do it like I did in first example, cause it works on every other browser.


text:
Q: using the loop on a page I'm trying to display the excerpt of the most recent post and just the titles of the 4 previous posts before that at the top of a page and display the content of the page below. I have a solution that's close and works but not sure if I need to reset query and how to get excerpt on most recent post and title on 4 previous. Here's the page with post titles at top (B's recommended articles) and the content (that can be edited) of the page is underneath. Here's the code http://pastebin.com/41x30Uyb

A: To use template tags within a foreach loop outputting the results of get_posts, use the function setup_postdata() to populate the global $post with the data it needs. To style the first post differently, use a counter to keep track of which post you're outputting. After finishing output, use wp_reset_postdata() to restore the $post global. wp_reset_query is only necessary if you modify the global $wp_query.
$posts = get_posts( 'category=124&numberposts=5' );
$count = 1;
foreach( $posts as $post ) {
    setup_postdata($post);
    if( 1 == $count ){
        the_title();
    } else {
        the_excerpt();
    }
    $count++;
}
wp_reset_postdata();


text:
Q: Case in Map vs no Case If I have this code in Scala below:
val prices = Map("bread" -> 4.56, "eggs" -> 2.98, "butter" -> 4.35)
prices.map((k,v) => (k, v-1.1)).toMap

I get the error:
The expected type requires a one-argument function accepting a 2-Tuple.
Consider a pattern matching anonymous function, `{ case (k, v) =>  ... }`

But when I change the second line to:
prices.map{ case(k,v) => (k, v - 1.1) }.toMap

The above error goes away? Can someone please explain when would I need to use case in the map function?

A: As mentioned in @chrisaycock's comment, there is no auto-untupling in a regular map. You need to use it like this:
scala> val prices = Map("bread" -> 4.56, "eggs" -> 2.98, "butter" -> 4.35)
prices: scala.collection.immutable.Map[String,Double] = Map(bread -> 4.56, eggs -> 2.98, butter -> 4.35)

scala> prices.map(kv => (kv._1, kv._2-1.1)).toMap
res0: scala.collection.immutable.Map[String,Double] = Map(bread -> 3.4599999999999995, eggs -> 1.88, butter -> 3.2499999999999996)


text:
Q: faster index retrieval/slicing in python pandas I have a ORM set up in python with flyweights and underlying data stored in HDF5 files/pandas dataframes in memory. The exact mechanics aren't super important - but I'm finding that data retrieval by indexing in pandas DataFrames is quite slow. For example see the following:

For explanation FutDaily('ESA Index')._data returns a multiindex Pandas dataframe like the following:

which is extremely fast because of the flyweight design pattern. However, I'm surprised that the indexing takes so long. Is there a faster way to pull out relevant data/slices from a Multiindex? Is it not doing some sort of dictionary lookup under the hood - in which case it should be super fast?


text:
Q: Why does create-react-app initialize twice? I've initialize a react app using npx create-react-app:
import React from 'react';

class Expensive {
  constructor() {
    console.log('constructing expensive class');
  }
}

function App() {
  const expensiveRef = React.useRef(new Expensive());
  return (
    <div className="App">
      app
    </div>
  );
}

export default App;

However, I am seeing that constructing expensive class is printed to the console twice. Why is this?
I get the same result if I replace
const expensiveRef = React.useRef(new Expensive());
with
const [expensiveState, setExpensiveState] = React.useState(new Expensive());

A: Every code is executed on every render that's why it is logged multiple times, even useState will remember the first instance.
If you want it to be initialized only once, use that useState version like this
const [expensiveState, setExpensiveState] = React.useState(() => new Expensive());

So you pass function instead of object initialization
see https://reactjs.org/docs/hooks-reference.html#lazy-initial-state


text:
Q: Existence of properly discontinuous and cocompact action Let $M$ be a complete Riemannian manifold. My question is, under what conditions does $M$ admit a discrete group of isometries $\Gamma$ which acts properly discontinuously and cocompactly on $M$, that is, $M / \Gamma$ is a compact Riemannian manifold? If needed, one can assume that $M$ has negative (and even constant negative) curvature. This is mainly a reference request.

A: The question is phrased very generally, so I'm not sure if the following is what you're looking for.  However, my answer to Does any surface of constant curvature admit a cocompact group action? might be useful to you, since you are interested in the case of constant negative curvature. The result can be summarised as follows:

Theorem A: If $M$ is a 2-dimensional, complete, non-compact hyperbolic manifold and $\pi_1M$ is finitely generated then $M$ admits a discrete, cocompact group action only if $M$ is simply connected.

Since a complete, simply connected, hyperbolic manifold is isometric to the hyperbolic plane, this necessary condition is of course also sufficient.
In higher dimensions, comparable results are much more difficult and delicate.  For instance, using the tameness theorem of Agol and Calegari--Gabai, one can conclude the following:

Theorem B: If $M$ is a 3-dimensional, complete, non-compact hyperbolic manifold and $\pi_1M$ is finitely generated then $M$ admits a discrete, cocompact group action only if $M$ is simply connected or homotopy equivalent to a closed surface.

In this case, the necessary condition is no longer sufficient: for instance, the quotient of hyperbolic 3-space by a surface group preserving an isometrically embedded copy of the hyperbolic plane cannot admit a cocompact action.
Above dimension 3, very little is known. For instance, it is an open question whether or not a closed hyperbolic 4-manifold can have a normal surface subgroup. (Note that the above results follow from classification theorems for normal subgroups of hyperbolic manifold groups.) However, you might be interested in the following result, which can be deduced from deep work of Paulin and others:

Theorem C: Let $M$ be any non-compact manifold of negative sectional curvature. If $M$ is homotopy equivalent to a closed negatively curved manifold of dimension greater than 2 then $M$ does not admit a properly discontinuous, cocompact group action by isometries.

I'm happy to provide further details if these kinds of results are what you are looking for.


text:
Q: find p such that the series Find all value of $p$ such that $\sum_{n=1}^∞ (\frac{1}{n}$  - sin $\frac{1}{n})^p$ convergen
I get the answes for $p>2$ but I'm not sure this is all the solutions of this question

A: First of all, notice that
$$\lim_{n\to\infty}\cfrac{\frac1n-\sin\frac1n}{\frac1{n^3}}=\frac16$$
Thus, by limit comparison test, we need only to consider whether the following converges:
$$\sum_{n=1}^\infty\left(\frac1{n^3}\right)^p=\sum_{n=1}^\infty\frac1{n^{3p}}$$
And by p-series, it converges for $p>1/3$.


text:
Q: Передача параметра в функцию в C В функции main я создаю переменную и сканирую ее следующим образом:
char reg[10];
printf("Input car registration number:");
scanf("%s", reg);

Далее в функцию я передаю ее таким образом:
void viewSpecificNodes(char reg) {

Попробовала с reg c * и программа зависла. Мне кажется, проблема в том, что я неправильно передаю переменную, потому что программа не доходит до этой функции - void viewSpecificNodes(char reg)
Спасибо заранее!

A: Все работает. Может ошибка в другом месте?
#include <stdio.h>

void viewSpecificNodes(char *reg)
{
    printf("%s", reg);
}

int main(void)
{
    char reg[10];
    scanf("%s", reg);
    viewSpecificNodes(reg);
    return 0;
}

A: передается именно char *, иначе это передача ОДНОГО символа. Это раз. Во вторых, может быть передано большее кол-во байт чем в reg. Т.е следует использовать в scanf модификатор
scanf("%10s", reg);


text:
Q: How do teachers get grades in scorm package based test? Is it manual or they get that automatically? What happens if there are more than 1 set of assignment for each subject?

A: The SCORM package will generate one or more scores NOT grades, they are merely measures on a scale. It is up to the "LMS", presumably in your case Moodle, to interpret a score on a course, section, objective, interaction, etc. into a "grade". What can be scored is dependent on the version of SCORM.
For Moodle this is most often done using a "Gradebook" plugin. How that plugin is configured is going to determine what types of grades are available, what scores are necessary to achieve a particular grade, how that grade is displayed, etc. See https://docs.moodle.org/33/en/Grades


text:
Q: Require SharePoint Multi-Edit Version Comments in MS Word My SharePoint library is set up not to force checkout as we want to multi-edit documents. However, after a document is edited, we want to be able to enter a brief summary of why/what was changed. I created a required custom column (Version Comments) which works great. I set the Word document up so that ' Document Properties - Server' show up below the ribbon.  This works great except when I open a document to edit from SharePoint, the previous version comments are still there, which doesn't force the user. Is there a way via VBA to clear that field when the word document opens so the user has to enter comments?
I tried:
ActiveDocument.CustomDocumentProperties("NameOfPropery") = "" ' clear
ActiveDocument.CustomDocumentProperties("NameOfPropery") = New Comment" ' change
But the property is neither custom nor built in.
Thanks in advance!


text:
Q: batchGet returns 0's when using multiple date ranges for particular account I am running into a problem with a batchGet query.  I am using the exact same batchGet query on two different GA accounts to query specific data for two date ranges, last month and last month a year ago.  When I run it on one account, I get data back.  However, when I run it on another account, I get nothing but 0's for every column/date range.
If I run two separate queries - one for the current date range, one for the previous date range - I get the data back just fine in both cases.  However, it'd be nice to not have to run two queries when it's possible to get away with one.  EDIT: Also, it appears that if I include a dimension in my query, the query returns just fine.  The only problem is with metric-less queries.
I think tbe problem it might have something to do with the fact that there is no GA data in the problematic GA account a year ago - thus maybe the fact that there was no data a year ago is somehow causing today's data to also be 0.  However, to test, I changed the second date range in my working GA account to ten years ago (to force it to return 0's) and I still get proper numbers back - correct numbers for the current date, 0's for the previous one.  So it appears there is some account-specific weirdness going on here.
Here is my request in JSON format:
{
   "reportRequests":[
      {
         "viewId":"_my_view_id_",
         "dateRanges":[
            {
               "endDate":"2017-10-31",
               "startDate":"2017-10-01"
            },
            {
               "endDate":"2016-10-31",
               "startDate":"2016-10-01"
            }
         ],
         "metrics":[
            {
               "alias":"users",
               "expression":"ga:users"
            },
            {
               "alias":"sessions",
               "expression":"ga:sessions"
            },
            {
               "alias":"averageSessionDuration",
               "expression":"ga:avgSessionDuration"
            },
            {
               "alias":"pageviews",
               "expression":"ga:pageviews"
            },
            {
               "alias":"avgTimeOnPage",
               "expression":"ga:avgTimeOnPage"
            },
            {
               "alias":"pageViewsPerSession",
               "expression":"ga:pageviewsPerSession"
            },
            {
               "alias":"percentNewSessions",
               "expression":"ga:percentNewSessions"
            },
            {
               "alias":"bounceRate",
               "expression":"ga:bounceRate"
            }
         ]
      }
   ]
}

I'm using the most up-to-date version of the PHP google/apiclient.

A: Are you using GA360 by chance?  I'm thinking you're hitting a sample threshold. Adding the dimension is forcing GA to use a full query, rather than hitting the pre-aggregated tables. That issue normally only happens for GA360 users so disregard if you're using GA free.
If it is GA360, and you're in fact getting hit with sampling, then you could continue to add your dimension without issue.


text:
Q: Why are there exclamation marks instead of the Shivering Isles Portal? I've just downloaded Shivering Isles on Oblivion Xbox 360. I can't wait to visit another realm! When I got the quest to investigate the secret portal, I traveled to the Bravil Stable and I saw a yellow blob up ahead. I went closer and then I saw this:

These yellow triangles with purple exclamation marks. That was where the portal was and now this! How do I fix these exclamation marks?

A: That's usually a sign of graphical error.  I suggest verifying that your download has no errors.

A: I have Oblivion for PC and that error means the Shivering Isles DLC is not loaded like other files (such as mods or Knights of the Nine). I've never played Oblivion on Xbox so I don' t know if it has a DLC load list or something similar.


text:
Q: Spree and rails - uninitialized constant ActiveSupport I have an issue with the command
rails g spree:install --user_class=Spree::User

I'm following the Spree guide from github : https://github.com/spree/spree
ans i have the error :
Uninitialize constant ActiveSupport::EventedFileUpdateChecker

I use ruby 2.3.0, rails 4.2.7.1 and Spree 3.0.10
Here my Gemfile:
gem 'rails'#, '~> 5.0.0', '>= 5.0.0.1'
gem 'pg', '~> 0.18'gem
gem 'puma', '~> 3.0'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.2'
gem 'jquery-rails'
gem 'turbolinks', '~> 5'
gem 'jbuilder', '~> 2.5'

group :development, :test do
  gem 'byebug', platform: :mri
end
group :development do
  gem 'web-console'
  gem 'listen', '~> 3.0.5'
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]
gem 'spree_gateway', '~> 3.0.0'
gem 'spree_auth_devise', '~> 3.0.0'
gem 'spree', '~> 3.0.10'

Any Idea ?

A: I think i found why it don't work. The project was created with rails 5.0.0.1 then i downgrade to 4.7.1 to be able to use spree.
Spree isn't compatible with rails 5 and some files are from the command line to create project on rails 5
I'm not sure at all but i guess i just can't use spree with this project. I must restart


text:
Q: How to create a non-relocatable symbol How can I create a non-relocatable symbol with recent (with PIC enabled) gcc?
I basically want to have the following C program printing NULL:
#include <stdio.h>

extern int mem_;

int main(void) {
  printf("%p\n", &mem_);
  return 0;
}

What I tried is a small assembler file:
    .data
    .globl  mem_
    .type mem_,@object
    .set mem_, 0

but this creates a relocatable symbol, which at runtime does not have the value 0.
Background: I am trying to get an old program running, which uses this trick to directly access (allocated) memory from Fortran as an array. Since the program has ≫10⁵ LOC, it would be not feasable to rewrite everything.
[edit] The GNU assembler manual documents an "absolute section" as
absolute section: Address 0 of this section is always "relocated" to runtime address 0. This is useful if you want to refer to an address that ld must not change when relocating. In this sense we speak of absolute addresses being "unrelocatable": they do not change during relocation.
This is probably what I would need here (right?), but I couldn't find a way enable this section. The .struct directive is documented to switch to the "absolute section"; however the following assembler does not work either:
    .globl  mem_
    .struct 0
mem_:

The symbol appears in this case as *ABS* with objdump:
$ objdump -t memc

memc:     file format elf64-x86-64
[...]
0000000000000540 g     F .text  000000000000002b              _start
0000000000201030 g       .bss   0000000000000000              __bss_start
000000000000064a g     F .text  000000000000003c              main
0000000000000000 g       *ABS*  0000000000000000              mem_
[...]

but it is still relocated.

A: You can put your symbol in a section "fixedloc" and specify the address at link time:
#include <stdio.h>
int mem_ __attribute__ ((section ("fixedloc")));

int main (void) {
        printf("%p\n", &mem_);
        return 0;
}

And compile/link it with
gcc -O2 mem.c -o mem -Wl,--section-start=fixedloc=0x1230000

$ nm mem
...
0000000001230000 D mem
...
$ ./mem
0x1230000

Note that it will not work with location 0 on recent linux kernels if /proc/sys/vm/mmap_min_addr is not set to 0 (default is 65536) and even then, the dynamic linker chokes on it. But other addresses work flawlessly.


text:
Q: Applying DataAnnotations (MVC3) I consume an API that has a full object set. I don't want to have to re-create an object model in the mvc3 code just to use the DataAnnotations.
Is there a way to use this feature with out a wrapper class? The objects have their own validation rules that I can reuse, but want to use the built in mvc framework to display the messages back.

A: You could use a metadata class as in the following example from this link though I guess you'd have to add the MetaDataType attribute programatically...
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace MvcApplication1.Models
{
    [MetadataType(typeof(MovieMetaData))]
    public partial class Movie
    {
    }

    public class MovieMetaData
    {
        [Required]
        public object Title { get; set; }

        [Required]
        [StringLength(5)]
        public object Director { get; set; }

        [DisplayName("Date Released")]
        [Required]
        public object DateReleased { get; set; }
    }

}

A: You can create a class which inherits from DataAnnotationsModelMetadataProvider, where you can consume your object set, and write out the items as DataAnnotations.  A brief example:
public class MyModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
    private MyEntities _db = new MyEntities();

    protected override ModelMetadata CreateMetadata(
        IEnumerable<Attribute> attributes,
        Type containerType,
        Func<object> modelAccessor,
        Type modelType,
        string propertyName)
    {
        var modelMetadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);

        // load object
        var objectSet = _db.ObjectSets.FirstOrDefault(x => x.PropertyName == propertyName);

        // check attributes
        if (objectSet.IsRequired)
            modelMetadata.IsRequired = true;

        return modelMetadata;
    }
}

Then, register your provider in Global.asax.cs in the Application_Start method, as follows:
        ModelMetadataProviders.Current = new MyModelMetadataProvider();

A: I never tried this. You can write a base class in MVC model that all API classes inherit. Implement IValidatableObject on that base class and use your existing validation rules. Using MetadataType, you will still have to rewrite the class with those fileds you need validation on.


text:
Q: php read line by line and retrieving data I have a list(data1.php) which contains data like below:
06/26/2015,33.51718,-81.71856,0.0,4001,15:39:57,39256,1,0.0,13.6,
06/26/2015,33.51721,-81.71858,0.0,4001,15:40:57,39256,1,0.0,13.7,
06/26/2015,33.51720,-81.71860,0.0,4001,15:41:57,39256,1,0.0,13.6,
06/26/2015,33.51719,-81.71858,0.0,4001,15:42:58,39256,1,0.0,13.7,
06/26/2015,33.51720,-81.71860,0.0,4001,15:43:58,39256,1,0.0,13.6,

I am trying to retrieve only the 2nd and 3rd data(lat and long). The out put file has results like below:
Lat:33.51718
Long:-81.71856
Lat:33.51720
Long:-81.71860
Lat:33.51720
Long:-81.71860

It is skipping every other line. Here is my code. Please help.
<?php
    $fn = fopen("data1.php",'r') or die("fail to open file");
    $fp = fopen('output.php', 'w') or die('fail to open output file');
    while($row = fgets($fn)) {
      echo fgets($fn). "

A: Your problem is right here:
 while($row = fgets($fn)) {
echo fgets($fn). "<br";

You read 1 line from the file and immediately after that you read and echo another line without actually processing it. Remove the echo and you should be fine

A: Try this one :
<?php
$fn = fopen("data1.php",'r') or die("fail to open file");

$fp = fopen('output.php', 'w') or die('fail to open output file');

$stop = "0";

while($row = fgets($fn)) {

$num = explode(",", $row);

$lat = $num[1];
$long =  $num[2];
if($stop == "1" or $stop == "2"){

echo "
Lat: {$lat}
";
echo "
Long: {$long}
";

fwrite($fp, "Lat:$lat\n");
fwrite($fp, "Long:$long\n");
}else{}

$stop++;
   }
fclose($fn);
fclose($fp);

  ?>


text:
Q: Proving circles that are indentical Here is a GRE problem
And the answer is B which is "Quantity B is greater". How do you prove that the three circles are identical given the area of the intersection of any two is the same, which is 15 here.

A: So, when two circles intersect, we know their area of overlap will be $15$. Also, we know the area of each circle is $40$.
Here we can do something clever: The bottom left shaded region is equal to the same shaped in the top right circle. That is, we know have area equal to a full circle minus a section of intersection. This place of intersection, however, has to be $15$ per the statement, and the area of a circle is $40$. So, $40-15=25$. Clearly, $25<30$..


text:
Q: How to stop string from replacing previous elements? I'm trying to run this program that reads an input of type str:int:int:int and then splits the values into their respective arrays. The problem is the string part keeps getting replaced everytime the function runs. This is my code:
 int main(){
        char *str[100];
        int stock[100][3],idp=0;

        while(idp<100){
          fgets(data,80,stdin);
          str[idp]=strtok(data,":");
          stock[idp][0]=atoi(strtok(NULL,":"));
          stock[idp][1]=atoi(strtok(NULL,":"));
          stock[idp][2]=atoi(strtok(NULL,":"));
          idp++;
        }
    return 0;
    }

After running the while() cycle 3 times with the inputs abc:3:4:5 abcde:1:5:6 def:5:6:7 i get the following values:
str[0]=def stock[0][0]=3 stock[0][1]=4 stock[0][2]=5
str[1]=def stock[1][0]=1 stock[1][1]=5 stock[1][2]=6
str[2]=def stock[2][0]=5 stock[2][1]=6 stock[2][2]=7

As you can see, while the values of the stock[][] array are getting stored correctly,all of the previous strings on the str[] array are getting replaced. I'd like to know how to stop this from happening. Thanks in advance.

A: In these statements
      fgets(data,80,stdin);
      str[idp]=strtok(data,":");

pointers str[idp] are always set to the address inside the same variable data. So what the variable stores in the current moment is what the pointers point to.
You have to make copies of the pointed strings.
That is you need to declare a two dimensional arrau of characters liek for example
char str[100][10];

and then write for example
strcpy( str[idp], strtok(data,":") );

A: You making shallow copies. You need real copies. One way is to make str a 2D array like char str[100][80]. Then instead of this
str[idp]=strtok(data,":");

do this
strcpy(str[idp], strtok(data,":"));

Also if your input is strictly that format you could use sscanf instead of atois and strcpy. Like this
sscanf(data, "%[^:]:%d:%d:%d", str[idp], &stock[idp][0], &stock[idp][1], &stock[idp][2]);

%[^:] will read in characters which not :.


text:
Q: PHP/Javascript Form Reset upon page entry or back I have a standard PHP form that has a series of checkboxes, radio, selects and text.  The form works fine and proceeds to a search results page.  My problem is that when you click Back browser in any browser the search page shows the previous selects.  How do I ensure that the back button displays the form as if its the first time the visitor visits the page?

A: You can reset form on window.onload or $(document).ready(for jQuery)
function formReset()
{
       document.getElementById("formId").reset();
}

A: you can do one thing.
Using jquery onReady function you can make form reset.
So, whenever user will press back button of browser page will be reload and onReady function your code for form reset will work.
$(document).ready(function() {
    $('#myform').get(0).reset();

});

A: You shouldn't reset it automatically. Provide a reset button.
The back button returns the user to the previous page, in the state he left it. This includes the settings of any form. I'm relying heavily on this feature, cannot count the times this back button saved me from loosing my efforts that went into a textbox for answering questions...
It's a different game if the user is on your result page and clicks a link that takes him to the search page again, but does not use the back button.


text:
Q: Cardinality of union of two families of finite sets Let $F=\{S_1,\dots,S_n\}$ be a family of finite sets and $G=\{T_1,\dots,T_m\}$ also be a family of finite sets. Define the union of $F$ and $G$ naturally as $F \cup G=\{S_1 \cup T_1, S_2 \cup T_1, \dots , S_n \cup T_1, \dots, S_1 \cup T_m, \dots, S_n \cup T_m\}$.
The maximum number of distinct elements in $F \cup G$ is $mn$, which occurs when all of the sets are disjoint. What is the minimum number of distinct elements in $F \cup G$?

A: The minimum is $1,$ which occurs when $S_i=\{1,2,3,\dots,n+m\}\setminus\{i\}$ for $i=1,2,3,\dots,n$ and $T_j=\{1,2,3,\dots,n+m\}\setminus\{n+j\}$ for $j=1,2,3,\dots,m;$ more generally, whenever the complements of all the sets are disjoint.


text:
Q: How to introduce a new existential condition from a witness in Coq? My question relates to how to construct an exist term in the set of conditions/hypotheses.
I have the following intermediate proof state:
X : Type
P : X -> Prop
H : (exists x : X, P x -> False) -> False
x : X
H0 : P x -> False
______________________________________(1/1)
P x

In my mind, I know that because of H0, x is a witness for (exists x : X, P x -> False), and I want to introduce a name:
w: (exists x : X, P x -> False)

based on the above reasoning and then use it with apply H in w to generate a False in the hypothesis, and finally inversion the False.
But I don't know what tactic/syntax to use to introduce the witness w above. The best I can reach so far is that Check (ex_intro _ (fun x => P x -> False)  x H0)). gives False.
Can someone explain how to introduce the existential condition, or an alternative way to finish the proof?
Thanks.
P.S. What I have for the whole theorem to prove is:
Theorem not_exists_dist :
  excluded_middle ->
  forall (X:Type) (P : X -> Prop),
    ~ (exists x, ~ P x) -> (forall x, P x).
Proof.
  unfold excluded_middle. unfold not.
  intros exm X P H x.

  destruct (exm (P x)).
    apply H0.
    Check (H (ex_intro _ (fun x => P x -> False)  x H0)).

A: You could use the assert tactic:
assert(w: exists x, P x -> False).

It will ask you to prove this statement in a new sub-goal, and will add w to your existing goal. For this kind of trivial proof, you can inline the proof directly:
assert(w: exists x, P x -> False) by (exists x; exact H0).

A: Here, since you already know how to construct a term of type False, you can add it to the context using pose proof. This gives:
pose proof (H (ex_intro (fun x => P x -> False)  x H0))

You can even directly destruct the term, which solves the goal.
destruct (H (ex_intro (fun x => P x -> False)  x H0))

Another way to finish your proof is to prove False. You can change the goal to False with tactics like exfalso or contradiction. With this approach, you can use hypotheses of the form _ -> False that are otherwise difficult to manipulate. For your proof, you can write:
exfalso. apply H. (* or directly, contradiction H *)
exists x. assumption.


text:
Q: Dynamic change the property name in typescript I would like to have a typing (No need implementation) which can help me to add some dynamic string in the class
For example:
class Dog() {
  bark: () => void
  eat: () => void
}
// But actually in runtime, bark is nobark; eat is noeat
// That's why I would like to have such type
inteface Husky extends addSomethingInClass(Dog, 'no') {}
// Husky.nobark && Husky.noeat can be autocompleted
inteface Corgi extends addSomethingInClass(Dog, 'go') {}
// Corgi.gobark && Corgi.goeat can be autocompleted

I wonder if it can be
Thanks for help


text:
Q: Multilevel study -- am I accounting for an effect twice? I am running a multilevel study, with the level setup of ObservationsOverTime/Headmaster/Schools/SchoolType
I want to predict headmaster job satisfaction levels, and one of my predictors is the level of funding the school receives. I believe that headmasters's job satisfaction depends not on the absolute level of funding, but on the difference of funding to the average school of the same type. Because he/she is likely to compare with similar others.
So my predictor is "funding_of_the_school - average_funding_of_same_school_type"
One thing I am wondering about now: Am I accounting twice for school type effects here? Does my inclusion of SchoolType effectively capture the average funding already?


text:
Q: Choosing two points from $[0,1]$ probability We are choosing two random points among section $[0,1]$. These create 3 sections. The sections lengths are different and called $x,y,z$. Show the sample space using $x,y$.
My solution:
$\displaystyle  \begin{array}{{>{\displaystyle}l}}
\Omega\ =\ \{< x,\ y,\ z> \ |\ 0\leqslant x< y< z\ |\ x+y+z\ =\ 1\}\\
=\ \{< x,\ y,\ z> \ |\ 0\leqslant x< y< z\ |\ z\ =\ 1-x-y\}\\
=\ \{< x,\ y,1-x-y> \ |\ 0\leqslant x< y< 1-x-y\}\\
=\ \{< x,\ y,\ 1-x-y> \ |\ 0\leqslant x< y< 1-x-y\}
\end{array}$
I don't know if it's right. They are now asking me to draw this graphically and I have no idea how to, which makes me think is might be wrong.

A: If you're asking about the sample space $\Omega$ of possibles triplets $(x,y,z)$ formed by the different lengths of the sections, you're almost right.
First of all, let's clarify that if you're considering ordering $x,y,z$ then it is because you're taking $x$ as the length of the shortest section, $z$ as the length of the largest section, and $y$ as the length of the left one. If you wanted to consider $x,y,z$ as the lengths of the first, second and third section respectively, then they wouldn't have to be ordered at all.
Having said that, your sample space seems almost ok. You can't get rid of the $z=1-x-y$ so easily, since there was hidden the condition $z\le1$, that we need to say $y\le1$. You can correct this simly writing $\Omega=\{(x,y,1-x-y)\mid0\le x<y<1-x-y\le1\}$.
I'd like to make a note: As were pointed out in the comments and you wrote yourself, $z$ is completely determined by $x$ and $y$ (in fact any of them is determined by the other two), so you don't need it as part of your triplet. It's not wrong, it's just superfluous, so you could do a sample space considering the possible pairs $(x,y)$ instead (with the same conditions $0\le x<y<1-x-y\le1$), and get rid of the extra information. It depends on what you want to construct.

A: Decided to post this as an answer so I can include a picture. I think its easier to start with the picture and then try to write out the sample space algebraically.
$z$ is totally determined by $x$ and $y$ so we can just focus on $x$ and $y$.
First, ignore equality conditions. The sample space is then the green area below:

Now, we need to remove the parts of this where any of $x$, $y$, and $z$ are equal. Each of these are lines in the plane. To find these, we use the fact that $x + y + z = 1$. For:
(1) $x=y$ the line is $y=x$
(2) $x=z$ it is $x + y + x = 1$ so $y = 1 - 2x$
(3) $y = z$ it is $x + y + y = 1$ so $y = (1 - x)/2$
We can draw these lines in red to show what is excluded:

If you want to write it out algebraically, you can do that like this:
$\Omega=\{<x, y>|x+1=1,x>0, y>0\}-\{<x, y>|y=x\}-\{<x, y>|y=1-2x\}-\{<x, y>|y=(1-x)/2\}$