text:
Q: Как выводить рандомную строку? Как выводить рандомную строку после остановки анимации, например?
На данный момент у меня реализовано так:
    @Override
    public void onAnimationEnd(Animation animation) {
        //вывод текст здесь
        String[] texts = {};
        Set<Integer> generated = new HashSet<Integer>();
        Random random = new Random ();
        int pos = random.nextInt(texts.length);

        ((TextView) findViewById(R.id.myTextView)).setText(texts[pos]);
    }

    @Override
    public void onAnimationRepeat(Animation animation) {

    }
});

Но проблема в том, что значений в String[] texts = {раз, два, ......, тысяча}; больше тысячи это во первых, а во вторых хотелось бы хранить все в строках, так как в дальнейшем планируется локализация для разных языков.

@Override
            public void onAnimationEnd(Animation animation) {
                //вывод текст здесь

                Resources res = getResources();
                String[] planets = res.getStringArray(R.array.planets_array);

                Set<Integer> generated = new HashSet<Integer>();
                Random random = new Random ();
                int pos = random.nextInt(R.array.planets_array);

                ((TextView) findViewById(R.id.myTextView)).setText(planets[pos]);

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

    }

    }

CatLog выдает следующее:
-09 23:03:08.846 3579-3579/ru.infernal93.butilochka E/AndroidRuntime: FATAL EXCEPTION: main
                                                                        Process: ru.infernal93.butilochka, PID: 3579
                                                                        java.lang.ArrayIndexOutOfBoundsException: length=4; index=2122146214
                                                                            at ru.infernal93.butilochka.ActivityGame$2.onAnimationEnd(ActivityGame.java:81)
                                                                            at android.view.animation.Animation$3.run(Animation.java:376)
                                                                            at android.os.Handler.handleCallback(Handler.java:742)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                            at android.os.Looper.loop(Looper.java:154)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:5527)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
10-09 23:03:08.848 3579-3579/ru.infernal93.butilochka E/MQSEventManagerDelegate: failed to get MQSService.

A: В ресурсах можно хранить массивы
<resources>
    <string-array name="planets_array">
        <item>Mercury</item>
        <item>Venus</item>
        <item>Earth</item>
        <item>Mars</item>
    </string-array>
</resources>

Resources res = getResources();
String[] planets = res.getStringArray(R.array.planets_array);


text:
Q: sprocket file oclazyLoad not found I am using bower rails gem
gem "bower-rails" #, "~> 0.9.0"

On my Bowerfile
asset 'oclazyload'

This produces a bower.json file with
"ocLazyLoad": "latest"

Then I require the module
//= require oclazyLoad

This works on localhost but when I deploy I am getting an error.
Sprockets::FileNotFound: couldn't find file 'oclazyLoad' with type 'application/javascript'

redpajama_set_name: RedPajamaStackExchange


text:
Q: Different layout for orientation AND screen size - Android I know you can specify a different layout file for orientation by creating a directory;
layout-land
And I know you can create another layout file for a large(tablet) screen size by creating a directory;
layout-large
My question is, can you create a directory that supports both? Something like;
layout-land-large
It's vital for a piece of work that a certain screen layout is displayed only on a tablet device in landscape mode, otherwise it's the default. If my solution isn't valid, is there another way to do this?
Thanks.

A: Change the folder name to: layout-large-land
This link explains how provide resources for different configurations:
http://developer.android.com/guide/topics/resources/providing-resources.html


text:
Q: ASP.NET MVC Web API value encoding I'm passing values from a C# application to an ASP.NET MVC Web API that's been created. I've learned that when my value includes "\" like the the following:
{ id:"1", path:"D:\Backup\DataSource\MyFile.txt", name:"test" }

that the parameter in MyAction is null.
[HttpPost]
public CustomResponse MyAction(CustomEntity entity)
{
  ... // do stuff
}

public class CustomEntity
{
  public string id { get; set; }
  public string path { get; set; }
  public string name { get; set; }
}

If the path does NOT include "\" everything works as intended. I'm guessing this is some type of encoding issue. However, I'm not sure what kind of encoding I need to use before I send the values from my C# app to the Web API.
What kind of encoding do I need to use?


text:
Q: How to add unique entries of Map to List using Java Streams? I have a List<Object> element in Java which contains Map<String, String> before adding a new Map<String, String> I would like to know if there is any Map in List already has that Key, if so do not add it. If there is no matching then add it.
I am trying to use the flatMap approach but getting a bit confused halfway through and unable to find an efficient approach. Hence, Looking for some suggestions on efficient and less processing approaches.
Also, if I am doing the check on the empty list then it's failing as well and not adding the values. I would like to do the check for the key before adding every map if not present then add it, if present skip it.
Following is the code I have so far:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Test {
    public static void main(String[] args) {
        List<Object> list = new ArrayList<>();
        list.add("String Element");

        Map<String, String> map1 = new HashMap<>();
        map1.put("key1", "value1");
        list.add(map1);

        Map<String, String> map2 = new HashMap<>();
        map2.put("key2", "value2");
        list.add(map2);

        Map<String, String> map3 = new HashMap<>();
        map3.put("key3", "value3");
        list.add(map3);

        System.out.println("Before Duplicate Addition : " + list);
        Map<String,String> dupChecker = list.stream().filter(c -> c instanceof Map<?, ?>).map(c -> (Map<String, String>) c).flatMap(m -> m.entrySet().stream()).collect(Collectors.toMap(en->en.getKey(), en-> en.getValue(), (r1, r2) -> r1));

    }
}

A: You have to split the problem into 3 steps:

*

*collect the entries (groupsByKey)

*group by key and get the number of entries per key (groupsByKey)

*filter the entries having a count equal to 1 (finalResult)

List<Map.Entry<String, String>> entries = list.stream()
        .filter(c -> c instanceof Map<?, ?>)
        .map(c -> (Map<String, String>) c)
        .flatMap(m -> m.entrySet().stream())
        .toList();

Map<String, Long> groupsByKey = entries.stream()
        .collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.counting()));

Map<String, String> finalResult = entries.stream()
        .filter(e -> groupsByKey.get(e.getKey()) == 1)
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));


text:
Q: What is the positive class in anomaly detection? Currently, I try to implement an anomaly detection algorithm with scikit-learn in python. I relabeled the dataset to Inliers (Normal instances) are labelled 1, while outliers (Anomaly instances) are labelled -1 (Reference)
For the calculation of accuracy_score, precision_score, recall_score and f1_score I get different values when I set pos_label=1 or pos_label=-1.
So what is the label of the positive class in the context of anomaly detection: 1 or -1?

A: You are interested in finding what samples are outliers. Then, positive class is the outliers.
Note: Generally, you should try to improve the recall rather than the precision score, because you need to reduce false negatives (predict that an outlier is an inlier)


text:
Q: Invite friends to event facebook api My script is pretty slow when inviting users to event, because it has to check if user already is invited to the event, or else it will give a facebook ouath error.
Can i make it faster?
foreach ( $_POST['friends'] as $ids ) {
    if ( $i < 199 ) {
        $iZ = $facebook->api("/".$event_id."/invited/".$ids, "GET");
            if ( $iZ['data'][0]['rsvp_status']):
                    $status = $iZ['data'][0]['rsvp_status'];
            else:
                    $status="";
            endif;

    if ( ($status != 'declined' && $status != 'attending' && $status != "unsure" && $status !=     "not_replied") || empty($status)) {
            $id.=$ids . ",";
            $i=$i+1;
    }
 }
}

$id = substr_replace($id ,"",-1);

echo $facebook->api("/".$event_id . "/invited",'POST', array("users" => $id));

A: Like Cbroe says, use FQL, here is the code:
SELECT uid,name FROM user WHERE uid IN
(SELECT uid1 FROM friend WHERE uid2=me()) AND NOT
(uid IN (SELECT uid FROM event_member where eid = 306212359507086))

This will give you the list of friends not invited to that event.
Dont forget to change the event id
Try it on Graph Explorer
Cheers

A: Two possible approaches:

*

*use batch requests to post the invite for each user id individually (individually, but still all with one request) – if single invite fails, that does not matter, the following invite posts will still be made.

*"cross-sect" your friend id list with the FQL event_members table first – get the list of all event members that match your friend ids (using WHERE eid='event_id' AND uid IN(…,…)), and then "subtract" the result (people that have already been invited to the event) from your original friend id list. (In PHP you could use array_diff for that.)


text:
Q: Homomorphisms $h:C_5 \to Aut(C_{31})$ (first course in group theory) I am asked to show explicitly all homomorphisms $h: C_q \to Aut(C_{31})$ for $q=5,3,2,29$
For $q=5$, $C_5 =\{1,y^2,...,y^4\}$ and $Aut(C_{31})=C_{30}=\{1,\alpha,...,\alpha^{29}\}$ so we know the order of $h(y)$ is 5. There are 4 elements of order 5 in $C_{30}$: $\alpha^6,\alpha^{12},\alpha^{18}$ and $\alpha^{24}$. But what is the strategy for identifying these explicitly in terms of automorphisms $\phi_a: x \mapsto x^a$? The only way I can think of is computing the orders of $\phi_a$ (all 30 of them...) and see which ones have order 5 but this can't be the best strategy(?!) I suppose I need to solve $a^5 $(mod 31) $=1$ but is there a way of doing this without going mental with the calculator? Finally, can I perhaps identify a generator $\phi_a$ of $Aut(C_{31})$ then the homomorphisms would be $\phi_a^6, \phi_a^{12},\phi_a^{18},\phi_a^{24}$ and what is a quick way of identifying $\phi_a$? Thanks.

A: By a theorem,  $\rm{Aut}(C_{31})$ is cyclic.
You will indeed need a primitive $\pmod{31}$, to describe these explicitly. There's no method for finding a primitive generally, so pick an element at random and check it.  Try $2$.  By a theorem,  it will be primitive precisely when $2^6\equiv 64\equiv 2\not\equiv 1$,  $2^{10}\equiv32\equiv 1$.  Oops, that means $2$ isn't primitive.   So try $3$.  $3^6\equiv 16\not\equiv 1$.  And $3^{10}\equiv 16\cdot 19\equiv 304\equiv-6\not \equiv 1$.  Finally $3^{15}\equiv -6\cdot 243\equiv 30\equiv-1$
Thus $3$ is primitive. So $\phi _3$ given by $\phi_3(1)=3$ generates $\rm{Aut}(C_{31})$.
Now, that means it has order $30$.  So the  $\varphi (5)=4$ elements of order $5$ are:  $3^6,3^{12},3^{18},3^{24}$.  These are $16,8,4,2$.
Now take $C_5$.  Any homomorphism is determined by $h(1)$.  So there are $5$.  They coincide with $h(1)=1,16,8,4,2$.
Use the same idea for $C_3,C_2$.  There's respectively $3$ and $2$ homomorphisms.
For $C_{29}$, things are particularly simple,  because $(29,30)=1$.  This means that there is only one homomorphism,  the trivial one.

