text:
Q: SQLException when using PreparedStatement.RETURN_GENERATED_KEYS This is the code block in question:
String sq = "INSERT INTO survey (session_id, character_id, timestamp) VALUES (?,?,?)";
PreparedStatement sadd = conn.prepareStatement(sq, PreparedStatement.RETURN_GENERATED_KEYS);
sadd.setLong(1, sessionId);
sadd.setLong(2, character_id);
sadd.setString(3, dateTime);
int affectedrows = sadd.executeUpdate();

//get the ID
long resultId = 0;
ResultSet key = sadd.getGeneratedKeys();
if (key.next()) {
    resultId = key.getLong(1);
}

This query worked fine without the PreparedStatement.RETURN_GENERATED_KEYS option, but when I add it suddenly executeUpdate() throws an exception:

com.microsoft.sqlserver.jdbc.SQLServerException: A result set was generated for update.

If I take the PreparedStatement.RETURN_GENERATED_KEYS out, it works again fine. Out of frustration, I changed executeUpdate() to executeQuery() just to see if I could get the key back and got an exception that it can't get keys because the statement must be executed first.
How can I get the generated key? I am using SQL Server 2008 and the latest JDBC driver.

A: Looks like a driver bug to me.
You should try a newer 4.0 driver from here -> http://www.microsoft.com/download/en/details.aspx?id=11774
If that does not work, one work around would be to create an 'insert' stored procedure and return the generated id as a stored procedure output parameter.

A: Looks like a bug. Could you give the uglier alternative a try?
  String dateTimeS = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm").format(dateTime);
  String sq = "INSERT INTO survey (session_id, character_id, timestamp) "
          + "VALUES (" + sessionId + ", " + character_id + ", '" + dateTimeS + "')";
  Statement sadd = conn.createStatement();
  int affectedrows = sadd.executeUpdate(sq, Statement.RETURN_GENERATED_KEYS);

A: I'm having the same issue with the 4.0 & 4.1 JDBC drivers. After a while an insert on a autonumber table would give a "A result set was generated for update." at random. I use connection pooling and somehow the driver can get into a state where executeUpdate in combination with Statement.RETURN_GENERATED_KEYS doesn't work anymore. I found out that in this state an executeQuery does the trick, but in the initial state executeQuery does not work. This lead me to the following workaround:
PreparedStatement psInsert = connection.prepareStatement("INSERT INTO XYZ (A,B,C) VALUES(?,?,?)", Statement.RETURN_GENERATED_KEYS);
ResultSet rs = null;
try {
    psInsert.setString(1, "A");
    psInsert.setString(2, "B");
    psInsert.setString(3, "C");
    Savepoint savePoint = connection.setSavepoint();
    try {
        psInsert.executeUpdate();
        rs = psInsert.getGeneratedKeys();
    } catch (SQLServerException sqe)
    {
        if (!sqe.getMessage().equals("A result set was generated for update."))
            throw sqe;
        connection.rollback(savePoint);
        rs = psInsert.executeQuery();
    }
    rs.next();
    idField = rs.getInt(1);
} finally {
    if(rs != null)
        rs.close();
    psInsert.close();
}


text:
Q: Windows Universal application halts at CreateFileAsync() I am working on Universal application Windows 10 in C# where I am creating several files in documents library folder during different thread processes.
var folder = await KnownFolders.DocumentsLibrary.CreateFolderAsync("TestApplication", CreationCollisionOption.OpenIfExists);

var file = await folder.CreateFileAsync(String.Format("{0}.ref", tableName), CreationCollisionOption.ReplaceExisting);

After some successful attempts, my application gets halted at above line (CreateFileAsync). I put debugger but it just get halted and does not show any result or exception.
Can you please suggest what is the best way to mitigate it?
Thanks.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Use CSS variable in Vue component (scoped) At the moment I need to have 3 card components, all with three different colors. The colors are applied to the :before pseudo-element (and multiple other areas), and therefore the easiest solution I believe would be to apply this with a CSS variable / property.
At the moment, I instantiate a new CSS property / variable in the mounted() of my component, and this works fine with 1 card, but breaks with multiple. When I have multiple components, only the first one gets the color and the second one does not even get the color. It seems to overwrite the previous color with the first component, and then ignores the second one completely (no color property is shown in dev tools in the second one).
My question is, what would be the best solution to this problem? Is there a way to easily add a scoped CSS variable that does not override the other variables? Or would be the best course of action be to add all these styles in JavaScript?
Vue component
<template>

{{ title }}

{{ message }}

            Learn more

</template>

Vue with all components

<template>

  <Card
      title="Lorem1"
      message="Lorem"
      color="#00838d"
      clss="col-span-4"
  >
  </Card>

  <Card
      title="Lorem2"
      message="--bg-color"
      color="#0066b2"
      clss="col-span-4"
  >
  </Card>

</template>

A: You have to use this.$refs here instead of document.querySelector('.card').
The document.querySelector('.card') is taking the one first element on the page. Using refs you're picking a reference to DOM element inside of your card item. Please add the ref attribute to your div in the template and replace document.querySelector('.card') with reference to your div using this.$refs .
Reference: https://v3.vuejs.org/guide/component-template-refs.html

A: CSS are cascading, the variable should be applied to a hierarchy of elements. It's a bad sign that DOM is directly accessed in Vue component. document.querySelector queries all elements, regardless of component instance they belong to, also accesses only one that can be unrelated to current component instance.
If DOM elements need to be acccessed in a component, this is commonly done through refs:

and
mounted() {
  this.$refs.card.style.setProperty(`--color`, this.color);
},

CSS variables (custom properties) are primarily needed to provide a value for nested styles. This isn't needed if a style is specified in the same component:


text:
Q: Error in named query (QuerySyntaxException: unexpected token) I am currently working on a utility project which will help me to manage the users of an application (a user has one or more role, and a role has one or more rights).
I am new to Hibernate, and I don't know why I have encountered the following issue :
ERROR [hibernate.internal.SessionFactoryImpl] HHH000177: Error in named query: right.findAllByRoleId
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: right near line 1, column 8 [select right from com.google.code.jee.utils.user.management.model.Role as r left join r.rights as right where r.id = :roleId]
    at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:54)
    at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:47)
    at org.hibernate.hql.internal.ast.ErrorCounter.throwQueryException(ErrorCounter.java:79)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:276)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:180)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:106)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:81)
    at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:167)
    at org.hibernate.internal.SessionFactoryImpl.checkNamedQueries(SessionFactoryImpl.java:1130)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:523)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1740)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1778)
    at org.springframework.orm.hibernate4.LocalSessionFactoryBuilder.buildSessionFactory(LocalSessionFactoryBuilder.java:189)
    at org.springframework.orm.hibernate4.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:350)
    at org.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:335)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:848)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:790)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at Demo.main(Demo.java:9)

Right class :
@Entity
@Table(name = "RIG_RIGHT")
@NamedQueries({
    @NamedQuery(name = RightDao.COUNT_BY_NAME, query = "select count(*) from Right as rig where rig.name = :name"),
    @NamedQuery(name = RightDao.FIND_BY_NAME, query = "from Right as rig where rig.name = :name"),
    @NamedQuery(name = RightDao.COUNT_FOR_ROLE_ID, query = "select count(*) from Role as r where r.id = :id"),
    @NamedQuery(name = RightDao.FIND_ALL_BY_ROLE_ID, query = "select right from Role as r left join r.rights as right where r.id = :roleId"),
    @NamedQuery(name = RightDao.COUNT_FOR_ROLE_ID_AND_NAME, query = "select count(*) from Role as r left join r.rights as right where r.id = :roleId and right.name = :rightName"),
    @NamedQuery(name = RightDao.FIND_BY_ROLE_ID_AND_NAME, query = "select right from Role as r left join r.rights as right where r.id = :roleId and right.name = :rightName") })
@SuppressWarnings("serial")
public class Right extends AbstractHibernateDto<Integer> {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "RIG_ID", nullable = false)
    private Integer id;

    @Column(name = "RIG_NAME", nullable = false, unique = true, length = 50)
    private String name;

       // Getters & Setters

Role class :
@Entity
@Table(name = "ROL_ROLE")
@NamedQueries({
    @NamedQuery(name = RoleDao.COUNT_BY_NAME, query = "select count(*) from Role as r where r.name = :name"),
    @NamedQuery(name = RoleDao.FIND_BY_NAME, query = "from Role as r where r.name = :name"),
    @NamedQuery(name = RoleDao.COUNT_FOR_USER_ID, query = "select count(*) from User as u where u.id = :id"),
    @NamedQuery(name = RoleDao.FIND_ALL_BY_USER_ID, query = "select role from User as u left join u.roles as role where u.id = :userId"),
    @NamedQuery(name = RoleDao.COUNT_FOR_USER_ID_AND_NAME, query = "select count(*) from User as u left join u.roles as role where u.id = :userId and role.name = :roleName"),
    @NamedQuery(name = RoleDao.FIND_BY_USER_ID_AND_NAME, query = "select role from User as u left join u.roles as role where u.id = :userId and role.name = :roleName") })
@SuppressWarnings("serial")
public class Role extends AbstractHibernateDto<Integer> {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "ROL_ID", nullable = false)
    private Integer id;

    @Column(name = "ROL_NAME", nullable = false, unique = true, length = 50)
    private String name;

    @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.LAZY)
    @JoinColumn(name = "RIG_ROLE_ID", nullable = false)
    private List<Right> rights;

    // Getters & Setters

Right DAO :
public interface RightDao extends GenericDao<Integer, Right> {

    public final String COUNT_BY_NAME = "right.countByName";
    public final String FIND_BY_NAME = "right.findByName";
    public final String COUNT_FOR_ROLE_ID = "right.countForRoleId";
    public final String FIND_ALL_BY_ROLE_ID = "right.findAllByRoleId";
    public final String COUNT_FOR_ROLE_ID_AND_NAME = "right.countForRoleIdAndName";
    public final String FIND_BY_ROLE_ID_AND_NAME = "right.findByRoleIdAndName";

    /**
     * Search the number of elements with the 'name' parameter.
     *
     * @param name the name
     * @return the number of element found
     */
    public Integer countByName(String name);

    /**
     * Search an element by its name.
     *
     * @param name the name
     * @return the right
     */
    public Right findByName(String name);

    /**
     * Count the number of rights of a specific role
     *
     * @param roleId the role id
     * @return the number of rights
     */
    public Integer countForRoleId(Integer roleId);

    /**
     * Finds all rights by roleId.
     *
     * @param roleId the role primary key
     * @return the list
     */
    public List<Right> findAllByRoleId(Integer roleId);

    /**
     * Count the number of rights with a specific name and corresponding to
     * a specific role
     *
     * @param roleId the roleId
     * @param rightName the right name
     * @return the number of rights
     */
    public Integer countForRoleIdAndName(Integer roleId, String rightName);

