text:
Q: Duplicate Verification In Sql I have a table which contains two columns where I'm checking out for duplicates.I have written code for duplicates and it is
        DbCommand cmd = db.GetSqlStringCommand("SELECT MyTable.* FROM MyTable. INNER JOIN(SELECT MainUrl, COUNT(*) as counter FROM MyTable GROUP BY MainUrl HAVING COUNT(*) >1) t ON t.MainUrl=MyTable.MainUrl");
        int count = db.ExecuteNonQuery(cmd);
        DataSet ds = db.ExecuteDataSet(cmd);
        return ds;

Whereas in my columns I have Amazon.com,http://Amazon.com,https://Amazon.com.I want even these two duplicates.I want to return all the columns in my table with those duplicates.But from my code I can't achieve this,Can anyone help me out from this

A: Using CHARINDEX and SUBSTRING:
It considers 'amazon.com', http://amazon.com', and  https://amazon.com'  as duplicate.
WITH MyTable(OriginalURL) AS(
    SELECT 'http://Amazon.com' UNION ALL
    SELECT 'https://Amazon.com' UNION ALL
    SELECT 'Amazon.com' UNION ALL
    SELECT 'http://Stackoverflow.com' UNION ALL
    SELECT 'Stackoverflow.com' UNION ALL
    SELECT 'http://google.com'
)
SELECT
    CASE
        WHEN CHARINDEX('http://', OriginalURL, 1) > 0 THEN SUBSTRING(OriginalURL, 8, LEN(OriginalURL) - 7)
        WHEN CHARINDEX('https://', OriginalURL, 1) > 0 THEN SUBSTRING(OriginalURL, 9, LEN(OriginalURL) - 8)
        ELSE OriginalURL
    END AS OriginalURL
    , COUNT(*) AS DupeCount
FROM MyTable
GROUP BY
    CASE
        WHEN CHARINDEX('http://', OriginalURL, 1) > 0 THEN SUBSTRING(OriginalURL, 8, LEN(OriginalURL) - 7)
        WHEN CHARINDEX('https://', OriginalURL, 1) > 0 THEN SUBSTRING(OriginalURL, 9, LEN(OriginalURL) - 8)
        ELSE OriginalURL
    END
HAVING COUNT(*) > 1

A: Considering one field. We can use this:
SELECT field, Count(*) FROM table
GROUP BY field
HAVING Count(*) > 1
ORDER BY Count /*optional DESC*/


text:
Q: Draw an arrow on a closed path in TikZ Like this, only it doesn't work:
\documentclass{standalone}

\usepackage{tikz}

\begin{document}

\begin{tikzpicture}

 \draw [->] (0, 0) ellipse [x radius = 2, y radius = 3];
 \draw [->] (0, 0) -- (1, 0) -- (0, 1) -- cycle;

\end{tikzpicture}

\end{document}

(Edited, twice, to include an MWE that actually compiles, as requested).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why string can't be converted to object class What could be wrong in my code? I use HashMap to make update easier in the database, but whenever I try to fetch this data from the database to FirebaseRecyclerAdapter I keep getting an error.
I have searched for many similar problems, tried their solutions but not working.
Below is the exception
com.google.firebase.database.DatabaseException: Can't convert object of type java.lang.String to type com.project.android.designlibdemo.model.RecipeModel

Getter and setter
public class RecipeModel {

private String name;

public RecipeModel(){

}

public RecipeModel(String name){
    this.name = name;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

ViewHolder class
public class ViewHolderRecipe extends RecyclerView.ViewHolder {

String LOG_TAG = ViewHolderRecipe.class.getSimpleName();
public View view;
private TextView ingredient_txt;

public ViewHolderRecipe(View itemView) {
    super(itemView);

    view = itemView;

    ingredient_txt = itemView.findViewById(R.id.ingredient_list);
}

public void setRecipeName(String recipe){

    ingredient_txt.setText(recipe);

}

How i send data to database
 Map postRecipeMap = new HashMap();

        final DatabaseReference sendRecp = FirebaseDatabase.getInstance().getReference().child
                ("Post").child("PostRecipe").push();

        sendRecp.updateChildren(postRecipeMap)
                .addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {

                        if (task.isSuccessful()) {
                            mProgressDialog.dismiss();

                            AlertDialog.Builder alertDialogBuilder = new android.support.v7.app
                                    .AlertDialog.Builder(PostingRecipeActivity.this);

                            alertDialogBuilder.setTitle("Successfully");
                            alertDialogBuilder.setMessage("You can click next");
                            alertDialogBuilder.setPositiveButton("OK",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface arg0, int arg1) {

                                            //Launch PostDetailActivity

                                            Intent i = new Intent(PostingRecipeActivity.this, ContentIngredientList.class);

                                            final String reportKey = sendRecp.getKey();
                                            i.putExtra(ContentIngredientList.EXTRA_FIR_KEY, reportKey);
                                            mProgressDialog.dismiss();
                                            startActivity(i);

                                        }
                                    });

                            AlertDialog aDialog = alertDialogBuilder.create();
                            aDialog.show();

                        }

How I retrieve the data
public class ContentIngredientList extends AppCompatActivity {

public static final String EXTRA_FIR_KEY = "recipeKey";
private FirebaseRecyclerAdapter<RecipeModel, ViewHolderRecipe> mAdapter;

//private RecyclerView mIngredient_list;

String LOG_TAG = PostingRecipeActivity.class.getSimpleName();
private String recipeKey;

public ContentIngredientList(){

}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.content_ingredient_list);

    // Get post key from intent
    recipeKey = getIntent().getStringExtra(EXTRA_FIR_KEY);
    if (recipeKey == null) {
        throw new IllegalArgumentException("Must pass EXTRA_POST_KEY");
    }

    DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("Post").child
            ("PostRecipe").child(recipeKey);

    RecyclerView mRcyclerViewIngredient = findViewById(R.id.ingredient_list_recycler);
    //mIngredient_list = findViewById(R.id.ingredient_list);

    Log.e(LOG_TAG,  "url" + mDatabase.getRef()) ;

    // [END create_database_reference]

    // mDirectionList.setHasFixedSize(true);
    mRcyclerViewIngredient.setLayoutManager(new LinearLayoutManager(this));

    //  mIngredient_list.setHasFixedSize(true);
    //mIngredient_list.setLayoutManager(new LinearLayoutManager(this));

    mAdapter = new FirebaseRecyclerAdapter<RecipeModel, ViewHolderRecipe>(RecipeModel.class,
            R.layout.ingredient_posting, ViewHolderRecipe.class, mDatabase) {
        @Override
        protected void populateViewHolder(ViewHolderRecipe viewHolder, RecipeModel model, int position) {

            viewHolder.setRecipeName(model.getName());
        }
    };

    mRcyclerViewIngredient.setAdapter(mAdapter);
}

}

A: To get the list of post recepies, then your database shoundn't be:
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("Post").child
            ("PostRecipe").child(recipeKey);

But rather:
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference().child("Post").child
            ("PostRecipe");

You were referencing a particular PostRecipe, then when Firebase UI tried to get the object it only found the string name.


text:
Q: Script for adding virtual interfaces to ubuntu Anyone know of a script or command to add all the needed information to /etc/interfaces to add a new virtual interface?
It would need to add a new:
iface eth0:4 inet static
address x.y.x.y
netmask 255.255.240.0

and update primary network interfaces.
auto eth0 eth0:1 eth0:2 eth0:3 eth0:4

A: #!/bin/sh
# Usage: addif alias_nic address netmask
cat >>/etc/network/interfaces <<EOF
auto $1
iface $1 inet static
address $2
netmask $3
EOF

ifup $1

A: I usually do something like this in my interfaces file to bind additional addresses with an interface.  I use the up/down to execute the external ip command that is part of the iproute package.
auto eth0
iface eth0 inet static
        address 192.168.32.10
        netmask 255.255.255.0
        network 192.168.32.0
        broadcast 192.168.32.255
        gateway 192.168.32.1
        # bind .25 for bar
        up ip addr add 192.168.32.25/24 brd + dev eth0
        down ip addr del 192.168.32.25/24 brd + dev eth0
        # bind .47 for foo
        up ip addr add 192.168.32.47/24 brd + dev eth0
        down ip addr del 192.168.32.47/24 brd + dev eth0

Of course it is also legal to put something like this in your interfaces file, even though I kinda like the former better.
auto eth0
iface eth0 inet static
        address 192.168.32.10
        netmask 255.255.255.0
        network 192.168.32.0
        broadcast 192.168.32.255
        gateway 192.168.32.1

auto eth0:1
iface eth0:1 inet static
        address 192.168.32.25
        netmask 255.255.255.0

auto eth0:2
iface eth0:2 inet static
        address 192.168.32.47
        netmask 255.255.255.0


text:
Q: how to update a column in a table with unique values, but not all the rows, not incremented
Possible Duplicate:
Is it possible to perform multiple updates with a single UPDATE SQL statement?

I am updating a table with some new values for a particular column as below, so i am updating table Prepay, column PrepayTransactionDesc, on certain fows indicated by prepayId
update Prepay
set PrepayTransactionDesc = 'Funded Repeat Voucher 153429'
where prepayId = 58045

It works fine, but i want to do multiple updates.
I have tried a few different ways but failed. the was i was trying to do it was using CASE when and then.
for instance, i have the following prepayid and prepaytransactiondesc fields
57770   Funded Repeat Voucher 153118
57771   Funded Repeat Voucher 153119
57772   Funded Repeat Voucher 153120
57773   Funded Repeat Voucher 153121
57774   Funded Repeat Voucher 153122
57775   Funded Repeat Voucher 153123
57776   Funded Repeat Voucher 153124
57894   Funded Repeat Voucher 153276
57895   Funded Repeat Voucher 153277
57896   Funded Repeat Voucher 153278

How would i do them in 1 go? It cant be that difficult but i seem to be missing something when i try to do the task.

A: You could try
UPDATE Prepay
SET PrepayTransactionDesc =
   CASE
     WHEN prepayID = 57770 THEN 'Funded Repeat Voucher 153118'
     WHEN prepayID = 57771 THEN 'Funded Repeat Voucher 153119'
     WHEN prepayID = nextID THEN 'Next Value'
   END
WHERE  prepayID in (1,2,4,57770... all your ids here)

A: Put your data to update into a temp variable table.  Then join it with the table you want to update in the FROM clause of your update statement.  This will allow you to update multiple rows in one statement.
DECLARE @data TABLE (id INT, desc VARCHAR(200))
INSERT @data VALUES (57770, 'Funded Repeat Voucher 153118')
INSERT @data VALUES (57771, 'Funded Repeat Voucher 153119')

UPDATE Prepay
SET PrepayTransactionDesc = @data.desc
FROM Prepay
    INNER JOIN @data ON Prepay.prepayID = @data.id

A: update Prepay
  set PrepayTransactionDesc =
    case
      when prepayId = 58045 then 'Funded Repeat Voucher 153429'
      when prepayId = 57770 then 'Funded Repeat Voucher 153118'
    end
where
  prepayId in (58045 , 57770)

Obviously add the other values