A: Well here is one approach: pick a random element $b\neq 0 \pmod{31}$ and set $a\equiv b^6 \pmod{31}$. Unless you got unlucky and $b$ happened to be in the subgroup of order 6 (which only has probability $6/30=1/5$), then you'll have $a\neq 1$. Then
$$a^5 = (b^6)^5 = b^{30} = 1 \pmod{31}$$
so $\phi_{a}$ will be an automorphism of order 5, and the others will be $\phi_a^2, \phi_a^3$, and $\phi_a^4$.

A: A generator for $\text{Aut}(C_{31})$ is $\alpha: x \mapsto x^3$ ($3$ is a primitive element for $(\Bbb Z_{31})^{\times}$). So the $4$ elements of $\text{Aut}(C_{31})$ of order $5$ will be:
$\alpha^6: x \mapsto x^{16}$
$\alpha^{12}: x \mapsto x^8$
$\alpha^{18}: x \mapsto x^4$
$\alpha^{24}: x \mapsto x^2$
Don't forget to include the trivial homomorphisms $C_q \to \text{Aut}(C_{31})$ given by $h(y) = \text{id}_{C_{31}}$ for all $y \in C_q$.


text:
Q: Debezium: Check if snapshot is complete for postgres initial_only I'm using Debezium postgres connector v1.4.2.Final.
I'm using snapshot.mode=initial_only, where I only want to get the table(s) snapshot and not stream the incremental changes. Once the snapshot is completed, I want to stop/kill the connector. How can I find out if the snapshotting is complete and that it's safe to kill the connector?
I'm using this to be able to add new tables to an existing connector. For doing that I'm trying this:

*

*kill the original connector (snapshot.mode=initial)

*start a new connector with snapshot.mode=initial_only for new tables

*stop the new connector once snapshotting is complete

*Start original connector after adding new tables to table.whitelist

A: please check JMX metrics. Verify if this one https://debezium.io/documentation/reference/1.5/connectors/postgresql.html#connectors-snaps-metric-snapshotcompleted_postgresql would suite to your needs.


text:
Q: Can you run multiple Flask SQLAlchemy queries in parallel? In my current setup, if I do five 100ms queries, they take 500ms total. Is there a way I can run them in parallel so it only takes 100ms?
I'm running Flask behind nginx/uwsgi, but can change any of that.
Specifically, I'd like to be able to turn code from this:
result_1 = db.session.query(...).all()
result_2 = db.session.query(...).all()
result_3 = db.session.query(...).all()

To something like this:
result_1, result_2, result_3 = run_in_parallel([
  db.session.query(...).all(),
  db.session.query(...).all(),
  db.session.query(...).all(),
])

Is there a way to do that with Flask and SQLAlchemy?

A: Parallelism in general
In general, if you want to run tasks in parallel you can use threads or processes. In python, threads are great for tasks that are I/O bound (meaning the time they take is spent waiting on another resource - waiting for your database, or for the disk, or for a remote webserver), and processes are great for tasks that are CPU bound (math and other computationally intensive tasks).
concurrent.futures
In your case, threads are ideal. Python has a threading module that you can look into, but there's a fair bit to unpack: safely using threads usually means limiting the number of threads that can be run by using a pool of threads and a queue for tasks. For that reason I much prefer concurrent.futures library, which provides wrappers around threading to give you an easy to use interface and to handle a lot of the complexity for you.
When using concurrent.futures, you create an executor, and then you submit tasks to it along with a list of arguments. Instead of calling a function like this:
# get 4 to the power of 5
result = pow(4, 5)
print(result)

You submit the function, and its arguments:
You would normally use concurrent.futures a bit like this:
from concurrent.futures import ThreadPoolExecutor
executor = ThreadPoolExecutor()
future = executor.submit(pow, 4, 5)
print(future.result())

Notice how we don't call the function by using pow(), we submit the function object pow which the executor will call inside a thread.
To make it easier to use the concurrent.futures library with Flask, you can use flask-executor which works like any other Flask extension. It also handles the edge cases where your background tasks require access to Flask's context locals (like the app, session, g or request objects) inside a background task. Full disclosure: I wrote and maintain this library.
(Fun fact: concurrent.futures wraps both threading and multiprocessing, using the same API - so if you find yourself needing multiprocessing for CPU bound tasks in future, you can use the same library in the same way to achieve your goal)
Putting it all together
Here's what using flask-executor to run SQLAlchemy tasks in parallel looks like:
from flask_executor import Executor
# ... define your `app` and `db` objects

executor = Executor(app)

# run the same query three times in parallel and collect all the results
futures = []
for i in range(3):
    # note the lack of () after ".all", as we're passing the function object, not calling it ourselves
    future = executor.submit(db.session.query(MyModel).all)
    futures.append(future)

for future in futures:
    print(future.result())

Boom, you have now run multiple Flask SQLAlchemy queries in parallel.


