text:
Q: Unable to get Android HamBurger in actionBar This is what my code looks like, my activity extends Activity.  I am having trouble getting the Hamburger menu icon as i get back arrow menu icon. which i dont want.
code in mainactivity:
    ActionBar actionBar = getActionBar();
    actionBar.setCustomView(R.layout.action_bar);
    actionBar.setDisplayShowCustomEnabled(true);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.left_drawer);
    menu_list = new ArrayAdapter<String>(this, R.layout.drawer_list,
            getResources().getStringArray(R.array.menu_options));
    mDrawerList.setAdapter(menu_list);
    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.drawable.ic_drawer ,R.string.app_name,  R.string.app_name);
    mDrawerLayout.setDrawerListener(mDrawerToggle);
    actionBar.setDisplayShowHomeEnabled(true);
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setHomeButtonEnabled(true);

code in action_bar.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="vertical"
android:background="#29ABE2" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="center_horizontal"
    android:gravity="center_vertical"
    android:textColor="#FFF"
    android:textSize="25dp"
    android:text="DataVision" />

</LinearLayout>

additional methods:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Pass the event to ActionBarDrawerToggle
    // If it returns true, then it has handled
    // the nav drawer indicator touch event
    if (mDrawerToggle.onOptionsItemSelected(item)) {
      return true;
    }

    // Handle your other action bar items...

    return super.onOptionsItemSelected(item);
}

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    mDrawerToggle.syncState();
}

A: You need to wrap your existing LinearLayout in a DrawerLayout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

then your LinearLayout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:orientation="vertical"
    android:background="#29ABE2" >

    <TextView
        android:id="@+id/textView1"
        etc.
           ...

</LinearLayout>

then the drawer:
<ListView android:id="@+id/left_drawer"
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:choiceMode="singleChoice"
    android:divider="@android:color/transparent"
    android:dividerHeight="0dp"
    android:background="#111"/>
</android.support.v4.widget.DrawerLayout>

see also: https://developer.android.com/training/implementing-navigation/nav-drawer.html


text:
Q: PACT: How to guard against consumer generating incorrect contracts We have two micro-services: Provider and Consumer, both are built independently. Consumer micro-service makes a mistake in how it consumes Provider service (for whatever reason) and as a result, incorrect pact is published to the Pact Broker.
Consumer service build is successful (and can go all the way to release!), but next Provider service build will fail for the wrong reason. So we end up with the broken Provider service build and a broken release of Consumer.
What is the best practice to guard against situations like this?
I was hoping that Pact Broker can trigger the Provider tests automatically when contracts are published and notify Consumers if they fail, but it doesn't seem to be the case.
Thanks!

A: This is the nature of consumer-driven contracts - the consumer gets a significant say in the API!
As a general rule, if the contract doesn't change, there is no need to run the Provider build, albeit there is currently no easy way to know this in the Broker (see feature request https://github.com/bethesque/pact_broker/issues/48).
As for solutions you could use one or more of the below strategies.
Effective use of code branches
It is of course very important that new assumptions on the contract be validated by the Provider before the Consumer can be safely released. Have branches tested against the Provider before you merge into master.
But most importantly - you must be collaborating closely with the Provider team!
Use source control to detect a modified contract:
If you also checked the master pact files into source control, your CI build could conditionally act - if the contract has changed, you must wait for a green provider build, if not you can safely deploy!
Store in separate repository
If you really want the provider to maintain control, you could store contracts in an intermediate repository or file location managed by the provider. I'd recommend this is a last resort as it negates much of the collaboration pact intends to facilitate.
Use Pact Broker Webhooks:

I  was hoping that Pact Broker can trigger the Provider tests automatically when contracts are published and notify Consumers if they fail, but it doesn't seem to be the case.

Yes, this is possible using web hooks on the Pact Broker. You could trigger a build on the Provider as soon as a new contract is submitted to the server.
You could envisage this step working with options 1 and 2.
See Using Pact where the Consumer team is different from the Provider team in our FAQ for more on this use case.

A: You're spot on, that is one of the current things lacking with the Pact workflow and it's something I've been meaning of working towards once a few other things align.
That being said, in the meantime, this isn't solving your current problem, so I'm going to suggest a potential workaround in your process.  Instead of running the test for the consumer, them passing, and then releasing it straight away, you could have the test run on the consumer, then wait for the provider test to come back green before releasing the consumer/provider together.  Another way would be to version your provider/consumer interactions (api versioning) so that you can release the consumer beforehand, but isn't "turned on" until the correct version of the provider is released.
None of these solutions are great and I wholeheartedly agree.  This is something that I'm quite passionate about and will be working on soon to fix the developer experience with pact broker and releasing the consumer/provider in a better fashion.
Any and all comments are welcome.  Cheers.

A: I think the problem might be caused by the fact that contracts are generated on the consumer side. It means that consumers can modify those contracts how they want. But in the end producer's build will suffer due to incorrect contracts generated by consumers.
Is there any way that contracts are defined by producer? As I think the producer is responsible for maintaining its own contracts. For instance, in case of Spring Cloud Contracts it is recommended to have contacts defined in producer sources (e.g. in the same git repo with producer source code) or in a separate scm repo that can be managed by producer and consumer together.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Make a Qmenu behave like Qaction in Pyqt5 I want to make a Qmenu such as File be triggered just a Qaction in Pyqt5.
I'm writing an application that needs to have only a Qmenu such as File for example, behave like Qaction, that is can be triggered..

A: Handle the aboutToShow() signal of QMenu.  In your handler, call your QAction's trigger() slot.
http://doc.qt.io/qt-5/qmenu.html#aboutToShow
http://doc.qt.io/qt-5/qaction.html#trigger


text:
Q: Сортировка списка python У меня есть список list_access из таких элементов
((name, description, str(number), row)).
Я пробовал сортировать этот список по полю number двумя способами:

*

*list_access.sort(key=lambda item: item[2])

*list_access.sort(key=itemgetter(2))
Но в обоих случаях список не сортируется и остается без изменений.
Подскажите пожалуйста - почему?

A: Сортировка по ключу:
list_access = [
    (('name', 'description', str(2), 1)),
    (('name', 'description', str(1), 2)),
    (('name', 'description', str(6), 3)),
    (('name', 'description', str(3), 4)),
]
print(list_access)

list_access.sort(key=lambda x: x[2])

print(list_access)

Результат:
[('name', 'description', '2', 1), ('name', 'description', '1', 2), ('name', 'description', '6', 3), ('name', 'description', '3', 4)]
[('name', 'description', '1', 2), ('name', 'description', '2', 1), ('name', 'description', '3', 4), ('name', 'description', '6', 3)]

PS.
Тут скобки лишние (('name', 'description', str(2), 1)), правильно так: ('name', 'description', str(2), 1). Такие лишние скобки не повлияют на код, но они мешают и легко из них случайно сделать кортеж, добавив запятую: (('name', 'description', str(2), 1),)


text:
Q: Implementing interfaces in C# .NET Consider the following interface
public interface ICustomData
{
    String CustomData { set; get; }
}

According to MSDN documentation, interfaces members are automatically public.
Lets say I now want to implement my interface:
public class CustomDataHandler : ICustomData
{
}

This would break at compile time, telling me that I have not implemented "CustomData"
This on the otherhand would work:
public class CustomDataHandler : ICustomData
{
    public String CustomData { set; get; }
}

My question is: If the member of the interface is automatically public, why MUST I declare the implementation in the class? If the interface declaration is syntactically identical to the class declaration, why can the compiler not infer this automatically from my interface?
EDIT:
My reason for asking. Imagine a scenario where you are building data models, entities etc. I might code some interfaces to these models like so:
public interface IUserAccount
{
    Guid Identity { set; get; }
    String FirstName { set; get; }
    String LastName { set; get; }
    String EmailAddress { set; get; }
    String Password { set; get; }
}

public interface IUserDataEntry
{
    Guid DataIdentity { set; get; }
    String DataName { set; get; }
    String Data { set; get; }
}

It would be far simpler to construct the models like so:
public class UserAccount : IUserAccount
{
}

public class UserDataEntry : IUserDataEntry
{
}

public class Combined : IUserAccount, IUserDataEntry
{
}

A: An interface is not there to provide an implementation,  it is there to define a contract.  This then allows for different implementations to be built which implement it.

A: They may be syntactically identical, but they mean different things (i.e. they are not semantically identical).
In the interface, the syntax means that an implementing class must expose such a property, with get and set accessors implemented as it sees fit (either explicitly or implicitly). An interface merely defines the outward behaviour that a class must provide; it does not provide any implementation of that behaviour.
In the class, the syntax is an "auto-property", an implementation of the property defined by the interface, and the get and set accessors are implicitly converted into full implementations with a backing field. It looks something like this when it's compiled:
public class CustomDataHandler : ICustomData
{
    private string customData;

    public string CustomData
    {
        get
        {
            return customData;
        }
        set
        {
            customData = value;
        }
    }
}

A: You are implicitly implementing the interface. In this instance the method signatures of the class must match those of the interface (including accessibility). Ensuring that the methods are marked as public ensures that there are no surprises when looking at the class, for instance:
public class CustomDataHandler : ICustomData
{
  String CustomData {get; set}
  String PrivateCustomData {get;set;}
}

Even though both properties are declared the same, the CustomData property would be public by virtue of it being declared on the interface even though the declaration looks identical to that of PrivateCustomData. This would be inconsistent and lead to harder to maintain code.
If you do not wish to set the access modifier, you could explicitly implement the interface:
public class CustomDataHandler : ICustomData
{
    String ICustomData.CustomData { set; get; }
}

A: The interface declaration is only specifying the behaviour which the interface defines. In your case, this is a property called CustomData which has a get and set (it is a read/write property) which is of type string.
The class which implements the interface needs to do exactly that - to specify the implementation.
Now in your case, you are using auto implemented properties { get; set; } which looks the same as the interface declaration, however you could also have a backing field and behaviour in your get or set methods.