A: Update Prepay SET PrepayTransactionDesc = 'Funded Repeat Voucher 153429' WHERE  prepayID  BETWEEN yourid AND yourid


text:
Q: SWIG generated python file not found I have created a library in c++ to perform string matching, and am trying to port the code into python using SWIG. I have created a .i file, and have generated a .py file. In testing the file, everything has been working, and I have been able to access the functions and classes as expected. However, the problem I am running into is now when trying to use the code in a more complex environment, I am running into an error because of these lines in my generated .py file.
# Import the low-level C/C++ module
if __package__ or "." in __name__:
    from . import _EESM
else:
    import _EESM

For my project, EESM.py is my created python file, and inside it there is an import for _EESM.py, with the underscore. I use PyCharm for writing code and it warns me that no module _EESM is found. When attempting to run the project, the same error occurs.  I thought that maybe it was referring to the _EESM.so file that was generated by SWIG, but whenever I placed that file in my directory I still received the same errors. The question I have is what do I do with the _{File_Name} module, and how do I find it?


text:
Q: JPA Entities shared between several applications (Wildfly - Hibernate - Maven) Is there a way to configure various persistence.xml contained in different applications (war or ear) that all use a shared jar that contains all entities?
Something like:
  deployments/
    |-ArchiviBase.war
      |-WEB-INF\classes\META-INF\persistence.xml
      |-WEB-INF\classes\META-INF\TipoAbitazione.hbm.xml
    |-Application2.war
      |-WEB-INF\classes\META-INF\persistence.xml
    |-Application3.war
      |-WEB-INF\classes\META-INF\persistence.xml
  lib/
    |-models.jar
      |- it\test\archiviBase\beans\TipoAbitazione.java

With all files (persistence.xml, hbm.xml and java class) within the war the mapping works correctly, but I need to share java entities with all applications, so I would like to move them to models.jar.
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
    xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="archiviBasePU">
        <jta-data-source>java:jboss/jdbc/myDataSource</jta-data-source>
        <properties>
            <property name="jboss.entity.manager.factory.jndi.name"
                            value="java:jboss/hibernate/app1SF" />
            <property name="jboss.entity.manager.jndi.name"
                            value="java:/hibernate/app1SF" />
            <property name="hibernate.generate_statistics" value="true" />
            <property name="hibernate.default_schema"
                            value="app_schema" />
            <property name="hibernate.show_sql" value="true" />
        </properties>
    </persistence-unit>
</persistence>

TipoAbitazione.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping auto-import="true"
    default-access="property" default-cascade="none" default-lazy="true">
    <class dynamic-insert="false" dynamic-update="false"
        mutable="true"
        name="it.test.app1.beans.TipoAbitazione"
        optimistic-lock="version" polymorphism="implicit"
        select-before-update="false" table="tipo_abitazione">
        <id column="tpab_codice" name="codice" type="java.lang.String">
            <generator class="assigned" />
        </id>
        <property column="tpab_descrizione" generated="never"
            lazy="false" length="100" name="descrizione" not-null="true"
            optimistic-lock="true" type="java.lang.String" unique="false" />
        <property column="tpab_flag_attivo" generated="never"
            lazy="false" length="1" name="attivo" optimistic-lock="true"
            type="java.lang.Boolean" unique="false" />
    </class>
</hibernate-mapping>

TipoAbitazione.java
package it.test.archiviBase.beans;

import java.io.Serializable;

public class TipoAbitazione implements Serializable {

    private static final long serialVersionUID = 1L;

    private String codice;
    private String descrizione;
    private Boolean attivo;

    public TipoAbitazione() {
    }

    public TipoAbitazione(String codice, String descrizione) {
        this.codice = codice;
        this.descrizione = descrizione;
    }

    public TipoAbitazione(String codice, String descrizione, Boolean attivo) {
        this.codice = codice;
        this.descrizione = descrizione;
        this.attivo = attivo;
    }

    public String getCodice() {
        return this.codice;
    }

    public void setCodice(String codice) {
        this.codice = codice;
    }

    public String getDescrizione() {
        return this.descrizione;
    }

    public void setDescrizione(String descrizione) {
        this.descrizione = descrizione;
    }

    public Boolean getAttivo() {
        return this.attivo;
    }

    public void setAttivo(Boolean attivo) {
        this.attivo = attivo;
    }
}

Each application should define its own persistence unit, using its own hbm.xml files, but the java entities will all be contained in the shared models.jar file
This is the error when I try to deploy the war:

1-03-25 15:20:46,406 ERROR [org.jboss.msc.service.fail] (ServerService
Thread Pool -- 3) MSC000001: Failed to start service
jboss.persistenceunit."archiviBaseTest2-0.0.1-SNAPSHOT.war#archiviBasePU":
org.jboss.msc.service.StartException in service
jboss.persistenceunit."archiviBaseTest2-0.0.1-SNAPSHOT.war#archiviBasePU":
javax.persistence.PersistenceException: [PersistenceUnit:
archiviBasePU] Unable to build Hibernate SessionFactory
at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:198)
at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:128)
at java.security.AccessController.doPrivileged(Native Method)
at org.wildfly.security.manager.WildFlySecurityManager.doChecked(WildFlySecurityManager.java:664)
at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1.run(PersistenceUnitServiceImpl.java:213)
at org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
at org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1990)
at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
at java.lang.Thread.run(Thread.java:748)
at org.jboss.threads.JBossThread.run(JBossThread.java:513) Caused by: javax.persistence.PersistenceException: [PersistenceUnit:
archiviBasePU] Unable to build Hibernate SessionFactory
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:1327)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1253)
at org.jboss.as.jpa.hibernate5.TwoPhaseBootstrapImpl.build(TwoPhaseBootstrapImpl.java:44)
at org.jboss.as.jpa.service.PersistenceUnitServiceImpl$1$1.run(PersistenceUnitServiceImpl.java:170)
... 10 more Caused by: org.hibernate.MappingException: Could not get constructor for
org.hibernate.persister.entity.SingleTableEntityPersister
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:123)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:77)
at org.hibernate.metamodel.internal.MetamodelImpl.initialize(MetamodelImpl.java:154)
at org.hibernate.internal.SessionFactoryImpl.(SessionFactoryImpl.java:295)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:467)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1250)
... 12 more Caused by: org.hibernate.HibernateException: Unable to instantiate default tuplizer
[org.hibernate.tuple.entity.PojoEntityTuplizer]
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:91)
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructDefaultTuplizer(EntityTuplizerFactory.java:116)
at org.hibernate.tuple.entity.EntityMetamodel.(EntityMetamodel.java:413)
at org.hibernate.persister.entity.AbstractEntityPersister.(AbstractEntityPersister.java:557)
at org.hibernate.persister.entity.SingleTableEntityPersister.(SingleTableEntityPersister.java:124)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:96)
... 17 more Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:88)
... 26 more Caused by: java.lang.IllegalArgumentException: Could not create type
at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:154)
at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:365)
at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:174)
at net.bytebuddy.TypeCache$WithInlineExpunction.findOrInsert(TypeCache.java:376)
at org.hibernate.bytecode.internal.bytebuddy.ByteBuddyState.load(ByteBuddyState.java:183)
at org.hibernate.bytecode.internal.bytebuddy.ByteBuddyState.loadProxy(ByteBuddyState.java:107)
at org.hibernate.proxy.pojo.bytebuddy.ByteBuddyProxyHelper.buildProxy(ByteBuddyProxyHelper.java:54)
at org.hibernate.proxy.pojo.bytebuddy.ByteBuddyProxyFactory.postInstantiate(ByteBuddyProxyFactory.java:62)
at org.hibernate.tuple.entity.PojoEntityTuplizer.buildProxyFactory(PojoEntityTuplizer.java:103)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.(AbstractEntityTuplizer.java:155)
at org.hibernate.tuple.entity.PojoEntityTuplizer.(PojoEntityTuplizer.java:51)
... 31 more Caused by: java.lang.IllegalStateException: Error invoking Unsafe::defineClass
at net.bytebuddy.dynamic.loading.ClassInjector$UsingUnsafe$Dispatcher$Enabled.defineClass(ClassInjector.java:1997)
at net.bytebuddy.dynamic.loading.ClassInjector$UsingUnsafe.injectRaw(ClassInjector.java:1774)
at net.bytebuddy.dynamic.loading.ClassInjector$AbstractBase.inject(ClassInjector.java:112)
at net.bytebuddy.dynamic.loading.ClassLoadingStrategy$ForUnsafeInjection.load(ClassLoadingStrategy.java:546)
at net.bytebuddy.dynamic.TypeResolutionStrategy$Passive.initialize(TypeResolutionStrategy.java:100)
at net.bytebuddy.dynamic.DynamicType$Default$Unloaded.load(DynamicType.java:5662)
at org.hibernate.bytecode.internal.bytebuddy.ByteBuddyState.lambda$load$0(ByteBuddyState.java:187)
at net.bytebuddy.TypeCache.findOrInsert(TypeCache.java:152)
... 41 more Caused by: java.lang.NoClassDefFoundError: org/hibernate/proxy/HibernateProxy
at sun.misc.Unsafe.defineClass(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at net.bytebuddy.dynamic.loading.ClassInjector$UsingUnsafe$Dispatcher$Enabled.defineClass(ClassInjector.java:1987)
... 48 more Caused by: java.lang.ClassNotFoundException: org.hibernate.proxy.HibernateProxy from [Module
"deployment.external.global-directory.lib" from Service Module Loader]
at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:255)
at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:410)
at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:398)
at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:116)
... 54 more
2021-03-25 15:20:46,411 ERROR
[org.jboss.as.controller.management-operation] (External Management
Request Threads -- 1) WFLYCTL0013: Operation ("add") failed - address:
([("deployment" => "archiviBaseTest2-0.0.1-SNAPSHOT.war")]) - failure
description: {"WFLYCTL0080: Failed services" =>
{"jboss.persistenceunit."archiviBaseTest2-0.0.1-SNAPSHOT.war#archiviBasePU""
=> "javax.persistence.PersistenceException: [PersistenceUnit: archiviBasePU] Unable to build Hibernate SessionFactory
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: archiviBasePU] Unable to build Hibernate
SessionFactory
Caused by: org.hibernate.MappingException: Could not get constructor for
org.hibernate.persister.entity.SingleTableEntityPersister
Caused by: org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]
Caused by: java.lang.reflect.InvocationTargetException
Caused by: java.lang.IllegalArgumentException: Could not create type
Caused by: java.lang.IllegalStateException: Error invoking Unsafe::defineClass
Caused by: java.lang.NoClassDefFoundError: org/hibernate/proxy/HibernateProxy
Caused by: java.lang.ClassNotFoundException: org.hibernate.proxy.HibernateProxy from [Module
"deployment.external.global-directory.lib" from Service Module
Loader]"}} 2021-03-25 15:20:46,412 ERROR [org.jboss.as.server]
(External Management Request Threads -- 1) WFLYSRV0021: Deploy of
deployment "archiviBaseTest2-0.0.1-SNAPSHOT.war" was rolled back with
the following failure message: {"WFLYCTL0080: Failed services" =>
{"jboss.persistenceunit."archiviBaseTest2-0.0.1-SNAPSHOT.war#archiviBasePU""
=> "javax.persistence.PersistenceException: [PersistenceUnit: archiviBasePU] Unable to build Hibernate SessionFactory
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: archiviBasePU] Unable to build Hibernate
SessionFactory
Caused by: org.hibernate.MappingException: Could not get constructor for
org.hibernate.persister.entity.SingleTableEntityPersister
Caused by: org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]
Caused by: java.lang.reflect.InvocationTargetException
Caused by: java.lang.IllegalArgumentException: Could not create type
Caused by: java.lang.IllegalStateException: Error invoking Unsafe::defineClass
Caused by: java.lang.NoClassDefFoundError: org/hibernate/proxy/HibernateProxy
Caused by: java.lang.ClassNotFoundException: org.hibernate.proxy.HibernateProxy from [Module
"deployment.external.global-directory.lib" from Service Module
Loader]"}}