text:
Q: Why smaller alloc doesn't change malloc_info but larger ones does I was playing around with malloc_info today and I discovered some very strange behaviors. The malloc_info size doesn't grow linearly with the size of malloc I am calling. It jumps around with different parameters to malloc and there are certain magic numbers that just keeps showing up. I was guessing this might be some kind of optimization by c to allocate chunk by chunk without actually using all of them.
Some interesting magic numbers
<aspace type="total" size="135168"/> happens for most of malloc calls that don't ask for a huge memory. Like malloc(1500)
<system type="current" size="270336"/> happens for slightly larger ones. Like malloc(1500 called 100 times in a loop.
But the interesting thing is, malloc(1000) called 100 times in a loop gives me the magic number 135168 again. So it seems to be some arbitrary cut off between 1000 and 1500 called 100 times in a loop.
Can anyone shine some light on this strange behavior? I am doing a task of replacing old mallinfo with 64 bit compatible function


text:
Q: Simulating click via Android Accessibility Service I am trying to simulate a click function in an android application utilizing the Accessability Service. I have set up the service in the manifest, and enabled it in my phones settings. I have a class MouseAccessabilityService which contains a the following click function:
// Clikc function that clicks at a specific x and y coordinate
@RequiresApi(api = Build.VERSION_CODES.N)
public static GestureDescription click(float x, float y) {
    // for a single tap a duration of 1 ms is enough
    final int DURATION = 1;

    Path clickPath = new Path();
    clickPath.moveTo(x, y);
    GestureDescription.StrokeDescription clickStroke =
            new GestureDescription.StrokeDescription(clickPath, 0, DURATION);
    GestureDescription.Builder clickBuilder = new GestureDescription.Builder();
    clickBuilder.addStroke(clickStroke);
    return clickBuilder.build();
}

I am calling the click function in the MainActivity via a button press that triggers the click (for testing purposes):
Buttonclick = (Button)findViewById(R.id.clickbutton);

    Buttonclick.setOnClickListener(new View.OnClickListener() {
        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void onClick(View view) {
            //changeButtonText.setText("Second Text");
            MouseAccessabilityService.click(centerX, centerY);
        }
    });

The X and Y is being passed as an integer variable from some other functionality. I can not seem to get the click() function to work from within my app and press on a button.
Am I on the right page? Can this functionality even work? I am at a standstill with this and would appreciate any help.
Thanks.

A: You can use the dispatchGesture function.
Try replacing your click function's return with :
return dispatchGesture(clickBuilder.build(), null, null);
https://codelabs.developers.google.com/codelabs/developing-android-a11y-service/#7


text:
Q: How do install the generated Maven RPM artifact to local m2 repo with the correct rpm name? So I can use the maven RPM plugin successfully to generate the RPM artifact as expected.
I use the attached-rpm goal in a pom.xml (packaged as a pom) so that the RPM plugin installs the artifact into the local m2 repository (as it is  bound to the package phase).
Problem: The RPM generated name is great and is as follows : code-module-1.0.3-SNAPSHOT20120727095507.amd64.rpm
However when maven installs this to my local repo I end up with:
code-module-rpm-1.0.3-SNAPSHOT-rpm.rpm
I lose the the full name, the architecture part of the RPM and instead Maven is appending rpm to the end of the name before the .rpm extension (the classifier that I havent defined) and is using my pom artifact id as the rpm name instead of the rpm name itself.
I tried using the build-helper plugin to point to the generated RPM in the target directory but this doesnt work as the rpm name is dynamically generated and the build-helper plugin only accepts full file name no wildcards etc.
I dont want to change the final name of the artifact as I'd be breaking maven convention.
Here is the maven output:
[INFO] Installing /home/xzcx/Development/repository/svn/source/parent-project
/code-module-rpm/target/rpm/code-module/RPMS/amd64/code-module-1.0.3-
SNAPSHOT20120727145507.amd64.rpm to
/home/xzcx/.m2/repository/com/xpackage/ypackage/codepackage/code-module-rpm/1.0.3-
SNAPSHOT/code-module-rpm-1.0.3-SNAPSHOT-rpm.rpm

Any thoughts please?
Update: I noted that the RPM Plugin site states that using the attached:RPM goal will allow you to build multiple RPMs say with different architectures etc...but based on the above the only way this would work would be to use classifiers as the arch bit of the RPM name doesnt get carried over to the installation on the local repo.

A: The classifier field is an important piece because often the file extension is not enough to differentiate project artifacts (e.g. foobar-1.0.jar, foobar-1.0-javadoc.jar, foobar-1.0-sources.jar all have file extension jar).

Beside the main artifact there can be additional files which are
  attached to the Maven project. Such attached filed can be recognized
  and accessed by their classifier.

http://maven.apache.org/plugins/maven-deploy-plugin/examples/deploying-with-classifiers.html
All project artifacts are associated with each other by the  project.artifactId + project.version and consequently are named <artifactId>-<version>-<classifier>.<ext>.
http://maven.apache.org/plugins/maven-install-plugin/examples/installing-secondary-artifacts.html

A: I am having the same issue, but the main thing I want is to remove the -rpm from code-module-rpm-1.0.3-SNAPSHOT-rpm.rpm because I feel it is redundant.  I should have been named this: code-module-rpm-1.0.3-SNAPSHOT.rpm (at a minimum)


text:
Q: Como escolher um certificado digital? O que levar em conta? Estou trabalhando em uma loja virtual, e preciso saber qual o melhor certificado em relação Custo x Benefício, preciso indicar um certificado para o cliente, mas essa é a primeira vez que trabalho com um.
Lembrando que como é uma loja virtual, ela trabalhará com alguns dados sensíveis como número de cartão de crédito e etc. Então é vital que a comunicação transite em um canal seguro e também que o usuário possa reconhecer essa segurança.
Algumas opções de Certificado Digital:
 ____________________________________________________________________________________________________________________________________________________
| Certificadora     | Certificado           | Encriptação                   | Informações                                       | Preço              |
|-------------------------------------------|-------------------------------|---------------------------------------------------|--------------------|
| GeoTrust          | Rapid SSL             | 128 bits                      | Compatibilidade com 99% dos browsers              | R$ 74.00BRL /ano   |
|                   |                       |                               | Selo GeoTrust True Site                           |                    |
|                   |-----------------------|-------------------------------|---------------------------------------------------|--------------------|
|                   | Quick SSL             | SSL até 256-bits              | Compatibilidade com 99% dos browsers              | R$ 290.00BRL /ano  |
|                   |                       |                               | Emissão rápida e instalação fácil                 |                    |
|                   |-----------------------|-------------------------------|---------------------------------------------------|--------------------|
|                   | QuickSSL Premium      | 256-bits                      | Compatibilidade com 99% dos browsers              | R$ 330.00BRL /ano  |
|                   |                       |                               | Selo GeoTrust True Site                           |                    |
|                   |-----------------------|-------------------------------|---------------------------------------------------|--------------------|
|                   | True BusinessID       | SSL 256-bit                   | Compatibilidade com 99% dos browsers              | R$ 450.00BRL /ano  |
|                   |                       |                               | Fácil e rápido de instalar                        |                    |
|===================|=======================|===============================|===================================================|====================|
| VerySign          | Secure Site           | SSL até 256-bits              | Selo VerySign Secured®                            | R$1,100.00BRL /ano |
|                   |                       |                               | Verificador de instalação                         |                    |
|                   |-----------------------|-------------------------------|---------------------------------------------------|--------------------|
|                   | Secure Site Pro       | SSL de 128-bit até 256-bit    | Validação domínio e organização                   | R$2,400.00BRL /ano |
|                   |                       |                               | Selo VerySign Secured®                            |                    |
|                   |-----------------------|-------------------------------|---------------------------------------------------|--------------------|
|                   | Secure Site EV        | SSL até 256-bits              | Validação Avançada (EV): Barra de endereço verde  | R$2,600.00BRL /ano |
|                   |                       |                               | Selo VerySign Secured®                            |                    |
|                   |-----------------------|-------------------------------|---------------------------------------------------|--------------------|
|                   | Secure Site Pro EV    | SSL de 128-bit até 256-bit    | Validação Avançada (EV): Barra de endereço verde  | R$4,200.00BRL /ano |
|                   |                       |                               | Selo VerySign Secured®                            |                    |
|___________________|_______________________|_______________________________|___________________________________________________|____________________|

As dúvidas que tenho são as seguintes:

*

*Os certificados da GeoTrust são inferiores aos da VerySign?

*

*Por isso são mais baratos?

*Ou apenas tem "menos nome" no mercado?

*Por que as encriptações são até X-bits?

*

*X-bits é o tamanho da chave de criptografia?

*Compensa pagar mais por uma "barra verde"?

*

*Por quê?

*Tem alguma influência por baixo dos panos?

A: Certificados mais baratos:

*

*tem menos nome, isto importa em algumas situações, em parte existe um motivo para ter menos nome, em parte é marketing;

*são aceitos em menos navegadores e outros softwares (em geral sistemas operacionais) que buscam certificados, mas isto não costuma ser um problema sério hoje em dia já que todos os principais são aceitos em navegadores até bem antigos e aplicações que você tem controle pode adicionar entidade certificadora, isto é importante mas já foi mais que hoje;

*as indenizações se ocorrer alguma quebra são maiores nos mais caros, os mais baratos talvez nem exista tal compensação;

Os certificados da GeoTrust são inferiores aos da VerySign?
  - Por isso são mais baratos?
  - Ou apenas tem "menos nome" no mercado?

Se os gratuitos, GeoTrust, Verisign ou outra marca são inferiores vai da necessidade e objetivo de cada um. Para a maioria dos casos, faz pouca ou nenhuma diferença. Por isso hoje o grosso do uso vai com Let's Encrypt.

Por que as encriptações são até X-bits?
  - X-bits é o tamanho da chave de criptografia?

A quantidade de bits indica a força da proteção da chave, o quanto é difícil quebrar a criptografia da chave. Não dos dados que sua aplicação/site trafega. Evidentemente há um custo de processamento maior com chaves maiores. Mas o custo é maior por razões comerciais e talvez porque ele ofereça algo a mais, tenha um processo de verificação mais apurado e obviamente mais custoso. Isto não costuma ser um problema nos dias de hoje.
Mas tenha em mente que a certificação só garante quem é que está daquele lado, ele não te protege de nada e não protege o usuário além de dizer que o fornecedor que eles está acessando é aquilo mesmo.

Compensa pagar mais por uma "barra verde"?
  - Por quê?
  - Tem alguma influência por baixo dos panos?

Se compensa pagar mais depende do objetivo. Você acha necessário que os usuários vejam a tal barra verde para se sentirem mais seguros? O mesmo vale para os demais selos de garantia ou barras de outras cores. Mas é só psicológico, marketing.
Cada categoria tem um nível de exigência diferente. Os mais caros exigem mais comprovações da organização certificada e podem deixar os usuários mais seguros. Novamente, você escolhe que nível de segurança (no sentido psicológico mesmo) quer dar ao seu usuário.
É claro que os mais caros podem ter um fluxo de verificação que evitam alguns tipos de ataques como o Man in the Middle. Mas não consegue resolver por completo.
Quanto mais você paga, mais você está dizendo para quem entenda dessas coisas que você quer se mostrar um fornecedor seguro. É claro que o fraudador fará o mesmo para enganar os incautos.
Mesmo nas certificadoras mais caras existem casos graves de fraudes.
O termo segurança usado aqui foi mais no sentido de confiabilidade da pessoa que está atrás do software (provavelmente um site) que o usuário está usando. Mesmo assim diz muito pouco.
A única coisa que o certificado ajuda na segurança é ter uma chave pública de verificação confiável a ser usada. nada impede de você mesmo providenciar esta chave pública. O problema é que os seus usuários terão que confiar 100% em você, não existirá ninguém atestando que você é minimamente confiável. Isto funciona em alguns casos. Mas raramente em sites públicos.

A: No geral, quanto mais caro o certificado, mais "confiável" ele é -- do ponto de vista do cliente.
O tamanho da chave influencia também nesta confiabilidade, mas não é o principal fator. Qualquer certificado novo tem chave suficientemente forte. A chave é "até x bits" porque um browser mais antigo pode negociar uma chave menor (eu acho).
"Confiável" quer dizer que a autoridade certificadora tomou providências para verificar se quem pediu o certificado é realmente a entidade que alega ser.
Um certificado do mais barato, que custa apenas US$ 5 por ano, só verifica que você controla o domínio. Se você tem um e-mail @foobar.com.br, a CA presume que você controla foobar.com.br.
Certificados baratos também costumam ser emitidos por "sub-certificadoras", ou seja, a autoridade certificadora que o browser confia (A) assina o certificado B, que assina o certificado C, e a entidade C é quem vai assinar seu certificado D. Então a cadeia fica A-B-C-D, e provavelmente você terá de incluir os certs. intermediários B e C junto com seu certificado D, pois o browser só conhece A e nem todos fazem download dos certificados intermediários. (Testar o site com o www.sslabs.com é uma boa para pegar este tipo de problema.)
Já o certificado mais caro é assinado direto pela entidade A, então a cadeia de confiança fica bem curta. Não é uma vantagem técnica, mas diminui a chance de problemas, caso um dos certificados intermediários seja falsificado...
Certificados "barra verde" tem EV (Extended Validation), onde o processo de verificação de identidade é mais rigoroso, e mais importante, padronizado. Este tipo de certificado é desejável para bancos, e-commerce, etc. Qualquer hacker pode conseguir um certificado SSL para itauu.com.br, mas só o Itaú vai conseguir um certificado EV "Itaú", e a barrinha só vai ficar verde para itau.com.br.
Seja como for, a confiabilidade do certificado depende da qualidade da autoridade certificadora, e aí uma Verisign da vida tem mais nome que outras.

A: O ponto básico é verificar garantia de compatibilidade com browsers.
Na verdade ninguém precisa comprar certificados SSL pois podem ser gerados gratuitamente.
O problema é que os browsers populares não reconhecem tais certificados a menos que o usuário instale-o no próprio browser e isso é inviável para o público geral. Isso acontece por questões de segurança pois seria um caos se os browsers permitissem qualquer emissor de certificados.
A diferença entre os certificadores homologados está nos recursos oferecidos.
Volume de dados, seguros que variam entre 100k USD e 20m USD (isso mesmo.. 20 milhões de dólares), tipos de cripotografia, dentre outros.
Normalmente oferecem preço mais caro para a green bar, onde a barra da URL fica completamente verde.

Visualmente dá uma melhor impressão, como se fosse mais seguro. Mas para mim, não passa de ostentação. Mas enfim, é apenas um recurso a mais que as empresas emissoras de certificados arranjaram para monetizar mais serviços.
Recomendo os provedores baratos para websites de pequeno e médio porte. Se o site não passa de 15 ou 30 mil acessos únicos / dia, pode usar desses mais baratos. Mas não recomendo um que chama-se "namecheap". Não é ruim, o problema é o nome que aparece na url do browser como "name cheap", causando uma má impressão como se o site fosse barato.
Desses baratos que eu posso recomendar é o "GlobeSSL". Boa reputação, excelente serviço e convenientemente barato.
De qualquer forma, não importa qual o tipo escolher, do mais barato ao mais caro, esteja sempre atento a segurança pois o SSL não é garantia de segurança, como já mencionado em outros comentários.


text:
Q: In Repository, how to replace deprecated load() function? I know we should use service contracts(Repository) over $model->load(), but in Repository itself, how to replace the deprecated load() function?
For example, in Magento\Cms\Model\PageRepository, the official Magento 2.1.9 used the deprecated load() function too.
public function getById($pageId)
{
    $page = $this->pageFactory->create();
    $page->load($pageId);
    if (!$page->getId()) {
        throw new NoSuchEntityException(__('CMS Page with id "%1" does not exist.', $pageId));
    }
    return $page;
}

Reference
When Should We Use a Repository and Factory in Magento 2?
Is there ever a reason to prefer $model->load() over service contracts?

A: You can use ResourceModel's load() instead, which extends
Magento\Framework\EntityManager\EntityManager's load() method.
We could see a example in: Magento\Cms\Model\BlockRepository
public function getById($blockId)
    {
        $block = $this->blockFactory->create();
        $this->resource->load($block, $blockId);
        if (!$block->getId()) {
            throw new NoSuchEntityException(__('CMS Block with id "%1" does not exist.', $blockId));
        }
        return $block;
    }


text:
Q: django-URL inside anchor tag becomes relative to the current page django urls.py
    path('add_a_product_to_store/<store_id>',views.add_a_product_to_store,name='add_a_product_to_store'),
    path('show_a_store/<store_id>', views.show_a_store,name='show_a_store')

show_a_store.html
Add a product

When user enters ip:port/show_a_store/5 .  . . . show_a_store.html is shown.
But the link inside anchor tag points to http://127.0.0.1:8000/show_a_store/add_a_product_to_store/5 instead of http://127.0.0.1:8000/add_a_product_to_store/5
How to make  it point to actual url irrespective of current page?

A: add slash as shown below
path('add_a_product_to_store/<store_id>/',views.add_a_product_to_store,name='add_a_product_to_store'),
path('show_a_store/<store_id>/', views.show_a_store,name='show_a_store')

and template
Add a product

A: You need to use the url template tag
Add a product

A: Thanks for the answers.
I committed a mistake in html.
When using anchor tag, means **ip:port/url-of-current-page/foo/...
But

means ip:port/foo/
If there is no forward slash (/) at the beginning of url,it is treated as a relative url and url of current page is appended to the url.


text:
Q: Which .Net standard version should i use in a library if i have to target both Dot Net Core 3.0 and .Net Framework 4.7.2 I have to migrate few existing Dot Net core 2.2 project to Dot Net core 3.1.
There is a project which is devolved based on .Net Framework 4.7.2.
So we have a common library developed based on .Net Standard 2.0 so that it can target both dotnet 2.2 and .Net framework 4.7.2.
Now if i have to migrate my Dotnet core 2.2 to Dotnet core 3.1 and still continue to use the common library i would have to migrate the common libs to .Net Standard 2.1 (In order to support Dot net core 3.x) but this migration to .Net Standard 2.1 will not allow a .net framework project to use the common library.
Is there any way to handle this current situation?

A: You don't need to update your .NET Standard libraries from 2.0 to 2.1. You can still use them in your .NET Core 3.1 projects. It works the other way if you switch to .NET Standard 2.1 then the version of the project that uses this library will have to be minimum .NET Core 3.0.


text:
Q: How to sum the cost of each item in a One To Many relationship JPA? How could I calculate the total of an order in a one to many relationship, when the customer buys a certain number of items in the order attribute, he wants to know, he could start to investigate, to carry out that. I'm really a little confused, I really want to learn
@Entity
@Table(name = "orders")
class Order(
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        val id: Int? = 0,

        val name: String? = "",
        val address: String? = "",
        val phone: String? = "",

        val totalOrderPrice: Long? // total based on the cost of each item

        @OneToMany(cascade = [CascadeType.MERGE])
        @JoinColumn(name = "order_id")
        val items: List<Items>? = mutableListOf()
)

@Entity
@Table(name = "items")
class Items(
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        val id: Long? = null,
        val name: String? = null,

        val price: Long?, // cost item

    )

A: First you need to correct your mapping. In child entity, you should have parent entity's reference. Which mean in "Items" class add reference to Order id as column "orderId". Then your class should look like this
@Entity
@Table(name = "items")
class Items(
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        val id: Long? = null,
        val orderId: int? = null,
        val name: String? = null,

        val price: Long?, // cost item
    )

Now, You have 3 options here to calculate the total price of order

*

*Write JPA query like this
@Query("SELECT SUM(m.price) FROM Items m where orderId = :orderId")
Long getOrderPrice(@Param("orderId") Long orderId);

*Write Native SQL query like this
@Query("SELECT SUM(price) FROM items where order_id = :orderId", nativeQuery = true)
Long getOrderPrice(@Param("orderId") Long orderId);

*In Java using streams or for loop, calculate the total price
Long sum = order.getItems.map(i->i.getprice()).stream().reduce(Long::sum).get();


text:
Q: how to fetch the other tags by targeting a particular tag Here I have pasted a sample of XML that was tag names like 21A,50F,21D,22B.
Normally if I need to fetch a particular tag,  I can use logic below easily in XSLT:
<xsl:choose>
    <xsl:when test="tag[name = '21A'] ">
        <xsl:choose>
            <xsl:when test="substring(tag[name = '21A']/value,1,1) = '/'">
                <xsl:variable name="result" select="concat(translate(tag[name = '21A']/value,',',' '),'
')"/>
                <xsl:value-of select="substring(substring-before(substring-after($result,'
'),'
'),1,11)"/>
            </xsl:when>
            <xsl:when test="substring(tag[name = '21A']/value,1,1) != '/'">
                <xsl:value-of select="substring(tag[name = '21A']/value,1,11)"/>
            </xsl:when>
        </xsl:choose>
    </xsl:when>
</xsl:choose>

but here I have a requirement as Sequence A and Sequence B.

*

*the tags which populated above 50F come under sequence A

*the tags which populated below 50F come under sequence B
since we need to fetch the tags based on using 50F tag. Can any one please give a suggestion?
<local>
    <message>
        <block4>
            <tag>
                <name>21A</name>
                <value>ALW1031</value>
            </tag>
            <tag>
                <name>50F</name>
                <value>TESTING CITI BANK EFT9</value>
            </tag>
            <tag>
                <name>21D</name>
                <value>OUR</value>
            </tag>
            <tag>
                <name>22B</name>
                <value>ipubby</value>
            </tag>
        </block4>
    </message>
</local>

output required:
ALW1031,OUR

Previously if suppose they have populate 21A two times means I have used the position as [1] and [2] as while calling tag values. Now they will populate 21 tag repeatedly but tags may be A or D so I need to target 50f tag blindly. Whatever tag they will provide, either A or D before 50F I need to fetch similarly whatever they populate tags after 50F we able to fetch so avoiding positions.

Summary:
@Treemonkey: hope you had a glance of my sample XML. It has some tag like 21A,50F and so on. Assume if I have two fields field1,field2 earlier they have populated tags as same repeated tags as 21A at that time I have fetched as 21A having beside by marking position [1] for field 1 (tag[name = '21A'][1])
Similarly 21A having beside by marking position [2] for field 2, now they will populate 21 but tags were different as A or D. As I have said field1 should concentrate sequence A and field2 should concentrate as sequence B so now we should not bother about positions for fetch we have a demarcation like tag 50F whatever fields will populate before 50F has to treated as sequence A and after 50F has to be treated as sequence B.
So finally we need to write as XSLT by targeting 50F. If I want to display 21A field in (sample XML)  which before 50F so we need write a logic in XSLT as select tag 21A  before 50F tag for to produce data in field 1 and for field 2 we need to fetch as 21D after 50F so we need to write a logic as select 21D after 50F.

A: Your requirements aren't exactly clear, but the following expressions should help.
Select all siblings before the tag whose child name has a particular value:
/*/*/*/tag[name='50F']/preceding-sibling::*

Select following siblings:
/*/*/*/tag[name='50F']/following-sibling::*

Select just the immediately preceding element:
/*/*/*/tag[name='50F']/preceding-sibling::*[1]

Select preceding siblings having a child name with a particular value:
/*/*/*/tag[name='50F']/preceding-sibling::*[name='21A']

Select following siblings having a child name with a particular value:
/*/*/*/tag[name='50F']/following-sibling::*[name='21D']


text:
Q: Dedicated GRUB2 Partition and Windows 8 Ok so as many of you may know the Windows 8 developer preview was released today and as such I'm very eager to use it but I have both Ubuntu and Windows 7 installed on my machine. I don't want to disturb these drives and have recently set up a dedicated grub partition on /media/sdb8
My question is if I install windows 8 will it overwrite the grub partition and if so what are the steps I should take to recover it.

A: Windows 8 will not overwrite your boot partition (/media/sdb8) if you you specifically tell Windows not to do so during the installation process (hard disk setup where you select which partition to install C: drive on...). But Windows 8 will overwrite your MBR, as far as I know. So, once Windows 8 is installed, you will not be able to boot into Ubuntu; even though you will still be able to boot into Windows 7.
To fix this problem, you will need the same version of the Ubuntu LiveCD from which you had installed Ubuntu. Using the LiveCD, you can fix the MBR to show a boot screen to select Windows 8, 7 and Ubuntu. The detailed instructions can be found here: https://help.ubuntu.com/community/Grub2#Copy_LiveCD_Files.
I am listing them here for convenience.

*

*Boot the LiveCD Desktop.

*Open a terminal by selecting Applications, Accessories, Terminal from the menu bar.

*Determine the partition with the Ubuntu installation. The fdisk option "-l" is a lowercase "L". sudo fdisk -l or sudo blkid. The device/drive is designated by sdX, with X being the device designation. sda is the first device, sdb is the second, etc. For most users the MBR will be installed to sda, the first drive on their system. The partition is designated by the Y. The first partition is 1, the second is 2. Note the devices and partitions are counted differently. Example: the MBR may be installed on /dev/sdb and the Ubuntu partition may be on /dev/sdb3.

*Mount the partition containing the Ubuntu installation: sudo mount /dev/sdXY /mnt. Example: sudo mount /dev/sdb3 /mnt. Note: If the user has a separate /boot partition, this must be mounted to /mnt/boot. Since you have a separate boot partition (which contains grub - /media/sdb8 - you will need to run the following command as well: sudo mount /dev/sdb8 /mnt/boot. Note: If the user has a separate /home partition, this must be mounted to /mnt/home. Encrypted home partitions should work.

*Run the grub-install command as described below. This will reinstall the GRUB 2 files on the mounted partition to the proper location and to the MBR of the designated device. If you are using 10.04 or 10.10, then run sudo grub-install --root-directory=/mnt /dev/sdX. Example: sudo grub-install --root-directory=/mnt /dev/sdb. If you are using 11.04 or 11.10, then run sudo grub-install --boot-directory=/mnt/boot /dev/sdX. Example: sudo grub-install --boot-directory=/mnt/boot/ /dev/sdb.

*Reboot into the Ubuntu installation on your hard disk.

*Refresh the GRUB 2 menu by typing the following command in your terminal: sudo update-grub.

NOTE: As answered by Steve, "Windows 8 uses the new Protogon file system". Grub does not have support for this file system (yet!). Once this support comes, you can use Grub to boot into the Windows 8 bootloader. Until that time, as suggested by jart, use a separate hard disk to hold the Windows 8 partition and it's bootloader. This way, even the Ubuntu hard disk MBR will not get over-written. Unplug the Ubuntu hard disk when you are installing to the Windows 8 hard disk. Once the installation is complete, plug the Ubuntu hard disk back in, boot into the Ubuntu hard disk (by setting it in the BIOS boot sequence) and follow the steps which I have outlined above.

A: Watch out - Windows 8 uses the new Protogon file system and Grub can't find it.
This means that when you put grub back - you lose the ability to get into Windows 8

A: If money is not a problem, then buy a new hard drive and install windows 8 in that one. That way you will have ubuntu and windows 7 in one, and windows 8 in the other hard drive. You will have to boot windows 8 from the bios though, but you won't have to worry about messing up windows 7 or ubuntu. Before you install windows 8 remember to first unplug the hard drive containing windows 7 and ubuntu. One's you install windows 8 in the new drive re-plug the hard drive containing window 7 and ubuntu.

A: I'm guessing most people finding this question will find it AFTER having already b0rked their bootloader.  I installed Windows 8 on a totally separate disk, and planned on re-installing grub after as usual after doing something hokey with Windows.  Re-installing grub wasn't sufficient fix my boot menu, unfortunately.
So after fixing grub per ubuntu's instructions, I ran
apt-get install startupmanager

in terminal, ran the startupmanager application, and it found the appropriate menus.  Closed it, rebooted, and everything worked.
Please note that using the shutdown option from the Windows 8 menu actual hibernates, so in order to boot back into Linux after hanging out in Windows 8 you'll need to use the restart option, or run the following command in terminal to fully shut it down.
shutdown /s /full / t 0

A: When you install Windows, Windows assumes it's the only OS on the machine—or at least it doesn't account for Linux. So, it replaces GRUB with its own bootloader.
What you have to do is to replace the Windows bootloader with GRUB. Simply chroot into your install and run update-grub.
Here's how: How can I repair grub? (How to get Ubuntu back after installing Windows?)


text:
Q: can i c.connect once in a access.form instead of each form.event? i do have ms.sql backend and ms.access frontend and always retrive the data shown in a form by following code:
    Private Sub combo_search_Change()
        Dim c As New ADODB.Connection
        Dim rs As New ADODB.Recordset

        Dim cmd As ADODB.Command
        Dim Srv As Variant
        Dim db As Variant
        Dim UID As Variant
        Dim pwd As Variant

        Dim strSQL As String

        Dim tbl_name As String
        tbl_name = "tblSQLxxx"

        Srv = CurrentDb.OpenRecordset("SELECT DISTINCT Server FROM [" & tbl_name & "]")(0)
        '-------------------------------------------------------
        db = CurrentDb.OpenRecordset("SELECT DISTINCT db FROM [" & tbl_name & "]")(0)
        '-------------------------------------------------------
        UID = CurrentDb.OpenRecordset("SELECT DISTINCT uid FROM [" & tbl_name & "]")(0)
        '-------------------------------------------------------
        pwd = CurrentDb.OpenRecordset("SELECT DISTINCT pwd FROM [" & tbl_name & "]")(0)
        '---------------------------------------------------------------------------

        c.ConnectionString = "Driver={SQL Server};Server=" & _
                              Trim([Srv]) & ";Database=" & Trim([db]) &""

and then calling with c.open & rs.open the needed data. as i have couple of list.boxes filled on the form, i place on each "on change" "exit" ... this above connection code and therefore flooding my code. is there a way to place the connection.code once in the form and then only call "c.open"&"rs.open" in all the "change/exit/entry" parts of the vba.code?


text:
Q: How to fill the dropdown list dynamically in symfony? (select the cities of the region) I explain my problem:
I have to create a form where the drop-down lists are filled according to our choices in the previous ones.
I have two entities:
A Region may have several Cities (ManyToOne) relationship.
I followed the documentation from here How to Dynamically Modify Forms Using Form Events (Dynamic Generation for Submitted Forms) .
Here is the code for the entities:
Region entity:
class Region
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="nom", type="string", length=255)
     */
    private $nom;

    /**
     * @var int
     *
     * @ORM\Column(name="numero", type="smallint")
     */
    private $numero;
}