A: You must explicitly implement it because... You are not limited to implementing it that way. You could use a field, or do something else in your method. An interface is only a method contract that guaranty that this method exist.
public class CustomDataHandler : ICustomData
{
    public String CustomData
    {
        get { return "None of your business!"; }
        set { } // Decide to do nothing
    }
}

The interface only guaranty this method will exist. Not what you're gonna do with it.
EDIT: As for your edit of your question, you probably seek to have a parent class instead of an interface if you want to implement the method only once for a collection of classes. However, while you can combine interface, you cannot combine parent classes. But, you can add interface at different point of a classes hierarchy.

A: Here's an example where the CustomData property is private in a derived class:
public class CustomDataHandler : ICustomData
{
    private string CustomData { set; get; }

    string ICustomData.CustomData { get; set; }
}

But this code compiles, because there is also an explicit implementation of the property.
So, the public modifier is not redundant in this case.


text:
Q: Simulating Phase Space Evolution I am interested in modeling the time evolution of phase-space $\rho(\vec{q},\vec{p},t)$.  I have attempted to use Liouville's theorem $\partial_t\rho=-\sum_{i=1}^{3}(\partial_{q_i}\rho)\dot q_i+(\partial_{p_i}\rho)\dot p_i$, but even in the simple 1D case with no potential my numerical simulation fails.
I would like help with the simplest case, where there is one spatial dimension ($q=x$), and for the sake of simplicity we can assume m=1, so $p=v$, and Liouille's equation becomes $\partial_t \rho = v \partial_x \rho$, with $\rho=\rho(x,v,t)$.  What I want is to numerically simulate $\rho(x,v,t)$ given $\rho(x,v,0)$, but I'm not sure how to make this happen.  My attempt to do this was by using Mathematica, calling the NDSolve command and passing the simplified liouville equation and an initial distribution, but no sensible results are obtained.  There is a warning thrown that I don't have enough boundary conditions on $x$, but I don't know what additional boundary conditions should look like.

A: You might be best off creating a bunch of trial systems and evolving each one independently using the (much easier) Hamilton's equations, which are good old ordinary differential equations. After all this is how the Liouville equation was constructed in the first place by people like Gibbs---in the limit of an infinite number of trial systems, you get the continuous version for a point density $\rho$.
That's the trick I used in creating the following animation, where 20000 dots represent trial systems [ https://commons.wikimedia.org/wiki/File:Hamiltonian_flow_classical.gif
 ]:

It won't work for all purposes but it is likely good enough to give you a feeling for the evolution.


text:
Q: What do you call something that everyone says will happen but never does? Is there a term for something that lots of people say is going to happen, but it never happens (at least in the immediate future)?
For example, say everyone says "the tech bubble's going to burst" - yet it's 3 or 4 years until it does.
Is there a generic term or phrase for this concept?
I don't think this always has to be an alarming situation. It could be something like "Xbox prices are going to go up", but they never do. More like a prediction that never happens.

A: I can think of many terms for an event that occurs or passes, but without the expected result; for example, a nonevent, a false alarm, or a damp squib. For example, you could say:

The Y2K bug got a lot of press, but in the end it was a nonevent.

For something less well-defined, like the tech bubble, you might say it defied conventional wisdom. There's also a specific kind of expression sometimes used in technology: if something is hotly anticipated or talked about as being imminent, but never quite gets there, you might say:

I don't want to wait for that tech to be ready; it's always five years away.

Or:

Don't get too excited about the new cold fusion study; that tech has been five years away for fifty years.

A: Usually we call that a false alarm.

a warning that is given about something that fails to occur

[TFD Online]

A: I would simply call that an inaccurate prediction, or possibly a false prediction.


text:
Q: Comparator Declaration Syntax I am implementing a priority queue and comparator interface in Java using the following code and using Java 8 as advised below:

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.PriorityQueue;

class Student {
    private int token;
    private String name;
    private double cgpa;

    public Student(int id, String name, double cgpa) {
        super();
        this.token = id;
        this.name = name;
        this.cgpa = cgpa;}

    public int getToken() {
        return token;}

    public String getName() {
        return name;}

    public double getCgpa() {
        return cgpa;}
}

class Priorities {
    public List < Student > getStudents(List <String> events) {
        PriorityQueue < Student > student_queue = new PriorityQueue(Comparator.comparing(Student::getCgpa).reversed().thenComparing(Student::getName).thenComparing(Student::getToken));
        List <Student> students = new ArrayList <Student> ();
        for (String e: events) {
            Scanner in =new Scanner(e);
            String event = in.next();
            if (event.equals("ENTER")) {
                String name = in.next();
                float cgpa = in.nextFloat();
                int token = in.nextInt();

                Student student = new Student(token, name, cgpa);
                student_queue.add(student);
            } else if (event.equals("SERVED")) {
                Student first = student_queue.poll();
            } in .close();
        }
        Student first = student_queue.poll();
        if (first == null) {
            return students;
        } else {
            while (first != null) {

                students.add(first);
                first = student_queue.poll();

            }
            return students;
        }

    }
}

public class Solution {
    private final static Scanner scan = new Scanner(System.in);
    private final static Priorities priorities = new Priorities();

    public static void main(String[] args) {
        int totalEvents = Integer.parseInt(scan.nextLine());
        List<String> events = new ArrayList<>();

        while (totalEvents-- != 0) {
            String event = scan.nextLine();
            events.add(event);
        }

        List<Student> students = priorities.getStudents(events);

        if (students.isEmpty()) {
            System.out.println("EMPTY");
        } else {
            for (Student st: students) {
                System.out.println(st.getName());
            }
        }
    }
}

I am getting the following errors but have been unable to resolve the problem.
Solution.java:30: error: cannot find symbol
        PriorityQueue < Student > student_queue = new PriorityQueue(Comparator.comparing(Student::getCgpa).reversed().thenComparing(Student::getName).thenComparing(Student::getToken));
                                                                    ^
  symbol:   variable Comparator
  location: class Priorities
Solution.java:30: error: invalid method reference
        PriorityQueue < Student > student_queue = new PriorityQueue(Comparator.comparing(Student::getCgpa).reversed().thenComparing(Student::getName).thenComparing(Student::getToken));
                                                                                ^
  non-static method getCgpa() cannot be referenced from a static context
Solution.java:30: error: invalid method reference
        PriorityQueue < Student > student_queue = new PriorityQueue(Comparator.comparing(Student::getCgpa).reversed().thenComparing(Student::getName).thenComparing(Student::getToken));
                                                                                ^
  non-static method getName() cannot be referenced from a static context
Solution.java:30: error: invalid method reference
        PriorityQueue < Student > student_queue = new PriorityQueue(Comparator.comparing(Student::getCgpa).reversed().thenComparing(Student::getName).thenComparing(Student::getToken));
                                                                                ^
  non-static method getToken() cannot be referenced from a static context
Note: Solution.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
4 errors

A: "Java" on Hackerrank means Java 7.
You need to choose "Java 8" to get support for the Student::getCpa syntax.
https://www.hackerrank.com/environment/languages
Also note that the current (long-term-supported) Java version is Java 11. So be careful when using newer constructs or API that may not be available on Java 8 either.

A: The only error I can find is you forgot the import for PriorityQueue.
import java.util.PriorityQueue;

Other than that, cut-and-paste into my IDE compiles fine.


text:
Q: SQL Server select query to retrieve quoted text I have a table named Test, where columns are as follows..
AC_ID varchar(50)
Region varchar(50)
Areas varchar(50)
Month varchar(50)
Revenue money
Margin money

and the entries of varchar columns are in quotes like, Acc_ID is '100', Region is' XYZ', Areas is 'ABC' etc...
I want a select statement to query total revenue of a particular region in a particular month.
I am using SQL Server

A: Try this:-
SELECT SUM(Revenue) AS "Total Revenue"
FROM Test
WHERE Region = 'Some Text'
and Month = 'Some Text'
GROUP BY Region, Month;

This might be helpful to you.

A: Select  Region, Month, SUM(ISNULL([Revenue money],'0'))
From    Test
Where   Region = 'RegionXYZ'
            and month = 'Month123'
Group by Region, Month

Might be worth considering storing the month in a datetime column, or have a year column too. Otherwise you will be summing up the Revenue Money for the month for all the years of data you have in your table.