    /**
     * Finds the right.
     *
     * @param roleId the role primary key
     * @param rightName the right name
     * @return the right
     */
    public Right findByRoleIdAndName(Integer roleId, String rightName);

}

Role DAO :
public interface RoleDao extends GenericDao<Integer, Role> {

    public final String COUNT_BY_NAME = "role.countByName";
    public final String FIND_BY_NAME = "role.findByName";
    public final String COUNT_FOR_USER_ID = "role.countForUserId";
    public final String FIND_ALL_BY_USER_ID = "role.findAllByUserId";
    public final String COUNT_FOR_USER_ID_AND_NAME = "role.countForUserIdAndName";
    public final String FIND_BY_USER_ID_AND_NAME = "role.findByUserIdAndName";

    /**
     * Search the number of elements with the 'name' parameter.
     *
     * @param name the name
     * @return the number of element found
     */
    public Integer countByName(String name);

    /**
     * Search an element by its name.
     *
     * @param name the name
     * @return the user
     */
    public Role findByName(String name);

    /**
     * Count the number of roles of a specific user
     *
     * @param userId the user id
     * @return the number of roles
     */
    public Integer countForUserId(Integer userId);

    /**
     * Finds all roles by user id.
     *
     * @param userId the user primary key
     * @return the list
     */
    public List<Role> findAllByUserId(Integer userId);

    /**
     * Count the number of roles with a specific name and corresponding to
     * a specific user
     *
     * @param userId the userId
     * @param roleName the role name
     * @return the number of roles
     */
    public Integer countForUserIdAndName(Integer userId, String roleName);

    /**
     * Finds the role.
     *
     * @param userId the user primary key
     * @param roleName the role name
     * @return the role
     */
    public Role findByUserIdAndName(Integer userId, String roleName);

}

Any idea ? Thank you in advance !
Julien Neuhart

A: It seems like the source of the error is using right as a variable name in one of your named queries (RightDao.FIND_ALL_BY_ROLE_ID, RightDao.FIND_BY_ROLE_ID_AND_NAME). right is a reserved word in HQL (right outer join)
Either:

*

*Use different alias for right:

@NamedQuery(name = RightDao.FIND_ALL_BY_ROLE_ID,
    query = "select r from Role as role left join role.rights as r
                 where role.id = :roleId"),
@NamedQuery(name = RightDao.FIND_BY_ROLE_ID_AND_NAME,
    query = "select r from Role as role left join role.rights as r
                 where role.id = :roleId and r.name = :rightName") })

*Escape the reserved word right in the query by surrounding it with square brackets [right], or backticks. Also, you might fins the following related question useful: How to escape reserved words in Hibernate's HQL.


text:
Q: In pandas how to correctly load values with decimal ","? In Python 3 and pandas I have this dataframe:
import pandas as pd

ano_2016_exec = pd.read_excel('emendas/emendas_executadas_autores_2016.xls',sheet_name='Sheet1', decimal = ",")

ano_2016_exec.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 10428 entries, 0 to 10427
Data columns (total 9 columns):
Autor               10427 non-null object
Emenda              10427 non-null object
UO_Ajustada         10427 non-null object
Funcional           10427 non-null object
Acao_e_Subtitulo    10427 non-null object
Valor_aprovado      10428 non-null float64
Empenhado           10428 non-null float64
Depesa_Executada    10428 non-null float64
Pago                10428 non-null float64
dtypes: float64(4), object(5)
memory usage: 733.3+ KB

In the original file, the columns "Valor_aprovado", "Empenhado", "Despesa_Executada" and "Pago" are numbers with a decimal point -> ",". Example:
3647087716,31449 -> represents in decimal "." 3,647,087,716.31449
498820,7 -> 498,820.7

But the loaded file transformed these columns into float, with notation:
colunas_selecionadas = ["Valor_aprovado", "Empenhado", "Depesa_Executada", "Pago"]
ano_2016_exec[colunas_selecionadas].head()
Valor_aprovado  Empenhado   Depesa_Executada    Pago
0   9.100292e+09    7.268573e+09    7.268573e+09    3.647088e+09
1   6.471218e+06    6.471218e+06    6.471218e+06    0.000000e+00
2   1.200000e+06    3.421430e+05    3.421430e+05    1.710710e+05
3   7.471218e+06    6.713361e+06    6.713361e+06    0.000000e+00
4   2.000000e+05    1.000000e+05    1.000000e+05    1.000000e+05

Like:
7.268573e+09
3.647088e+09
6.471218e+06

I want these numbers to appear in my dataframe with two decimals and not in notation. Like this:
7,268,572,739.83
3,647,087,716.31

Please, is this possible?
How should I properly load the data file 'emendas_executadas_autores_2016.xls'?

A: Set a locale that interprets numbers in this way. The Spanish locale does so: es_ES.UTF-8
Use this parameter in the same way as listed here - but for the opposite purpose:
How do I use Python to convert a string to a number if it has commas in it as thousands separators?


text:
Q: three@0.119 is breaking calculation of min and max for the bounding box I am using three.js lib on my backend to calculate AABB (axis aligned bounding box).
getAABB: function (position, scale, orientation) {
    const cube = new Mesh(new BoxGeometry(0, 0, 0));
    cube.position.set(...position);
    cube.scale.set(...scale);
    cube.rotation.set(...orientation);

    const bb = new Box3().setFromObject(cube);
    const { min, max } = bb;

    return {
      x: {
        min: min.x,
        max: max.x,
      },
      y: {
        min: min.y,
        max: max.y,
      },
      z: {
        min: min.z,
        max: max.z,
      }
    };
  }

For three@0.118 the results are looking good:
{
  x: { min: 0.5391231359521602, max: 3.46087686404784 },
  y: { min: 0.32046946879189564, max: 3.6795305312081044 },
  z: { min: 0.4349899537033477, max: 3.5650100462966523 },
}

But once I do update to three@0.119 it is starting to return wrong results:
{
  x: { min: 2, max: 2 },
  y: { min: 2, max: 2 },
  z: { min: 2, max: 2 },
}

In this example you can see the wrong results for 0.119  https://jsfiddle.net/yura_syedin/zwm3jkdL/
Here is the correct result for 0.118 https://jsfiddle.net/yura_syedin/5801pLaw/34/
According to release notes there are not too many changes

A: It looks like the BoxGeometry constructor had a bug fixed in r119.

*

*In r118 when you constructed a box with 0, 0, 0 width/height/depth parameters, the constructor thought they weren't being defined, and it would default to 1, 1, 1. Here's the implementation for r118.

*In r119 when you construct a box with 0, 0, 0, it respects those dimensions, and gives you a box with min: 2, max: 2, since it's respecting that the dimensions are 0 units. Here's the implementation for r119.

Just make sure you're initializing the box with some non-zero value, and you'll get equal results across versions.


text:
Q: MD5 of file downloaded from database, from a JSONObject My requirement is to compare the MD5 hashes of a file on the local disk and a file downloaded from a database.
The file is stored on SQL Server in a VARBINARY(MAX) column. The file can be any type. I'm currently testing with a PDF file. I get the file from the database using a HttpPost request. A JSONObject is built using the HttpResponse object. The JSONObject contains the file contents in binary format.
Now I have to compare the MD5 hash of the received binary data against the MD5 hash of the same file on disk. I have written the following code but the MD5 hashes do not match.
I think I'm going wrong in simply calculating the MD5 of the downloaded binary contents. Is there a correct way to do this? Thanks in advance.
// Read response from a HttpResponse object 'response'
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line="";
StringBuilder sb = new StringBuilder();
while((line=reader.readLine())!=null) {
      sb.append(line);
}

// construct jsonobject
JSONObject jsonResponse = new JSONObject(sb.toString());

//Read file from disk
FileInputStream fis = new FileInputStream(new File(this.getClass().getResource("C:\\demo.pdf").getPath()));

// Calculate MD5 of file read from disk
String md5Request = org.apache.commons.codec.digest.DigestUtils.md5Hex(fis);

// Calculate MD5 of binary contents. "binfile" is name of key in the JSONObject
// and binary contents of downloaded file are in its corresponding value field
String md5Response = org.apache.commons.codec.digest.DigestUtils.md5Hex(jsonResponse.getString("binfile"));

Assert.assertEquals("Hash sums of request and response must match", md5Request, md5Response);

When I debug, I see this value against the binfile key in the JSONObject 'jsonResponse'
binfile=[37,80,68,70,45,49,46,52,13,37,-30,-29,-49,-45,13,10,52,48...]

and what follows is a lengthy stream of binary data.

A: OK, in SQL there's a build-in function that looks like this:
select *,
convert(varchar(50),master.sys.fn_repl_hash_binary(a.BinaryField),2) as 'MD5Hash'
from SomeTable a

You give the fn_repl_hash_binary the name of the binary field you're reading, plus "2" as an argument which tells SQL to calc the value as an MD5; I think "1" is SHA.
And in Java, you can use something like this:
private String getMD5Hash(byte[] bytes) throws java.lang.Exception{
   String s="This is a test";
   MessageDigest m=MessageDigest.getInstance("MD5");
   m.update(bytes,0,bytes.length);
   return new BigInteger(1,m.digest()).toString(16);
}

This should do the trick. Best of luck, CodeWarrior.

A: It is not a new post but here is a possible solution, as I faced this problem too on python and made a bunch of test to find how to do...
As you treat all data in binary, you need to open the file to compare in binary mode.
My original code that was failing every time to read the correct MD5 checksum:
    with open(filepath, "r") as file_to_check:
        tile_file = file_to_check.read()

Corrected code:
    with open(filepath, "rb") as file_to_check:
        tile_file = file_to_check.read()

Simply adding the b (binary) after the read (r) flag to let python know it need to read the file as binary and now it works.
This might be what will help you find your problem... Hope it helps!


text:
Q: How to delete from 2 tables using join query in SQL Server [Table relationships][1]

Here are the screenshots of my database.
I want to delete all the data from the Student table using the Student_grade table where Grade='FAIL'.
ALL the information of the failed students should be deleted from the database.
Delete from Student
where Student_ID IN (Select Student_ID
                     from Student_Grade
                     where Grade = 'FAIL');

Tried this but it's not working. I think data should be deleted from both tables at once because when it deletes from one Student table there is no references for FK in student_grade table.
Please can anyone provide the SQL Server query to do this?

A: you can't delete from 2 tables in one go.
Keep the list of studend_id to be deleted in a temp table and then use that to join to the actual table and delete one at a time.
-- put the list of Fail students in temp table #Fail
Select Student_ID INTO #Fail from Student_Grade where Grade='FAIL'

-- delete from grade table
DELETE g FROM #Fail f INNER JOIN Student_Grade g ON f.Student_ID = g.Student_ID

-- delete from student table
DELETE s FROM #Fail f INNER JOIN Student s ON f.Student_ID = s.Student_ID

A: I actually like Squirrel's temp approach (+1).  It allows for a more complex selection criteria.
That said, if #temp tables are "off-the-table", you can do the following:
Delete A
 From  Student A
 Join  Student_grade B on (A.Student_ID=B.Student_ID)
 Where B.Grade='Fail';

Delete From Student_grade Where Grade='Fail';

A: There is two way doing it.
first way,use transaction when using more than one DML
begin try
begin tran

-- Child table
Delete From Student_grade Where Grade='Fail';

-- Parent table
Delete A
 From  Student A
 Join  Student_grade B on (A.Student_ID=B.Student_ID)
 Where B.Grade='Fail';

commit TRAN
end try
begin catch
if (@@Trancount>0)
rollback
end catch

Another way is to use

Delete Cascade

,if you want to delete parent table straight away.
Delete data with foreign key in SQL Server table


text:
Q: How to create a custom form template in magento from admin panel?
I had used web-forms extension which was a very good solution but my main problem is it is only allowing to create 10 fields whereas my form contains 18 fields... please provide a solution for this... thanks in advance

A: The solution is very simple: buy the Professional Version for $89. The 10 fields limit is a limitation of the free version of this extension.
Obviously, you're satisfied with the extension. Then why spend so much time on getting around the limitations?


text:
Q: Is current waveform of given dc-dc converter correct?
I don't understand how current (in continuous mode of operation ) at steady state is bounded for this dc-dc converter circuit.
What I thought qualitatively that current should keep increasing like this -
My analysis was something like that -
At t=0 ;
We close the switch and initially inductor has zero intial current ,and after that current keep increasing and reaches to some value
$$I1max$$
and at that instant we open the switch which causes inductor current to decay through resistive load and reaches to a value
$$I1min$$
and then again switch closes and again current of inductor rises and  just before opening of switch current will be
$$I2max$$
BUT
$$I2max > I1max $$
Because this time inital condition is I1min while previously it was zero ,and hence we can say that as time passes initial condition keep increasing and which causes current to increase in every cycle and hence it become a  unbounded function!
But whatever I analysed is not what actually happens so where did I make mistake in my analysis ? Or this waveform is not correct?

A: The mistake you have made is that you have assumed that the peak current will rise linearly with time (at the end of each charging cycle) and for all time. It won't because of the load resistor; it ultimately limits the current to a maximum value: -
$$I_{0(pk)} = \dfrac{V_S}{R_{LOAD}}$$
You physically cannot get a load current higher than the above.


text:
Q: Dual GPS Antenna Connection to Positioning Module I am using a Positioning module that has a SMA port to hot plug an SMA antenna. It also has pins available through its footprint to connect a GPS Antenna.
The module name is SIM908. I was not able to spot a place in its data sheet that describes if both antennas can be connected at once.
I want to solder a passive chip antenna about 5-10cm away from the GPS module to be used in case should the external SMA antenna is broken or disconnected. At least with a longer fix time, I would still have some fix, without having no fix at all.
Would having two antennas connected, one through PCB trace and other through direct SMA cable be a problem for the performance of the device?

A:

"Would having two antennas connected, one through PCB trace and other through direct SMA cable be a problem for the performance of the device?"

Absolutely. RF is a fickle creature and having stubs on a PCB is a good way of having neither antenna work.
However, all is not lost. The Hittite/ADI HMC849 is designed to switch between antennas and is not too expensive.  If you need it to automatically switch, try detecting any DC current to the external (active) antenna. More than about 2mA and you can safely say an external antenna is plugged in.

A: Yes, you can connect both. Look at the block diagram. One port is for a passive GPS antenna, the other port is for an active antenna that outputs a serial signal. Then there is a third port that is for RF (GSM).
I would suggest you obtain the "SIM908-C AT Command Manual" listed in the back (but without a link) to figure out how, among other things, to select which GPS data to use.


text:
Q: is there a way to solve the problem No module named 'werkzeug.posixemulation' on odoo14 I have configured pycharm to develop odoo modules and launch the odoo server. it worked without problem and one day I launched a python flask project under the same interpreter and since then I can't launch my odoo server, when I try I get this error "No module named 'werkzeug.posixemulation'". I'm a beginner and how can I solve my problem. thank you. I'll throw in an image if needed. enter image description here

A: I've got it, I just need to uninstall werkzeug 2.0.1 and install werkzeug 1.0.1 with the command pip install werkzeug==1.0.1

A: The werkzeug version listed in the requirements.txt file is0.16.1:
Werkzeug==0.16.1

It is preferable to use the same version


text:
Q: Intercepting network requests through Selenium and DevToolsProtocol I'm new to Selenium and I'm trying to write this code [See 7:37]https://www.youtube.com/watch?v=HueQp6FWH9g) in Python.
I can't seem to find the equivalent functions for python. My code looks something like this:
import selenium.webdriver.common.devtools.v107 as Devtools
from pydispatch import dispatcher
import requests

some_function()
Devtools.network.enable()
dispatcher.connect(receiver = self.__handle_devtools_message__, sender = Devtools.network.RequestWillBeSent(), signal = requests.Request)
self.WebDriver.get(some_URL)

def __handle_devtools_message__(self, request):
        print(request)
        return

Here is the error message:
TypeError: RequestWillBeSent.__init__() missing 12 required positional arguments: 'request_id', 'loader_id', 'document_url', 'request', 'timestamp', 'wall_time', 'initiator', 'redirect_has_extra_info', 'redirect_response', 'type_', 'frame_id', and
'has_user_gesture'

Python is telling me that I'm missing 12 positional arguments in devtools.network.RequestWillBeSent(), but the youtuber does not seem to be passing any arguments.
Am I using pydispatcher correctly? Should I use a different package?


text:
Q: Why were the authorities so lenient towards Ye Wenjie? During her interrogation, Ye Wenjie confesses to at least the following:

 Two murders,
 unauthorised use of a classified military installation,
 conspiracy with a foreign power in order to facilitate a military invasion.

This is in addition to the fact that she has been caught red-handed

 presiding over an organization which has threatened to detonate a nuclear device in the nation's capital, and has just summarily executed one of its members in public.

It would seem that she would meet easily the threshold for a number of serious crimes. Yet her interrogator seems to see her rather sympathetically, as a naïve person misled by idealism. In addition, she is permitted to make a journey to the ruins of Red Coast Base, a request which is not straightforward to grant as it is in a remote mountainous region.
Why did the authorities treat her so leniently?

A:
Yet her interrogator seems to see her rather sympathetically, as a naïve person misled by idealism.

I wouldn't characterize the interrogator as considering Ye to be a naive person. I think that they took her very seriously. You can see that they came prepared to question her thoroughly.
For example, during her interrogation, the following exchange happens:

INTERROGATOR: (a pause) [proceeds to give a smart question that shows some knowledge of the underlying physics being discussed]
YE: You're very clever.
INTERROGATOR: (points to his earpiece) I have the world's foremost scientists behind me.

They also knew Ye's history, as someone who was a methodical scientist at the top of her field, and as someone who was willing to endure pain and sacrifice to serve her mission. So I think that they decided to not press Ye hard during the interview because they knew that they would only get good information from her if it was being given willingly. And they knew that she had good reason to cooperate with then, given that

 one of the goals of the interrogation was to prevent Mike Evans and his Adventist followers from being able to advance their plot to aiding in the destruction of the human race, something that went against the Redemptionist ethos of Ye

It was in their best interest to be cordial towards Ye. And it worked.
On a more pragmatic level, Ye was at this time a very old woman, and any more forceful interrogation technique (even if one might suppose that this would be successful) could very easily injure her to a degree where her life could be at risk.


text:
Q: File upload not working I installed wordpress in a media temple server and noticed that couldn't upload files. After tryng several solutions decided to replicate the problem with a simple script (http://pastie.org/2349720).
<?php
if($_FILES)
        print_r($_FILES);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 200000))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "
";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "
";
    echo "Type: " . $_FILES["file"]["type"] . "
";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb
";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "
";

    if (file_exists("uploads/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else if (!file_exists($_FILES["file"]["tmp_name"]))
      {
      echo 'temp file doesn\'t exists';
      }
    else
      {
      $uploaded=move_uploaded_file($_FILES["file"]["tmp_name"],
      $_FILES["file"]["name"]);
      if($uploaded)
        echo "Stored in: " . "uploads/" . $_FILES["file"]["name"];
      else
        echo "fallo la carga del archivo";
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>

<form action="" method="post"
enctype="multipart/form-data">
Filename:
<input type="file" name="file" id="file" />

<input type="submit" name="submit" value="Submit" />
</form>

Looks like move_upload_file() is returning false without a warning or error, looked in php documentation and found this

If filename is not a valid upload file, then no action will occur, and
  move_uploaded_file() will return FALSE.

I've checked and the file upload doesn't report any errors and the temporary file exist before trying to move it. Already set 777 permission in folder and still not having any luck, any idea on what can be causing this behavior and how to fix it?
thanks.

A: What does this give you:
$_FILES[...]['error']

If it doesn't give you zero, you can check what goes wrong here: http://php.net/manual/en/features.file-upload.errors.php.
If it does, make sure the folder your folder in is accessible by PHP. You could try running this command:
sudo -s -u [php_user]
cd [destination_directory]

Check whether you can reach the directory =)!

A: move_uploaded_file will also fail if the destination is not writable.  Is the root folder writable (I ask that because you aren't tacking on the uploads folder into the filename when moving it).  I know you mentioned you set the permission to 777 but is that for the uploads directory or the entire folder that the application is in.

A: You are checking whether destination exists in certain directory and then copying source to another directory:
if (file_exists("uploads/" . $_FILES["file"]["name"]))
...
$uploaded=move_uploaded_file($_FILES["file"]["tmp_name"], $_FILES["file"]["name"]);

A: Try absolute paths for the destination of move_uploaded_file()

A: Turns out i had fastCGI disabled, i've just enabled and things are working as expected. Thanks for your help.

A: check if u can reach d dir, There is no need in deleting it in temporary folder since it will be moved automatically,the target destination is still within d file. so why dont you try moving it to another destination

A: I don't know if this helps but I found this problem a few hours ago and the problem was the write permissions of my folder (I don't own the server I was working on) and the response for the people I work with was

The "yours" folder must be writable by the user apache runs as (www-data) this can be accomplished by making the folder world writable or setting the "where you want to put your files" folder to be owned by group www-data and make it group writable.


text:
Q: Diablo3: gem prices and artisans necessity I've recently found out, that price on gems on the market is MUCH lower than cost of upgrading gems with Artisans:
I can buy the Square Topaz (+30 intelligence) for around 150, but even flawless topaz crafting cost 500 gold...
What is logic here and why is such a big discrepancy? Is that because high level player sell GOOD gems for the low price and that affect the price of other gems? Or there is another reason?
In any case, with such prices the only use of artisan i see is to extract gems from the items and there are no any reason to try to use it for gems crafting (at least now).

A: I would say it's just supply and demand at work.
While the lower level gems drop regularly in game, especially if people are farming for gear, the higher level gems either don't drop, or drop rarely. Personally, I'm just starting Inferno and I have a bunch of gems just lying around (around a dozen of all the square gems and a half dozen or more of each of the flawless square). I also have an entire stash tab devoted to gem storage for all the gems I've picked up along the way. If every player has this sort of stash, you can see that there is a large supply at work. Conversely, there is very small demand for any particular tier of gems. Think about how many you actually use compared to how many you pick up regardless of quality.
From this, you can see that the jewelcrafter much like the blacksmith is really intended for higher level characters. These people:

*

*Have a large disposable income. I'm just starting inferno (reads: getting my face smashed pre-Leoric), and I can still make ~100k within a relatively short amount of time,just vendoring items. The Auction House can inflate this further very quickly.

*Want and need the higher level gems which don't drop.

This leaves these people with two options: get their own jewel crafter leveled, or buy gems at vastly higher prices on the Auction House. Keep in mind that the last three tiers of gems are only available via recipes which drop. These recipes are individual gems also, so there are a total of 12.
For everyone else, there's the Auction House which has large numbers of gems of lower quality that other people no longer need. These are usually gems that have dropped, not ones that have been combined using the jewel crafter, which explains the lower cost.

A: Here is an interesting link from Blizzard  http://us.battle.net/d3/en/blog/6262208/Patch_103_Design_Preview-6_6_2012#blog (scroll down to the "Just Three Two Easy Payments" section).
It looks like the price will be ajusted in 1.0.3 patch. That answers the question...


text:
Q: Glassfish 4.1, JPA 2.1 persistance.xml i faced with error like this :
Caused by: javax.xml.bind.UnmarshalException: unexpected element (uri:"http://xmlns.jcp.org/xml/ns/persistence", local:"persistence"). Expected elements are <{http://java.sun.com/xml/ns/persistence}persistence>
        at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:740)
        at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:262)

I'm try build a simple osgi jpa 2.1 module, which will run on Glassfish 4.1 and use Postgres 9.4.
JDBC resources on GF was created and it work fine (i mean "ping" button), as well as was write a persistence.xml file on META-INF dir :
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
    <persistence-unit name="something" transaction-type="JTA">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <jta-data-source>jdbc/myjdbc</jta-data-source>
        <properties>
            <property name="javax.persistence.schema-genaration" value="drop-and-create"/>
        </properties>
    </persistence-unit>
</persistence>

And most interesting is that - if i replace jpa 2.1 schema to jpa 2.0 it will work fine, but only can't create a table from entity class.
So, how to solve this problem and use JPA 2.1 xml schema.
Add.information :
News entity is here :
@Entity
public class News {

    @Id
    @GeneratedValue
    private Long ID;
    private String title;
    private String content;
    private Long views;

    // getters and setters.... default non-arg constructor was omitted

My pom.xml file :
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>myTestProject</artifactId>
        <groupId>com.myTestProject</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.myTestProject.module.domain</groupId>
    <artifactId>module.domain</artifactId>
    <packaging>bundle</packaging>

    <name>module.domain</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Export-Package>com.myTestProject.module.domain.*</Export-Package>
                        <Import-Package>javax.persistence.*, org.osgi.framework</Import-Package>
                        <Meta-Persistence>META-INF/persistence.xml</Meta-Persistence>
                        <Bundle-Activator>com.myTestProject.module.domain.Activator</Bundle-Activator>
                    </instructions>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>org.eclipse.persistence.jpa</artifactId>
            <version>2.5.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.osgi</groupId>
            <artifactId>org.osgi.core</artifactId>
            <version>4.3.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>


text:
Q: how to count the number of times a visualforce page opened by user? I need to understand the process of how we can count the number of a specific visualforce page opened by a user. The reason for this question is to see if i can find out what are the pages mostly used by users and enhance it so that i can make users life easier :).
What i know is we need to use some kind of function when page is loading. If there is any otherway i would love to understand it. If you have questions please feel free to ask, i know sometimes we can't put something in writing what we have inour mind.

A: Server-side
VF page controllers (both the custom controllers and extensions) are not allowed to run any DML operations. The reasoning behind that is somewhat simple - the act of just navigating to given page and maybe reading some data shouldn't have side effects like DB updates. So if you're thinking about saving some data - you'd be doing it either in the actions invoked on these pages or in the <apex:page ... action="{!doSomething}">. But the action parameter is frowned upon because it's a nasty workaround for this (sane) limitation. If you plan to submit your code to SF security review or the Checkmarx code quality review - this will be pointed out.
Client-side
Install some tracking javascript either into sidebar or into the VF pages. (this JS could even  do RemoteAction or something like that as an alternative to this action).
You can also have a look at Google Analytics (depends if you're fine with aggregated top 10 visited pages or you need something per user).
As @jordan.baucke mentioned - try cross-posting on Salesforce.StackExchange.com :)

A: Its simple with JavaScript, Global Variables, and object and some ajax calls(RemoteAction). The sample code would be:
<script src="http://code.jquery.com/jquery-1.10.2.min.js"/>
<script>
    var j$ = jQuery.noConflict();
    j$(document).ready(function(){
        var userID = '{!userInfo.getUserID}';    //Gets user ID

        Visualforce.remoting.Manager.invokeAction(
            '{!$RemoteAction.ClassName.MethodName}',    //Method where you increment the click counter stored in the record for that object
                userID,
               //Function on completion
        );
    });
</script>

However, I suggest that its not wise to do any DML/SOQL on page load.


text:
Q: Replace all and only complete words from JS string (not nested words) I want to replace words from text files uploaded by the user. So I don't know the exact structure of the text or which word(s) will be replaced.The word(s) to replace, will be the word that shows up most amount of times in the users text.
But I found some issues with my current method which is using .replace() with new RegExp() to replace globally and case-insensitive (gi). This works.
My issue is when a longer word or name contains the word that I want to replace.
Ex: I want to replace "is" with "xx" in the phrase "This is Isak".
I want: "This xx Isak".
But I get: "Thxx xx xxak".
So I tried replacing with " is " (to ignore any nestled words).
But that has it own issues.
If that word shows up multiple times next to itself "is is is" then the result will be "xx is xx" instead of "xx xx xx". (Because of the second "is" not having a space on it's left side?)
Or if it is next to a dot or comma "That is, like this." the result will be: "That is, like this."
But I want: "That xx, like this."

I've searched stackoverflow and google but can only find answers to related questions but not how to solve this "nested word" problem.
Any ideas?

  A. Wrong results (with RegExp replace function):

  thxxandthat, xx, thxx xx xxak. xx it xxak xx xx xx it?

  B. Wrong results (with spaces in RegExp replace function):

  thisandthat, is, this xx isak. xx it Isak xx is xx it?

  Wanted results:

  thisandthat, is, this xx isak. xx it Isak xx xx xx it?

A: You want to add a word boundary to make sure that you are replacing once a word and not a part of a word.
  ...
    function myFunction() {
  // colors are only to make it clear for everyone what is replaced
  let str = "thisandthat, is, this is isak. Is it Isak is is is it?"
  var regexp = new RegExp(/\bis\b/,'gi')
    ...


text:
Q: Postgresql More than onw row returned by a subquery in a insert to script I need to create entries based on the id's of a SELECT query, but i cant manage to do this in anyway, tried UNION ALL but im not experto on SQL.
this is my current code, the SELECT works fine alone, but with INSERT INTO it gives me the error "more than one row returned by a subquery used as an expression"
INSERT INTO payment_consent_state (
    id,
    consent_id,
    status,
    created_at
)
SELECT uuid_in(overlay(overlay(md5(random()::text || ':' || random()::text) placing '4' from 13) placing to_hex(floor(random()*(11-8+1) + 8)::int)::text from 17)::cstring) as id,
(SELECT consent_id FROM payment_consent_state
    WHERE  created_at < current_timestamp - interval '185 minutes'
    GROUP BY consent_id
    HAVING COUNT(consent_id) = 1)
,
'REJECTED' as status,
now() as data

A: The error message you're seeing is being caused by the fact that the subquery in the SELECT clause of your INSERT INTO statement is returning more than one row. The INSERT INTO statement is expecting a single value for each column, but the subquery is returning multiple rows.
You can try to fix this by using the IN operator instead of = in the HAVING clause of the subquery. This will match multiple values instead of just one. For example:
HAVING COUNT(consent_id) IN (1,2,3)

Another solution is to use a join instead of a subquery, this way you can insert multiple rows at once using the results of the SELECT statement.
INSERT INTO payment_consent_state (
    id,
    consent_id,
    status,
    created_at
)
SELECT uuid_in(overlay(overlay(md5(random()::text || ':' || random()::text) placing '4' from 13) placing to_hex(floor(random()*(11-8+1) + 8)::int)::text from 17)::cstring) as id,
pcs.consent_id, 'REJECTED' as status, now() as data
FROM payment_consent_state pcs
WHERE  pcs.created_at < current_timestamp - interval '185 minutes'
GROUP BY pcs.consent_id
HAVING COUNT(pcs.consent_id) = 1

Keep in mind that this is just an example and you should adjust it to your specific needs, also, you might need to add an ORDER BY clause to make sure you are selecting the correct rows to be inserted

A: Is this helpful :
INSERT INTO payment_consent_state (
    id,
    consent_id,
    status,
    created_at
)
SELECT uuid_in(overlay(overlay(md5(random()::text || ':' || random()::text) placing '4' from 13) placing to_hex(floor(random()*(11-8+1) + 8)::int)::text from 17)::cstring) as id,
consent_id,
'REJECTED' as status,
now() as data
FROM payment_consent_state
WHERE  created_at < current_timestamp - interval '185 minutes'
GROUP BY consent_id
HAVING COUNT(consent_id) = 1)

This considered as multi rows itself
(SELECT consent_id FROM payment_consent_state
    WHERE  created_at < current_timestamp - interval '185 minutes'
    GROUP BY consent_id
    HAVING COUNT(consent_id) = 1)


text:
Q: How do I add a menubar to a tabbed pane? Is it possible to add a menubar to one of the windows in a tabbed pane? And is a frame the only container which can have a menubar?

A: As Suraj mentioned, you can force the issue as as they are both, both components and containers however you will have to do the extra work to organize it in your pane's layout along with the rest of the components in the pane -- unlike with a JFrame which has methods to support it outright (setJMenuBar and you're outta there).  Normally, when added to a JFrame, the JMenuBar is not in the content pane, it is in a layered pane which contains both the menu bar and the content pane below it.
You might also want to consider using a JToolBar which is very flexible (more easily customized) and has some optional built-in goodies like being separable/dockable.

A: Though you can directly add a JMenubar in to a JtabbedPane as both are JComponents. But it wont look nice(usable), if you have tried it.
I would suggest to subclass BasicTabbedPaneUI and override installComponents(), there you can add you JmenuBar at the top or wherever you want.

A:
Is it possible to add a menubar to one
  of the windows in a tabbed pane?

What problem did you have when you tried to do this?
If you need more help post your SSCCE showing the problem.


text:
Q: Set gnome as default display manager Today I wanted to try gnome 3 as the desktop environment. So I removed openbox completely and installed gnome 3 and run dpkg-reconfigure after. I also had dwm installed, which I left as is.
sudo apt-get install gdm3
sudo dpkg-reconfigure gdm3

So when I logged out, I had the gnome login screen. So far so good.
The problem is that the session switcher doesn't show gnome shell or gnome session in the items. I see

*

*System X11 default

*Default Xsession

*WM from xsession script

All of these items take me into a dwm session. The third option is coming from user-session.desktop I created
[Desktop Entry]
Encoding=UTF-8
Name=WM from xsession script
Comment=Runs the window manager defined by xsession script
Exec=/etc/X11/Xsession
Type=Application

and the ~/.xsession contains:
# xfce4-power-manager stuff

#xsetroot stuff

exec dwm

When I run the update-alternatives, I don't see gnome.
$ sudo update-alternatives --config x-window-manager
There is only one alternative in link group x-window-manager (providing /usr/bin/x-window-manager): /usr/bin/mutter
Nothing to configure.
$ sudo update-alternatives --config x-session-manager
There is only one alternative in link group x-session-manager (providing /usr/bin/x-session-manager): /usr/bin/lxsession
Nothing to configure.

How can I make gnome 3 as my default desktop environment and make sure gnome 3 comes up in the session switcher?

A: You need to install more packages than only gdm3, gdm3 is just the login manager.
To have a very minimal Gnome desktop environment, you need to install the following packages (maybe some are already installed in your system):
sudo apt-get install -y ca-certificates libgl1-mesa-dri x11-xserver-utils \
fonts-cantarell gdm3 gnome-session gnome-shell gnome-themes-standard \
gvfs-backends gvfs-fuse mousetweaks network-manager-gnome pulseaudio \
sound-theme-freedesktop xdg-user-dirs


text:
Q: Integral of differential forms vs orientability Let $\omega$ be an $n$-form on an $n$-manifold $M$, and $F: M\to M$ be a diffeomorphism. Here for simplicity let $\phi:U\to S$ and $\psi:V\to T$ be two charts of $M$ such that $F(U) = V$.
I believe we have the definition $\int_U \omega = \int_S (\phi^{-1})^* \omega$, and similar for $\int_V \omega$.
I believe we have $\int_U F^* \omega = \pm \int_V \omega$, positive if $F$ is orientation-preserving, and negative otherwise. I am attempting to understand the this equality.
Let $x^k$ be the local coordinates on $U$, and $y^k$ be that on $V$. Write $\omega = \omega_{12...n} dx^1 \wedge dx^2  \wedge \cdots \wedge
dx^n$ on $U$ and $\omega = \omega_{12...n}' dy^1 \wedge dy^2 \wedge \cdots \wedge dy^n$ on $V$.
Also let $f: S\to T$ be the local representation of $F$.
To make things absolutely clear, I am also going to write $s^k$ for coordinates on $S$, and $t^k$ for that on $T$.
Now
$\begin{equation}
\begin{aligned}
\int_U F^* \omega &= \int_S (\phi^{-1})^* F^* \omega \\
&= \int_S f^* (\psi^{-1})^* \omega \\
&= \int_S f^* (\omega_{12...n}'\circ \psi^{-1} dt^1 \wedge dt^2 \wedge \cdots \wedge dt^n) \\
&= \int_S (\omega_{12...n}'\circ \psi^{-1} \circ f) \det(df) \cdot ds^1 \wedge ds^2 \wedge \cdots \wedge ds^n \\
&= \int_S (\omega_{12...n}'\circ \psi^{-1} \circ f(s)) \det(df)(s) \cdot ds^1 ds^2 \dots ds^n
\end{aligned}
\end{equation}$
Then by multivariable calculus the above becomes
$\text{sign}\det(df) \int_T \omega_{12...n}'\circ \psi^{-1} (t) \cdot dt^1 dt^2 \dots dt^n
= \text{sign}\det(df) \int_T (\psi^{-1})^* \omega
= \text{sign}\det(df) \int_V \omega$.
If everything so far is correct, then $\text{sign}\det(df)$ should correspond to whether $F$ is orientation-preserving.
But what if I change the chart $\psi$ to $\psi_0: V\to T_0$, where $\psi_0 (v)$ switches the first two coordinates of $\psi(v)$? Then we have a new set of coordinates $z^k$ on $V$ and $u^k$ on $T_0$, new expression $\omega = \omega_{12...n}'' dz^1 \wedge dz^2 \wedge \cdots \wedge dz^n$ on $V$, and a new local representation $f_0: S\to T_0$ of $F$.
We do the exact same computation as before. From what I can see nothing seems to break, and we still get $\int_U F^* \omega = \text{sign}\det(df_0) \int_V \omega$.
But $df_0$ switches the first two columns of $df$, so $\det(df_0)$ and $\det(df)$ must have different signs.
This seems to be not great. For the life of me I couldn't figure out where exactly things went wrong.


text:
Q: Laravel eloquent get date format from string In my table, I have enforce column as string (like: '20170502').
I want to get the week of the day from this string so I try to convert to date format but that not working.
$event = VEventMp::where('event_seq', '=', $mypage_data->event_seq)
    ->select(
        'ENFORCE_PLACE',
        'ENFORCE_FROM',
        \DB::raw("DATE_FORMAT(STR_TO_DATE(ENFORCE_FROM,'%y/%m/%d'), '%m月%d日')
         AS day"),
        \DB::raw('(CASE WHEN WEEKDAY(day) = 0 THEN "月"
        WHEN WEEKDAY(start_time) = 1 THEN "火"
        WHEN WEEKDAY(start_time) = 2 THEN "水"
        WHEN WEEKDAY(start_time) = 3 THEN "木"
        WHEN WEEKDAY(start_time) = 4 THEN "金"
        WHEN WEEKDAY(start_time) = 5 THEN "土"
        WHEN WEEKDAY(start_time) = 6 THEN "日" END) AS weekday')
    ->first();

Where did I make mistake?
Thank you!

A: You have a couple of issues, firstly if the date format is like 20170502 then you must match that in your call to STR_TO_DATE, so change that to:
STR_TO_DATE(ENFORCE_FROM,'%Y%m%d')

Secondly, you can't use an alias in the SELECT part of the query so you need to change your CASE expression to
(CASE WHEN WEEKDAY(STR_TO_DATE(ENFORCE_FROM,'%Y%m%d')) = 0 THEN "月"
      WHEN WEEKDAY(STR_TO_DATE(ENFORCE_FROM,'%Y%m%d')) = 1 THEN "火"
      WHEN WEEKDAY(STR_TO_DATE(ENFORCE_FROM,'%Y%m%d')) = 2 THEN "水"
      WHEN WEEKDAY(STR_TO_DATE(ENFORCE_FROM,'%Y%m%d')) = 3 THEN "木"
      WHEN WEEKDAY(STR_TO_DATE(ENFORCE_FROM,'%Y%m%d')) = 4 THEN "金"
      WHEN WEEKDAY(STR_TO_DATE(ENFORCE_FROM,'%Y%m%d')) = 5 THEN "土"
      WHEN WEEKDAY(STR_TO_DATE(ENFORCE_FROM,'%Y%m%d')) = 6 THEN "日" END) AS weekday


text:
Q: how to load data from json file to radio buttons using purely JS? When clicking on one of the radio buttons in HTML file, I want to get the frameworks data (names and images) from data.json file and filter them according to the button chosen
  {
  "frameworks": {
    "backend": [
      { "name": "nodeJS", "imgURL": "./img/node.png" },
      { "name": "Django", "imgURL": "./img/django.png" },
      { "name": "Ruby on Rails", "imgURL": "./img/rails.png" },
      { "name": "laravel", "imgURL": "./img/laravel.png" }
    ],
    "frontend": [
      { "name": "ReactJS", "imgURL": "./img/react.png" },
      { "name": "Angular", "imgURL": "./img/angular.png" },
      { "name": "vueJS", "imgURL": "./img/vue.png" },
      { "name": "JQuery", "imgURL": "./img/jquery.png" }
    ],
    "mobile": [
      { "name": "flutter", "imgURL": "./img/flutter.png" },
      { "name": "React Native", "imgURL": "./img/react.png" }
    ]
  }
}

and i want to display the data that loaded from json file in dev that holds frameworksDisplay id

Frameworks

The purpose of framework is to allow designers and developers to focus on building an unique feature for their web based projects rather than re-inventing by coding. Framework is specially created to help you boost the performance and efficiency of your web app development task.

                <form id="frameworksForm">
                    <input type="radio" name="frameworksSelection" id="all" value="all">All
                    <input type="radio" name="frameworksSelection" id="backend" value="backend">Backend
                    <input type="radio" name="frameworksSelection" id="frontend" value="frontend">Frontend
                    <input type="radio" name="frameworksSelection" id="mobile" value="mobile">Mobile
                </form>

can you guys help me out in this one i tried to do it but got no result so far i am still new with JS.

A: Here is a sample code to start with. You can modify to meet how you want to show the data inside 'frameworksDisplay' div.

const apiData = {
  "frameworks": {
    "backend": [
      { "name": "nodeJS", "imgURL": "./img/node.png" },
      { "name": "Django", "imgURL": "./img/django.png" },
      { "name": "Ruby on Rails", "imgURL": "./img/rails.png" },
      { "name": "laravel", "imgURL": "./img/laravel.png" }
    ],
    "frontend": [
      { "name": "ReactJS", "imgURL": "./img/react.png" },
      { "name": "Angular", "imgURL": "./img/angular.png" },
      { "name": "vueJS", "imgURL": "./img/vue.png" },
      { "name": "JQuery", "imgURL": "./img/jquery.png" }
    ],
    "mobile": [
      { "name": "flutter", "imgURL": "./img/flutter.png" },
      { "name": "React Native", "imgURL": "./img/react.png" }
    ]
  }
};

var radioBtns = document.querySelectorAll('input[type=radio]');
for (var radio of radioBtns) {
  radio.addEventListener('click', function(event) {
    let framework;
    let html = '';
    if (event.target.value === 'all') {
      framework = apiData.frameworks;
      for (category in framework) {
        html += ''+ category +'
';
        // Loop the next level as well
      }
    } else {
      framework = apiData.frameworks[event.target.value];
      html = '
';
      for (index in framework) {
        html += '
Name: '+ framework[index]['name'] +'
';
      }
      html += '
';
    }
    document.getElementById("frameworksDisplay").innerHTML = html;
  });
}

Frameworks

The purpose of framework is to allow designers and developers to focus on building an unique feature for their web based projects rather than re-inventing by coding. Framework is specially created to help you boost the performance and efficiency of your web app development task.

                <form id="frameworksForm">
                    <input type="radio" name="frameworksSelection" id="all" value="all">All
                    <input type="radio" name="frameworksSelection" id="backend" value="backend">Backend
                    <input type="radio" name="frameworksSelection" id="frontend" value="frontend">Frontend
                    <input type="radio" name="frameworksSelection" id="mobile" value="mobile">Mobile
                </form>

A: This one will give you the data from the selected radio button, except "all" which will give you all of the others.

const jsonData = {
    "frameworks": {
        "backend": [
            { "name": "nodeJS", "imgURL": "./img/node.png" },
            { "name": "Django", "imgURL": "./img/django.png" },
            { "name": "Ruby on Rails", "imgURL": "./img/rails.png" },
            { "name": "laravel", "imgURL": "./img/laravel.png" }
        ],
        "frontend": [
            { "name": "ReactJS", "imgURL": "./img/react.png" },
            { "name": "Angular", "imgURL": "./img/angular.png" },
            { "name": "vueJS", "imgURL": "./img/vue.png" },
            { "name": "JQuery", "imgURL": "./img/jquery.png" }
        ],
        "mobile": [
            { "name": "flutter", "imgURL": "./img/flutter.png" },
            { "name": "React Native", "imgURL": "./img/react.png" }
        ]
    }
};

document.getElementsByName('frameworksSelection').forEach(e => {
    e.addEventListener('change', () => {
        let html = '';
        if (e.value === 'all') {
            document.getElementsByName('frameworksSelection').forEach(k => {
                if (!k.checked) html += getObject(k.value)
            });
        }
        else
            html = getObject(e.value)

        document.getElementById('frameworksDisplay').innerHTML = html;
    })
});

function getObject(key) {
    let html = `<h2>${key}</h2>`;
    jsonData.frameworks[key].forEach(o => {
        html += `<div>${o.name}: ${o.imgURL}</div>`;
    });
    return html;
}

    <form id="frameworksForm">
        <input type="radio" name="frameworksSelection" id="all" value="all">
        All
        <input type="radio" name="frameworksSelection" id="backend" value="backend">
        Backend
        <input type="radio" name="frameworksSelection" id="frontend" value="frontend">
        Frontend
        <input type="radio" name="frameworksSelection" id="mobile" value="mobile">
        Mobile
    </form>


text:
Q: Syntax error in FROM clause Estoy intentando sumar los valores que retornan estas dos consultas en MS Access, y recibo el error

"Syntax error in FROM clause"

Ya he intentado de muchas maneras lograr la suma de estas dos consultas, alguien podría decirme en que me estoy equivocando. Gracias
SELECT SUM(SUMA) AS ahorro, generador  FROM (SELECT sum(ahorro) as SUMA,
generador from kaizen where ESTATUS= 'Cerrado' AND YEAR(fechaValidacion)
= '2018' and tipoAhorro= 'Hard Perimetral'  GROUP BY generador) + SELECT
sum(ahorro1) as SUMA,generador from kaizen where ESTATUS= 'Cerrado' AND
YEAR(fechaValidacion) = '2018' and tipoAhorro1= 'Hard Perimetral' and
generador GROUP BY generador

A: El error sintáctico está con el signo "+" de la tercera línea
GROUP BY generador) + SELECT

Tienes dos maneras de hacer eso:
La primera es asegurarte de solo devolver un único campo por cada SELECT, y agrupar usando parentesis las dos subconsultas
SELECT (SELECT SUM(ahorro1) FROM ...) + (SELECT SUM(ahorro2) FROM ...) AS SUMA

La segunda es utilizando el operador UNION en lugar del signo +. (Ver https://support.office.com/en-us/article/use-a-union-query-to-combine-multiple-queries-into-a-single-result-1f772ec0-cc73-474d-ab10-ad0a75541c6e)
Quedaría algo como:
SELECT SUM(SUMA), Generador
FROM
(
    SELECT sum(ahorro) as SUMA, generador from kaizen ...
    UNION
    SELECT sum(ahorro) as SUMA, generador from kaizen ...
) GROUP BY generador

Un consejo para detectar los errores de sintaxis es pasar tu consulta en validadores de este estilo.
https://www.eversql.com/sql-syntax-check-validator/
Espero que te sirva la respuesta,
Saludos


text:
Q: getting element values from an xml soap response when there is double xml tag I HAVE THIS XML RESPONSE FROM A SOAP CALL:
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><loginResponse xmlns="http://wws.adomain.com/"><loginResult><xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"><xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:MainDataTable="replay" msdata:UseCurrentLocale="true"><xs:complexType><xs:choice minOccurs="0" maxOccurs="unbounded"><xs:element name="replay"><xs:complexType><xs:sequence><xs:element name="code" type="xs:string" minOccurs="0" /><xs:element name="description" type="xs:string" minOccurs="0" /></xs:sequence></xs:complexType></xs:element></xs:choice></xs:complexType></xs:element></xs:schema><diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1"><DocumentElement xmlns=""><replay diffgr:id="replay1" msdata:rowOrder="0" diffgr:hasChanges="inserted">OK<description>
<?xml version="1.0" encoding="UTF-8"?><root><token>e6d354f2-b284569e20-b2def8f3ef4a</token><nmDealer>SAP001 NAME</nmDealer><idRegDealer>8763</idRegDealer><idRegGrupo>-1</idRegGrupo><idRegPuntoVenta>-1</idRegPuntoVenta><idRegUsuario>35350731</idRegUsuario><idRegVendedor>-1</idRegVendedor><idRegZona>-1</idRegZona><dsTpUsuario>CLIENTES</dsTpUsuario><dsPais>PRODUCCION</dsPais><idioma>EN</idioma><idRegIdioma>9</idRegIdioma><isImputar>False</isImputar><moneda>€</moneda><tpUsuario>1</tpUsuario><idRegComisionVariableDealer>-1</idRegComisionVariableDealer><permitirComisionVariableDealer>1</permitirComisionVariableDealer><firstAccess>0</firstAccess><acceptedConditions>False</acceptedConditions><idRegInsured>-1</idRegInsured><idRegAuditor>-1</idRegAuditor></root></description></replay></DocumentElement></diffgr:diffgram></loginResult></loginResponse></soap:Body></soap:Envelope>

http://prntscr.com/9cfdwk

I want to be able to get the values of element (eg token) in the second xml tag (<?xml version="1.0" encoding="UTF-8"?>) Any prompt assistance will be appreciated.
HERE IS MY CODE:
$s = new soapclientw($wsdlfile);
if (empty($proxyhost))
{

}
else{
    $s->setHTTPProxy($proxyhost,$proxyport,$proxyusr,$proxypassword);
}
$result = $s->send($msg,'http://wws.domain.com/login',60);

$myXMLData = $s->responseData;

libxml_use_internal_errors(true);

$xml = simplexml_load_string($myXMLData);

if ($xml === false) {
    echo "Failed loading XML: ";
    foreach(libxml_get_errors() as $error) {
        echo "
", $error->message;
    }
}
else{
    echo $xml->token;
}

A: Given your original, highly dubious xml, the following is a bit of a hack but it works..
    $strxml='
    <?xml version="1.0" encoding="utf-8"?>
        <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
            <soap:Body>
                <loginResponse xmlns="http://wws.adomain.com/">
                    <loginResult>
                        <xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
                            <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:MainDataTable="replay" msdata:UseCurrentLocale="true">
                                <xs:complexType>
                                    <xs:choice minOccurs="0" maxOccurs="unbounded">
                                        <xs:element name="replay">
                                            <xs:complexType>
                                                <xs:sequence>
                                                    <xs:element name="code" type="xs:string" minOccurs="0" />
                                                    <xs:element name="description" type="xs:string" minOccurs="0" />
                                                </xs:sequence>
                                            </xs:complexType>
                                        </xs:element>
                                    </xs:choice>
                                </xs:complexType>
                            </xs:element>
                        </xs:schema>
                        <diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
                            <DocumentElement xmlns="">
                                <replay diffgr:id="replay1" msdata:rowOrder="0" diffgr:hasChanges="inserted">
                                    OK
                                    <description>
                                        <?xml version="1.0" encoding="UTF-8"?>
                                        <root>
                                            <token>e6d354f2-b284569e20-b2def8f3ef4a</token>
                                            <nmDealer>SAP001 NAME</nmDealer>
                                            <idRegDealer>8763</idRegDealer>
                                            <idRegGrupo>-1</idRegGrupo>
                                            <idRegPuntoVenta>-1</idRegPuntoVenta>
                                            <idRegUsuario>35350731</idRegUsuario>
                                            <idRegVendedor>-1</idRegVendedor>
                                            <idRegZona>-1</idRegZona>
                                            <dsTpUsuario>CLIENTES</dsTpUsuario>
                                            <dsPais>PRODUCCION</dsPais>
                                            <idioma>EN</idioma>
                                            <idRegIdioma>9</idRegIdioma>
                                            <isImputar>False</isImputar>
                                            <moneda>€</moneda>
                                            <tpUsuario>1</tpUsuario>
                                            <idRegComisionVariableDealer>-1</idRegComisionVariableDealer>
                                            <permitirComisionVariableDealer>1</permitirComisionVariableDealer>
                                            <firstAccess>0</firstAccess>
                                            <acceptedConditions>False</acceptedConditions>
                                            <idRegInsured>-1</idRegInsured>
                                            <idRegAuditor>-1</idRegAuditor>
                                        </root>
                                    </description>
                                </replay>
                            </DocumentElement>
                        </diffgr:diffgram>
                    </loginResult>
                </loginResponse>
            </soap:Body>
        </soap:Envelope>';

    $strxml=htmlentities( $strxml );
    $search=array(
        htmlentities( '<?xml version="1.0" encoding="utf-8"?>' ),
        htmlentities( '<?xml version="1.0" encoding="UTF-8"?>' )
    );
    $strxml=html_entity_decode( str_replace( $search, '', $strxml ) );

    libxml_use_internal_errors( true );
    $dom = new DOMDocument('1.0','utf-8');
    $dom->validateOnParse=false;
    $dom->standalone=true;
    $dom->preserveWhiteSpace=true;
    $dom->strictErrorChecking=false;
    $dom->substituteEntities=false;
    $dom->recover=true;
    $dom->formatOutput=false;
    $dom->loadXML( $strxml );
    libxml_clear_errors();

    $col=$dom->getElementsByTagName('root')->item(0);
    if( $col ){
        foreach( $col->childNodes as $node ) echo $node->tagName.' '.$node->nodeValue.BR;
    }
    $dom=null;

A: Thanks all, I was able to figure it out myself.
Here is the code that worked for me:
$myXMLData = strip_tags($s->responseData);
$temp = explode("OK", $myXMLData);
$myXMLData = $temp[1];
$xml = new SimpleXMLElement(htmlspecialchars_decode($myXMLData));

I stripped off all the soap tags, living me with the final xml data but with a leading 'OK' which I removed by explode().  Replacing the 'OK' with an empty string would have also worked.


text:
Q: Is this a characterization of commutative $C^{*}$ algebras? Assume that $A$ is  a  $C^{*}$ algebra with self adjoint elements $A_{sa}$. Assume that for all  $a,b\in A$  we  have $$ab\in A_{sa} \iff  ba \in A_{sa}$$

Is  $A$ necessarily a  commutative  algebra?

This question is in line of this post

A: Yes. I will show that any two positive elements of $A$ commute. Since every element is a linear combination of positive elements, this suffices.
Say $a$ and $b$ are positive. Then $a^{1/2}ba^{1/2} \in A_{sa}$, so by hypothesis $ba^{1/2}a^{1/2} = ba \in A_{sa}$. That is, $ba = (ba)^* = a^*b^* = ab$. QED


text:
Q: Django iterate queryset just n number of times in templates My issue is quite simple. I am using Django taggit.
I want to iterate this only 2 times. Means to display only 4 tags in templates.
 {% for tag in data.tags.all %}
     {{tag}}
 {% endfor %}

I have tried this, but it is not making any sense:
 {% for tag in data.tags.all|ljust:"2" %}
    {{tag}}
 {% endfor %}

Can anyone suggest how can I achieve it?

A: You can make use of the |slice template filter [Django-doc]:
{% for tag in data.tags.all|slice:':2' %}
    {{ tag }}
{% endfor %}


text:
Q: Error when checking input: expected conv2d_1_input to have shape (3, 32, 32) but got array with shape (32, 32, 3) I want to train  CNN for cifar10 datasets but got this error
Error when checking input: expected conv2d_10_input to have shape (3, 32, 32) but got array with shape (32, 32, 3)
this is my CNN model
epochs = 10
batch_size = 32
model.fit(X_train, Y_train, validation_data=(X_test, Y_test), epochs=epochs, batch_size=batch_size, verbose = 1)

A: It seems like the dataset is in (Height, Width, CHannel) format but the model is expecting (Channel, Height, Width) format.
We can convert between these using the tf.transpose() function which can "switch" around the dimensions of a tensor.
TO convert a single image tensor from HWC to CHW just do:
reshaped = tf.transpose(image_tensor, (2,0,1))

To convert a batch you can do:
reshaped = tf.transpose(images_tensor, (0,3,1,2))


text:
Q: Auto-correlation with weekly data I am a new user to R and try to calculate weekly auto correlation between 2 financial time series with ccf function.
Here is my code:
SPX_ImpliedVola_ts<-ts(SPX_ImpliedVola$x, start=c(2005), end=c(2014), freq=52)
SPX_GSV_ts<-ts(SPX_GSV$x, start=c(2005), end=c(2014), freq=52)
plot(ccf(SPX_ImpliedVola_ts,SPX_GSV_ts, type= "correlation"))

The results of ccf function make sense, but the labelling of x-axis is wrong. My lags should be weeks. The plot function uses years instead and therefore on lag is =1/52. I do not have enough reputation points to post the plot
Is there an easy way to format the x axis, so that 1 lag = 1 week?
Here is my data for the year 2013:
SPX_GSV_ts
structure(c(-0.172545978, -0.085914629, -0.051152522, -0.191885526,
0.10720997, 0.120573931, 0.123062732, -0.073231914, 0.122783425,
-0.073231914, -0.091330136, -0.108595771, -0.149988456, -0.077412223,
0.017728767, -0.057991947, -0.04522754, 0.098925304, 0.019744058,
-0.042403849, 0.097955247, 0.060480747, -0.096910013, 0.04275198,
-0.111150452, -0.123384909, 0.020203386, 0.02540458, 0.046743404,
0.046743404, 0.096910013, -0.029289376, -0.020203386, 0.019305155,
0.124938737, 0.071494417, 0.080655932, 0.032184683, -0.072195125,
0.08058446, 0.109144469, -0.116215168, -0.003792989, -0.011685758,
0.033281387, -0.011685758, 0.044203662, -0.137383556, -0.023912157,
0.023065304, 0.037141808, -0.128799157, -0.036045104), .Tsp = c(2013,
2014, 52), class = "ts")

SPX_ImpliedVola_ts:
structure(c(0.1551244, 0.1764986, 0.169477, 0.1509566, 0.14180975,
0.1455916, 0.1320918, 0.150884, 0.1519094, 0.1670364, 0.1769658,
0.1491722, 0.14883, 0.13545475, 0.134158, 0.1292596, 0.13465,
0.14380075, 0.136281, 0.1350982, 0.1384192, 0.1467728, 0.161534,
0.14764, 0.1332734, 0.1353106, 0.126313, 0.1268324, 0.1200864,
0.1242202, 0.127857, 0.1382412, 0.1319932, 0.1441192, 0.1316964,
0.1217246, 0.1262966, 0.11574475, 0.1166192, 0.1231602, 0.119756,
0.10622025, 0.1133376, 0.1245488, 0.1124368, 0.11566475, 0.1196388,
0.1003482, 0.0994486, 0.0972232, 0.10798775, 0.1115012, 0.1148464
), .Tsp = c(2013, 2014, 52), class = "ts")

A: It seems that ccf does not plot the number of lags properly for ts class. You need to change the class of your data to data.frame to get the proper number of lags on the x-axis. You can use the following code:
ccf.results<-ccf(data.frame(SPX_ImpliedVola_ts),data.frame(SPX_GSV_ts), type= "correlation", ylab="Auto-correlation", main="Weekely Auto-corelations")

You can remove type= "correlation" and you will still get the same results as the default type for ccf is correlation
Also the plot you have from last code does not give access to the specific value of each lag. To check the value of each lag you need to assign the ccf results variable name and thin print it as follow:
ccf.results<-ccf(data.frame(SPX_ImpliedVola_ts),data.frame(SPX_GSV_ts), type= "correlation")
print(ccf.results)

You will get:
Autocorrelations of series 'X', by lag

   -14    -13    -12    -11    -10     -9     -8     -7     -6     -5     -4     -3     -2     -1
-0.010  0.076  0.011 -0.017 -0.031 -0.057 -0.037  0.059  0.067  0.033  0.105  0.000 -0.242 -0.181
     0      1      2      3      4      5      6      7      8      9     10     11     12     13
-0.189 -0.157 -0.079  0.041  0.080 -0.015 -0.098 -0.302 -0.303 -0.355 -0.323 -0.264 -0.222 -0.116
    14
-0.121

Note that 0 in the results above means the correlation without any lags.


text:
Q: Elm can't find the elm whitespace error I keep getting a whitespace compiler error and I can't spot the error.
Here is the error

I need whitespace, but got stuck on what looks like a new declaration.
  You are either missing some stuff in the declaration above or just
  need to add some spaces here:
41| view : Model -> Html -> Msg
      ^ I am looking for one of the following things:
whitespace

Here is the code
view : Model -> Html -> Msg
view model =
    div [] [
        h2 [] [text ("Counter: " ++ (toString model))]
        , button [type_ "button", onClick Add ] [text "add"]
        , button [type_ "button", onClick Sub ] [text "subtract"]
        , button [type_ "button", onClick Reset ] [text "reset"]
    ]

I have to be missing something very simple, but I can't spot it.

A: you need a few spaces after a function call. Like
x =
0

won't compile, but
x =
    0

will compile, so saying that. you need to indent div [] like so
view : Model -> Html -> Msg
view model =
    div []
        [ h2 [] [ text ("Counter: " ++ (toString model)) ]
        , button [ type_ "button", onClick Add ] [ text "add" ]
        , button [ type_ "button", onClick Sub ] [ text "subtract" ]
        , button [ type_ "button", onClick Reset ] [ text "reset" ]
        ]

also, the type annotation for view is off, currently you have
view : Model -> Html -> Msg

but it should be
view : Model -> Html Msg

Just a tip for when you are learning, you can leave off the type alias
--view : Model -> Html Msg
view model =

is perfectly fine, you can add the annotations later when you are more comfortable with the language, that's how I learned.
See here for a link to the working version.

A: Your type definition is a little bit wrong. The following:
view : Model -> Html -> Msg

Should be:
view : Model -> Html Msg

Html Msg is a single type. The corresponding type definition is type alias Html msg. msg starts with a lower case which indicates that this type is a generic type. This means that any type could be placed here. We could, for example, write Html Int or Html String. Since the view code returns messages when we click a button for example, we use this message type as the generic type. This results in Html Msg.


text:
Q: Getting thumbnails of a custom posts featured images in a page-templates metabox I guess I need to know how to call meta data into metaboxes for beginners.
I'm using
$posts = get_posts(array(
        'post_type'   => 'slidertype',
        'post_status' => 'publish',
        'posts_per_page' => -1,
        'fields' => 'ids'
        )
    );
    //loop over each post
    foreach($posts as $p){
        //get the meta you need form each post
        $thumb = get_post_meta($p,"_thumbnail_id",true);

        echo $thumb;

To try to get thumbnails of my custom post type 'slidertype' to show up in a page's metabox. Right now it's displaying a number which doesn't make sense to me. No advice is bad advice guys! Thanks.

A: You can get the image from your $thumb integer with the following additional code:
$thumb = get_post_meta($p,"_thumbnail_id",true);
$image = wp_get_attachment_image_src($thumb);
echo $image[0];

This will return the URL of the image, just put that in an img tag to display it.

A: You can also use get_the_post_thumbnail without having to first fetch the ID:
foreach( $posts as $p ){
    echo get_the_post_thumbnail( $p->ID, 'thumbnail' );
}

Or using setup_postdata you can use template tags that only work "in the loop":
foreach( $posts as $p ){
    setup_postdata( $p );
    the_post_thumbnail( 'large' );
}
wp_reset_postdata();


text:
Q: Pandas: Create several rows from column that is a list Let's say I have something like this:
df = pd.DataFrame({'key':[1,2,3], 'type':[[1,3],[1,2,3],[1,2]], 'value':[5,1,8]})

key type        value
1   [1, 3]      5
2   [1, 2, 3]   1
3   [1]         8

Where one of the columns contains a list of items.
I would like to create several rows for each row that contains multiple types.
Ontaining this:
key type  value
1   1     5
1   3     5
2   1     1
2   2     1
2   3     1
3   1     8

I've been playing with apply with axis=1 but I can't find a way to return more than 1 row per row of the DataFrame.
Extracting all different 'types' and then looping-concatenating seems to be ugly.
any ideas?
Thanks!!!

A: import itertools
import pandas as pd
import numpy as np

def melt_series(s):
    lengths = s.str.len().values
    flat = [i for i in itertools.chain.from_iterable(s.values.tolist())]
    idx = np.repeat(s.index.values, lengths)
    return pd.Series(flat, idx, name=s.name)

melt_series(df.type).to_frame().join(df.drop('type', 1)).reindex_axis(df.columns, 1)

setup
df = pd.DataFrame({'key':[1,2,3],
                   'type':[[1,3],[1,2,3],[1,2]],
                   'value':[5,1,8]})
df


text:
Q: Web.py Period after variable in template I have a template where I'm passing string1 and string2 to it.
I then want to display the passed variables like string1string2.zip but the problem is it gets read as if I want to get the zip attribute from string2 instead of displaying it as separate text.
The error created is
AttributeError: 'str' object has no attribute 'zip'
Any way around this?
Not sure why this was downvoted..

A: Try this:
$(string1)$(string2).zip


text:
Q: Python, al iterar sobre los elementos de una lista, muestra elementos difrentes soy nuevo en esto y estoy haciendo un programa en python que pase un número decimal a hexadecimal. Como ustedes sabrán, hay un método que consiste en pasar de decimal a binario y de binario a hexadecimal (agrupando los bits de cuatro en cuatro, de derecha a izquierda y mirando luego en la tabla a qué número corresponde cada grupo de bits). Yo he escogido ese método para traducirlo al algoritmo del programa. He conseguido que primero pase el número decimal a binario y que cada bit lo ponga en una misma lista. Ahora tocaría agrupar de cuatro en cuatro cada bit de derecha a izquierda. El problema es que, si la longitud de la lista > 4, el programa al iterar sobre cada elemento de la lista y al añadírselo a otra lista, el output muestra un numero diferente, no sé si me explico.
bin_hex_dict = {
    '0000' : '0',
    '0001' : '1',
    '0010' : '2',
    '0011' : '3',
    '0100' : '4',
    '0101' : '5',
    '0110' : '6',
    '0111' : '7',
    '1000' : '8',
    '1001' : '9',
    '1010' : 'A',
    '1011' : 'B',
    '1100' : 'C',
    '1101' : 'D',
    '1110' : 'E',
    '1111' : 'F',
}

num = input("Introduzca un numero decimal para pasarlo a hexadecimal: ")
potencias = []
binary_num = []
binary_num_def = []
binary_num_def2 = []
binary_num_def_matrix = []

while True:
    potencias =  [2**x for x in range(int(num), -1, -1)]
    for y in potencias:
        if int(num)-y<0:
            binary_num.append(0)
            finish = True
        else:
            binary_num.append(1)
            num = int(num) - y
            finish = True
    if finish:
        break

print(binary_num)

for x in range(0, len(binary_num)):
    if binary_num[x] == 1:
        for y in binary_num[0:x]:
            binary_num.remove(binary_num[y])
        break

print(binary_num)

times = 0

if len(binary_num) ==  4:
    for x in range(len(binary_num)-1, -1, -1):
        binary_num_def.insert(0, binary_num[x])
    binary_num_def_matrix.insert(0, binary_num_def)
elif len(binary_num) < 4:
    for x in range(len(binary_num)-1, -1, -1):
        binary_num_def.insert(0, binary_num[x])
    binary_num_def_matrix.insert(0, binary_num_def)
else:
    for x in range(len(binary_num)//4):
        if times == 4:
            for y in range(len(binary_num)-times-1, len(binary_num)-times-5, -1):
                print(f'y : {y}')
                print(f'binary_num[y]: {binary_num[y]}')
                binary_num_def2.insert(0, binary_num[y])
                print(f'binary_num_def2 : {binary_num_def2}')
                binary_num.remove(binary_num[y])
            binary_num_def_matrix.insert(0, binary_num_def2)
        elif times < 4:
            for y in range(len(binary_num)-1, len(binary_num)-5, -1):
                print(f'y: {y}')
                print(f'binary_num[y]: {binary_num[y]}')
                binary_num_def.insert(0, binary_num[y])
                print(f'binary_num_def : {binary_num_def}')
                binary_num.remove(binary_num[y])
                times += 1
            binary_num_def_matrix.insert(0, binary_num_def)
    binary_num_def_matrix.insert(0, binary_num)

print(binary_num_def_matrix)
print(binary_num)

Al ejecutar el código y poner el número 10010 (decimal) sale esto en pantalla:

Lo que yo quiero saber es por qué me sale que binary_num[y] es un número diferente del número que debería ser.
Muchas gracias.

A: Te complicas mucho la vida.
num = 100010
hexa = []
while num:
    digito = num % 16
    hexa.append("0123456789ABCEDF"[digito])
    num = num >> 4
valor = ''.join(hexa[::-1])
print(valor)

La idea es iterar hasta que num desaparezca. En cada iteración extraemos los cuatro últimos bits de num; eso es lo que se obtiene al calcular el resto de num % 16. Esos cuatro bits los transformamos a hexadecimal usandolo como indice del string:
hexa.append("0123456789ABCEDF"[digito])

También tenemos que reducir num, eliminado los cuatro últimos dígitos. Eso se hace con un shift a la derecha por cuatro bits:
num = num >> 4

Al terminar la iteración tenemos una lista de digitos hexadecimales en el orden inverso. Usamos [::-1] para invertir la lista y luego juntamos todos los caracteres.
Método alternativo
También puedes hacer
valor = f"{num:x}"

para llegar a lo mismo.


text:
Q: C# to XML serialization The following code is throwing an exception called "Object reference not set to an instance of an object." suggest required changes
public List<WorkspaceRootObject> wrObj=null;
        public RootObject rtObj=new RootObject();
        Hashtable ht = new Hashtable();
        Dictionary<int, Object> d = new Dictionary<int, Object>();
string contextUrl = txtRegServerLocation.Text + "/servlet/rest/v1/contexts";
                    Console.WriteLine("Url is:\n" + contextUrl);
                    HttpWebRequest contextReq = (HttpWebRequest)WebRequest.Create(contextUrl);
                    NetworkCredential ncr = new NetworkCredential("testuser1", "testuser1");
                    CredentialCache creCache = new CredentialCache();
                    creCache.Add(new Uri(contextUrl), "Basic", ncr);
                    contextReq.Credentials = creCache;
                    HttpWebResponse contextRes = (HttpWebResponse)contextReq.GetResponse();
                    Stream str = contextRes.GetResponseStream();
                    StreamReader strReader = new StreamReader(str);
                    string finalContextRes = strReader.ReadToEnd();
                    Console.WriteLine("response is...\n" + finalContextRes);

                    //Deserialzing Json

                     rtObj = JsonConvert.DeserializeObject<RootObject>(finalContextRes);
                    foreach (Item i in rtObj.items)
                    {
                        // Console.WriteLine("{0}",i.id);
                        string curId = i.id;
                        showWorkSpace(curId);
                    }
                    insertRecordInTable();
                    //DataGridViewRow row = new DataGridViewRow();
                    //erverDetails.Rows.Add(imageList1.Images[0], txtRegServerName.Text,txtRegServerLocation.Text);
                }
                else
                {
                    MessageBox.Show("Invalid Url please provide full url");
                }
            }
            catch (WebException ex)
            {
                using (Stream stream = (Stream)ex.Response.GetResponseStream())
            {
                using (var reader = new StreamReader(stream))
                {
                    Console.WriteLine(reader.ReadToEnd());
                }
            }
            }

Catch block is throwing this exception System.NullReferenceException was unhandled ?

A: Thoughts
Looking at your code, although there are lots of improvements and error checking that can be done, and a few places that could lead to null exceptions, the most likely (especially if it is repeating) is the fact that JsonConvert.DeserializeObject<T>() will return null if the string does not match the object type T or is badly formatted.
Without more information such as the line of error this crashed on and the RootObject code and the string returned from string finalContextRes = strReader.ReadToEnd(); it is impossible to answer in any more detail or confidence.
Proposed Answer
Without further details, it is save to assume your issue is these lines:
rtObj = JsonConvert.DeserializeObject<RootObject>(finalContextRes);
    foreach (Item i in rtObj.items)

Because rtObj is null (due to JSON string not matching the RootObject model, the rtObj.items is the position that throws the null exception.
To fix this you need to check the JSON string against your root object class and ensure they match. You can paste your JSON string here and see if your class matches up as expected.

I would also highly recommend adding error checking and exception catching where exceptions are known. So at least do if (rtObj == null) { Console.WriteLine("Failed to deserialiez root"); return; }, and then for places that could throw exceptions wrap them in try/catch blocks with specific error messages and handling


text:
Q: Searching and Sorting Using MySQL Inner Join I guess I can't explain my problem properly. I want to explain this to you with a picture.
Picture 1
In the first picture you can see the hashtags in the trend section. These hashtags are searched for the highest total and it is checked whether the date has passed. If valid data is available, the first 5 hashtags are taken.
Picture 2
In the second picture, it is checked whether the posts in the hashtag are in the post, if any, the oldest date value is taken, LIMIT is set to 1 and the id value from the oyuncular table is matched with sid. Thus, the name of the person sharing can be accessed.
Picture 3
My English is a little bad, I hope I could explain it properly.
SELECT
    social_trend.hashtag,
    social_trend.total,
    social_trend.tarih,
    social_post.sid,
    social_post.tarih,
    social_post.post,
    oyuncular.id,
    oyuncular.isim
FROM
    social_trend
INNER JOIN
    social_post
ON
    social_post.post LIKE '%social_trend.hashtag%' ORDER BY social_post.tarih LIMIT 1
INNER JOIN
    oyuncular
ON
    oyuncular.id = social_post.sid
WHERE
    social_trend.tarih > UNIX_TIMESTAMP() ORDER BY social_trend.total DESC LIMIT 5

A: YOu should use a sibquery
and add a proper join between subqiery and social_trend
(i assumed  sing both sid)
 SELECT
    social_trend.hashtag,
    social_trend.total,
    social_trend.tarih,
    t.sid,
    t.tarih,
    t.post,
    oyuncular.id,
    oyuncular.isim
FROM     (
select social_post.*
from social_post
INNER JOIN social_trend  ON  social_post.post LIKE concat('%',social_trend.hashtag,'%' )
ORDER BY social_post.tarih LIMIT 1
) t
INNER JOIN social_trend ON social_trend.hashtag= t.post
INNER JOIN  oyuncular ON  oyuncular.id = t.sid
WHERE
    social_trend.tarih > UNIX_TIMESTAMP() ORDER BY social_trend.total DESC LIMIT 5

but looking to your new explanation and img  seems you need
 SELECT
    t.hashtag,
    t.total,
    t.tarih_trend,
    t.sid,
    t.tarih,
    t.post,
    oyuncular.id,
    oyuncular.isim
FROM     (
    select social_post.sid
        , social_post.tarih
        , social_post.post
        , st.hashtag
        , st.total
        , st.tarih tarih_trend
    from social_post
    INNER JOIN (
        select * from social_trend
        WHERE social_trend.tarih > UNIX_TIMESTAMP()
        order by total DESC LIMIT 5
    ) st ON  social_post.post LIKE concat('%',st.hashtag,'%' )
    ORDER BY social_post.tarih LIMIT 5
) t
INNER JOIN  oyuncular ON  oyuncular.id = t.sid