Ville Entity:
class Ville
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="nom", type="string", length=255)
     */
    private $nom;

    /**
     * @var int
     *
     * @ORM\Column(name="numero", type="smallint")
     */
    private $numero;

    /**
     * @var int
     *
     * @ORM\Column(name="codePostal", type="smallint")
     */
    private $codePostal;

    /**
     * @var Region
     *
     * @ORM\ManyToOne(targetEntity="GE\CandidatBundle\Entity\Region")
     */
    protected $region;
}

my problem:
I retrieve the list of regions with the query_builder option but how do I retrieve the list of cities according to the choice of region.
AnnonceType:
 $builder
->add('region', EntityType::class, [
                'label' => 'Region *',
                'label_attr' => [
                    "class" => "smaller lighter blue",
                    "style" => "font-size: 21px;",
                ],
                'class'         => 'GECandidatBundle:Region',
                'choice_label'  => 'nom',
                'multiple'      => false,
                'query_builder' => function(RegionRepository $repository) {
                    return $repository->getListeRegion();
                }
            ])
            ->add('ville', TextType::class, [
                'label' => 'Ville *',
                'label_attr' => [
                    "class" => "smaller lighter blue",
                    "style" => "font-size: 21px;",
                ],
            ]);
$formModifier = function (FormInterface $form, Region $region = null) {
            $ville = null === $region ? array() : $region->getNom();

            $form->add('ville', EntityType::class, array(
                'class' => 'GECandidatBundle:Ville',
                'placeholder' => '',
                'choices' => $ville,

                'label' => 'Ville *',
                'label_attr' => [
                    "class" => "smaller lighter blue",
                    "style" => "font-size: 21px;",
                ],
                'choice_label'  => 'nom',
                'multiple'      => false,
                /*'query_builder' => function(VilleRepository $repository) {
                    return $repository->getVilleByRegion();
                }*/
            ));
        };

        $builder->addEventListener(
            FormEvents::PRE_SET_DATA,
            function (FormEvent $event) use ($formModifier) {
                $data = $event->getData();
                $formModifier($event->getForm(), $data->getVille());
            }
        );

        $builder->get('region')->addEventListener(
            FormEvents::POST_SUBMIT,
            function (FormEvent $event) use ($formModifier) {
                $region = $event->getForm()->getData();
                $formModifier($event->getForm()->getParent(), $region);
            }
        );