A: <!-- Define persistence unit -->
<persistence-unit name="archiviBasePU">
    ...
    <jar-file>models.jar</jar-file>
    ...
</persistence-unit>

A: You have to put the persistence.xml in the same library as the loaded classes if you don't want to have to explicitly list them in the persistence.xml of every application.


text:
Q: Notify GCD background thread I have 15 GCD background threads that runs 15 parallel workers. While I've seen a lot of examples for sending notification / delegate from background to main thread. I wonder how I can send signal to all 15 threads from the main thread?

A: Firstly I assume you are talking about queues but not threads, because there is no guarantee that each queue will create separate thread for it's work. If so than you should look to dispatch_group topic. If there is not enough power to solve your problem, than check out NSOperation queue, it's much more powerful. Hope it helps.


text:
Q: Regex to allow letters, one space between words and a total length of 50 I'm trying to build a regular expression with the following conditions:

*

*Only letters

*One space between words (no more than one space)

*Maximum length 50

And this is what I have done so far:
^(([A-Za-z]+( [A-Za-z])+){1,50})$

This allows me to validate the spaces between words and only letters conditions but it is not working for the length and it's not working for words without spaces, example:hello. Can someone help me with this?
Example:
What I need:
Regex that allows sentences (with max length 50) like this:
Hello this is an example
Hello
a b c

A: Try this:
^\b(?!.*?\s{2})[A-Za-z ]{1,50}\b$

Demo
[A-Za-z ]{1,50} will check for the characters and length, while the negative lookahead (?!.*?\s{2}) will check for the spaces condition. (\b) to disallow white space at ends.


text:
Q: evolution equation satisfied by projection Consider the linear parabolic problem (as in Evans)
$$\begin{cases}
\partial_t u+Lu=f\ \: \mbox{in} \:\Omega \times (0,T]\\
u=0\ \: \mbox{on} \:\partial \Omega \times (0,T]\\
u(\cdot,0)=g \ \: \mbox{in} \:\Omega
\end{cases}$$
where $L$ is the operator given by
$$Lu=-\mathrm{div}(A(x,t)\nabla u)+b(x,t)\cdot\nabla u+c(x,t)u$$
which we assume to be parabolic with bounded coefficients (and $A$ symmetric).
A weak solution is given by a function $u \in L^2(0,T;H^1_0(\Omega))$ with $u'\in L^2(0,T;H^{-1}(\Omega))$ that satisfies the initial condition and the following equation:
$$\forall 0 < t \leq T,\:\forall v \in H^1_0(\Omega),\: \langle u'(t), v \rangle + a(t;u(t),v)=(f(t),v)_{L^2}$$
(here $a$ is the usual bilinear form, depending on time, associated to $L$)
Consider a Hilbert basis $(w_i)$ of $L^2(\Omega)$ formed by the eigenfunction of the Laplace operator, so that
$$w_i \in H^1_0(\Omega),\:\int_\Omega w_i w_j = \delta_{ij},\:\int_\Omega \nabla w_i\cdot \nabla w_j =||\nabla w_i||^2_{L^2} \delta_{ij}$$
Set $V_m=\overline{\mathrm{span}}(\{ w_i| 1 \leq i \leq m\})$ and denote by $P_m$ the projection on $V_m$.
If $u$ is a weak solution, is it true that $u_m=P_m \circ u$ is a solution of the following approximated problem on $V_m$?
$$\forall 0 < t \leq T,\:\forall v \in V_m,\: (u_m'(t), v)_{L^2} + a(t;u_m(t),v)=(f(t),v)_{L^2}$$
I have been able to prove the following. If $u(t)=\sum_{i=1}^\infty y_i(t) w_i$, then $y_i \in H^1(0,T)$ so that $u_m \in H^1(0,T;V_m)$ with $u_m(t)=\sum_{i=1}^m y_i(t)w_i$ and $u'_m(t)=\sum_{i=1}^m y'_i(t)w_i$. Then one can see that for all $v \in V_m$
$$\langle u'(t),v \rangle=(u'_m(t),v)_{L^2}$$
$$ \int_\Omega A(\cdot,t)\nabla u(t) \cdot \nabla v=\int_\Omega A(\cdot,t)\nabla u_m(t) \cdot \nabla v$$
$$ \int_\Omega c(\cdot,t)u(t)v=\int_\Omega c(\cdot,t)u_m(t)v$$
I don't know if is true that it works also for the $b$ term, that is if for $v \in V_m$
$$\int_\Omega b(\cdot,t)\cdot v \nabla u(t)=\int_\Omega b(\cdot,t) \cdot v \nabla u_m(t)$$
I think it would be sufficient to know that $\int_\Omega w_j \nabla w_i=0$ for all $i \neq j$, but I don't know if it is true and (eventually) how to prove it.


text:
Q: lambda function with rank My dataset is as follows,

index
advance to deposit

company1
86.8%

company2
96.2%

I tried with following code,
bank_ratios['rank3'] = bank_ratios['Advance to Deposit'].apply(lambda x:0 if x>100%  or x<85%  else `rank(ascending=False))`

I want to rank the company based on the value, but I want to return a value 0 if <80% or >100%, if it is in between, rank the company.
In this code it says invalid syntax. Here I used the this column as object.
How to set the condition using lambda?
Thanks

A: Get the percentage as float
df['advance_percentage'] = df['advance to deposit'].str.replace('%', '').astype(float)

Get rank column
df['rank3'] = np.where(
    df.advance_percentage.between(80, 100),
    df.advance_percentage.rank(ascending=False),
    0
)


text:
Q: parse error php en html intento de meter codigo html dentro de php, pero me sale este error
Parse error: syntax error, unexpected '{', expecting ',' or ';' on line 3
Mi codigo php
 <?
 echo'

    ';
    ?>

A: En vez de hacer concatenaciones complicadas, mejor escapa los caracteres.
Entonces esa línea, siguiendo el formato, se puede reescribir así:
echo '
';

Lo cual imprime:


text:
Q: ¿Cómo puedo hacer que el estado planificador de eventos siempre esté activo? phpMyAdmin Tengo una duda con respecto al estado de planificador de eventos, estoy usando el phpMyAdmin localmente y cada que inicio el servidor y la base de datos con XAMPP el estado planificador de eventos se desactiva, siempre será así o cómo podría solucionarlo? Pasa que con ello desactivo los eventos y no se ejecutan y, en mi caso, tengo eventos que corresponden al tiempo máximo de sesión y demás.

No tiene nada que ver, pero dejo el evento del cierre de sesión que se ejecuta cada cierto tiempo.

DELETE FROM tablaSesiones WHERE tablaSesiones.inicioSesion IS NOT NULL AND
NOW() >= DATE_ADD(tablaSesiones.inicioSesion, INTERVAL 1 HOUR)

A: Para que el "Planificador de eventos" siempre inicie activo, podrías hacer lo siguiente:

*

*Buscar el archivo my.ini dentro del directorio de XAMPP
Ejemplo:
xampp\mysql\bin\my.ini

*Agregar:
[mysqld]
event_scheduler=ON

Nota: Puede que [mysqld] ya exista, en tal caso agregar solo la línea event_scheduler=ON debajo.

*Guardar el archivo.

*Reiniciar el servicio de MySQL.


text:
Q: Anyway to debug web projects on AS7(Jboss) with intellij Community Edition Anyway to debug web projects on AS7(Jboss) with intellij Community Edition?
I am looking for a way to debug my spring mvc project in intellij running on jboss AS7

A: You can use Remote debug for plain Java code debugging, but you can't debug JSP code at all with the Community Edition.


text:
Q: Looking To Set An int Answer To The Form Of A Currency I am coding my first app in java, it is a simple Tip Calculator. The problem I am having is I am having a hard time trying to figure out how I can get my final answer to come back properly formatted in US currency form ($##.##) Whenever I would try something like setting up a currency string in my code it would say it is being ignored by my strings and this was not doing anything. Here is my main Java code:
    package com.rockdrummer.calculating.calculating;

    import android.app.Activity;
    import android.os.Bundle;
    import android.text.InputFilter;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import java.util.Locale;

    public class MainScreen extends Activity {
    Button ten, fifteen, twenty;
    TextView tip;
    EditText bill_amount;
    double a;
    double b;
    double af;
    double bf;
    double ac;
    double bc;

    @Override
    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_screen);
    initControls();
    Locale.setDefault(Locale.US);

    }

    protected void initControls() {
    ten = (Button) findViewById(R.id.bTen);
    fifteen = (Button) findViewById(R.id.bFifteen);
    twenty = (Button) findViewById(R.id.bTwenty);
    tip = (TextView) findViewById(R.id.tip);
    bill_amount = (EditText) findViewById(R.id.bill);

    tip.setFilters(new InputFilter[]{
            new InputFilter.LengthFilter(20)});

    ten.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View ten) {
            try {
                calculate();
            } catch (IndexOutOfBoundsException e) {
                e.printStackTrace();
            }
        }
    });
    fifteen.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View fifteen) {
            try {
                calculate_f();
            } catch (IndexOutOfBoundsException e) {
                e.printStackTrace();
            }
        }
    });
    twenty.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View twenty) {
            try {
                calculate_t();
            } catch (IndexOutOfBoundsException e) {
                e.printStackTrace();
            }
        }
    });
    }

    private void calculate() {
    a = Double.parseDouble(bill_amount.getText().toString());
    b = a * 0.1;
    tip.setText("You Should Tip $" + Double.toString(b));
    }

    private void calculate_f() {
    af = Double.parseDouble(bill_amount.getText().toString());
    bf = af * 0.15;
    tip.setText("You Should Tip $" + Double.toString(bf));
    }

    private void calculate_t() {
    ac = Double.parseDouble(bill_amount.getText().toString());
    bc = ac * 0.20;
    tip.setText("You Should Tip $" + Double.toString(bc));
    }

    }

I appreciate any help. Thank you in advance!

A: With doubles, you are going to need to apply a rounding mode, to avoid any inconsistent bits. You will get some strange results if you don't. The easiest method I've found is using the Java class BigInteger:
http://developer.android.com/reference/java/math/BigInteger.html
Then use DecimalFormat:
http://developer.android.com/reference/java/text/DecimalFormat.html