text:
Q: Close popup box before opening new one So I came across this thread and it works very well - How to generate a simple popup using jquery. However, I have a second link and I've changed the class name and everything. Works fine but there are two issues.
1 - If I click on one link and then decide to click on the other link, it displays the second div on top of the first one. If I click "Cancel," I end up having to close BOTH divs in succession. Not a big deal but I'm trying to make it idiot proof.
2 - If I click on "Add Room" and then happen to click on it again, then I can't click the "Cancel" button to hide the div overlay. I could display the div over the link so the user can't click it again, but it doesn't look as clean.
Here's the code.
$(function() {
    $("#add_room").live('click', function(event) {
        $(this).addClass("selected").parent().append('
<form method="post" action="/room/add">Room Name
<input type="text" size="10" class="text" name="location_name" id="room" />

<input type="submit" value="Add" name="commit" class="submit small" id="room_submit"/>Cancel
</form>
');
        $(".pop").slideFadeToggle(function() {
            $("#room").focus();
        });
        return false;
    });

    $(".close").live('click', function() {
        $(".pop").slideFadeToggle(function() {
            $("#add_room").removeClass("selected");
        });
        return false;
    });

    $("#add_item").live('click', function(event) {
        $(this).addClass("selected").parent().append('
<form method="post" action="/room/add">Item Name
<input type="text" size="10" class="text" name="item_name" id="item" />

<input type="submit" value="Add" name="commit" class="submit small" id="room_submit"/>Cancel
</form>
');
        $(".pop1").slideFadeToggle(function() {
            $("#item").focus();
        });
        return false;
    });

    $(".close1").live('click', function() {
        $(".pop1").slideFadeToggle(function() {
            $("#add_room").removeClass("selected");
        });
        return false;
    });

});

$.fn.slideFadeToggle = function(easing, callback) {
    return this.animate({ opacity: 'toggle', height: 'toggle' }, "fast", easing, callback);
};

A: Ouch, that seems like a lot of code.  In the same link you posted in your question is another answer that mentions using jQuery UI Dialog instead.  I'd highly recommend using that instead, as it is by far easier to use.


text:
Q: VBscript, which will MAKE a local user change their password at next login Ok, so I have been going at this forever now and I am finding no answers to this that actually work. So, I am trying to create a Script which will make a local user change their password when they next logon. I have looked and looked and looked, but nothing helps. Though I feel like I'm close but missing something. Now I will say I am very, very new to scripting in general so sorry if I seem dumb, but I'd love the help. Also, I am using Windows 10 (not sure if that will make a difference). I am also creating this for a school assignment and I did ask my teacher for a hand, but it's been a week sense I have heard anything. Thank you!
Now here is what I have:
strComputer = "LAPTOP-56BDJGPQ"
Set usr = GetObject("WinNT://LAPTOP-56BDJGPQ/Guest,user")
usr.Put "PasswordExpired", 1
usr.SetInfo

Now, I know that maybe where it says /Guest,user might be incorrect but I have also tried using my account which is the admin, even that seem to do nothing.
Here is what happens when I run it (now, I do run everything through command prompt)
c:\Comp230>cscript USER_Logon_reset.vbs
Microsoft (R) Windows Script Host Version 5.812
Copyright (C) Microsoft Corporation. All rights reserved.

c:\Comp230>

Now this to me shows it ran, but when I go to test to see if it worked well nothing happens.
I will say I have tried other ways of scripting this part like replacing usr.Put to objUser.Put, etc. I would love any input I could get because this is frustrating.

A: If the Password Never Expires flag is set, you need to delete it first to expire the password.
Try the following instead.
Const ADS_UF_DONT_EXPIRE_PASSWD = &H10000 ' 65536

Set usr = GetObject("WinNT://LAPTOP-56BDJGPQ/JohnDoe,user")
currentFlags = usr.Get("UserFlags")

'check if "password never expires" flag is set. if so, remove it
If currentFlags And ADS_UF_DONT_EXPIRE_PASSWD Then
    newFlags = currentFlags - ADS_UF_DONT_EXPIRE_PASSWD
    'setting new flags
    usr.Put "UserFlags", newFlags
End If
usr.Put "PasswordExpired", 1
usr.SetInfo

You may also need to remove the User Cannot Change Password flag if it's set.


text:
Q: mongodb spring connection lost overnight I'm using azure cosmosdb with mongoAPI (spring data, mongoRepository)
Each morning, first request to fetch data from mongo causes exception:
Following requests succeed without doing any actions.
Any idea what might be causing this?
Is there a way to have spring automatically recover connections without failing request?
Thanks
The exception:
org.springframework.data.mongodb.UncategorizedMongoDbException: Exception sending message; nested exception is com.mongodb.MongoSocketWriteException: Exception sending message
        at org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:107)
        at org.springframework.data.mongodb.core.MongoTemplate.potentiallyConvertRuntimeException(MongoTemplate.java:2135)
        at org.springframework.data.mongodb.core.MongoTemplate.executeFindMultiInternal(MongoTemplate.java:1978)
        at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1784)
        at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1767)
        at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:641)
        at org.springframework.data.mongodb.repository.query.MongoQueryExecution$CollectionExecution.execute(MongoQueryExecution.java:79)
        at org.springframework.data.mongodb.repository.query.MongoQueryExecution$ResultProcessingExecution.execute(MongoQueryExecution.java:411)
        at org.springframework.data.mongodb.repository.query.AbstractMongoQuery.execute(AbstractMongoQuery.java:94)
        at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:483)
        at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:56)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
...
Caused by: com.mongodb.MongoSocketWriteException: Exception sending message
        at com.mongodb.connection.InternalStreamConnection.translateWriteException(InternalStreamConnection.java:465)
        at com.mongodb.connection.InternalStreamConnection.sendMessage(InternalStreamConnection.java:208)
        at com.mongodb.connection.UsageTrackingInternalConnection.sendMessage(UsageTrackingInternalConnection.java:90)
        at com.mongodb.connection.DefaultConnectionPool$PooledConnection.sendMessage(DefaultConnectionPool.java:429)
        at com.mongodb.connection.CommandProtocol.sendMessage(CommandProtocol.java:189)
        at com.mongodb.connection.CommandProtocol.execute(CommandProtocol.java:111)
        at com.mongodb.connection.DefaultServer$DefaultServerProtocolExecutor.execute(DefaultServer.java:168)
        at com.mongodb.connection.DefaultServerConnection.executeProtocol(DefaultServerConnection.java:289)
        at com.mongodb.connection.DefaultServerConnection.command(DefaultServerConnection.java:176)
        at com.mongodb.operation.CommandOperationHelper.executeWrappedCommandProtocol(CommandOperationHelper.java:216)
        at com.mongodb.operation.CommandOperationHelper.executeWrappedCommandProtocol(CommandOperationHelper.java:207)
        at com.mongodb.operation.CommandOperationHelper.executeWrappedCommandProtocol(CommandOperationHelper.java:113)
        at com.mongodb.operation.FindOperation$1.call(FindOperation.java:516)
        at com.mongodb.operation.FindOperation$1.call(FindOperation.java:510)
        at com.mongodb.operation.OperationHelper.withConnectionSource(OperationHelper.java:431)
        at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:404)
        at com.mongodb.operation.FindOperation.execute(FindOperation.java:510)
        at com.mongodb.operation.FindOperation.execute(FindOperation.java:81)
        at com.mongodb.Mongo.execute(Mongo.java:836)
        at com.mongodb.Mongo$2.execute(Mongo.java:823)
        at com.mongodb.DBCursor.initializeCursor(DBCursor.java:870)
        at com.mongodb.DBCursor.hasNext(DBCursor.java:142)
        at org.springframework.data.mongodb.core.MongoTemplate.executeFindMultiInternal(MongoTemplate.java:1964)
        ... 129 common frames omitted
Caused by: java.net.SocketException: Broken pipe (Write failed)
        at java.net.SocketOutputStream.socketWrite0(Native Method)
        at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:111)
        at java.net.SocketOutputStream.write(SocketOutputStream.java:155)
        at sun.security.ssl.OutputRecord.writeBuffer(OutputRecord.java:431)
        at sun.security.ssl.OutputRecord.write(OutputRecord.java:417)
        at sun.security.ssl.SSLSocketImpl.writeRecordInternal(SSLSocketImpl.java:886)
        at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:857)
        at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:123)
        at com.mongodb.connection.SocketStream.write(SocketStream.java:75)
        at com.mongodb.connection.InternalStreamConnection.sendMessage(InternalStreamConnection.java:204)
        ... 150 common frames omitted

A: It closes the connection because of passing the maximum connection idle time.
You will need to set this property according to your requirement.
maxConnectionIdleTime

This can be set either on your Mongo configuration or application profile.
Good luck.

A: You can set keep-alive like that:
    @Bean
    public MongoDbFactory mongoDbFactory() throws Exception {
        MongoClientOptions.Builder optionsBuilder = MongoClientOptions.builder();
        optionsBuilder.socketKeepAlive(true);
        return new SimpleMongoDbFactory(new MongoClientURI(mongoUri, optionsBuilder));
    }