new.html.twig:
    {{ form_start(form) }}
        {{ form_row(form.region) }}    {# <select id="ge_candidatbundle_annonce_region" ... #}
        {{ form_row(form.ville) }} {# <select id="ge_candidatbundle_annonce_ville" ... #}
        {# ... #}
    {{ form_end(form) }}
<script>
        var $region = $('#ge_candidatbundle_annonce_region');
        $region.change(function() {
            var $form = $(this).closest('form');
            var data = {};
            data[$region.attr('nom')] = $region.val();
            $.ajax({
                url : $form.attr('action'),
                type: $form.attr('method'),
                data : data,
                success: function(html) {
                    $('#ge_candidatbundle_annonce_ville').replaceWith(
                        $(html).find('#ge_candidatbundle_annonce_ville')
                    );
                }
            });
        });
    </script>

A: UPDATE

*

*I modified the entities.

*I modified the AnnonceType.

*I modified the new.html.twig.
Here is the code for the entities:
Region entity:
class Region
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="nom", type="string", length=255)
     */
    private $nom;

    /**
     * @var int
     *
     * @ORM\Column(name="numero", type="smallint")
     */
    private $numero;
/**
 * @ORM\OneToMany(targetEntity="GE\CandidatBundle\Entity\Ville", mappedBy="region")
 **/
protected $villes;

/**
 * Get villes
 *
 * @return \Doctrine\Common\Collections\Collection
 */
public function getVilles()
{
    return $this->villes;
}
}

Ville Entity:
class Ville
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="nom", type="string", length=255)
     */
    private $nom;

    /**
     * @var int
     *
     * @ORM\Column(name="numero", type="smallint")
     */
    private $numero;

    /**
     * @var int
     *
     * @ORM\Column(name="codePostal", type="smallint")
     */
    private $codePostal;

/**
 * @var Region
 * @ORM\ManyToOne(targetEntity="GE\CandidatBundle\Entity\Region", inversedBy="villes")
 */
protected $region;
}

AnnonceType:
     $builder
    ->add('region', EntityType::class, [
                    'label' => 'Region *',
                    'label_attr' => [
                        "class" => "smaller lighter blue",
                        "style" => "font-size: 21px;",
                    ],
                    'class'         => 'GECandidatBundle:Region',
                    'choice_label'  => 'nom',
                    'multiple'      => false,
                    'query_builder' => function(RegionRepository $repository) {
                        return $repository->getListeRegion();
                    }
                ])
                ->add('ville');