text:
Q: Excel 2003: Why does creating links to other spreadsheets take so long? My Excel application creates links to other Excel files. It takes approx 1 sec to create a link for 1 cell, but I have several hundred cells to link so it's painfully slow.
There is no difference in speed whether the source file is opened or closed. I have, however, noticed that creating links manually (e.g., by copying and pasting the formula containing the link into other cells by hand) is much faster while the source file is opened.
In my program I have configured
Application.Calculation to be Manual instead of Automatic.
I tried accomplish the linking in two ways (please note this is not a real code, but I hope it shows what I mean):
1.
Copy the formula link to the external source from Range("A1") using
a foreach loop on every Cell in a range:
Cell.FormulaR1C1 = Range("A1").FormulaR1C1
2.
Copy the formula from Range("A1") to another range without using a foreach loop:
Range("thisIsMyTargetRange").FormulaR1C1 = Range("A1").FormulaR1C1
Both methods are equally slow, and as I said I've checked both of the above methods with the source file opened and closed.
Is there any way to speed this up? Does anyone know enough about the linking mechanism in Excel 2003 to offer advice on how to improve the linking performance?

A: Is it pertinent to have the formulas? If not use .value instead of .formular1c1.
Also if the ranges are the same size then use a range copy instead of the loop. e.g.
range(a1:a500).value = range(a1:a500)

Added Alternative Method:
Also, an alternative method would be to create a table using the data import functionthat is refreshed when the file opens, if a sheet is what you after. Then if you wanted bits of that sheet, use the data in the import sheet/table. This will keep the updating or linking to only one large import when opening the file.

A: I had to do this for months of data taken around once a second.
Open the document you want to copy data from.  Then copy any sheets that hold that data into the workbook you are using.  Grab the data from them, then delete those sheets from your workbook.  Do this in a macro so it can be done quickly and repeatedly.


text:
Q: How is partial application working here? > map (++ "!") ["a", "b", "c"]
["a!","b!","c!"]
> (++) "!" "a"
"!a"

These two lines don't make sense to me. When using ++ in map, it seems like the first parameter is appended to the second, but in the second list it's the other way around. How does Haskell reason about the behavior in the map function?

A: The (++ "!") is a bit of special syntax called an operator section. It's partially-applying the second parameter of the infix operator, whereas (++) "!" works like normal partial application and is applying the first parameter.
You can also do the same thing with regular functions used infix-style with backticks: (`map` [1..3]) is equivalent to (\f -> map f [1..3]).
It seems odd because it is, it's a special-case extra feature that's in there just because it's darn useful.

A: The partial application (++ "!") is identical to (\x -> x ++ "!"). In other words, the expression (++ "!") is smart enough to know that the "!" is the second argument to (++). It knows this because it knows that ++ is an infix operator. In the second expression, (++) "!" "a" is identical to "!" ++ "a", and does what you'd expect.