text:
Q: Webpack file-loader : rewrite the path How to change the output directory of file copied with file-loader ?
Configuration :
var SRC_DIR = path.resolve(__dirname, 'src');
...
loaders : [
{
  test : /\.html$/,
  include : SRC_DIR + "/main/html",
  loader : 'file?name=[path][name].[ext]'
},

*

*If I use [path], output = full source directory.

*If I don't, output=files are on root output directory

How to keep only a part of the initial path ?
Example :
 source : /src/main/html/app/sample.html
 output : /dist/app/sample.html

A: You can try this (I haven't tested it)
plugins: [
     ...
     new CopyWebpackPlugin([
       { from: SRC_DIR + "/main/html" }
     ]),
     ...
  ]


text:
Q: When is a $j$-invariant supersingular? Assume $j \in \mathbb{F}_p$ is the $j$-invariant of a curve $E/\mathbb{F}_p$. The modular polynomial $\Phi_l(T,S)$ is such that the roots of $\Phi_l(T,j)$ are the $j$-invariants of curves $l$-isogenous to $E$, but apparently there are cases where this doesn't work, like if the $j$-invariant turns out to be $0$ or $1728$, or if the $j$-invariant comes from a supersingular curve. How do I know if the a $j$-invariant is supersingular?

A: Too long for a comment, I think I have a way to make sense to OP's question:
Let  $E/\Bbb{F}_p$ be non-supersingular such that $E$ is not isogeneous to a curve with $j\in 0,1728$ (ie. $(End(E)\otimes_\Bbb{Z}\Bbb{Q})_{tors}^\times = \pm 1$ and $End(E)$ is an order in an imaginary quadratic field),  together with an isogeny $f:E\to E_2$, of degree $l$, with $E_2/\Bbb{F}_p$,
where $f$ is defined over an extension $\Bbb{F}_{p^n}$ with possibly $n> 1$.
From the assumptions the Frobenius and the dual isogeny satisfiy $$\phi_{E_2}^n f=f\phi_{E}^n,\qquad f^* f=[l]$$
Observe that $f^*\phi_{E_2} f\in End(E)$ satisfies $$(f^*\phi_{E_2} f)^n=[l^{n-1}]f^*\phi_{E_2}^n f= [l^{n-1}]f^* f \phi_{E}^n= [l^n]\phi_{E}^n=([l] \phi_{E})^n$$
Whence $$f^*\phi_{E_2} f= u [l] \phi_{E}= u f^* f\phi_E$$ for some $u\in (End(E)\otimes_\Bbb{Z}\Bbb{Q})_{tors}^\times$, which must be $u=\pm 1$.

*

*If $u=1$ then "the" Frobenius commutes with $f$ so that $f$ is defined over $\Bbb{F}_p$.

*If $u=-1$ then let $h$ be the isomorphism (defined over $\Bbb{F}_{p^2}$) from $E_2$ to its quadratic twist $E_3/\Bbb{F}_p$ (so that $j(E_2)=j(E_3)$).
We get that $$ \phi_{E_3}hf=-h\phi_{E_2}f=hf\phi_{E}$$ so that "the" Frobenius commutes with $hf$ which is defined over $\Bbb{F}_p$.
Therefore, when $p\nmid l$ the roots $\in \Bbb{F}_p$ of $\Phi_l(T,j(E))\in \Bbb{F}_p[T]$ are exactly the $j(C)$ such that there is an isogeny $E\to C$ of degree $l$ defined over $\Bbb{F}_p$.


text:
Q: How can I show that the arguments that minimize a function are not affected by a constant (or not affected much by a constant)? Edit: I feel this question is better suited for MathOverflow, so I added a significant amount of context and posted there. I don't know if I should delete the question on this site, but I feel I should provide the link to not duplicate work. Here is the link: https://mathoverflow.net/questions/375682/how-can-i-analyze-the-the-affect-of-a-constant-on-the-arguments-that-minimize-a
Consider the a function $f(x,y,c)$ where $c$ is a constant. I just wrote $c$ as an argument to emphasize the function contains an important parameter $c$. Now, consider
$$\text{argmin}_{x,y} \; f(x,y,c)$$
How can I either (1) show that the arguments that minimize $f$ is not affected by the choice of $c$, or furthermore, (2) how can I determine how much the parameter $c$ affects the arguments that minimize $f$. I am mostly interested in (2), but I am convinced I need to understand (1) to work out (2).
While the problems I am typically working with are not so simple, I will provide a simple example to illustrate my question.
Example 1: Consider
$$ f(x,y,c) = cx^2 + y^2 $$
where $c > 0$. The minimum of this function is $x=0$ and $y=0$ regardless of the value of $c$. This is simple to see for this function.
Example 2: Consider the following equations,
$$ f_1(x,y,c) = (x+c*0.00001)^2 + y^2 $$
$$ f_2(x,y,c) = (x+c)^2 + y^2 $$
The value of $c$ in the first equation $f_1$ does not affect the minimizing arguments as much as the value of $c$ in the second equation $f_2$.

A: This answer is sourced from Oregon State University Calculus Undergraduate Study Guide.
[See References]
Compute $f'_x(x,y,c)$ and $f'_y(x,y,c)$ the partial derivatives of $f(x,y,c)$ w.r.t. $x$ and $y$ respectively.
Equate the partial derivatives to $0$ and solve them simultaneously to determine critical points (i.e., maxima or minima) where the tangent plane is horizontal with its normal pointing in the $z$ direction.
Let $(x_c,y_c)$ be a critical point on the 2D surface given by $f(x,y,c)$.
Define $D(x_c,y_c) = f''_x(x,y,c)f''_y(x,y,c) - [f''_{xy}(x_c, y_c, c)]^2$
where
$f''_x(x,y,c)$ and $f''_y(x,y,c)$ are the second derivatives w.r.t $x$ and $y$ respectively and
$f''_{xy}(x,y,c)$ is the second derivative of $f(x,y,c)$ w.r.t $x$ first followed by $y$ next.
We have four cases:

*

*If $D>0$ and $f_xx(x_c,y_c)<0$, then $f(x,y)$ has a relative maximum
at $(x_c,y_c)$.

*If $D>0$ and $f_xx(x_c,y_c)>0$, then $f(x,y)$ has a relative minimum
at $(x_c,y_c)$.

*If $D<0$, then $f(x,y)$ has a saddle point at $(x_c,y_c)$.

*If $D=0$, the second derivative test is inconclusive.
From this we can see that for the question posed, if $c$ appears in the partial derivatives $f'_x(x,y,c)$ or $f'_y(x,y,c)$ we can conclude that it impacts the maxima or minima for general $f(x,y,c)$. The extent of the impact is defined exactly by the system of two equations that equate the partial derivatives to $0$ in the computation of the critical points.
References:
Maxima and Minima of Functions of Two Variables. Oregon State University, Calculus study guide.


text:
Q: Is it possible to change vscode settings from my custom extension? I'm developing a vscode extension and I want to add a few values on the entry "file.associations" in the settings file when the user install my extension.
Is it possible? I can't find any resource in the documentation.
If someone can guide me in where to look for, I'd appreciate it.

A: Yes, You can change vscode settings from extensions
Create your first Extension
Tutorial 2
What can extensions do?

*

*Change the look of VS Code with a color or icon theme - Theming

*Add custom components & views in the UI - Extending the Workbench

*Create a Webview to display a custom webpage built with HTML/CSS/JS - Webview Guide

*Support a new programming language - Language Extensions Overview
Support debugging a specific runtime - Debugger Extension Guide


text:
Q: Conditional replacement of row values I would like to generate a presence/absence file from a matrix that looks like this by applying some condition
source    Bin1    Bin2    Bin3    Bin4    Bin5
  A         0.1       1       2       2       3
  B         1       1       1       1       1
  C         0.2       0       0       1       0
  D         0       0.3       2       0       0
  E         4.4       0.02       0       1       0
  F         1       0       1       0.01       1
  G         0.1       5       0       0       0

I want to define low values as being >0.1, so that any value greater than 0.1 gets replaced with a value of 1. The expected results would look like this [values are either 0 or 1]:
source    Bin1    Bin2    Bin3    Bin4    Bin5
  A         0       1       1       1       1
  B         1       1       1       1       1
  C         1       0       0       1       0
  D         0       1       1       0       0
  E         1       0       0       1       0
  F         1       0       1       0       1
  G         0       1       0       0       0

I would like to do this is R.


text:
Q: Limit camera rotation- Unity Clamp Quaternion I have this code that allows a camera to rotate through an input from the touch screen, I need to lock the rotation in a specific range. I tried to use the "Math.Clamp" unsuccessfully. Can someone help me?
I tried to enter this string, but the visual got an error message that says "Unable to convert from 'UnityEngine.Quaternion' to 'float'"
rotationY  = Mathf.Clamp(rotationY, -30, 30);

I leave you here the code that allows the camera to run without a limit.
Thanks everyone for the help
 private Touch touch;
    private Vector2 touchPosition;
    private Quaternion rotationY;
    private float rotateSpeedModifier = 0.01f;
    //public float yPos;

    // Update is called once per frame
    void Update()
    {
        if(Input.touchCount > 0)
        {

            touch = Input.GetTouch(0);

            if(touch.phase == TouchPhase.Moved)
            {
                    rotationY = Quaternion.Euler(0f, -touch.deltaPosition.x * rotateSpeedModifier, 0f);
                    transform.rotation = rotationY * transform.rotation;
                    Debug.Log(rotationY * transform.rotation);

            }
        }
    }

A: You can't clamp a Quaternion.
You could however rather store the float of the angle you already rotated and clamp that instead:
private Touch touch;
private Vector2 touchPosition;
private float rotationY;
private float rotateSpeedModifier = 0.01f;

private Quaternion originalRotation;

private void Start ()
{
    originalRotation = transform.rotation;
}

// Update is called once per frame
void Update()
{
    if(Input.touchCount > 0)
    {
        touch = Input.GetTouch(0);

        if(touch.phase == TouchPhase.Moved)
        {
            rotationY -= touch.deltaPosition.x * rotateSpeedModifier;
            rotationY = Mathf.Clamp(rotationY, -30, 30);

            transform.rotation = originalRotation * Quaternion.Euler(0, rotationY, 0);
        }
    }
}


text: Q: Subgroups of a group algebraic space I found in the literature many references on the representability of quotients of group schemes but almost nothing about subgroups. For this reason I hope that my question is a silly one and that what I am asking is well known to experts. Let $G$ be a group algebraic space over a base which is the spectrum of a discrete valuation ring. Let $H\subset G$ be a subgroup functor of $G$ which is also an etale sheaf. Under which conditions is it known that $H$ is a group algebraic space? We can assume that $G$ has a trivial obstruction and deformation theory if it could help. We can also assume that $H$ is the kernel of an homomorphism of group sheaves $G\rightarrow K$ but $K$ is not necessarily represented by an algebraic space.


text:
Q: More polite forms of "you" In French,  "vous" can be used instead of "toi" for this purpose. A seemingly rude example in English is when someone wants to instruct a lawyer, and writes 'I would like to instruct you.' I recognise the legal definition of 'to instruct', but this still sounds too forceful. What are  pleasant, but formal alternatives?

A: "You" is the polite form (equivalent to "vous").
The more familiar form (equivalent to "toi") is or was "thou", which is now archaic/obsolete.

A: I would like to instruct you is both polite and formal. Modern English has no alternate pronoun forms to denote politeness, formality or etiquette; it's correct to translate both tu and vous (and their nominative forms as well; you serves both functions) as you.
Instead, in English we can use different verb constructions to show politeness, similar to using vous + future tense for polite requests in French. This is not strictly analogous to the differences between tu and vous, but it's the closest thing we have.
And you've constructed your sentence in the polite register already. Would like is the more polite and formal version of want, and generally in English politeness and formality go hand in hand. Here are two translations for comparison. Apologies for any errors in the French; mine is extremely rusty. I also suspect my translation of instruct (meaning to issue a formal set of instructions) is quite poor, since I'd be much more likely to translate ordonner as order rather than instruct, but my French vocabulary isn't so hot. Please feel free to edit and change ordonner to the correct verb.

Je veux vous ordonner.
  I would like to instruct you.
Je veux toi ordonner.
  I want to instruct you.

Additionally, instruct is quite formal, but not forceful. Synonyms in this case include direct, order and command. The latter two are decidedly less polite than instruct, because these are the forceful verbs in English. Direct is just as formal as instruct and a touch more polite, but it's also slightly vaguer. If you say I would like to direct you, it might be taken to mean something like I want to guide you in a general direction as opposed to I want to give you instructions; an instruction is more specific than a direction.
If you provide a bit more context on exactly what type of instructions are being given to the attorney, I can suggest more nuanced synonyms. For example, brief may (or may not) be an appropriate choice here.

A: "You" is already the polite and formal form.
Simply put
You=Vous
Tu=Thou, a term no longer existing and replaced by "you".


text:
Q: How to get Country name by its coordinates using qml? I tried with Geocodemodel reversing process but after calling it 2-3 times or giving timer then only its giving correct value that to its working sometimes only.
Plugin {
id: mapPlugin
name: "osm"
}
GeocodeModel {
    id: geocodeModel
    plugin: mapPlugin
    autoUpdate: false
}
function _country()
{
    geocodeModel.query = coordinates.text
    geocodeModel.update()
    if(geocodeModel.count > 0)
    {
        console.log("Name of the Country "+geocodeModel.get(0).address.country)
        return geocodeModel.get(0).address.country;

    }
}

For first time call,its showing this error QCoreApplication::postEvent: Unexpected null receiver how to remove this error and fetch country name by first call itself.
Thanks in advance.

A: I got an answer instead calling geocodemodel in function we can do below thing. will get country name when count is incremented but it takes bit time.
GeocodeModel {
        id: geocodeModel;
        plugin: mapPlugin;
        autoUpdate: false;
        onLocationsChanged:
        {
            if( count > 0 )

                var country=geocodeModel.get(0).address.country;
                console.log("Country ="+country);
            }
        }
    }
    function _country()
    {
        geocodeModel.query = dstId.text
        geocodeModel.update()

    }


text:
Q: Escaping characters in Azure Devops Library variables When using Azure Devops Pipelines to release a web application with variable substitution enabled, how can I disable escaping special characters?
I am using the File Transform task by Microsoft. Task information: (1) file format = JSON; (2) target files = **/appsettings.json.
E.g. I want to replace value in appsettings.json with a variable from Library. But when library variable contains special characters, e.g. password\", it will get escaped and the value in appsettings becomes password\\\".
What do I need to do to get the value password\" substituted into my appsettings?


text:
Q: Elasticsearch : Shield Authentication not working in AJAX call I am trying to send an ajax call to elasticsearch with shield authentication
$.ajax({
        url: 'http://localhost/test2/test/_search',
        type: 'POST',
        //contentType: 'application/json; charset=UTF-8',
        crossDomain: true,
        dataType: 'json',
        username: "admin",
        password: "admin123",
        data: JSON.stringify(queryBody),
        success: function(response) {
                alert(response)
                var data = response.hits.hits;
                var titleArray = [];
                //alert(data.length);
                if (data.length > 0) {
                /*
                   if (data.length > 5)
                       data.length=5;
                */
                   for (var i = 0; i < data.length; i++) {
                        if(data[i].fields.Title[0].indexOf(settings.fieldValue) > -1)
                                        {
                                            titleArray.push(data[i].fields.DocumentID[0]+":"+data[i].fields.Title[0]);
                                        }
                                    }
                responseS(titleArray);
                titleArray=[];
                } else {    }
        },
        error: function(jqXHR, textStatus, errorThrown) {
                       var jso = jQuery.parseJSON(jqXHR.responseText);
                       alert('section', 'error', '(' + jqXHR.status + ') ' + errorThrown + ' --
' + jso.error);
               }
});

but I get:

POST http://localhost:9200/test2/test/_search 401(Unauthorized)

I also tried:
$.ajax({
                            url: 'http://admin:admin123@localhost/test2/test/_search',
                            type: 'POST',
                            //contentType: 'application/json; charset=UTF-8',
                            crossDomain: true,
                            dataType: 'json',
                            data: JSON.stringify(queryBody),
                            success: function(response) {
                                alert(response)
                                var data = response.hits.hits;

                                var titleArray = [];

                                //alert(data.length);
                                if (data.length > 0) {
                                    /*
                                    if (data.length > 5)
                                        data.length=5;
                                    */
                                    for (var i = 0; i < data.length; i++) {

                                        if(data[i].fields.Title[0].indexOf(settings.fieldValue) > -1)
                                        {

                                            titleArray.push(data[i].fields.DocumentID[0]+":"+data[i].fields.Title[0]);
                                        }
                                    }

                                    responseS(titleArray);
                                    titleArray=[];

                                } else {

                                }

                            },

                            error: function(jqXHR, textStatus, errorThrown) {
                                var jso = jQuery.parseJSON(jqXHR.responseText);
                                alert('section', 'error', '(' + jqXHR.status + ') ' + errorThrown + ' --
' + jso.error);
                            }
                        });

but I got the same 401 error.
next I tried :
    $.ajax({
                                    url: 'http://localhost/test2/test/_search',
                                    type: 'POST',
                                    //contentType: 'application/json; charset=UTF-8',
                                    crossDomain: true,
                                    dataType: 'json',
                                    data: JSON.stringify(queryBody),
                                    beforeSend: function (xhr) {
    xhr.setRequestHeader ("Authorization", "Basic " + btoa("admin:admin123"));
},                                   success: function(response) {
                                        alert(response)
                                        var data = response.hits.hits;

                                        var titleArray = [];

                                        //alert(data.length);
                                        if (data.length > 0) {
                                            /*
                                            if (data.length > 5)
                                                data.length=5;
                                            */
                                            for (var i = 0; i < data.length; i++) {

                                                if(data[i].fields.Title[0].indexOf(settings.fieldValue) > -1)
                                                {

                                                    titleArray.push(data[i].fields.DocumentID[0]+":"+data[i].fields.Title[0]);
                                                }
                                            }

                                            responseS(titleArray);
                                            titleArray=[];

                                        } else {

                                        }

                                    },

                                    error: function(jqXHR, textStatus, errorThrown) {
                                        var jso = jQuery.parseJSON(jqXHR.responseText);
                                        alert('section', 'error', '(' + jqXHR.status + ') ' + errorThrown + ' --
' + jso.error);
                                    }
                                });

but now I get

XMLHttpRequest cannot load http://localhost:9200/test2/test/_search.
  Request header field Authorization is not allowed by
  Access-Control-Allow-Headers in preflight response.
      localhost/:1 Uncaught SyntaxError: Unexpected token u

What is the proper way to send username and password to elastic via ajax call?
here is my elasticsearch.yml
action.disable_delete_all_indices: true

http.cors.enabled: true
http.cors.allow-origin: "*"
http.cors.allow-headers: "Authorization, X-Requested-With, Content-Type, Content-Length"
http.cors.allow-credentials: true

bootstrap.mlockall: true

# For reference: https://www.elastic.co/guide/en/elasticsearch/guide/current/_limiting_memory_usage.html

# controls how much heap space is allocated to fielddata. When you run a query that requires access to new field values,
# it will load the values into memory and then try to add them to fielddata. If the resulting fielddata size would
# exceed the specified size, other values would be evicted in order to make space.
indices.fielddata.cache.size:  40%

# The fielddata circuit breaker limits the size of fielddata to 60% of the heap, by default.
indices.breaker.fielddata.limit: 60%

# The request circuit breaker estimates the size of structures required to complete other parts of a request,
# such as creating aggregation buckets, and limits them to 40% of the heap, by default.
indices.breaker.request.limit: 40%

# The total circuit breaker wraps the request and fielddata circuit breakers to ensure that the combination
# of the two doesn't use more than 70% of the heap by default.
indices.breaker.total.limit: 70%
#shield.enabled: false
shield:
  authc:
    realms:
      native1:
        type: native
        order: 0
    realms:
      esusers:
        type: esusers
        order: 1
        files:
          users: ElasticSearch\elasticsearch-2.3.1\elasticsearch-2.3.1\config\shield\users
          users_roles: ElasticSearch\elasticsearch-2.3.1\elasticsearch-2.3.1\config\shield\users_role

A: The way to solve this is to configure CORS to accept the Authorization header in to your elasticsearch.yml file:
http.cors.allow-headers: "Authorization, X-Requested-With, Content-Type, Content-Length"

Also make sure that you have the following three settings in your elasticsearch.yml file:
http.cors.enabled: true
http.cors.allow-origin: /https?:\/\/localhost(:[0-9]+)?/
http.cors.allow-credentials: true


text:
Q: Large delay when earning reputation back from deleted question Whenever I do a question and it receives a large number of downvotes, I usually tend to delete them instead of editing, as I am nervous about losing my reputation. From my past experience with Stack Exchange, I always knew that deleting questions can get your reputation back.
Oddly enough, when you delete a question in hopes of earning your reputation back, it will take a long period of time to earn it back. Earning your reputation can take about several minutes to half an hour.
Should this issue with having to wait a long amount of time be fixed?

A: I do not think that this is a bug.
To me a delay of 15-30 minutes between deleting a post and seeing any reputation changes on it reversed seems reasonable because those reputation changes are probably performed by a script that runs every 15-30 minutes.


text:
Q: How to use Configuration.assertionMode = AssertionMode.SOFT; with mixed framework (selenium + selenide) I'm working with old framefork which uses selenium, but now i'm trying use Selenide.
BaseTest has listeners:
@Listeners({TestMethodListener.class, TestListener.class, TimeoutTransformer.class, SoftAsserts.class})

And in @BeforeSuite
Configuration.assertionMode = AssertionMode.SOFT
I always getting
java.lang.IllegalStateException: Using soft asserts, but without @SoftAsserts annotation

To use Selenide methods i just setting current driver to WebDriverRunner
WebDriverRunner.setWebDriver(driver)
Does anyone had similar problems?


text:
Q: How do I use floating point number literals when using generic types? Regular float literals do not work:
extern crate num_traits;

use num_traits::float::Float;

fn scale_float<T: Float>(x: T) -> T {
    x * 0.54
}

fn main() {
    let a: f64 = scale_float(1.23);
}

error[E0308]: mismatched types
 --> src/main.rs:6:9
  |
6 |     x * 0.54
  |         ^^^^ expected type parameter, found floating-point variable
  |
  = note: expected type `T`
             found type `{float}`

A: In certain cases, you can add a restriction that the generic type must be able to be multiplied by the type of the literal. Here, we allow any type that can be multiplied by a f64 so long as it produces the output type of T via the trait bound Mul<f64, Output = T>:
use num_traits::float::Float; // 0.2.6
use std::ops::Mul;

fn scale_float<T>(x: T) -> T
where
    T: Float + Mul<f64, Output = T>,
{
    x * 0.54
}

fn main() {
    let a: f64 = scale_float(1.23);
}

This may not work directly for the original problem, but it might depending on what concrete types you need to work with.

A: Use the FromPrimitive trait:
use num_traits::{cast::FromPrimitive, float::Float};

fn scale_float<T: Float + FromPrimitive>(x: T) -> T {
    x * T::from_f64(0.54).unwrap()
}

Or the standard library From / Into traits
fn scale_float<T>(x: T) -> T
where
    T: Float,
    f64: Into<T>
{
    x * 0.54.into()
}

See also:

*

*How do I use number literals with the Integer trait from the num crate?

A: You can't create a Float from a literal directly. I suggest an approach similar to the FloatConst trait:
trait SomeDomainSpecificScaleFactor {
    fn factor() -> Self;
}

impl SomeDomainSpecificScaleFactor for f32 {
    fn factor() -> Self {
        0.54
    }
}

impl SomeDomainSpecificScaleFactor for f64 {
    fn factor() -> Self {
        0.54
    }
}

fn scale_float<T: Float + SomeDomainSpecificScaleFactor>(x: T) -> T {
    x * T::factor()
}

(link to playground)

A: These days the numeric_literals crate and its replace_float_literals feature can be helpful in doing the necessary substitutions on a complex piece of code.


text:
Q: Python: Float value addition and substraction give wrong value I just check following thing in python 2.7
print 0.1 + 0.2
output :- 0.3
print 0.1 + 0.2 - 0.3
output :- 5.55111512313e-17
But I expect the 0.0
So, how to achive this thing ?

A: The problem here is that the float type doesn't have enough precision to display the result you want. If you try to print the partial sum 0.1 + 0.2 you'll see that the float result you get is 0.30000000000000004.
So, 5.55111512313e-17 is the closest approximation possible with float type variables to that result. If you try to cast the result to int, so:
int(0.2 + 0.1 - 0.3)

You'll see 0, and that's the right integer approximation.
You can get 0.0 with floating point variables by using the decimal class.
Try this:
from decimal import Decimal
Decimal("0.2") + Decimal("0.1") - Decimal("0.3")

And you'll see that the result is Decimal("0.0")


text:
Q: Python internals - How do objects know about global variables? I recently discovered some interesting behavior that left me wondering about how an object knows about which global variables exist. For example, suppose I have a file "test.py":
globalVar = 1
toDelete = 2

class Test(object):
    classVar = 3

    def runTest1(self):
        print globalVar
        print toDelete
        print missingVar

    def runTest2(self):
        print self.classVar
        print toCreate
        print missingVar

Then in an interactive shell I do this:
>>> import test
>>> tester = test.Test()
>>> tester.runTest1()
1
2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "test.py", line 10, in runTest1
    print missingVar
NameError: global name 'missingVar' is not defined
>>> tester.runTest2()
3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "test.py", line 14, in runTest2
    print toCreate
NameError: global name 'toCreate' is not defined

Nothing surprising. Then I change the first few lines of "test.py" to this:
globalVar = 4
toCreate = 5

class Test(object):
    classVar = 6

Now back to the interactive shell:
>>> reload(test) # test = reload(test) gives the same result
<module 'test' from 'test.py'>
>>> tester.runTest1()
4
2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "test.py", line 10, in runTest1
    print missingVar
NameError: global name 'missingVar' is not defined
>>> tester.runTest2()
3
5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "test.py", line 15, in runTest2
    print missingVar
NameError: global name 'missingVar' is not defined
>>> dir(test)
['Test', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'globalVar', 'toCreate', 'toDelete']

So tester now knows about toCreate, which showed up after tester itself was created. It still knows about toDelete because reloading a module apparently doesn't affect a global variable that was deleted. Here comes a twist:
>>> import sys
>>> import importlib
>>> del(sys.modules['test']) # remove cached version
>>> test = importlib.import_module('test') # same result if I don't have 'test = '
>>> tester.runTest1()
None
None
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "test.py", line 10, in runTest1
    print missingVar
NameError: global name 'missingVar' is not defined
>>> tester.runTest2()
3
None
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "test.py", line 15, in runTest2
    print missingVar
NameError: global name 'missingVar' is not defined
>>> dir(test)
['Test', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'globalVar', 'toCreate']

Deleting the module from sys.modules and then reimporting the module results in all the global variables becoming None.
Also of interest is that if I delete test and sys.modules['test'], it still knows about the values of the variables for a while. After a little while (which I assume is how long it takes for the module to be garbage collected) the values become None. Reimporting the module causes the garbage collection (or whatever is going on) to happen immediately.
So how does tester find out about a new global variable being created, and then once the module is gone why does it still know which variables existed even though it no longer knows what values they held?

A: Any name that is not a local (has not been assigned to in the current scope) is instead assumed to be a global. The name is looked up every time the code runs.
So at runtime the name is looked up in the global namespace, which is just a dictionary. If the name doesn't exist at that time, a NameError exception is raised.
You can see this when you disassemble a function; bytecode is shown when using the dis module:
>>> import dis
>>> def foo():
...     bar = 'baz'  # local
...     bar  # reference the local
...     baz  # reference something else; e.g. a global
...
>>> dis.dis(foo)
  2           0 LOAD_CONST               1 ('baz')
              3 STORE_FAST               0 (bar)

  3           6 LOAD_FAST                0 (bar)
              9 POP_TOP

  4          10 LOAD_GLOBAL              0 (baz)
             13 POP_TOP
             14 LOAD_CONST               0 (None)
             17 RETURN_VALUE

bar is a local (it was assigned to in the block), while baz is a global. The local is referenced by LOAD_FAST, while the global is referenced by LOAD_GLOBAL.
To do this, function objects have a function.__globals__ reference linking it to the module globals mapping; see the User-defined functions section in the datamodel documentation:
>>> foo.__globals__ is globals()
True

Python also cleans up globals when deleting modules; to prevent circular references holding up finalisation globals are rebound to None at that time (although this behaviour changed in Python 3.4). If you however maintain a reference to tester, your code will find those None values.
Your tester instance, still referencing the original class and it's methods, are still referencing their module through their function.__globals__ references. So, although you deleted the sys.modules reference to the module, triggering the module cleanup, the globals dictionary is still referenced by the class methods. This globals dictionary now holds None values for each global.


text:
Q: Sqlite frequent Header access I am using sqlite in my application only for read access. The DB gets hit often by my application and I could see that the header(100 bytes) of the database is read every time when i access the database.
Precisely speaking, 16 bytes from the 24th byte of the header is read everytime. My question is , if the database is used only for read purpose, why the header is read everytime as the database connection is not closed?..can we make it read it only once?
Thanks!!

A: Google search gave me this link, and it says
"Your process may promise that it will only read the database, but there
might be some other process writing to it.
Not being a server, sqlite has no other way to find that out than by
reading the header over and over again. It has to check whether the
schema was changed, or whatever other info is in those bytes."
http://www.mail-archive.com/sqlite-users@sqlite.org/msg69900.html


text:
Q: React.js Sorting asc and desc in same button hi i did a sorting function where i defined the default sort of my data.map is asc and in my button i change to desc so my question is how i can do both asc and desc on the button
function AvailableVet() {
const [vets, setVets] = useState([]);
const  [sortType,setSorted] = useState('asc');
const sorted = vets.sort((a,b)=>{
    const isReversed = (sortType ==='asc') ? 1 : -1;
    return isReversed * a.name.localeCompare(b.name)
})
const onSort = sortType =>{
    setSorted({sortType})

}

<React.Fragment>

                {vets.length} médicos vetenários disponíveis

             <Button  align='left' className='text-field' placeholder='Ordenar'   onClick={()=>onSort('desc')}  endIcon={<UnfoldMoreSharpIcon></UnfoldMoreSharpIcon>}>Ordenar</Button>

            {sorted.map((data) => (
                <ObterMedicos
                    key={data.user_id}
                    id={data.user_id}
                    name={data.name}
                    specialty={data.specialty}
                />
            ))}

    </React.Fragment>

A: Try this snippent.
const onSort = () => {
  const sortOrder = sortType === 'asc' ? 'desc' : 'asc';
  setSorted(sortOrder);
}

and then don't need to pass argument to onSort
onClick={onSort}


text:
Q: ReactJS - Overwrite array if same keys I want to overwrite the array if the keys are the same. And push if keys are different.
From this:
const fieldData = [
 {
    "field_1": {
        "value": "oldValue"
    },
    "field_2": {
         "value": "oldValue"
    }
  }
];

const [data, setData] = useState(fieldData);

const pushData = (newData) => {
  setData(current => [...current, newData]);
}

The result if the keys are the same:
 {
    "field_1": {
        "value": "newValue"
    },
    "field_2": {
         "value": "oldValue"
    }
  }

The result if the keys are diffrent:
 {
    "field_1": {
        "value": "newValue"
    },
    "field_2": {
         "value": "oldValue"
    },
    "field_3": {
         "value": "newValue Field 3"
    }
  }

A: I would recommend you to work with a different data structure.
Change your array and work with a dictionary.
const fieldData =  {
    "field_1": {
        "value": "oldValue"
    },
    "field_2": {
         "value": "oldValue"
    }
  }

const [data, setData] = useState(fieldData);

const pushData = (newData) => {
  setData(current => ({...current,...newData}));
}

In this case, if you have a new [key, value] it will be added to your object. Otherwise the value will be overridden


text:
Q: How do I find the file path from a namespace.class name? I'm programatically looking ito a .aspx file and getting the file class name declared in its CodeBehind.  For example, when analyzing myFile.aspx I read in its Page Directive and found its CodeBehind equals "myApplication\myPage.aspx.vb".  Then I use the code below:
[Code]
Dim Assm As System.Reflection.Assembly = System.Reflection.Assembly.LoadFrom("myApplication\bin\myApplication.dll")
Dim ClassType As Type = Assm.GetType("myApplication\myPage.aspx.vb")

' myBaseType = "myApplication.Forms.BasePage"
Dim myBaseType As System.Type = ClassType.BaseType
[/Code]

Now I want to read the BaseFile (class = myApplication.Forms.BasePage).  However, to read in this file, I need I need to get its full path instead of its namespace/class hiearchy.  In this case, the BasePage is wrapped in a different namespace declaration thus I cannot just change the '.' to '\'.
How can I get the path of BasePage so I can read it?  Thank you - Frank

A: I think you need to focus on getting the 'Type' of the class regardless of location via a GetType() method, and then apply Reflection on that type to get its location.  So don't concentrate on the namespace but rater the type within the BaseFile namespace.  Here is some code I translated from the MSDN to get the physical location of my 'Customer' class.  You should be able to use this to get the location of any binary based on its type in your application:
    Dim SampleAssembly As [Assembly]
    ' Instantiate a target object.
    Dim myType As New Customer()
    Dim Type1 As Type
    ' Set the Type instance to the target class type.
    Type1 = myType.GetType()
    ' Instantiate an Assembly class to the assembly housing the Integer type.
    SampleAssembly = [Assembly].GetAssembly(myType.GetType())
    ' Gets the location of the assembly using file: protocol.
    Console.WriteLine(("CodeBase=" + SampleAssembly.CodeBase))

You can read up on this more at the following link:
Assembly.CodeBase Property:
http://msdn.microsoft.com/en-us/library/system.reflection.assembly.codebase.aspx


text:
Q: Returning scope identity using sqlCommand.ExecuteNonQuery() I have a stored procedure that looks like so.
ALTER PROCEDURE dbo.addPackage(

    @PackageStatus                      VARCHAR(50) = null,
    @OrgCode                            VARCHAR(50) = null,
    @SystemID                           VARCHAR(50) = null,
    @ID                               int OUTPUT
)
AS
BEGIN
    insert into package_table
    (
            PackageStatus,
            OrgCode,
            SystemID
            )
            values
            (@PackageStatus,
            @OrgCode,
            @SystemID
            )
            SET @ID =  SCOPE_IDENTITY()
END

And my function adds the following parameters to the sql command and calls sqlCommand.ExecuteNonQuery();
List<SqlParameter> parameters = new List<SqlParameter>();

parameters.Add(new SqlParameter("@PackageStatus", package.PackageStatus));
parameters.Add(new SqlParameter("@OrgCode", package.OrgCode));
 parameters.Add(new SqlParameter("@SystemID", package.SystemID));

SqlParameter outParameter = new SqlParameter("@ID", SqlDbType.Int);
outParameter.Direction = ParameterDirection.Output;
parameters.Add(outParameter);

but I keep getting a 0 back from the stored porcuedure evne though I have an out parameter declared and set it before the stored procedure exits. The record is successfully added with the auto incrementing value for the ID but the ID is not returned when I get the output parameter back. It is set to 0.
Any suggestions?

A: You've defined the output parameter - but do you also read it out after your call to .ExecuteNonQuery() ?? Unfortunately, you're not showing that code...
Basically, you need
SqlCommand cmd = new SqlCommand(..., connection); .....

// set up your parameter as above

connection.Open();
cmd.ExecuteNonQuery();

var outputValue = cmd.Parameters["@APID"].Value;  // you need to read it out!

connection.Close();

Are you doing this?? And that's where you're getting 0 back all the time??
The output parameter is NOT the return value from the .ExecuteNonQuery() call - you need to explicitly read out the parameter value after the call.


text:
Q: How to show pylint message codes in VScode? Anyone know how to show pylint message code in the problem section?

It only shows descriptions, not the codes like F821 and E0601.

A: type this command in vscode terminal
pylint FILENAME

A: Unfortunately, VS Code has hardcoded the pylint --msg-template argument as:
--msg-template='{line},{column},{category},{symbol}:{msg}'
and cannot be configured. You can view the VS Code source code for this.
For more info, see How to change pylint message template in VS Code linter?

A: Pylint is a Python static code analysis tool that can find programming errors, help implement coding standards, and provide simple refactoring suggestions.
It usually does not display the code containing the error on the terminal, but displays the type and suggestion of the error, and displays the precise location of the error code in the terminal with numbers. (For example: [49,7], line 49, 7th)
For "print(jfile)", Pylint can only recognize that "jfile" is an undefined variable. The error here is that it needs to be defined.
For "jfile = "hello" print jfile ", Pylint will recognize that "jfile" is a string. The error here is that it needs to use "print(jfile)" to output using python3: ("pylint" will give code output suggestions here)


text:
Q: How to add nofollow to drop down I have a drop down list which filters category ASC and DESC. Google doesn't seem to understand that is duplicate content. How can I prevent Google from not following the drop down selections:
<select>
        <select class="sort-by-dropdown" onchange="document.location.href=this.options[this.selectedIndex].value;" name="ssort">
        <option onclick="window.location = "http://mysite.com/category1/sort/_post_name-pp-asc/"; return false;" selected="" value="http://mysite.com/category1/sort/_post_name-pp-asc/">Name ASC</option>
        <option onclick="window.location = "http://mysite.com/category1/sort/_post_name-pp-desc/"; return false;" value="http://mysite.com/category1/sort/_post_name-pp-desc/">Name DESC</option>
    </select>

A: Pretty sure rel="nofollow" only works within <a> tags.
Don't think it will work with a window.location


text:
Q: Filter an ArrayList to between two dates I have a ArrayList "List"
Receipts{
int invoice;
String date;
double amount;
....
}

i want to filter the List to between two dates.
public List<Receipts> sortListByDate(String date1,String date2,List<Receipts> receipts){

   List<Receipts> sortedList = new ArrayList<>();

  // if receipts.date() is between(or including) date1 and date2 then sortedList.add(that object)

  return sortedList;
}

receipt.date() , date1 and date2 are in the format String "dd-MM-yyyy"
Help me to filter (that is, to complete the "sortListByDate" function)

A: From the stream of receipts, you need to filter the elements based on dates (i.e. not before date1 and not after date2), sort the resulting stream, collect it into a List and return the same.
Steps:

*

*Parse the date stings using DateTimeFormatter.

*Create a stream from receipts and apply filter with the required criteria.

*Sort the resulting stream.

*Collect the resulting stream into a List and return the same.

Code:
public List<Receipts> sortListByDate(String date1, String date2, List<Receipts> receipts) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
    LocalDate localDate1 = LocalDate.parse(date1, formatter);
    LocalDate localDate2 = LocalDate.parse(date2, formatter);

    return receipts.stream()
            .filter(e -> !LocalDate.parse(e.date(), formatter).isBefore(localDate1)
                    && !LocalDate.parse(e.date(), formatter).isAfter(localDate2))
            .sorted()
            .collect(Collectors.toList());
}

A: you can implements Comparable in Receipts class and overRide the compareTo method by any thing you want
and after that just call sort method on your list
see the docs for more information to how to do it:
https://www.javatpoint.com/Comparable-interface-in-collection-framework


text:
Q: how to load pretrained LSTM models weights in Tensorflow I want to implement a LSTM model with pretrained weights in Tensorflow. These weights may come from Caffee or Torch.
I found there are LSTM cells in file rnn_cell.py, such as rnn_cell.BasicLSTMCell and rnn_cell.MultiRNNCell. But how can I load the pretrained weights for these LSTM cells.

A: Here's a solution for loading a pre-trained Caffe model. See the full code here, which is referenced in the discussion in this thread.
net_caffe = caffe.Net(prototxt, caffemodel, caffe.TEST)
caffe_layers = {}

for i, layer in enumerate(net_caffe.layers):
    layer_name = net_caffe._layer_names[i]
    caffe_layers[layer_name] = layer

def caffe_weights(layer_name):
    layer = caffe_layers[layer_name]
    return layer.blobs[0].data

def caffe_bias(layer_name):
    layer = caffe_layers[layer_name]
    return layer.blobs[1].data

#tensorflow uses [filter_height, filter_width, in_channels, out_channels] 2-3-1-0
#caffe uses [out_channels, in_channels, filter_height, filter_width] 0-1-2-3
def caffe2tf_filter(name):
    f = caffe_weights(name)
    return f.transpose((2, 3, 1, 0))

class ModelFromCaffe():
    def get_conv_filter(self, name):
        w = caffe2tf_filter(name)
        return tf.constant(w, dtype=tf.float32, name="filter")

    def get_bias(self, name):
        b = caffe_bias(name)
        return tf.constant(b, dtype=tf.float32, name="bias")

    def get_fc_weight(self, name):
        cw = caffe_weights(name)
        if name == "fc6":
            assert cw.shape == (4096, 25088)
            cw = cw.reshape((4096, 512, 7, 7))
            cw = cw.transpose((2, 3, 1, 0))
            cw = cw.reshape(25088, 4096)
        else:
            cw = cw.transpose((1, 0))

        return tf.constant(cw, dtype=tf.float32, name="weight")

images = tf.placeholder("float", [None, 224, 224, 3], name="images")
m = ModelFromCaffe()

with tf.Session() as sess:
  sess.run(tf.initialize_all_variables())
  batch = cat.reshape((1, 224, 224, 3))
  out = sess.run([m.prob, m.relu1_1, m.pool5, m.fc6], feed_dict={ images: batch })
...


text:
Q: How to add BuildListener to ant without command line option? I wrote an ant org.apache.tools.ant.BuildListener that does stuff if the build fails. I can use it  from the command line with ant -listener org.smottguyz.antlisteners.SimpleListener build_all. But when I use the NetBeans IDE, there is no apparent way to specify a -listener option.
Is there a way to specify an additional build listener with ant (or NetBeans) properties, settings or configuration somewhere?
EDIT. It turns out this is pretty NetBeans specific, because, for whatever reason, NetBeans disables most of the approaches that work for most ant configurations. So Is it possible to specify logger for ant inside build.xml? is relevant, but not an answer :(
Thanks!

A: The short answer, is that with NetBeans 8.0, you can't use any normal technique. NetBeans ant does not use the platforms environment variables, so ANT_OPTS does not work, though it should. Also, nb_ant ignores ~/.ant/antlib, and even adding jars to foo/NetBeans 8.0.2/extide/ant/lib does not work. I'm filing this as a bug, but I expect it will be fruitless.
Anyway, you CAN edit a build file, and add a custom task that installs a custom listener. But you must also add the jar for your task+listener to NBs ant classpath in the correct NB dialog. So I created a tiny class:
public class Installer extends Task {

    @Override
    public void execute() throws BuildException {
       getProject().addBuildListener(new SimpleListener());
    }

}

and in my build.xml
<taskdef name="installListener" classname="org.smottguyz.antlisteners.Installer"/>
<installListener/>

The add the jar in the dialog "Options/Java/Ant/Classpath:"
Pretty annoying actually. Anyway, using scriptdef like on Josef Betancourt's blog post buys nothing in this case.


text:
Q: Bullet Chart: Can't get the d3.scale().linear().domain() right for each element in data array Trying to rebuild Mike Bostock's basic bullet chart example from the ground up, in order to understand what is going on.
Stuck at the point where I establish the domain, in order to get a different scale and axis ticks for each chart.
Temporarily set the domain to [0, 35], but what I really want is different domains for each individual chart, following the formula: .domain([0, semaine[x].disponibilite]).
Code and chart: bl.ock
...a simplification of objects array:
var semaine = [{"individu":"Stefan", "disponibilite": 28, "totalAffectations": 25},
{"individu":"Geneviève","disponibilite": 32, "totalAffectations": 14},
{"individu":"Marie","disponibilite": 35},
{"individu":"David","disponibilite": 40}];

...The line I can't seem to get right.
var disponibiliteScale = d3.scale.linear()
    **.domain([0, 35])**
    .range([0, width]);

Tried several ways, but I can't seem to get it right. Help would be most welcome... Thanks!


text:
Q: Firebase email saying my realtime database has insecure rules: Solution I've stopped to receive emails from Firebase telling me that my realtime database has insecure rules. Here is the beginning of the rules I have set:
{
  "rules": {
    "aaa":{
    ".read": "auth != null",
    ".write": "auth != null",
    },
    "bbb":{
    ".read": "auth != null",
    ".write": "auth != null",
    },
//..... rest of the rules.
  }
}

Here "aaa" and "bbb" are the nodes I use in my Firebase realtime databse. So you should mention all of yours.
Is this solution suitable?

A: Your security rules should only allow what your application code does, and nothing more.
So if your code writes directly to aaa and/or bbb and writes whatever data it wants there, then your rules match that.
But typically your code will write data of a specific structure, in which case you should validate that structure with validation rules.
Also: does your code really need to delete or replace the entire aaa and/or bbb node? Or does it only need to append new child nodes to it? Because right now, your rules allow any user to take the configuration from your application and then do firebase.database().ref("aaa").remove() and wipe whatever is under it. Again: if that matches with what your application does, then the rules match that. But... it seem unlikely.

A: Always try to include User UID for more security.
"aaa":{
   "$uid": {
      ".read": "auth != null && auth.uid === $uid",".write": "auth != null && auth.uid === $uid"
   }
}


text:
Q: Remote debugging in VB6 Is it possible to remotely debug a process started outside VB6?
The application is a VB6 application with quite a few dll/ocx resources. I am attempting to setup a ClickOnce deployment, using Registration-Free COM, of the VB6 app but have been getting errors when it executes.
My understanding of the way that VB6 redirects COM registerations will probably mean that this is not possible but I thought someone might have a better idea.

A: To support Darryl's answer suggesting Windbg - here's a 2006 blog post by a Microsoft guy about using Windbg with VB6, and 2004 blog post by another Microsoft guy with a brief introduction to Windbg.
EDIT: Just to make it totally clear. Windbg is a free standalone debugger from Microsoft. Compile your VB6 EXEs, DLLs and OCXs into native code with symbols (create PDB files) and you will be able to debug your ClickOnce application.
Key excerpt from the blog:

If you have limited access to the server machine then you can use the
  remote debugging facilities of WinDbg. Attach a copy of WinDbg to the
  process in the usual way and then turn it in to a debugging server
  (check out .server in the WinDbg help). You can then connect to it
  remotely from the File menu of WinDbg. It will be just like being
  there except for the lack of noise from the server room fans. When
  debugging a remote, your copy of WinDbg is just a very smart terminal
  so all extensions, symbols and so on have to be on the remote server.
  You set this up the exact same way for any DLL, VB6 or .NET.
The symbols for your component will not load until your component does
  and so you have to let the server run at least that long. You can put
  a break in early in your VB code if you want to stop the debugger at
  that point but if you do, remember that it will stop there every time
  through the code. Let's assume that you let it run and then break in.
  If you list the loaded symbols for your module with "x MyModule!*"
  then you will see all of your functions together with a lot of symbols
  bundled in there for you. VB adds interfaces and symbols quite
  unashamedly but you don't generally need to worry about those. One
  thing that will probably look strange is that all class/method syntax
  with the C++ double colon convention instead of the friendly little
  dot. WinDbg doesn't understand that VB is different and it is treated
  just like any DLL with symbols.
From here, you can set breakpoints in the usual way (bp etc) and step
  through code. You can also open up VB source code modules and set
  breakpoints in them with F9 although the VB file extensions are not in
  the source file type dropdown. Stepping through the code is revealing
  but might be a little alarming if you have not seen the code that VB
  generates for you before. You will be stepping through the assembler
  and there is a lot of COM goo in there. Hresults get checked a lot.
  You will probably need to refer to the source often to work out where
  you are since it takes a bit of practice to be able to know what the
  source code looked like. Variants are especially challenging because
  VB does a lot of work for you there and what looks like a simple
  equation can result in a great deal of code. Optimised code is even
  harder because the order of execution is often very different from
  what you might expect and it is harder than usual to see the data.
Data is not easy to get at this way. When you look at local variables
  (dv is the command) then you may see that variables are simply listed
  as eclipsed which means that the memory is being used for something
  else as well within the function lifetime or that the name is not
  unique in this context. Enums just show as integers or longs and
  objects show as pointers. In fact, they always were exactly that but
  the VB IDE hides that from you. VB strings are COM BSTRs (and
  accordingly Unicode) under the covers and byte arrays are really char
  arrays. You might be surprised to discover that VB strings are Unicode
  as VB appears to have no support for anything but ANSI. That is
  because the Ruby forms engine was ANSI only. The runtime converts the
  Unicode strings to ANSI for Ruby and API calls although there are ways
  to pass Unicode if you want.
You are not going to be able to get at the Err, App or Printer objects
  since you would need to go through a lot of internal and completely
  undocumented structures to get at them. Even if you could get there,
  they would just be raw data without the accessor functions that you
  use in VB. If you need to look at any of those fields, your best bet
  is to embed debug code in the source code to copy their values to
  somewhere that you can get at.
You can step in to the VB runtime if you want but it probably won't be
  very revealing if you are trying to debug your application. If you do,
  you will notice that VB's internals are very COM influenced. The
  influence was actually two way since some COM ideas came from VB
  originally.
You may see exceptions when running your code. Null reference
  exceptions (i.e dereferencing a null pointer) are not uncommon or
  anything to worry about. They will show up as first chance C000005
  exceptions with a 0 or almost 0 address. The runtime will sometimes do
  that if there are objects set to nothing but that is safe because the
  only possible values are null or a valid value. You will also see
  exceptions if your code does lookups in collections and the value is
  not there. Because exceptions are now so expensive, you probably want
  to avoid doing that if you can. Another exception that you will
  commonly see is c000008f. If you look the number up then you will find
  that it is a floating point inexact result exception. It is used in a
  different meaning here – since we don't generate real floating point
  inexact result exceptions, they can safely be thrown to indicate VB
  errors of the normal trappable type.
Debugging hangs and crashes in VB components is done very much in the
  same way as with any other unmanaged component but it is just a little
  harder because of the compilations described above. If you have to try
  debugging VB code this way, I would strongly recommend that you start
  on a "Hello world" application and work your way up. All the things
  that may VB an easy language to code in make it a terrible language to
  debug.

A: I believe that when debugging in VB6, it does not attach to a running binary but instead interprets the code within it's own process. This is why the Task Manager and Win32 APIs show VB6.exe as the running app when debugging.
Also as you say, VB6 sometimes short-circuits calls to COM libraries so intercepting these calls is not always possible.
You're probably going to have to resort to intelligent logging (i.e. log the values of variables around the points where the errors you are getting occur in the hope of locating the line of code it occurs on, and/or the state of relevant variables.)
Good luck

A: Have you tried windbg?  Just make sure you have pdb files for the project.


text:
Q: Two UserDetailsServices in Spring, Java config I am trying to configure two UserDetailsServices for the authentication of two different user groups and I came across this post. However, it is using xml configuration, how would I accomplish the same using Java configuration?
As far as I know, the http element is configured by overriding the configure(HttpSecurity http) method, but how do I configure multiple http elements?
I do know that in many scenarios, it would be sufficient to have one UserDetailsManager which manages two user database tables, but I am curious how the other solution would look like in case I decide for it.

A: I do not see any reason for you to be using 2 UserDetails implementations, as you are saying you need to authenticate two different user groups. Would suggest to look at http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#authorization and think would give you a lot of pointers where you should go from there.
What you are in need is upon authentication in system to know what the logged in user Role is and define it. Two ways are indeed one via xml second is Annotation based in a @Configuration java class with the specifics laid out there. Read up the above link I posted for you and you should be able to see what Spring offers and what you are in need to do actually.
Would take a lot of space First to put it down and Second it is a very broad question you are asking as the post link you are referring to is incorrect in the way it handles Spring Security.