$formModifier = function (FormInterface $form, Region $region = null) {
            $villes = null === $region ? array() : $region->getVilles();

            $form->add('ville', EntityType::class, array(
                'class' => 'GECandidatBundle:Ville',
                'placeholder' => '',
                'choices' => $villes,

                'label' => 'Ville *',
                'label_attr' => [
                    "class" => "smaller lighter blue",
                    "style" => "font-size: 21px;",
                ],
                'choice_label'  => 'nom',
                'multiple'      => false,

            ));
        };

        $builder->addEventListener(
            FormEvents::PRE_SET_DATA,
            function (FormEvent $event) use ($formModifier) {
                $data = $event->getData();
                $formModifier($event->getForm(), $data->getVille());
            }
        );

        $builder->get('region')->addEventListener(
            FormEvents::POST_SUBMIT,
            function (FormEvent $event) use ($formModifier) {
                $region = $event->getForm()->getData();
                $formModifier($event->getForm()->getParent(), $region);
            }
        );

new.html.twig:
    {{ form_start(form) }}
            {{ form_row(form.region) }}    {# <select id="ge_candidatbundle_annonce_region" ... #}
            {{ form_row(form.ville) }} {# <select id="ge_candidatbundle_annonce_ville" ... #}
            {# ... #}
        {{ form_end(form) }}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script>
            var $region = $('#ge_candidatbundle_annonce_region');
            $region.change(function() {
                var $form = $(this).closest('form');
                var data = {};
                data[$region.attr('name')] = $region.val();
                $.ajax({
                    url : $form.attr('action'),
                    type: $form.attr('method'),
                    data : data,
                    success: function(html) {
                        $('#ge_candidatbundle_annonce_ville').replaceWith(
                            $(html).find('#ge_candidatbundle_annonce_ville')
                        );
                    }
                });
            });
        </script>

A: Many solutions :
The simplier should be to add villes to your Region entity and do something like that :
class Region
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="nom", type="string", length=255)
     */
    private $nom;

    /**
     * @var int
     *
     * @ORM\Column(name="numero", type="smallint")
     */
    private $numero;

    /** @ORM\OneToMany(targetEntity="Ville", inversedBy="region") **/
    protected $villes;

    public function getVilles()
    {
       return $this->villes;
    }

    public function setVilles($villes)
    {
        $this->villes = $villes;

        return $this;
    }
    // [... + get/setVilles functions ...]
}

And in your Type :
$formModifier = function (FormInterface $form, Region $region = null) {
            $villes = null === $region ? array() : $region->getVilles();

            $form->add('ville', EntityType::class, array(
                'class' => 'GECandidatBundle:Ville',
                'placeholder' => '',
                'choices' => $villes,

                'label' => 'Ville *',
                'label_attr' => [
                    "class" => "smaller lighter blue",
                    "style" => "font-size: 21px;",
                ],
                'choice_label'  => 'nom',
                'multiple'      => false,
                /*'query_builder' => function(VilleRepository $repository) {
                    return $repository->getVilleByRegion();
                }*/
            ));
        };

        $builder->addEventListener(
            FormEvents::PRE_SET_DATA,
            function (FormEvent $event) use ($formModifier) {
                $data = $event->getData();
                $formModifier($event->getForm(), $data->getVille());
            }
        );

        $builder->get('region')->addEventListener(
            FormEvents::POST_SUBMIT,
            function (FormEvent $event) use ($formModifier) {
                $region = $event->getForm()->getData();
                $formModifier($event->getForm()->getParent(), $region);
            }
        );

Second option :
uncomment your query builder and implement in your VilleRepository your getVilleByRegion by passing in argument the region entity
UPDATE
You set your ajax data with a non existing attribute nom replace your javascript code by :
<script>
        var $region = $('#ge_candidatbundle_annonce_region');
        $region.change(function() {
            var $form = $(this).closest('form');
            var data = {};
            data[$region.attr('name')] = $region.val();
            $.ajax({
                url : $form.attr('action'),
                type: $form.attr('method'),
                data : data,
                success: function(html) {
                    $('#ge_candidatbundle_annonce_ville').replaceWith(
                        $(html).find('#ge_candidatbundle_annonce_ville')
                    );
                }
            });
        });
    </script>


text:
Q: Multiple independent stages in JavaFX Is there a way to launch multiple independent stages in JavaFX? By independent I mean that the stages are all created from the main thread.
At the moment my application is more or less an algorithm where I would like to plot some charts and tables during execution (mainly to check whether the results are correct/ to debug).
The problem is that I cannot figure out how to create and show multiple stages independently, i.e. I would like to do something like this
public static void main(){
    double[] x = subfunction.dosomething();
    PlotUtil.plot(x); //creates a new window and shows some chart/table etc.
    double[] y = subfunction.dosomethingelse();
    PlotUtil.plot(y); //creates a new window and shows some chart/table etc.
    .....
}

which would allow to use PlotUtil as one would use the plotting functions in other scripting languages (like Matlab or R).
So the main question is how to "design" PlotUtils? So far I tried two things

*

*PlotUtils uses Application.launch for each plot call (creating a new stage with a single scene every time) --> does not work as Application.launch can only be invoked once.

*Create some kind of "Main Stage" during the first call to PlotUtils, get a reference to the created Application and start subsequent stages from there --> does not work as using Application.launch(SomeClass.class) I am not able to get a reference to the created Application instance.

What kind structure/design would allow me to implement such a PlotUtils function?
Update 1:
I came up with the following idea and was wondering whether there are any major mistakes in this solution.
Interface to be implemented by all "Plots"
public abstract class QPMApplication implements StageCreator {
   @Override
   public abstract  Stage createStage();
}

Plotting functionality:
public class PlotStage {
    public static boolean toolkitInialized = false;

    public static void plotStage(String title, QPMApplication stageCreator) {
        if (!toolkitInialized) {
            Thread appThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    Application.launch(InitApp.class);
                }
            });
            appThread.start();
        }

        while (!toolkitInialized) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                Stage stage = stageCreator.createStage();
                stage.show();
            }
        });
    }

    public static class InitApp extends Application {
        @Override
        public void start(final Stage primaryStage) {
            toolkitInialized = true;
        }
    }
}

Using it:
public class PlotStageTest {

    public static void main(String[] args) {

        QPMApplication qpm1 = new QPMApplication() {
            @Override
            public Stage createStage() {
                Stage stage = new Stage();
                StackPane root = new StackPane();
                Label label1 = new Label("Label1");
                root.getChildren().add(label1);
                Scene scene = new Scene(root, 300, 300);
                stage.setTitle("First Stage");
                stage.setScene(scene);
                return stage;
            }
        };

        PlotStage.plotStage(qpm1);

        QPMApplication qpm2 = new QPMApplication() {
            @Override
            public Stage createStage() {
                Stage stage = new Stage();
                StackPane root = new StackPane();
                Label label1 = new Label("Label2");
                root.getChildren().add(label1);
                Scene scene = new Scene(root, 300, 200);
                stage.setTitle("Second Stage");
                stage.setScene(scene);
                return stage;
            }
        };

        PlotStage.plotStage(qpm2);

        System.out.println("Done");

    }
}

A: The easiest approach here would be just to refactor your application so that it is driven from the FX Application thread. For example, you could rewrite your original code block as
public class Main extends Application {