A: map (++ "!) ["a", "b", "c"]

is equivalent to
["a" ++ "!", "b" ++ "!", "c" ++ "!"]

And
(++) "!" "a"

is equivalent to
"!" ++ "a"

Hope this helps.


text:
Q: How to fix it in BST insertion and let the insertion function work The code showed in Visual StudioThe InsertBSTNode function is wrong. But I don't know how to fix it. The requirement is that do not change the type of the function.
TreeNode
 class TreeNode{
    public:
    int data;
    TreeNode* left;
    TreeNode* right;

    TreeNode(int x): data(x), left(NULL), right(NULL){}
    };

InsertBSTNode
void InsertBSTNode(TreeNode* &root, int val){
// Input your code here.
if (root==NULL){
    root->data=val;
    root->left=root->right=NULL;}
else if(val<root->data)
    root->left=InsertBSTNode(root->left,val);//error
else if(val>root->data)
    root->right=InsertBSTNode(root->right,val);//error
return root;//error

};

A: So this is the code I think you are trying to write
void InsertBSTNode(TreeNode* &root, int val) {
    if (root == NULL) {
        root = new TreeNode;
        root->data=val;
        root->left=root->right=NULL;
    }
    else if (val<root->data)
        InsertBSTNode(root->left,val);
    else
        InsertBSTNode(root->right,val);
}

I've fixed the invalid use of return values, and I've fixed the NULL pointer error by allocating a node at the place where you do the insert.

A: This is the solution for the question. Thanks for @john helping!
void InsertBSTNode(TreeNode* &root, int val){
if (root==NULL){
    root = new TreeNode(val);
    root->data=val;
    root->left=root->right=NULL;}
else if(val<root->data)
    InsertBSTNode(root->left,val);
else if(val>root->data)
    InsertBSTNode(root->right,val);
};


text:
Q: Find price pattern correlations on pandas dataframe see image given a financial dataset I have created a dataframe from it. I would find the correlation from price drops and price bounces (the ratio of bounce/drop persentage) please see pseudo code:
        for i, row in df['Close']:
               if i in row A > i in row B and
                  i in row B > i in row C
                  new_df['Drop']   = A.pct_change(B)
                  new_df['Bounce'] = B.pct_change(C)
                  new_df['Ratio']  = new_df['Drop'] / new_df['Bounce']

So: from a dataframe of financial data I would like to find the following pattern: If the price drops measure the % of the drop then when it goes up again measure the % of this and divide the persentages of the drop and bounce in order to get the ratio of the movement.
I have found code that kinda helped me here
Greatly appreciated any help!


text:
Q: iPhone OpenGl : importing 3D models General openGl question here. I guessing that to create 3D models to use with openGl-es I should use blender and save them as Obj. Do I have to make a parser or does openGl ES support a certain format? what about animations?

A: Open Asset Import Library can be used on the iOS and is licensed under the 3-clause BSD license.

A: Using blender to save your models as obj files is a great way to go, imo.  OpenGL doesn't, to my knowledge, have any pre-built functionality or preference for certain file formats.  You'll likely have to make your own parser to load the vertex data or, if you'd prefer, you can use one of the many .obj loaders others have written and posted online.  I would recommend writing your own loader, however.  It's fun and you'll learn a lot.  Obj files are pretty easy, too.  This might be a good starting point, if you just want to adapt pre-written code.
If you're still exploring 3D file formats though, I would recommend looking into Collada.  It's an XML format and supports textures, vert weights, and even animations.  There's also a plug-in available for blender.  On the downside, it's a bit harder to find pre-made loaders out there and making your own takes a leap in difficulty from obj files.  Sifting through Collada DOM should help get you well on your way, however, as it includes sample code for an OpenGL viewer and effects loader.  The Khronos faq might get you started if you have tons of questions about the format.


text:
Q: Why are vectors of a regular hexagon cos60 of each other? In a regular hexagon OABCDE $a$ , $b$ denote respectively the position vectors of $A$, $B$ with respect to $O$
I would have assumed that $\overrightarrow {OA} = \overrightarrow {AB} = \overrightarrow {BC}  $ since it's a regular hexagon. And, therefore, $\overrightarrow {OC}$ should equal $\overrightarrow {OA} + \overrightarrow {AB} + \overrightarrow {BC}  $ and therefore  $\overrightarrow {3AB}$.
However, in the literature I was reading, $\overrightarrow{OC}$ is defined as $\overrightarrow {OA}\cos60 + \overrightarrow {AB} + \overrightarrow {BC} \cos60 $, and thus $\frac12  \overrightarrow{AB} + \overrightarrow {AB} + \frac12 \overrightarrow {AB} $  — ultimately $\overrightarrow{2AB}$. Why is this?
An image is included below.

A: Hint:
Since $\overrightarrow{OA}$, $\overrightarrow{AB}$ and $\overrightarrow{BC}$ are not parallel it is not true that:
$$
\overrightarrow{OA}+\overrightarrow{AB}+\overrightarrow{BC}=3\overrightarrow{OA}
$$

A: What's true is that the lengths of $OA$ and $AB$ and $BC$ are all equal, but they're not equal as vectors -- they point in three different directions.

A: The actual vectors are:
$$\overrightarrow{OA}=\begin{pmatrix}\frac12\\\frac{\sqrt{3}}2\end{pmatrix}$$
$$\overrightarrow{AB}=\begin{pmatrix}1\\0\end{pmatrix}$$
$$\overrightarrow{BC}=\begin{pmatrix}\frac12\\\frac{\sqrt{3}}2\end{pmatrix}$$
So we have $|\overrightarrow{OA}|=|\overrightarrow {AB}|=|\overrightarrow{BC}|$.
And $\overrightarrow{OA}+\overrightarrow {AB}+\overrightarrow{BC}=\begin{pmatrix}\frac12\\\frac{\sqrt{3}}2\end{pmatrix}+\begin{pmatrix}1\\0\end{pmatrix}+\begin{pmatrix}\frac12\\\frac{-\sqrt{3}}2\end{pmatrix}=\begin{pmatrix}2\\0\end{pmatrix}=2\overrightarrow {AB}$.
The literature uses $OA \cos 60^\circ$ to mean $|\overrightarrow{OA}| \cos 60^\circ$, and not $\overrightarrow{OA} \cos 60^\circ$, to mean the length of $\overrightarrow{OA}$, which is $1$.


text:
Q: Passing Arrays through Fuctions - "Error: Cannot Convert 'float**' to 'float*' for argument '1'" Long time Reader, First time Asker.
So I'm working on a coding project of which the long term goal is to make a solar system simulator. The idea is that that it whips up a randomized solar system with a few rules like 'at formation the first planet after the frostline has to be the largest gas giant' etc, and calculates the orbits to check for stability.
Obviously it's not done yet, I'm having some trouble with using the arrays in the subroutines. I know that you can't directly take arrays in and out of functions, but you can take pointers to said arrays in and out of functions if you do it right.
I apparently have not done it right below. I've tried to comment and make the code as readable as possible, here it is.
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <tuple>
#include <vector>
#include <stdio.h>
#include <math.h>
#include <complex>
#include <stdint.h>
#include <time.h>
#include <string.h>
#include <algorithm>

//#include "mpi.h"

using namespace std;

double MyRandom(){

//////////////////////////
//Random Number Generator
//Returns number between 0-99
//////////////////////////

    double y = 0;
    unsigned seed = time(0);
    srand(seed);
    uint64_t x = rand();

    x ^= x << 13;
    x ^= x >> 7;
    x ^= x << 17;

    x = (1070739 * x) % 2199023255530;
    y = x / 21990232555.31 ;
    return y;
}
////////////////////////

///////////////////////
tuple< char& , float& , float& , float& , int& > Star(){

////////////////////////////
//Star will generate a Star
//Randomly or User Selected
//Class, Luminosity, Probability, Radius, Mass, Temperature
//Stars always take up 99% of the mass of the system.
///////////////////////////

char Class;
string Choice;
float L, R, M;
int T;
tuple< char& , float& , float& , float& , int& > star( Class = 'i', L = 1 , R = 1 , M = 1 , T = 3000) ;
cout << "Select Star Class (OBAFGKM) or Select R for Random: ";
cin >> Choice;
if ( Choice == "R" ) {
    double y;
    y = MyRandom();
    if (y <= 0.003) Class = 'O';
    if ((y > 0.003) && (y <= 0.133)) Class = 'B';
    if ((y > 0.133) && (y <= 0.733)) Class = 'A';
    if ((y > 0.733) && (y <= 3.733)) Class = 'F';
    if ((y > 3.733) && (y <= 11.333)) Class = 'G';
    if ((y > 11.333) && (y <= 23.433)) Class = 'K';
    else Class = 'M';
    }
    if (Class == 'O') {
        L = 30000;
        R = 0.0307;
        M = 16;
        T = 30000;
    }
    if (Class == 'B') {
        L = 15000;
        R = 0.0195;
        M = 9;
        T = 20000;
    }
    if (Class == 'A') {
        L = 15;
        R = 0.00744;
        M = 1.7;
        T = 8700;
    }
    if (Class == 'F') {
        L = 3.25;
        R = 0.00488;
        M = 1.2;
        T = 6750;
    }
    if (Class == 'G') {
        L = 1;
        R = 0.00465;
        M = 1;
        T = 5700;
    }
    if (Class == 'K') {
        L = 0.34;
        R = 0.00356;
        M = 0.62;
        T = 4450;
    }
    if (Class == 'M') {
        L = 0.08;
        R = 0.00326;
        M = 0.26;
        T = 3000;
    }

    return star;
}
////////////

////////////
float* Planet( float &L, float &R, float &M, int &T, int &n){

///////////////////////////
//Planet generates the Planets
//Random 1 - 10, Random distribution 0.06 - 6 JAU unless specified by User
//Frost line Calculated, First Planet after Frost line is the Jupiter
//The Jupiter will have the most mass of all Jovian worlds
//Otherwise divided into Jovian and Terrestrial Worlds, Random Masses within groups
//Also calculates if a planet is in the Habitable Zone
////////////////////////////

    float frostline, innerCHZ, outerCHZ;
    float a = 0.06; // a - albedo
    float m = M / 100; //Mass of the Jupiter always 1/100th mass of the Star.
    float sys[n];
    float* system[n][5] = {{0}};

    for (int i = 0 ; i < n ; i++){
        sys[i] = MyRandom()/10 * 3; //Distances in terms of Sol AU
    }
    sort(sys, sys + n );
    for (int i = 0 ; i < n ; i++){
        system[i][0] = &sys[i];
        system[i][1] = 0; //system[i][0] is x, system[i][1] is y
    }

    frostline = (0.6 * T / 150) * (0.6 * T/150) * R / sqrt(1 - a);
    innerCHZ = sqrt(L / 1.1);
    outerCHZ = sqrt(L / 0.53);

    for (int i = 0 ; i < n ; i++){
        if (system[i][0] <= &frostline) {
            float tmass = m * 0.0003 * MyRandom();
            system[i][2] = &tmass ; //system[i][2] is mass, [3] is marker for the Jupter
            system[i][3] = 0 ;
        }

        if ((system[i][0] >= &frostline) && (system[i-1][0] < &frostline)){
            system[i][2] = &m ;
            float J = 1;
            system[i][3] = &J ;
        }

        if ((system[i][0] >= &frostline) && (system[i-1][0] >= &frostline)) {
            float jmass = m * 0.01 * MyRandom();
            system[i][2] = &jmass ;
            system[i][3] = 0 ;
        }

        if ((system[i][0] >= &innerCHZ) && (system[i][0] <= &outerCHZ)){
            float H = 1;
            system[i][4] = &H;
        }
        else system[i][4] = 0; //[4] is habitable marker

    }

    return system[n][5];
}
////////////

////////////
float* Time( float *system , int n){

///////////////////////////
//Time advances the solar system.
//Plots the Orbits
//Uses MPI to spread it's calculations.
///////////////////////////

    return system;
}
////////////

////////////
void FinalCheck( float system){

///////////////////////////
//Final Checks
//Reports if a Planet spent the whole Time in the Habitable Zone
///////////////////////////

/*for (int i = 0 ; i < row ; i++){
    if (system[i][4] == 1.0) {
        cout << "Planet " << i << " in this system is Habitable." ;
        }
    // The Habitable stat only means liquid water can exist on the surface
    // Add pi if planet enters habitable zone, minus 1 if it leaves.
    // If planet was habitable but left, assuming all life was destroyed
    }
*/
}
////////////

int main(){

char Class;
int T;
float L, R, M;

tuple< char , float , float , float , int > star( Class , L , R , M , T );
star = Star();

int n = MyRandom()/10 + 1;

float * system[n][5] = {{0}};
float system1[n][5] = {{0}};
system[n][5] = Planet( L , R , M, T, n);

for (int i = 0 ; i < 100 ; i++) {
 system1[n][5] = Time( *system, n );
 system[n][5] = &system1[n][5];
}
FinalCheck( *system[n][5]);

///////////////////////////
//Report cleans everything up and gives the results
//Shows the plot, lists the Planets
//Reports the Positions and Masses of all Planets
//Reports which was the Jupiter and which if any were Habitable
//////////////////////////
return 0;
}

The problem is when I run a compiler over this line 227 gets flagged -
  system1[n][5] = Time( *system, n );

With the following error:
  error: cannot convert 'float**' to 'float*' for argument '1' to 'float* Time(float*, int)

I get that this means that the compiler things I'm trying to equate a pointer-to-a-pointer with a pointer, but I'm not sure how it arrived at that conclusion or how to fix it. I'd appreciate help with this, especially the second part. I also would love to hear anything about passing arrays through subroutines as apparently I'm not doing it right, or at least not well.
Update 1 : - Got the short-term fix in and the compiler makes it through but gives a segmentation fault (core dumped) error when I try to run it. Looks like I have some reading and updates to do though with the namespace, the pointers, and possibly changing the arrays into vectors instead. Feels like if I concentrate on those first it might fix the segmentation error.

A: Your variable system is declared as
float * system[n][5] = {{0}};

which is a pointer to a 2D array (which will decay to float*** when passed to a function).
Your Time function is declared as
float* Time( float *system , int n);

where the 1st argument needs to be a float*.
That means this call
system1[n][5] = Time( *system, n );

should actually be something like
system1[n][5] = Time( **system, n );

That being said, there are a number of issues in your code.
To start off, don't do using namespace std;.
Also, this line float sys[n]; is not allowed. You can't have variable length arrays in c++.

A: float* system[n][5]

system here is a 2D array of float*s, not floats.
So, in other words, system decays to float***, *system decays to float**, **system decays to float*, and ***system decays to float.
So, the compiler is correct. You're passing what decays to a float** to Time() which expects a float*.
You're going to have to reconfigure your code to pass the right thing, whatever that is.

Side note: please be advised that the way you're creating arrays isn't valid C++ and may cause issues later.


text:
Q: Splitting alphumeric column in SQL I currently have a dataset looking like this
J_J      WMT        MSF
6.7M     167.8M     1.6k
544K     700.7B     875k
888.7B   900K       98.5M

I want to split the string values for each column so I could watch something like this:
Column1   Column2
6.7         M
544         K
888.7       B

I am currently using the following code for the 1st column:
SELECT REPLACE("J_J", '[0-9]') AS Letters,
       REPLACE("J_J", '[A-Z-z]') AS Numbers
FROM   data

which gives me the following error:
The replace function requires 3 argument(s).

How could I declare argument function?,
Thanks in advance

A: Most databases support left() and right() and either len() or length().  That suggests:
select left(J_J, len(J_J) - 1), right(J_J, 1)


text:
Q: Can a website stop a program from downloading files automatically? I am writing a program in python that will automatically download pdf files from a website once a day.
When trying to test I noticed that the files downloaded had the correct extension but they are very small (<1kB) compared to the normal size of about 100kB when downloaded manually.
Can a website block a program from automatically downloading files?
Is there anything that can be done about this?

A: Yes. Cloudflare can block bots from downloading files. Blocking is usually done by detecting the user-agent or including javascript in a webpage. I would examine the pdf file in notepad and see what it contains also try adding a user-agent option in your python code.


text:
Q: How do I display different text than the cell text in a cell? I have an Excel sheet where I have two cells on one side, one of which includes a two-digit number with a leading zero formatted as text and the other one includes an explanation. On the other side I have another empty cell. I want the explanation text to be displayed in that empty cell but the cell should have the two-digit number that's formatted as text as its value internally. I got it to work with a number as the value, but not with the number that's formatted as text.
I've tried the .Text tag but it always throws a syntax error. My suspicion is that that's because of the .NumberFormat tag and how it's formatted. [Disclaimer: I didn't write this code myself but I have to fix it.]
Sub UserDefinedFormatting()

' Delete old output:

Range("G6:G500").ClearContents
Range("G6:G500").NumberFormat = "Text"

' Loop for new output:

For n = 5 To 200

    If Cells(n, 3).Value <> 0 Then

    Value_actual = Cells(n, 3).Value
    Value_shown = Cells(n, 4).Value

    Cells(n, 7).Value = Value_shown
    Cells(n, 7).NumberFormat = "[=" & Value_actual & "]""" & Value_shown & """;General"
    Cells(n, 7).Value = Value_actual

    End If

Next n

End Sub

Desired outcome:
| I1 |  I2  |      Output     |
| 05 | Test | Test[Value: 05] |

Actual outcome:
| I1 |  I2  |     Output     |
| 05 | Test | Test[Value: 5] |

Somehow it always takes away the leading zero which is essential.


text:
Q: Tracking unpaid google search keywords in conversions We track search terms in our adwords campaigns by appending urls with the relevant terms (utm_term, utm_source, etc). This means we can see the search terms within the submitted form and tag them to that visitor. Its really handy for tracking conversions and linking them to revenue for that particular customer.
I can't figure out how to do this for organic search terms?
And also for visitors who don't follow the exact conversion funnel. E.g. they hit our landing page but then go wandering through the site, lose the appended terms on the URL and then submit a form.
Do I need to use cookies? Or a tracking script? Or a service like kissmetrics?

A: Those parametrs are already written in user's browser cookies by GA tracing code. Try reaching your website from different channels and looking at __utm cookies in your browser. Since they're made by your website you can pass them through your form via hidden fields.


text:
Q: looping through array of associative arrays to remove some data adds wrong data to second item This is the result of a query to the DB:
array(2) {
    [0] array(21) {
        ["model_id"] 218
        ["total"] 10
        ["make"] "maker_a"
        ["model_name"] "some_name"
        ["picture"] "some_picture.jpg"
        ["color"] "Black"
        [1] 0
        [2] 0
        [3] 0
        [4] 6
        [5] 3
        [6] 1
        [7] 0
        [8] 0
        [9] 0
        [10] 0
        [11] 0
        [12] 0
        [13] 0
        [14] 0
        [15] 0
    }
    [1] array(21) {
        ["model_id"] 219
        ["total"] 10
        ["designer"] "maker_a"
        ["model_name"] "some_other_name"
        ["picture"] "some_other_picture.jpg"
        ["color"] "White"
        [1] 0
        [2] 0
        [3] 0
        [4] 5
        [5] 5
        [6] 0
        [7] 0
        [8] 0
        [9] 0
        [10] 0
        [11] 0
        [12] 0
        [13] 0
        [14] 0
        [15] 0
    }
}

I want to get rid of the items with value = 0, so I tried this loop:
$results = [];

foreach ($models as $i) {
    foreach ($i as $key => $value) {

        if ($value != 0 || !is_numeric($value)) {

            $result[$key] = $value;
        }

    }
    if (isset($result)) {
        $results[] = $result;

    }

}

var_dump($results);

but for some reason the result is incorrect, an item with value != 0 gets added in the second item, the value that is correctly present in the first item as [6] 1 gets
added to the second item where there were only [4] 5 and [5] 5. I don't get the reason of this result.
array(2) {
    [0] array(9) {
        ["model_id"] 218
        ["total"] 10
        ["makes"] "maker_a"
        ["model_name"] "some_name"
        ["picture"] "some_picture.jpg"
        ["color"] "Black"
        [4] 6
        [5] 3
        [6] 1
    }
        [1] array(9) {
        ["model_id"] 219
        ["total"] 10
        ["designer"] "maker_a"
        ["model_name"] "some_other_name"
        ["picture"] "some_other_picture.jpg"
        ["color"] "White"
        [4] 5
        [5] 5
        [6] 1 <---- THIS DOESN'T BELONG HERE!
    }
}

A: Damn, for some reason the loop is posting the last $result variable in the next item. Solution was adding unset($result); after insertion in the $results array:
$results = [];

    foreach ($models as $i) {
        foreach ($i as $key => $value) {

            if ($value != 0 || !is_numeric($value)) {

                $result[$key] = $value;
            }

        }
        if (isset($result)) {
            $results[] = $result;
            unset($result); // <--- HERE

        }

    }

    var_dump($results);


text:
Q: Showing that a homomorphism between groups of units is surjective. Let $n$ be a positive integer and let $d$ be some divisor of $n$. Consider the group of units modulo $n$, which we shall denote by $U(n)$. Likewise, denote the group of units modulo $d$ by $U(d)$.
Consider the homomorphism $f:\ U(n)\rightarrow U(d)$ given by reducing modulo $d$,
$$f(u) = u \pmod{d}$$
I wish to show that this map is surjective. Can anyone supply a simple proof of this fact?
Alternatively, it is sufficient to prove that the set
$$S = \left\{u\in U(n) \mid u\equiv 1 \pmod{d} \right\}$$
has cardinality $|S| = \phi(n)/\phi(d)$ where $\phi$ is the totient function.

A: Let $u$ be a unit modulo $d$ and confuse it with the integer $0 < u < d$. Clearly if $(u, n) = 1$ then $u$ is in the image of the map. So suppose $(u,n) \neq 1$. Then it suffices to find $x \in \mathbb{Z}$ such that $(u + xd, n) = 1$. Indeed, if this can be done, then the map sends $u+xd \rightarrow u$ with $u+xd$ a unit in $\mathbb{Z}/n\mathbb{Z}$.
Claim: Taking $x$ to be a product of all primes dividing $n$ which do not divide $u$ suffices.
Proof: Let $p$ be a prime dividing $n$. If $p \mid u$, then $p$ does not divide $x$ and $p$ does not divide $d$ by definition. Hence $p \nmid u+dx$. Now suppose $p \nmid u$.  Then $p \mid x$ by definition, so $p \nmid u + dx$.
Therefore every prime which divides $n$ does not divide $u+dx$, giving $(u+dx,n) = 1$.


text:
Q: Hide certain Iphone apps "More iPhone Apps by" In the Itunes Store when someone views my XYZ app they can see everything I have created with my developer account. Is there any way to remove a specific application that I developed from the "More iPhone Apps by " list ?
Thank you


text:
Q: How to display articles based on composed tag I'm encountering an issue when I want to display some articles based on a "composed" tag like "amnesty-international". The query doesn't return any results. The fact is I have two article tagged with this slug.
This is the code I use in the template archive.php:
$current_tag =  single_term_title("", false);
$args= array(
    'post_type' => 'adverts',
    'tag' => $current_tag
);

$adsQuery = new WP_Query($args);

So this url doesnt return anything : http://www.mydomain.net/tag/amnesty-international/
Should I use another function ?

A: Thanks to a similar topic I can do it with :
$tag       = get_queried_object();
$tag_slug  = $tag->slug;

Or with this snippet :
$current_tag =  single_term_title("", false);
tag_slug = str_replace(' ', '-', $current_tag);


text:
Q: Do I need client certs for mysql ssl replication? I'm setting up mysql replication using SSL, and have found two different guides.
The first one creates both client and server certs, while the second one only creates server certs.
I don't know enough about SSL to understand the implication of one option over the other.  Should the slave be using the client certs or the server certs?

A: No, you don't need client certificates if you only want to encrypt the connection.
But, if you have client certificates, the master can authenticate the slave using the much more secure public/private keys (in addition to the password).
I got pretty frustrated with the other guides, so I put together a very comprehensive step by step guide to setting up encrypted replication.  It shows both what's the minimum required to get encryption running, and how to use certs on both sides to beef up authentication.
http://mysql.wingtiplabs.com/documentation/ssl27yzv/encrypt-replication-traffic


text:
Q: How to fit many datasets at once with a cross-validated pipeline? Basically, I need to find a pipeline that will not only be the best on one dataset, but to be the best in average across an ensemble of dataset.
How would you solve this problem using a cross-validated pipeline (e.g.: Scikit-learn)? The thing is that it's made for fitting only one dataset, but I have a list of datasets.
Would you simply find the best classifier for each dataset, and then train another pipeline for fitting the problem of "x = dataset" and "y = estimated best hyperparameters for this dataset"?
I'd still prefer something simpler but that would perform good enough. Would you have another solution?
Note: this question is more about Machine Learning strategies than coding. The coding part here is optional. It's bad to see this question on hold. The reason for the question to be on hold is wrong. I don't see why this question should not be on the cross-validated stack exchange. Bad moderation on this question is wrong and would make this site poorer than it is already. If you believe this question doesn't belong here, please move it instead of putting it on hold. Thanks. Please read the new Code of Conduct as posted on Hacker News 5 hours ago: https://news.ycombinator.com/item?id=17715193
Other note: I've already tried to figure this out with Scikit-learn but I'm seeking a potentially simpler solution than what I thought of.


text:
Q: word page number in header table I have a table in header with 1 row, column 1 is a image and column 2 some text.
I want to add page number to the third cell with vertical alignment bottom.
I tried but do not know which object to add the .PageNumber.Add( )

A: Sounds like you want to do it to the .Cells(1,3) of the table. You might need .Range() on the end of that.
Tamar

A: just for helping others, after the last comment of using "oRange.end = oRange.End - 1" which was the answer I was looking:
I was trying to make a footer that has a hyperlink to the start of my document, and the page number.
When exporting this to .pdf, the link is clickable and takes you to the table of contents.
my code is:
foreach (Section wordSection in doc.Sections)
{
    Range footerRange = wordSection.Footers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
    footerRange.Font.Size = 12;
    Table ftable = doc.Tables.Add(footerRange, 1, 2);
    ftable.PreferredWidthType = WdPreferredWidthType.wdPreferredWidthPercent;
    ftable.PreferredWidth = 100;
    doc.Hyperlinks.Add(ftable.Cell(1, 1).Range, Address: "", SubAddress: "_top", ScreenTip: "", TextToDisplay: "Contents");
    Range t2r = ftable.Cell(1, 2).Range;
    t2r.End = t2r.End - 1;
    doc.Fields.Add(t2r, Type: WdFieldType.wdFieldPage);
    ftable.Cell(1, 2).Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight;
}

thank you user3876120


text:
Q: GWT input type won't work I have been developing small gwt screen with smartwgt components and nearly at the end of the task I found out not a single keyboard buttons are working on any input, I cannot type, cannot do tab between inputs. it was working few days ago while I was in the middle of development. I cannot think of any reason that makes this wont work. Here is the screen, I can only select from dropdown using mouse. Any idea what may be turned on, or canceling or keyboard events?
here is the screenshot
Thanks.

A: It's hard to offer a solution without seeing the code, but one possibility is that you added some empty panel on top of your other UI elements, and this panel consumes all user actions.

A: I turned out to be there was a native java method which was initializing a method to hand page keypress which messed up:
private static native void initKeyHandler()/*-{
        $wnd.onPageKeyPress = function (event) {}
}-*/;


text:
Q: React safelySetState - Anti pattern or good practice? I was recently met with the

"Can only update a mounted or mounting component."

error message when I tried setting the state after a asynchronous fetch call was made. It occurred because the component was unmounted before the http response got back.
Then I started googling, and found a solution to the problem.
What if a variable was holding the "mounted"-state, and every time I wanted to update the state, I would just check the variable? Like a safelySetState() function?
Here is an example:
componentDidMount = () => {
  this._mounted = true;
}

componentWillUnmount = () => {
  this._mounted = false;
}

safelySetState = (obj) => {
  if(this._mounted)
    this.setState(obj);
}

Then, every time I wanted to update the state, I would just use the this.safelySetState() function instead.
So my question is: Why should I not do this? Why isn't this already default in React?

A: My guess for it not being  default in React is that it is out of their scope. It would not have been great on their part to silently do nothing if the state cannot be set. Rather it is logical they throw an error so they let you know it cannot be done and leave how you want to handle that up to you.
Also I would be wary of always using your function for the same reasons... it can make debugging your app a little hard and obscure... probably you should implement it externally, not as a function... but inline with the rest of the code and just for the edge cases that really need it... or at the very least log a warning when the component is not available


text:
Q: Long task in Javascript Why in the following code I see the whole page at once ? Thanks !
HTML:

CSS:
div {
    width: 100px;
    height: 300px;
    border: 1px solid black;
    text-align: center;
}

Javascript:
$(function() {
    for (var i=0; i<15; i++) {
        sleep(100);
        $("div").append("--- " + i + " ---
");
    }

    function sleep(milliseconds) {
        var start = new Date().getTime();
        for (var i = 0; i < 1e7; i++) {
            if ((new Date().getTime() - start) > milliseconds){
                break;
            }
        }
    }
});

A: Because Javascript on web browsers is single-threaded (although that's changing; see below) and virtually no browser updates its UI while the (main) Javascript thread is busy. All your sleep function does is block everything for 100ms, it doesn't let the browser do anything else like update its UI (e.g., doesn't "yield").
There are a couple of ways to do what you're trying to do:

*

*Use the new web workers stuff; but note that it's not widely-supported yet.

*Make your loop a function that calls itself via setTimeout. That way, your code is yielding to the browser and letting it update its UI.
Here's a simple example of how you might apply #2 above to your code:
$(function() {
    var i;

    doOne();

    function doOne() {
        $("div").append("--- " + i + " ---
");
        if (i++ < 15) {
            setTimeout(doOne, 0);   // <== Won't really be zero, browsers clamp it at ~10
        }
    }

});

If you have a lot of loop iterations (e.g., a couple of hundred instead of 15), it may well be worth doing a chunk of them on each iteration rather than yielding on each iteration; the yield takes a measureable time (typically ~10-15ms).

A: You need to hand over some processing time to the UI since javascript is single threaded, like this:
$(function() {
    function appendDiv(i) {
        $("div").append("--- " + i + " ---
");
        if(i < 14)
            setTimeout(function() { appendDiv(i+1); }, 100);
    }
    appendDiv(0);
});

You can see a demo here
You could also use an interval for what you want, like this:
$(function() {
    var i = 0;
    var interval = setInterval(function() {
        $("div").append("--- " + i++ + " ---
");
        if(i == 15) clearInterval(interval);
    }, 100);
});


text:
Q: In self linking model, deleting the child node while parent node delete I want to delete all the child node(child categories) while deleting the parent category(using 'dependent'=> true). Here is the brief explanation
I am working with a Self-linking model. Let's consider I have 2 tables
1. Categories
2. Products

where the category is multilevel. so that I have a column in the Categories table named as "parent_category_id". I have self-linked my model as bellow,
$this->belongsTo('FileCategories', [
        'foreignKey' => 'parent_category_id',
        'className' => 'FileCategories',
        'joinType' => 'INNER',
        'dependent'=> true
    ]);

Dependent  "true" is not working in this cenerio, so Is I am doing something wrong or there is another method to do this.

A: You should also add hasMany relationship as below.
$this->hasMany('Parent', [
    'foreignKey' => 'parent_category_id',
    'className' => 'FileCategories',
    'joinType' => 'INNER',
    'dependent'=> true
]);

If it does not work, you can try this option ('cascadeCallbacks' => true).
$this->hasMany('Parent', [
    'foreignKey' => 'parent_category_id',
    'className' => 'FileCategories',
    'joinType' => 'INNER',
    'dependent'=> true,
    'cascadeCallbacks' => true
]);


text:
Q: Does -I belong to Weyl group? Let $\Phi$ be an irreducible root system, with positive roots $\Phi^+$ relative to the base $\Delta$.
If $W$ is the Weyl group, how can I determine if $-I$ belongs to $W$? Equivalently how can I see if the (unique) longest element in $W$ is $-I$?

A: The mnemonic I use: if the diagram has a natural involution, then $-w_0$ induces it, otherwise $w_0 = -1$. The only place this fails is in $D_n$, where one can switch the antlers, but shouldn't always, so how to remember when? In $D_4$, there's no natural involution, so that helps me remember that in $D_{2n}$, the involution is trivial.

A: As Koen S points out, the longest element of an irreducible Weyl group is treated in an earlier question (in fact, it comes up in several questions).  The question asked here presupposes a standard linear realization of the Weyl group, as occurs in the structure theory of a semisimple Lie algebra over $\mathbb{C}$ for instance.  In this context, the standard answer given by Max is formulated as Exercise 5 at the end of Section 13 in my 1972 Springer graduate text.   However one arrives at this conclusion, it obviously depends on the classification of irreducible root systems.
On the other hand, the question makes sense for any irreducible finite Coxeter group in its usual realization as a reflection group, and is approached in this spirit (via the Coxeter element) toward the end of Section 3.19 in my 1990 book on reflection groups and Coxeter groups.
P.S. For irreducible Weyl groups, a natural motivation for asking this question involves the criterion for all finite dimensional irreducible representations of the associated simple Lie algebra to be self-dual: If the given highest weight is $\lambda$, the dual has highest weight $-w_0 \lambda$ (where $w_0$ is the longest element of $W$).  This always coincides with $\lambda$ iff $-1 \in W$.

A: Depends on what you mean with $-I$...
If you mean an element $w\in W$ such that $w\Phi^+=\Phi^-$, then this does always exist and is always the longest element $w_0$. See for example Section 1.8 in "Reflection Groups and Coxeter Groups" by Humphreys (who is also a regular here ;).
If you meant to ask whether $w\in W$ exists such that $w$ acts like $-I$ on the natural geometric representation of $W$ (as defined in Section, then this is the case if and only if $W$ has non-trivial center, in which case the center has just two elements, $w_0$ and $1$, and you want $w=w_0$. Now obviously $w_0$ is in the center if and only if conjugation by $w_0$ is trivial. But in many cases, conjugation by $w_0$ induces a diagram automorphism. With some computations one can thus verify that $w_0$ is in the center for types $A_1$, $BC_n$, $D_{2n}$, $E_7$, $E_8$ and $F_4$. While you get a trivial center for type $A_n$ ($n>1$), $D_{2n+1}$ and $E_6$.


text:
Q: What is a good pattern for updating a viewmodel, both from user interaction and service events? Consider these two scenarios:

*

*a user presses a button in a view (e.g. Fulfill Order) and we want the view to update immediately (disable the button, add a progress bar, etc.)

*a service layer raises a business event, which ultimately must be reflected on the view (e.g. a product has become out-of-stock).

Both cases legitimately require some mechanism, X, to update the viewmodel. With MVVM, the view can do this by setting properties of the viewmodel in an event handler, through command binding, or via some other mechanism.
The service layer can do this using some mechanism, Y. For example, raising events in the business/domain model, creating commands to manipulate the viewmodel, calling methods on the viewmodel etc.
In fact, X and Y could be the same mechanism (or pattern).
What's a good one to do this, that keeps to the spirit of MVVM, but is DRY?

A: I think you need to pick an MVVM framework and follow the pattern for this that it supports.
In general:

*

*Your button will be hooked to a FulfillOrder method on your ViewModel, via an ICommand or whichever your MVVM-framework supports

*A "CanFulfillOrder" boolean property will be hooked up to disable your button via INotifyPropertyChanged, this can be triggered by the FulfillOrder method or the event you mention.  It could also be bound to the Visibility on a progress bar.

*Another property could provide the percentage on the progress bar and update it appropriately

A good, general-purpose MVVM framework is MVVM Light.
If you are looking for more power, and can handle more complexity, try Caliburn.
Or if you want to use dynamic and try something cutting edge, try my framework: NoMvvm.


text:
Q: How can jump to next TextFormField when one is filled? I am currently building the birthday page for my onboarding.
as you can see in the picture, i have created three textformfields in which the user can type in the day month and year(LengthLimitingTextInputFormatter = 2 for days and months, 4 for years).
How can i make it so when one textfield is filled with the required digits, e.g. 12 for Days, the focus will automatically jump to the next TextFormFiled month without the user clicking on anything besides the required digits.
thanks in advance!
birthday page of onboarding
@override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
        Text(
          dateComposition,
          style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
        ),
        SizedBox(height: 7),
        Container(
          margin: EdgeInsets.all(4),
          width: dateComposition == "Year"? 73: 55,
          child: TextFormField(
            textAlign: TextAlign.center,
            //Keyboardtype for numbers
            keyboardType: TextInputType.number,
            //only numbers can be typed in
            inputFormatters: <TextInputFormatter>[
              FilteringTextInputFormatter.digitsOnly,
              LengthLimitingTextInputFormatter(dateComposition=="Year"? 4 : 2),
            ],
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
            autofocus: true,
            cursorColor: kPrimaryMagentaColor,
            decoration: InputDecoration(
              enabledBorder: OutlineInputBorder(
                borderSide: BorderSide(color: kTextIconColorDarkBlue),
                borderRadius: BorderRadius.circular(15),
              ),
              hintText: dateCompositionHintText,
              hintStyle: TextStyle(fontWeight: FontWeight.w600, fontSize: 18.0),
              contentPadding: EdgeInsets.only(
                left: 10,
                right: 10,
                top: 10,
                bottom: 10,
              ),
              focusedBorder: OutlineInputBorder(
                borderRadius: BorderRadius.circular(15),
                borderSide: BorderSide(
                  color: kPrimaryMagentaColor,
                  width: 1.5,
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }
}
`````

A: for doing so, you have to assign FocusNode() to your TextField(), then on the onSubmitted method of your TextField, you have to mySecondTextFieldFocusNode.requestFocus().
 FocusNode textSecondFocusNode = new FocusNode();

    TextFormField textFirst = new TextFormField(
      onFieldSubmitted: (String value) {
        FocusScope.of(context).requestFocus(textSecondFocusNode);
      },
    );

    TextFormField textSecond = new TextFormField(
      focusNode: textSecondFocusNode,
    );

A: You could add the property textInputAction and set it to TextInputAction.next,
TextFormField(
  textInputAction: TextInputAction.next,
  ...
)


text:
Q: Create a Link to a Paypal setting the email address static I have been researching up creating my own link to PayPal, that when a person is logged in, it will generate a "specified email" in the "To:" text box on the form.
However, I am planning something a tad more ambitious; I'd like to know it is possible to build this link in my code to where the specified email "cannot be edited or changed?" Again, this would coming from my custom-made link:
https://www.paypal.com/us/cgi-bin/webscr?cmd=_send-money&nav=1&email=SomePresetEmail@mail.com

How can I code this to set "SomePresetEmail@mail.com" to be static?  Or is that even possible for me to do that, being I am not editing the code on Paypal's server side?  My site is currently built using Asp.Net WebForms.

A: DesignerMind,
I am not sure if I am following you correctly. But this link is displayed on the page to user and you want them to not be able to change the email?
Is it possible to have your link point to an address inside your application that gets redirected to Paypal?  When paypal recieves the request, they execute an internal mechanism to hash the request into a secured request variable. This means that when you navigate to the link the user is not seeing the actual link but a hashed version. A sample of the paypal hashed version is.
https://www.paypal.com/us/cgi-bin/webscr?cmd=_flow&SESSION=Itqgb8iQ3mW92FT9ldzgcFmJyRVQLUpE2u9UMqeKbGmvwdMTY80oBEmo0SS&dispatch=5885d80a13c0db1f8e263663d3faee8def8934b92a630e40b7fef61ab7e9fe63

Now you could try to do this such as.
On your aspx.net page.
<asp:HyperLink runat="server" ID="paypalLink" NavigateUrl="~/Paypal.aspx" />

or simply
Paypal

And in the Paypal.Aspx code
static string SecretEmail = "someone@somewhere.com",
                PaypalRedirectFormat = "https://www.paypal.com/us/cgi-bin/webscr?cmd=_send-money&nav=1&email={0}";

protected void Page_Load(object sender, EventArgs e)
{
    Response.Redirect(string.Format(PaypalRedirectFormat, SecretEmail));
}

This is just an idea and actually if this is what you wanted a GenericHandler would do the job quite nicely.
Let me know if this is not what you are looking for.


text:
Q: The 'defaultInputValue' prop of AsyncSelect in react-select? import AsyncSelect from 'react-select/async';

<AsyncSelect
              cacheOptions
              isClearable={false}
              defaultInputValue={doctor.name}
              loadOptions={async (search, callback) => {
                const doctors = await fetchDoctors(search);
                const doctorsList = doctors.map(item => ({
                  ...item,
                  label: item.doctorName,
                  value: item.doctorName,
                }));
                callback(doctorsList);
              }}
              backspaceRemovesValue
              placeholder='Search for a doctor...'
              onChange={async (newVal) => {
                const updatedOrder = { ...order };
                updatedOrder.doctorId = newVal.id;
                if (newVal.organization) {
                  updatedOrder.organization = newVal.organization;
                } else {
                  updatedOrder.organization = '';
                }
                updateOrderRemote(updatedOrder, newVal);
              }}
/>

The 'defaultInputValue' prop on the initial render gets passed with an undefined or empty string or a string.
However, after some interval doctor.name is available, however the defaultInputValue does not update hence maintaining the value on initial render.

A: You have two options:
1- You can make the render of the whole <AsyncSelect {...props} /> conditional to availability of doctor.name (which i assume is a state). Which i guess is not ideal for you.
2- You should pass inputValue prop instead of defautInputValue. Because as far as i know, default value is only passed in first render. So you need to change your onChange prop's function aswell to change the state that is being used as an initial value

A: As suggested by Ardalan Nahavendi I went the local state route.
But touching the inputValue prop caused another set of problems, so I went with the value prop.
Code:
import AsyncSelect from 'react-select/async';

  const [doc, updateDoctor] = useState({ label: doctor?.name, value: doctor?.name });

  useEffect(() => {
    if (doctor.doctorName) { //at initial render the doctor prop gets the 'doctorName' key
      updateDoctor({ label: doctor?.doctorName, value: doctor?.doctorName });
    } else {
      updateDoctor({ label: doctor?.name, value: doctor?.name });
    }
  }, [doctor]);

<AsyncSelect
  cacheOptions
  isClearable={false}
  value={doc}
  loadOptions={async (search, callback) => {
    const doctors = await fetchDoctors(search);
    const doctorsList = doctors.map(item => ({
      ...item,
      label: item.doctorName,
      value: item.doctorName,
    }));
    callback(doctorsList);
  }}
  backspaceRemovesValue
  placeholder="Search for a doctor..."
  onChange={async (newVal) => {
    updateDoctor(newVal); //has the label and value present due to loadOptions
    const updatedOrder = { ...order };
    updatedOrder.doctorId = newVal.id;
    if (newVal.organization) {
      updatedOrder.organization = newVal.organization;
    } else {
      updatedOrder.organization = '';
    }
    updateOrderRemote(updatedOrder, newVal);
  }}
/>


text:
Q: Getting "Invalid value type" error when trying to execute yarn in my react-rails project I am getting:
error An unexpected error occurred: "Invalid value type 2:0 in /Users/myname/Desktop/work2/reservations_fully_paid/Foggle/yarn.lock".
info If you think this is a bug, please open a bug report with the information provided in "/Users/myname/Desktop/work2/reservations_fully_paid/Foggle/yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.

When trying to execute yarn in my react-rails project


text:
Q: Multiple threads awaiting Task if it is already running I have app which have different timers running in the background doing synchronization with the API.
However, before the actual sync they all ping the API whether they can proceed or not. In order to not make multiple calls, I've made them await the same Task if it is already running. After the result comes from the task those who await should get the result and in the mean time if there is a call to the CanExecute method and the Task is not running it should rerun the Task and so on.
protected async Task<bool> CanExecute([CallerMemberName] string memberName = "")
{
    lock (_lockobj)
    {
        if (_runningTask == null)
        {
           _runningTask = CanExecuteTask(memberName);
        }
    }

    var result = await _runningTask;
    _runningTask = null;
    return result;
}

private async Task<bool> CanExecuteTask(string callingMemberName)
{
    var result = // do http call and some other method calls
    return result;
}

I'm not sure what the problem is, but I think it happens to deadlock and the synchronization doesn't proceed. What is the proper way to achieve that?

A: As written this code is not safe - you both read and write _runningTask outside of the lock. So for example, one thread can execute
_runningTask = null;

While another thread just got past the lock statement while task was not null and is about to execute await _runningTask. This will result in await null so in NullReferenceException.
You can avoid that while keeping the same principle by doing this:
private Task<bool> _runningTask = Task.FromResult(false);
protected async Task<bool> CanExecute([CallerMemberName] string memberName = "") {
    Task<bool> task;
    lock (_lockobj) {
        if (_runningTask.IsCompleted) {
            _runningTask = CanExecuteTask(memberName);
        }
        task = _runningTask;
    }

    var result = await task;
    return result;
}

Instead of setting task to null and then checking that - we check if task has been completed (which means succeeded, faulted, or cancelled). We then also start with already completed task instead of null.
Also we assign _runningTask to local variable inside the lock, and then await that, to avoid reading _runningTask field outside of the lock.
Awaiting the same task from multiple threads is safe, so we should be fine here.


text:
Q: Loading a file and processing it asynchronously in WinRT In Visual Studio 11, I am build a HTML5 Metro application that reads and processes a file on initialization.  I have the following code:
var ws = Windows.Storage;

Debug.enableFirstChanceException(true);
var myDataSource = {};

var id = function (elementID) {
    return document.getElementById(elementID);
}

WinJS.Namespace.define('ToDoToday', {
    id: id,
});

function initialize() {
Windows.Storage.KnownFolders.documentsLibrary.createFileAsync("taskList.todo", Windows.Storage.CreationCollisionOption.openIfExists)

.then(function (file) {
    return file.openAsync(Windows.Storage.FileAccessMode.readWrite);
})

.then(function (stream) {
    var inputStream = stream.getInputStreamAt(0);
    var reader = new Windows.Storage.Streams.DataReader(inputStream);

    var size = stream.size;
    if (size > 0) {
        reader.loadAsync(size).then(function(){
            myDataSource = reader.readString(size);
        })
    }
})
.then(function () {
    WinJS.Namespace.defineWithParent(ToDoToday, 'Tasks', {
        data: myDataSource,
    })
})
.then(function () {
    WinJS.UI.processAll()
})
.then(function () {
    var basicListView = WinJS.UI.getControl(document.getElementById("taskChecklist"));
    basicListView.dataSource = ToDoToday.Tasks.data;
    basicListView.refresh;
});
}
document.addEventListener("DOMContentLoaded", initialize, false);

The initialize function never loads the file. Because of the chained thens, the debugger doesn't return anything useful.  A breakpoint on the openAsync never is hit.
The eventual error is on the databind:
JavaScript runtime error: Object doesn't support property or method 'createListBinding'
The binding appears to work just fine if I don't read from a file.
I am sure my problem is a functional misunderstanding of how to chain async calls, and a second set of eyes can't hurt.


text:
Q: Discord.js database using repl.it I made a database script in repl.it and it's working but I keep getting null and then users database here is my code:
client.on("message", async (message) => {
    if (message.content.toLowerCase().startsWith("#مخالفات")) {
        var pfpMember = message.mentions.members.first() || message.member;

        const violation = await db.get(`wallet_${message.mentions.members.first()}`);

        if (violation === null) violation = "العضو ليس لديه اي مخالفات";

        const pembed = new Discord.MessageEmbed()
            .setTitle(`شرطة لوس سانتوس`)
            .setDescription(`المخالفات المرورية :` + violation)
            .setColor("RANDOM")
            .setFooter("شرطة لوس سانتوس")
            .setThumbnail(pfpMember.user.displayAvatarURL());
        message.channel.send(pembed);
    }
});

And here is a screenshot:

A: The issue is that you cannot reassign violation as it is a constant, not a variable.
Using the following should solve the issue:
client.on("message", async (message) => {
    if (message.content.toLowerCase().startsWith("#مخالفات")) {
        var pfpMember = message.mentions.members.first() || message.member;

        let violation = await db.get(`wallet_${message.mentions.members.first()}`);

        if (violation === null) violation = "العضو ليس لديه اي مخالفات";

        const pembed = new Discord.MessageEmbed()
            .setTitle(`شرطة لوس سانتوس`)
            .setDescription(`المخالفات المرورية :` + violation)
            .setColor("RANDOM")
            .setFooter("شرطة لوس سانتوس")
            .setThumbnail(pfpMember.user.displayAvatarURL());
        message.channel.send(pembed);
    }
});


text:
Q: afterCommentChange hook in HandsOnTable On HoT hooks tutorial one could see a (complete!?) list of hooks in HandsOnTable. However, none of them is comment related.
I'd like to add a custom callback after a comment has been added, deleted or updated.
Neither afterChange nor afterContextMenuExecute seem to trigger after a comment change and beforeRender seems to trigger too often.
Ideally, I'd like to use a specific hook, that only triggers when a comment is added, modified or removed, giving me access to the old and new values as well as the cell position.
At this point, I'd settle for anything that works. Even though I haven't found anything related to it, it's hard to believe nobody needed this before. As soon as I find the answer, I'll post it here.
Here's a basic HoT example, with comments enabled and specific actions added to context menu:

var data = function () {
  return Handsontable.helper.createSpreadsheetData(100, 10);
};

var container = document.getElementById('example');

var hot = new Handsontable(container, {
  data: data(),
  minSpareCols: 1,
  minSpareRows: 1,
  rowHeaders: true,
  colHeaders: true,
  contextMenu: ['undo','redo','commentsAddEdit','commentsRemove'],
  comments: true,
});
body {
  margin: 2rem;
  font-size: 13px;
  font-family: 'Open Sans', Helvetica, Arial;
}

h2 {
  margin: 20px 0 0;
  font-size: 18px;
  font-weight: normal;
}
<link href="https://docs.handsontable.com/pro/1.14.3/bower_components/handsontable-pro/dist/handsontable.full.min.css" rel="stylesheet"/>

Handsontable Basic Example (100x10)

A: Apparently, afterSetCellMeta is what I was looking for:
let hot = new Handsontable(container, {
  // ...,
  afterSetCellMeta: (row, col, key, value) => {
    if (key === 'comment') {
      // comment for cell @ `row`,`col` was changed to `value`
    }
  }
}


text:
Q: Render position does not match layout position I have a custom dropdown element that is positioned fixed and works in Firefox and Chrome. But in Edge the layout position does not match to the render position (see image). The marked element is the form with the Text+Filter+Order. It has a strange render offset. The element has no transformations. If you click to the window where the checkbox or input elements should be it works correctly.
Any ideas what could go wrong?


text:
Q: Разметка Listview и производительность Имеется 10 listview. Для каждого есть свой кастомный адаптер. В адаптерах переопределен метод getView.
Сейчас имеется одна разметка на всех. В этой разметке есть все необходимые виджеты для listview скрытые на разметке. В каждом адаптере использую visiblity GONE или VISIBLE.
Скажите, что будет лучше по производительность одна разметка на все listview или для каждого своя? Просто слышал, что xml разметка тратит много ресурсов, поэтому и сделал один на всех,но что то сомневаюсь что правильно я делаю.

A: Правильнее делать для каждого адаптера свою разметку.

..xml разметка тратит много ресурсов...

Это значит что плохо построенная xml долго отрисовывается. Поэтому для каждого адаптера лучше делать xml с минимальным количеством view, а не пихать все в одну xml. Хотя view у которых visibility=gone не отрисовываются. Но вы будете тогда тратить время в адаптаре для того чтобы выполнить setVisibility(VISIBLE) каждой view которую нужно отобразить.
В общем делайте разные xml для разных адаптеров

A: Действительно работа с xml довольно ресурсозатратная операция. Поэтому лучше использовать разные разметки и желательно с применением паттерна ViewHolder, который способствует увеличению производительности. Если проект только создается, то можно рассмотреть использование RecyclerView в качестве альтернативы ListView. При этом использование паттерна ViewHolder становится уже обязательным.