    @Override
    public void start(Stage primaryStageIgnored) {
        double[] x = subfunction.dosomething();
        PlotUtil.plot(x); //creates a new window and shows some chart/table etc.
        double[] y = subfunction.dosomethingelse();
        PlotUtil.plot(y); //creates a new window and shows some chart/table etc.
        //  .....
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Now PlotUtil.plot(...) merely creates a Stage, puts a Scene in it, and show()s it.
This assumes the methods you're calling don't block, but if they do you just have to wrap them in a Task and call PlotUtils.plot(...) in the onSucceeded handler for the task.
If you really want to drive this from a non-JavaFX application, there's a fairly well-known hack to force the JavaFX Application thread to start if it's not already started, by creating a new JFXPanel. A JFXPanel should be created on the AWT event dispatch thread.
Here's a very basic example of the second technique. Start the application and type "show" into the console. (Type "exit" to exit.)
import java.util.Scanner;
import java.util.concurrent.FutureTask;

import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

import javax.swing.SwingUtilities;

public class Main {

    private JFXPanel jfxPanel ;

    public void run() throws Exception {
        boolean done = false ;
        try (Scanner scanner = new Scanner(System.in)) {
            while (! done) {
                System.out.println("Waiting for command...");
                String command = scanner.nextLine();
                System.out.println("Got command: "+command);
                switch (command.toLowerCase()) {
                case "exit":
                    done = true;
                    break ;
                case "show":
                    showWindow();
                    break;
                default:
                    System.out.println("Unknown command: commands are \"show\" or \"exit\"");
                }
            }
            Platform.exit();
        }
    }

    private void showWindow() throws Exception {
        ensureFXApplicationThreadRunning();
        Platform.runLater(this::_showWindow);
    }

    private void _showWindow() {
        Stage stage = new Stage();
        Button button = new Button("OK");
        button.setOnAction(e -> stage.hide());
        Scene scene = new Scene(new StackPane(button), 350, 75);
        stage.setScene(scene);
        stage.show();
        stage.toFront();
    }

    private void ensureFXApplicationThreadRunning() throws Exception {

        if (jfxPanel != null) return ;

        FutureTask<JFXPanel> fxThreadStarter = new FutureTask<>(() -> {
            return new JFXPanel();
        });
        SwingUtilities.invokeLater(fxThreadStarter);
        jfxPanel = fxThreadStarter.get();
    }

    public static void main(String[] args) throws Exception {
        Platform.setImplicitExit(false);
        System.out.println("Starting Main....");
        new Main().run();
    }

}

Here is something more along the lines I would actually follow, if I wanted the user to interact via the OS terminal (i.e. using System.in). This uses the first technique, where the application is driven by an FX Application subclass. Here I create two background threads, one to read commands from System.in, and one to process them, passing them via a BlockingQueue. Even though nothing is displayed in the main FX Application Thread, it is still a very bad idea to block that thread waiting for commands. While the threading adds a small level of complexity, this avoids the "JFXPanel" hack, and doesn't rely on there being an AWT implementation present.
import java.util.Scanner;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class FXDriver extends Application {

    BlockingQueue<String> commands ;
    ExecutorService exec ;

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

        exec = Executors.newCachedThreadPool(runnable -> {
            Thread t = new Thread(runnable);
            t.setDaemon(true);
            return t ;
        });

        commands = new LinkedBlockingQueue<>();

        Callable<Void> commandReadThread = () -> {
            try (Scanner scanner = new Scanner(System.in)) {
                while (true) {
                    System.out.print("Enter command: ");
                    commands.put(scanner.nextLine());
                }
            }
        };

        Callable<Void> commandProcessingThread = () -> {
            while (true) {
                processCommand(commands.take());
            }
        };

        Platform.setImplicitExit(false);
        exec.submit(commandReadThread);
        exec.submit(commandProcessingThread);
    }

    private void processCommand(String command) {
        switch (command.toLowerCase()) {
        case "exit":
            Platform.exit();
            break ;
        case "show":
            Platform.runLater(this::showWindow);
            break;
        default:
            System.out.println("Unknown command: commands are \"show\" or \"exit\"");
        }
    }

    @Override
    public void stop() {
        exec.shutdown();
    }

    private void showWindow() {
        Stage stage = new Stage();
        Button button = new Button("OK");
        button.setOnAction(e -> stage.hide());
        Scene scene = new Scene(new StackPane(button), 350, 75);
        stage.setScene(scene);
        stage.show();
        stage.toFront();
    }

    public static void main(String[] args) {
        launch(args);
    }
}


text:
Q: Python sockets - auto connect client to server I have an application where Python acts as a client talking to another shell (tcl). I would like to have Python connect automatically - I have it all working now but I have to manually do a sock.connect in python. The problem is the tcl shell is started from the Python script in an os.system call:
def start_tcl():
    exit_tcl() #Close any existing connections
    server.reset(2540) #Create new socket
    os.system("vivado -mode tcl -source server.tcl") #Open tcl server and connect to socket

So if I put connect right after that, the server isn't actually opened yet, and I get endpoint not terminated. Is there a way to have Python wait to connect to the socket once the server is connected? I'm sure I don't fully understand sockets, am I going about this all wrong?

A: I ended up using a while loop in case anyone is interested:
    while ( server.connect() is "None" ):
        time.sleep(1)

– Kaleb Droskiewicz


text:
Q: Contact form 7 Class/ID Hi I'm currently making a website using wordpress. And I'm are working with multiple contact forms.
I chose to use contact form 7 and made serveral forms but the problem lies with the styling. When I target the contact form with
.wpcf7-form {
    height:600px;
    padding-left:20%;
    width:100%;
    background: linear-gradient(to right, rgba(250, 118, 34, 1) , rgba(243, 49, 27, 1) );
}

Of course it targets every single form but my question is can I give it a class or ID? Cause I cant find it in wordpress.

A: You can apply class and id both as per your requirement in form tag of contact form 7.
You might have already put the short code of contact form 7. Right? There are two parameters to set form id and form class to contact form 7  element.
These parameters are: html_id and html_class. Example:
[contact-form-7 id="your_auto_genarated_id" title="Contact form 1" html_id="contact-form-1234" html_class="form contact-form"]

For complete guide see: https://contactform7.com/faq/can-i-add-id-and-class-attributes-to-a-form-element/


text:
Q: Uploading A LOT of files via JS - PHP I been looking for days for any sample code (without having to install or include bunch of files plugins etc) to upload files to my website (And, something that shows progress for each file).
I been trying to find just basic javascript (with/without Ajax).
I found:  https://github.com/RonnieSan/uploadify
It works, it's not perfect. The problem is I need to be able to upload 200-500 files (each less than 1 MG).
And when selecting just 50 files, it freezes.
Are there any simple already made script you guys can recommend?
Thank you so much in advance!


text:
Q: How to find which languages are being used in a given project running on GraalVM? Say my team is working on a polyglot project where different devs are contributing using various JVM-based (Scala, Kotlin) or dynamic languages (JavaScript, Ruby, Python) languages. As a Devops engineer I would like to know what types of languages are being used for a given project that gets run/executed with GraalVM.
Is there any support built in GraalVM SDK that I can leverage and hash out a quick script?

A: JVM based languages are, practically speaking, indistinguishable after they are compiled, i.e. they are all just bytecode.
As far as dynamic languages go, you can check which languages are installed (usign https://www.graalvm.org/truffle/javadoc/org/graalvm/polyglot/Engine.html#getLanguages-- for example) but that does not mean they are all (or any of them) actually used.
To check which languages are actually used during execution, one could develop a Truffle Instrument (https://www.graalvm.org/truffle/javadoc/com/oracle/truffle/api/instrumentation/TruffleInstrument.html) which would, on loading of new sources (https://www.graalvm.org/truffle/javadoc/com/oracle/truffle/api/instrumentation/LoadSourceListener.html), make a note of the language of the source (https://www.graalvm.org/truffle/javadoc/com/oracle/truffle/api/source/Source.html#getLanguage--), allowing one to check at any point which Truffle languages have been in use thus far.


text:
Q: Vertical text recognition with VNRecognizeTextRequest During some tests on a iOS app (written in Swift 5) I'm working on I found problems with the recognition of text written vertically with VNRecognizeTextRequest. I also examined the modifiable parameters of VNRecognizeTextRequest but nothing considers the recognition of vertical texts.
Has anyone encountered the same problem? Thanks in advance


text:
Q: custom adapter showing wrong items I have a problem with my adapter when calling .notifyDataSetChanged(). It's showing wrong items
Problem:
I have 3 items saved in my ArrayList: Item 1, Item 2 and Item 3. When i remove for example Item 1 using .remove(Index) item 1 gets removed, but after calling notifyDataSetChanged() my ListView is showing: Item 1 and Item 2, last one is not showing, even when my ArrayList contains only Item 2 and Item 3.
Code and output below:
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {

                final int indexToDelete = i;
                Log.i("indexToDelete", Integer.toString(i));
                for (int ji = 0; ji < items.size(); ji ++ ) {

                    Log.i("ItemInside",items.get(ji).getItemName());

                }

                AlertDialog.Builder builder = new AlertDialog.Builder(UserSimplePlusNoteActivity.this);
                builder.setTitle("Do you want to delete this note?");
                builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                        final Item toDelete = items.get(indexToDelete);
                        String noteToDelete = toDelete.getItemName();

                        items.remove(indexToDelete);
                        for (int ji = 0; ji < items.size(); ji ++ ) {

                            Log.i("ItemInside2",items.get(ji).getItemName());

                        }
                        customAdapter.notifyDataSetChanged();

Log output before delete:
03-29 14:00:19.118 23457-23457/com.example.user.testingapp I/indexToDelete: 0
03-29 13:47:08.202 22165-22165/com.example.user.testingapp I/ItemInside: Test 1
03-29 13:47:08.202 22165-22165/com.example.user.testingapp I/ItemInside: Test 2
03-29 13:47:08.202 22165-22165/com.example.user.testingapp I/ItemInside: Test 3

After delete:
03-29 13:47:08.202 22165-22165/com.example.user.testingapp I/ItemInside: Test 2
03-29 13:47:08.202 22165-22165/com.example.user.testingapp I/ItemInside: Test 3

App screen is showing this
And here's my Adapter and Item:
public class CustomAdapter extends BaseAdapter {
    private Context context;
    private ArrayList<Item> items;

    public CustomAdapter(Context context, ArrayList<Item> items) {

        this.context = context;
        this.items = items;

    }

    @Override
    public int getCount() {
        return items.size();
    }

    @Override
    public Object getItem(int i) {
        return items.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int position, View view, ViewGroup parent) {

        if(view == null) {

            view = LayoutInflater.from(context).inflate(R.layout.custom_adapter, parent, false);

            Item currentItem = (Item) getItem(position);

            TextView textViewItemName = view.findViewById(R.id.titleID);
            TextView textViewItemDescription = view.findViewById(R.id.detailID);
            ImageView imageView = view.findViewById(R.id.imgID);

            textViewItemName.setText(currentItem.getItemName());
            textViewItemDescription.setText(currentItem.getItemDescription());
            switch (currentItem.getPriority()) {

                case 1:
                    break;
                case 2:
                    imageView.setImageResource(R.drawable.priority_urgent_icon);
                    break;
                case 3:
                    imageView.setImageResource(R.drawable.priority_important_icon);
                    break;
                    default:
                        Log.i("Ok", "Something strange happend");

            }

        }

        return view;
    }
}

Item:
public class Item {
    private String itemName;
    private String itemDescription;
    private int priority;

    public Item(String name, String description, int priority) {
        this.itemName = name;
        this.itemDescription = description;
        this.priority = priority;

    }

    public String getItemName() {

        return this.itemName;
    }

    public String getItemDescription() {

        return this.itemDescription;

    }

    public int getPriority() {

        return this.priority;

    }

}

A: It seems notifyDataSetChanged() doesn't properly refresh in this case. Refreshing the customAdapter with new items and setting this to listView i.e these two lines before notifyDataSetChanged() however solves the issue:
customAdapter = new CustomAdapter(getApplicationContext(), items);
listView.setAdapter(customAdapter);


text:
Q: Ubuntu 16.04: USB stick mounts, but standard user has no access My kids have on our home PC for security reasons only standard user access, but they want to use their USB sticks. But only I have access (Admin). On the kids accounts the usb stick mounts, but they are not granted any access, they can format it but even then - no further access. I tried to give them access via a group, but I can't activate this group in the Properties/Permission menu - it always switches back to the old content. I already tried several other methods (i.e. Chmod) suggested on the internet - didn't work. On windows 7 there is no problem with the USB stick at all. And, yes, I have formatted it several time (Fat32.0)
Any ideas / suggestions ?
TIA, Joe eoJ


text:
Q: WARNING: BLAS library not found, Qiskit Installation I'm trying to install Qiskit and am coming across an error:
****************************************************************
*** WARNING: BLAS library not found.
* You can include the BLAS library in the global environment LDFLAGS, eg
*   export LDFLAGS='-L/path/to/blas/lib -lblas'
* or specify the BLAS library path in  PYSCF_INC_DIR
*   export PYSCF_INC_DIR=/path/to/blas/lib:/path/to/other/lib
****************************************************************

I'm on Mac OS El Capitan, and using Python 3.7.
If it helps, I ran np.__config__ to see if I had BLAS installed, and it seemed to work since it returned this:
openblas_lapack_info:
libraries = ['openblas', 'openblas']
library_dirs = ['/usr/local/lib']
language = c
define_macros = [('HAVE_CBLAS', None)]

So I think this is just an issue with my Qiskit installation. Does anyone know how to fix this?

A: I got same error and I'm with Sierra.
Assuming you already created and activated an environment with Anaconda, try to run
conda install -c pyscf pyscf

and then again:
pip install qiskit

I got the solution from PySCF's docs.


text:
Q: Handlebars in a json object? I am trying to store a handlebars template in a json object. I want to then compile it in another function, but the output from the first function gives me [object Object]. I'm having trouble converting this back to the handlebars template to compile it. When I do a console.log() for the response, it comes back as the hansdlebars template. See below:
//Object to hold compile all templates output
var tmplatesJSON = "";

 //This function compiles all the external templates in the filesArray, and adds them to the 'main' tag in the html.
(function( $ ){
   $.fn.compileAllTemplates = function(templateNames) {
        //loop through all templates in array
            //var tmplJSON = '[{"template": [';
            var tmplJSON = '[';
            for (var i=0; i<templateNames.length; i++) {
                //console.log(templateNames.length);
                //for every template load it
                var template = templateNames[i];
                var templ = $.get(template, function (response){

                    var templ = response;
                    return templ;
                });

                tmplJSON += '{"tmplID": "'+templateNames[i]+'",';
                tmplJSON += '"tmplHTML": "' + templ +'"}';
                console.log(templ);
                    //this makes sure there isn't a ',' on the last one.
                    var j = templateNames.length - 1;
                    if(j!=i){
                        tmplJSON += ',';
                    } else{
                        tmplJSON += '';

                    }
            }
            tmplJSON += ']';

            templatesJSON = tmplJSON;
            templatesJSON = JSON.parse(templatesJSON);
   };
})( jQuery );

$(document).compileAllTemplates(templatesArray);

//This function
(function( $ ){
   $.fn.renderTemplates = function(templateName, dest) {
        //find the appropriate template id in the templatesJSON JSON object
        for (var i=0; i<templatesJSON.length; i++) {
            //console.log(templatesJSON[i].tmplID);
            var str = templatesJSON[i].tmplID.toString();
            if(str === templateName) {
                //console.log(templatesJSON[i].tmplHTML);

                /***********************
                TODO: Need to convert the object sent in the json to something consumable to Handlebars
                ***********************/

                //Render the compiled template to the specified html element
                var destination = $(document).find(dest);
                $(destination).append(templatesJSON[i].tmplHTML);
                return true;
            }
        }

   };
})( jQuery );
$(document).renderTemplates('templates/header.hbs', 'header');
$(document).renderTemplates('templates/nav-main.hbs', 'nav');
$(document).renderTemplates('templates/page-title.hbs', '.page-title');
$(document).renderTemplates('templates/footer.hbs', 'footer');

jsonReturned = [{"tmplID": "templates/header.hbs","tmplHTML": "[object Object]"},{"tmplID": "templates/page-title.hbs","tmplHTML": "[object Object]"},{"tmplID": "templates/nav-main.hbs","tmplHTML": "[object Object]"},{"tmplID": "templates/footer.hbs","tmplHTML": "[object Object]"}]


text:
Q: Installed OpenSSH on Mint 17 but it doesn't seem to be running So I've installed OpenSSH on Mint rafaela 17.2, but it doesn't seem to be running when using the modified config file.
Not sure why service says its up, but I don't have a PID, don't have a listener, and can't connect at all...
service --status-all shows [-] ssh.

service ssh start returns start:
Job is already running:ssh

ssh localhost returns connection refused
ps ax | grep ssh returns only the ssh-agent.
ss -lnp | grep ssh shows the gnome-keyring and ssh-agent listening, but not the ssh daemon. (grep sshd returns nothing at all)
I followed this for the setup - https://help.ubuntu.com/community/SSH/OpenSSH/Configuring
Any thoughts? I've been searching for hours on how to start the damn service and getting nothing.
Edit (More Info)
Played around some more, switched back to the default sshd config file and running service ssh restart returns ssh stop/waiting and ssh start/running, process
When I put the modified config file back in place and did a restart, no process ID comes up.
Looked at the log file, when trying to restart sshd with the new config file I see the following-
Aug 29 17:58:25 serenity kernel: [ 3867.828744] init: ssh main process (6151) terminated with status 255
Aug 29 17:58:25 serenity kernel: [ 3867.828754] init: ssh main process ended, respawning
Aug 29 17:58:31 serenity kernel: [ 3873.631306] [UFW AUDIT] IN= OUT=eth0 SRC=10.0.0.8 DST=255.255.255.255 LEN=142 TOS=0x00 PREC=0x00 TTL=64 ID=65238 DF PROTO=UDP SPT=17500 DPT=17500 LEN=122
Aug 29 17:58:31 serenity kernel: [ 3873.631323] [UFW ALLOW] IN= OUT=eth0 SRC=10.0.0.8 DST=255.255.255.255 LEN=142 TOS=0x00 PREC=0x00 TTL=64 ID=65238 DF PROTO=UDP SPT=17500 DPT=17500 LEN=122
Aug 29 17:58:31 serenity kernel: [ 3873.631346] [UFW AUDIT] IN=eth0 OUT= MAC= SRC=10.0.0.8 DST=255.255.255.255 LEN=142 TOS=0x00 PREC=0x00 TTL=64 ID=65238 DF PROTO=UDP SPT=17500 DPT=17500 LEN=122
Aug 29 17:58:39 serenity kernel: [ 3881.610999] [UFW BLOCK] IN=eth0 OUT= MAC=01:00:5e:00:00:01:00:1d:d1:7a:3c:91:08:00 SRC=10.0.0.1 DST=224.0.0.1 LEN=36 TOS=0x00 PREC=0x00 TTL=1 ID=0 DF PROTO=2

Default and new config files changes listed
diff sshd_config (NEW CONFIG) sshd_config.bckp (DEFAULT CONFIG)
24c24
< LogLevel VERBOSE
---
> LogLevel INFO
27c27
< LoginGraceTime 30
---
> LoginGraceTime 120
52c52
< PasswordAuthentication no
---
> #PasswordAuthentication yes
71,72c71,72
< MaxStartups 2:30:10
< Banner /etc/issue.net
---
> #MaxStartups 10:30:60
> #Banner /etc/issue.net
89,94d88
<
< AllowTcpForwarding no
<
< AllowUsers <username>
<
< ForwardAgent no

A: Sort of figured it out.  Obviously something in the config file was stopping the server from starting.
After implementing each file change one line at a time, finally found it was the ForwardAgent no line in the config that was causing problems.
After some more digging, found that you could start the daemon direct instead of through the services to see if you were getting an error message.
/usr/sbin/sshd -Ddp 10222
/etc/ssh/sshd_config: line 90: Bad configuration option: ForwardAgent
/etc/ssh/sshd_config: terminating, 1 bad configuration options

I don't know why the ForwardAgent setting there is causing issues, but commenting that out let me finally run the server.


text:
Q: Pandas concatenate values of all column into a new column list I am trying to concat all my columns into a new column. The concatenated values should be stored in a list.
My dataframe:
df = pd.DataFrame({'A': ['1', '2', nan],
                   'B': [nan, '5', nan],
                   'C': ['7', nan, '9']})

desired output:
df:
A   B   C   concat_col
1   nan 7   [1,7]
2   5   nan [2,5]
nan nan 9   [9]

What i tried:
df['concat'] = pd.Series(df.fillna('').values.tolist()).str.join(',')

Output i got:
A   B   C   concat_col
1   nan 7   1,,7
2   5   nan 2,5,,
nan nan 9   ,,9

A: The following code should work:
df['concat_col']=df.apply(lambda row: row.dropna().tolist(), axis=1)

A: You can use a list comprehension, taking advantage of the fact np.nan != np.nan:
df['D'] = [[i for i in row if i == i] for row in df.values]

print(df)

     A    B    C       D
0    1  NaN    7  [1, 7]
1    2    5  NaN  [2, 5]
2  NaN  NaN    9     [9]

Counter-intuitively, this is more efficient than Pandas methods:
df = pd.concat([df]*10000, ignore_index=True)

%timeit df.apply(lambda row: row.dropna().tolist(), axis=1)  # 8.25 s
%timeit [[i for i in row if i == i] for row in df.values]    # 55.6 ms


text:
Q: VMDisconnectedException while debugging Android App I am debugging my Android app by having it stop at a breakpoint. Indeed, execution stops at the breakpoint, but once I step over one step, then step into, the problems start: Instead of stepping into the function, the debugger seems to perform a step over, just highlighting the next line. When I then press step over, a message box pops up with one of the following messages:

com.sun.jdi.VMDisconnectedException: Got IOException from Virtual Machine occurred creating step request.

or

org.eclipse.jdi.TimeoutException: Timeout occurred while waiting for packet xxx occurred creating step request.

This happens whenever I perform the steps above (Always on the same breakpoint), which is preventing me from debugging my app.
I am debugging on a real device, using Eclipse on Windows.
I already tried:

*

*Restarting Eclipse

*Increasing the Debugging Timeout in Eclipse, which just leads to the first error to appear more often in comparison

Now here are my questions:

*

*Has anyone else come across this problem?

*What could I do to solve the problem?

A: These exceptions occur when you have a class that don't exists in the application to be debugged.
I did have this same problem with Java EE (no Android, but same exceptions). Two projects (jar files in this case) with same classes and package names. So, the code that was debugged wasn't the running code, then Eclipse throwed IOException.
Probably there are another cases that this occurs.


text:
Q: Upgrading Spring Boot from 2.4.1 to 2.6.1, getting `java.time.Instant` not supported by default error When I upgrade the Spring Boot App from 2.4.1 to 2.6.1. I got the below error.

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Java 8 date/time type java.time.Instant not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" to enable handling (through reference chain: org.springframework.boot.actuate.trace.http.HttpTrace["timestamp"])

A: With an upgrade from Spring Boot 2.4 to 2.6, you also upgrade Jackson from 2.11 to 2.13. And Jackson 2.12 contains the following change: https://github.com/FasterXML/jackson-databind/issues/2683
This produces the error message that you are seeing as the JSR 310 module is now compulsary if the corresponding date times are used.
You should only be affected by this, when you configure your own ObjectMapper such that the auto-configured one backs off. At the point where you configure that ObjectMapper, you need to explicitly add the JSR 310 module. That can be done with code like this:
objectMapper.registerModule(new JavaTimeModule());

There is also is a somewhat lengthy but insightful discussion on github about this: https://github.com/spring-projects/spring-boot/issues/26859