Stats on percentage of desktop and laptop computers with high resolution monitors

Question: Mobile phones and tablets nowadays all come with high-resolution (pixel density) screens. New Apple computers come with at least 218 pixels/inch.
– Does anyone know the percentage of desktop and laptop computer monitors currently (2022) being used that have a high resolution?
– The reason behind the question is among other how much one should care about selecting fonts that are optimized for low resolution screens (think Verdana, Georgia, etc) or not care that much at all about fonts that traditionally have not been recommended for screen use (think high contrast fonts such as Bodoni) today.
With variable fonts you could also fine tune the stroke thickness which could only be seen if you have more pixels.
– Monitors with a high pixel density open potentially up for a UI-design that could contain more detailed interface graphics than before.
Comment: I'm voting to close this question because I don't think monitor resolution statistics is a problem within the scope of UX. Maybe [SuperUser](https://superuser.com/) but I'm not sure.
Comment: I agree that specific monitor usage statistic are out of scope. However, whether or not to consider this kind of hardware differences in font selection feels very on topic IMO
Comment: I'm voting to close this question because I don't think monitor resolution statistics is a problem within the scope of UX.
Answer: I found this resource quite useful.
https://gs.statcounter.com/screen-resolution-stats
You can filter by the different screen resolutions:

Or you could filter by desktop or laptop:

And even by regions and years:
Comment: Thank you for your answer. Screen resolution tells me very little about pixel density. (For example, in the chart above, devices with a resolution about 375xXXX are iPhones, which has a very high pixel density.) I understand that that pixel density depends on the size of the monitor in combination with the graphic card capabilities.


Can I send data from my old Windows 7 to Ubuntu?

Question: I recently downloaded Ubuntu to run side by side by my Windows but Ubuntu only has 10gb of space and Windows has 130gb. Is it possible to send data from my Windows to Ubuntu? because I find Linux better for gaming and I need a lot more space than 10gb to run all those games.
Comment: In Ubuntu, can able to access the partitions of windows by mounting but transferring can do only with external or USB drives which will be efficient way to transfer the data.
Answer: You can access any partition you can access via Windows via Ubuntu (but not the other way around). This includes your system partition.
If you have an external storage device (usb stick, external hard drive), you can copy your data from the Windows partition to that device. Then remove it from the Windows partition (clean trash). After you did so, boot the PC with a live usb stick, launch GParted, decrease the size of the Windows partition, and increase the one of the Ubuntu partition. Then boot Ubuntu and copy the files back from the usb stick / external hard drive.
But remember that things can go wrong when changing partitions. Make a backup in advance, in case for example the power goes down and you're on a computer without backup power supply. Also, depending on your version of Windows, it may fail to boot after you played with the partitions. But this can be solved pretty easily by inserting the Windows DVD.


SQL Server: reset identity on any delete action

Question: Let's take a simple example. There's a table named test:

Now I'm gonna delete some data without reset the identity log:

When I insert new data, the new id will be 7:

I'd like that on every delete query the DBCC CHECKIDENT function was automatically called to reset the identity on table test. So, when I'd insert 'Purple', its id would be 4. Is there a way to do this?
Comment: If you do this, you may want to find a way to block other processes.  For example, the query could acquire an application lock or a table lock on the table.  Without any concurrency protection, someone could insert a new row in between the time you looked for the current maximum identity and the point at which you are going to set the new identity value.
Comment: If you care about the *numerical* values of an identity column, you're probably doing something wrong. You should just treat them as opaque binary blobs that happen to fit in numeric columns. Anything else is setting yourself up for pain in the future.
Comment: why you want do that?  That work if you delete the last ones, but what happen if you delete `2` ... you reset to `2` and then will get duplicate key error when try to insert `3`.
Comment: Don't get hung up on gaps in an identity value. It is normal and expected. What you want to happen if you delete ID 4?
Comment: Juan is right. But, supposing you check first if it was the last value that was deleted, you can achieve your goal using a trigger.
Comment: No, i'd like the identity log would be reset to the last (max) id, not to the one that was just deleted.
Answer: You can create a DELETE TRIGGER and then use
SQL Fiddle Demo
CREATE TRIGGER sampleTrigger
    ON dbo.test
    FOR DELETE
AS
    DECLARE @maxID int;

    SELECT @maxID = MAX(id)
    FROM test;

    DBCC CHECKIDENT (test, RESEED, @maxID);
GO

So next insert will use 4.

But again this isnt something you should really be worry about it
Comment: What would happen when multiple rows affected while deleting
Comment: @StackUser Not sure if you saw the fiddle demo, but there I delete `where id >3` and still id reset to max id value.


Find empty folders in subfolders with certain name?

Question: All the subfolders have the same folders with same names.
I want to check which subfolders named dbound are empty in all the directories inside a main folder as in the example.
About half of the folders with that name are empty. How to find out which?
I tried this:
from glob import glob

for i in  glob(r'C:\Users\user\Desktop\files1' + '**/*/*/*', recursive=True):
    print (i)

    if os.listdir(i) == []:
        print ("Empty")

Answer: glob can return directories and files. Check if entry is a directory before testing it. And to test the name use os.path.basename
if os.path.basename(i) == "dbound" and os.path.isdir(i) and not os.listdir(i):
    print ("{} is Empty".format(i))

I would prefer os.walk (at least directories are filtered out, and files are ignored):
for root,dirs,files in os.walk(r'C:\Users\user\Desktop\files1'):
   for d in dirs:
       if d=="dbound" and not os.listdir(os.path.join(root,d)):
           print("empty dbound: {}".format(os.path.join(root,d)))

Both solutions work, but somehow are unsatisfactory because you're scanning the disk twice (glob/os.walk and os.listdir)
To avoid scanning twice, you'd have to store the result in dictionary/defaultdict and count the files in each dir, filter the ones with no file in it. More complex. Do it only if disk performance matters.
Comment: check for folders named `dbound` .How do I do that?
Comment: sorry, missed a part of your question. Edited
Comment: So I do the glob line as it is and then put this code? I tried it but doesn't return anything although they are empty dbound folders?Keep in mind that the dbound folders are subfolders.
Comment: try the `os.walk` version too it's cleaner and works on old versions of python (more portable). I think there's a typo in the path: `glob(r'C:\Users\user\Desktop\files1' + '**/*/*/*', recursive=True):` makes your pattern `r'C:\Users\user\Desktop\files1**/*/*/*'`


find all roots of the system of 2 equations with scipy.optimize

Question: scipy.optimize.root is finding only one root (as I tried), to which it converges faster, as it is closer to initial guess. In order to solve a bounded [-4;4] system of equations I could create only cycle to find ALL roots - with initial visual estimation of init_guess at a glance for further optimization (in cycle):
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import root

x = np.linspace(-4,4,100)

def fs(y):
    return  (2*y**2+3)
def fd(x):
    return x**3+x**2-6*x+3

def obj(x):
    return fs(x)-fd(x)

# visualize approximate bounds to define init_guess for further root func
plt.plot(  x, fs(x), 'r-', x, fd(x), 'b-')
plt.show()

############## optimize
roots=[]

def find_root( guess):
    res = root(obj, [guess, ],  method='krylov',    tol=1.4e-100)
    if res.success== True:
        roots.append([round(res.x[0],2), round(fd(res.x[0]),2)])
    else:
        res.message
        exit

# cycle:  List Comprehension -
[ find_root(x) for x in np.array([4.,1.,-1.5], dtype=float) ]

############## plot
r= np.array(roots).T; print(r)

import pandas as pd
df= pd.DataFrame(r, {'x': r[1], 'y': r[0]}).T; print(df)
print(df)

plt.plot(df['x'], df['y'], 'yo', x, fd(x), 'r-', x, fs(x), 'b-', ms=20, )
plt.show()

Q: is there in scipy any method/function that allows to avoid cycle usage to find all roots & to avoid visual estimation to choose the best initial guesses -- in order to find ALL ROOTS programmically ??
Comment: Are you only dealing with polynomials?
Comment: Not exactly, equations are just for the example. But concerning trigonometric equations, I suppose, [periodicity](https://stackoverflow.com/questions/58477974/finding-all-roots-of-a-transcendental-equation-in-python-eg-bound-state-soluti) can matter. Just wanted to provide non-periodic example . But frankly speaking, would prefer some matrix example (like `A*A^T `) or to work with differential equations `dy/dx`
Comment: Does my solution answer the question? It appears that one of the answers in the periodicity link you shared has a similar approach (though they don't have to round since they're using sympy).
Comment: yes, it does answer
Comment: off: for periodicity I'm just interested sometimes only  in `y = a * np.sin(b*x/2 + c)   +m` for modelling, but still will need some robust objective func for outliers (am confused yet)... perhaps in another Q once..
Answer: Assuming you will not always be using polynomials, you can avoid manually looping by having scipy.optimize.root find all the roots for a large number of initial guesses. This will result in duplicates, but you seem to be rounding already, so you can just round the values and use np.unique.
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import root

def fs(y):
    return (2*y**2+3)

def fd(x):
    return x**3+x**2-6*x+3

def obj(x):
    return fs(x)-fd(x)

x = np.linspace(-4, 4, 100)
res = root(obj, x)
xroots = np.unique(res.x.round(2))
yroots = fd(xroots)

r = np.vstack((xroots, yroots))
print(r)

plt.plot(x, fs(x), x, fd(x))
plt.plot(xroots, yroots, ".k", zorder=2)
plt.show()

Comment: yes, I thought about `np.unique` , just wanted to show the shorter code, because `unique` still doesn't solve the problem of cycle, I thought, but you're right: multiple x as param to objective func together with `unique` gives what I wanted. Thanks for such simple solution (I previously made everything overcomlicated for my shame)
Comment: @JeeyCi If this answers your question then you can accept it.


Windows/Unbuntu - stuck at Grub menu

Question: I have Windows 10 installed, and Ubuntu installed on a USB where I can dual boot.  Typically, when starting the computer I'd see the standard "Purple Screen"  where I can choose to boot in Windows or Ubuntu.
Recently, when I started up my computer it launched the GRU GRUB version 2.02 screen with the grub> prompt.  Odd, but if I typed exit, it'd boot straight to Windows.
In an effort to get the Purple Screen back, in Windows I followed this tutorial and in the command prompt typed two commands: powercfg /h off and then bcdedit /set {bootmgr} path \EFI\ubuntu\grubx64.efi...
And now, when I do exit at the grub line, a message shows:

Secure Boot Violation
Invalid signature detected. Check Secure Boot Policy in Setup

Looking at various answers, including this one, in the Grub menu my grub> ls command returns:

(proc) (hd0) (hd0,msdos1) (hd1) (hd1,gpt[5,4,3,2,1]) (hd2) (hd2,gpt[5,4,3,2,1])

When I run ls (hd0,msdos1), this returns:
Partition hd0,msods1: No known filesystem detected - Partition start at ...
When I do ls (hd1,gpt2) it returns efi.  But ls (hd1,gpt2)/efi returns ubuntu/ Microsoft/ Boot/ dell which is not what I'm looking for correct?
Where can I find the correct drive to set prefix?
Or is there something else I'm missing to just get back to Windows?
Answer: Create a LiveUSB from "boot-repair" (https://sourceforge.net/projects/boot-repair-cd/files/) , it will find your OS and will redo a correct installation of your old Grub-Menu
It works in almost all cases
https://help.ubuntu.com/community/Boot-Repair
Comment: if your Ubuntu is also on a USB drive, and you remove it... boot-repair can't see it , so cant repair the Grub :D  but with a USB boot HDD be warning to use the "UUID=" in the /etc/fstab  otherwise without this, the location and therefore the boot logic may "change", depending on the usb port used, and the order of insertion of the USBs ... UUID refers to a physical ID of the partition, not its location
Comment: You must understand that Grub uses 2 things to function, 1 / a part which is installed on one of the partitions, this part does only one thing, go look for the info of the part (2 /) the 2 / it is present on your Ubuntu partition (/ boot / grub), so if this HDD is not present or if it has changed location, well the "1 /" part is lost and do not know where to find the info ... reason of the "grub>"
Comment: if you are using a "fixed" windows on your machine, and you have the Linux on USB, it is preferable not to use Grub as a boot loader, but to leave this management to Win 10 (which knows how to boot a Linux partition from its boot menu) a boot loader will live better on a no-removable disk
Comment: if the front door of your apartment / house is moved or worse, is not always present, how are you going to get home? (through the window) Grub is the door to your OS;)
Comment: I downloaded the ISO, flashed it to a USB with Universal USB Installer (the only working PC I have now is an old Vista machine), and plugged it in to my laptop (the Ubuntu USB is still in as well).  When I boot - it still goes to the Grub screen and `boot-repair` command can't be found.  What am I not doing?  In the BIOS, Boot Option #1 is "Ubuntu", second is "Windows Boot Manager".
Comment: Ah, got it. I removed the Ubuntu USB, put in the LiveUSB - started computer, F12 for BIOS options and booted from that USB and ran the repair program.  However, when I start the computer, Grub shows up and still says "Invalid Signature Detected: Check Secure Boot Policy"  Edit: Errm, I went to BIOS, selected a separate HDD Windows thing, and Dell launched some repair thing which seemed to have also worked :)

Windows/Unbuntu - stuck at Grub menu


Could not create a service principal with the right permissions

Question: I'm trying to run command:
az acs create --orchestrator-type kubernetes --resource-group myResourceGroup --agent-count 1 --name  myK8SCluster
--generate-ssh-keys

Which should generate principal and then kubernetes cluster.
But there is error:
Could not create a service principal with the right permissions. Are you an Owner on this project? Deployment failed. Correlation ID: 1e8e87ee-f01e-4394-8356-cc4956b44b5e. {   "error": {
    "code": "BadRequest",
    "message": "The Service Principal in ServicePrincipalProfile could not be validated. Please see https://aka.ms/acs-sp-help for more details. (The client 'ffc0ce03-2ba5-46e7-b0dd-99a7980da24b' with object id 'ffc0ce03-2ba5-46e7-b0dd-99a7980da24b' does not have authorization to perform action 'Microsoft.Authorization/roleAssignments/read' over scope '/subscriptions/b9a29aba-5bcd-45dd-99e5-8971de90d595/resourceGroups/myResourceGroup/providers/Microsoft.Authorization'.)" } }

I have administrator role for my azure account, my directory role is Global Administrator and I'm the only person using this azure account.
I have trying deleting contents of .azure folder to no avail. I'm on Windows 10.
Answer: Your login account should has Owner or Contributor role for your subscription.
You could check it on Azure Portal.

Also, you could give sp   myK8sCluster  Contributor role and check again.
Comment: It seems I'm owner (and Service Administrator):

http://www.screenshot.link/upload/up/bfj.png

So I should be able to just use --generate-ssh-keys.
Comment: You use this account `email@example.com` to login your Azure account?
Comment: Yes. That's my primary account. It's under Visual Studio Dev Essentials subscription.
Comment: Could you see sp `myK8SCluster` in subscription?
Comment: Also, your user has `Global Administrator` permission in your AD. Like this screenshot?  https://imgur.com/a/EXA16
Comment: Subscriptions -> Visual Studio Dev Essentials -> IAM -> Add.
There is only one user (me).
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/163305/discussion-between-shengbao-shui-msft-and-lukasz-baran).
Comment: I'm getting the same error and can't get it working following the [chat](http://chat.stackoverflow.com/rooms/163305/discussion-between-shengbao-shui-msft-and-lukasz-baran). I am global admin and can't get `--generate-ssh-keys` to create the correct service principal
Comment: Your account is a Microsoft account, you need create an Azure AD account firstly,


How to include properties from external file to hibernate.cfg.xml using spring in a standalone app(jar)

Question: I need to be able to store database config properties in an external file that well be used by the application jar and include it  in form of jstl expressions. (like : ${password} etc.)?
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>
 <property name="hbm2ddl.auto">update</property>
  <property name="dialect">org.hibernate.dialect.DB2Dialect</property>
  <property name="connection.url">jdbc:db2://localhost:50001/svntools</property>
  <property name="connection.username">root</property>
  <property name="connection.password">root</property>
  <property name="connection.driver_class">com.ibm.db2.jcc.DB2Driver</property>
-->

     <property name="show_sql">true</property>

 <mapping class="fr.gouv.education.sirhen.svnreporting.persistance.eo.BrancheEntity"/>
 <mapping class="fr.gouv.education.sirhen.svnreporting.persistance.eo.RevisionEntity"/>
 <mapping class="fr.gouv.education.sirhen.svnreporting.persistance.eo.ProjectEntity"/>
 <mapping class="fr.gouv.education.sirhen.svnreporting.persistance.eo.StatistiqueEntity"/>
 <mapping class="fr.gouv.education.sirhen.svnreporting.persistance.eo.DomaineEntity"/>

 </session-factory>

</hibernate-configuration>

SpringConfig.xml file
<?xml version="1.0" encoding="UTF-8"?>

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="projectDAO" class="fr.gouv.education.sirhen.svnreporting.persistance.impl.ProjectDAOImpl">
</bean>
<bean id="reportDAO" class="fr.gouv.education.sirhen.svnreporting.persistance.impl.ReportDAOImpl" />
<bean id="brancheDAO" class="fr.gouv.education.sirhen.svnreporting.persistance.impl.BrancheDAOImpl" />

<bean id="domaineDAO" class="fr.gouv.education.sirhen.svnreporting.persistance.impl.DomaineDAOImpl" />

<bean id="svnKitDa"
    class="fr.gouv.education.sirhen.svnreporting.domaine.DA.impl.SVNKitDAImpl" />
<bean id="RevisionServicesBean"
    class="fr.gouv.education.sirhen.svnreporting.domaine.impl.RevisionsServicesImpl">
    <property name="svnKitDa" ref="svnKitDa" />
    <property name="brancheDAO" ref="brancheDAO" />
</bean>

<bean id="parser" class="fr.gouv.education.sirhen.svnreporting.transvers.utils.ParserImpl" />

<bean id="reportServices"
    class="fr.gouv.education.sirhen.svnreporting.service.impl.ReportServicesImpl">
    <property name="reportDAO" ref="reportDAO" />
    <property name="brancheDAO" ref="brancheDAO" />
    <property name="projectDAO" ref="projectDAO" />
    <property name="parser" ref="parser" />
</bean>
<bean id="projectServices"
    class="fr.gouv.education.sirhen.svnreporting.service.impl.ProjectServicesImpl">
    <property name="projectDAO" ref="projectDAO" />
</bean>

<bean id="domaineServices"
    class="fr.gouv.education.sirhen.svnreporting.service.impl.DomaineServicesImpl">
    <property name="domaineDAO" ref="domaineDAO" />
</bean>

<bean id="generator"
    class="fr.gouv.education.sirhen.svnreporting.domaine.generatorDocServices.impl.GeneratorDocServiceImpl" />

The class that use the session:
package fr.gouv.education.sirhen.svnreporting.persistance.impl;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;

import fr.gouv.education.sirhen.svnreporting.persistance.ProjectDAO;
import fr.gouv.education.sirhen.svnreporting.persistance.eo.ProjectEntity;

public class ProjectDAOImpl implements ProjectDAO {

    private static final String Location_Hibernate =
            "resources/hibernate.cfg.xml";
    private SessionFactory sessionFactory;

     public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public void addProject(ProjectEntity project) {
        File hibernatePropsFile = new File(Location_Hibernate);
         Session session=new Configuration().configure(hibernatePropsFile).buildSessionFactory().openSession();
           Transaction t=session.beginTransaction();
           session.saveOrUpdate(project);
           t.commit();
           session.close();
    }

    public List<ProjectEntity> getProjects() {
        File hibernatePropsFile = new File(Location_Hibernate);
         Session session=new Configuration().configure(hibernatePropsFile).buildSessionFactory().openSession();
           Transaction t=session.beginTransaction();

          List<ProjectEntity> projects= session.createCriteria(ProjectEntity.class).list();
           t.commit();
           session.close();
           return projects;
    }

    public List<String> getProjectsNames() {
        File hibernatePropsFile = new File(Location_Hibernate);
         Session session=new Configuration().configure(hibernatePropsFile).buildSessionFactory().openSession();
           Transaction t=session.beginTransaction();

          List<ProjectEntity> projects= session.createCriteria(ProjectEntity.class).list();
           t.commit();
           session.close();
           List<String> ProjectsNames=new LinkedList<String>();
           for( ProjectEntity projet : projects)
           {
               ProjectsNames.add(projet.getName());
           }
           return ProjectsNames;
    }

}

Comment: Hi @Yasser Malek, your ask is not clear enough but still as per my understanding i can provide you an answer
Comment: am developing a standalone app (executable jar) and I want to be able to make db connection info defined in hibernate.cfg parametred from outside the jar using a propertis file
Comment: I will update my answer accordingly you can follow that
Comment: I have edited my question so that you can relate
Comment: you can see that i have updated my answer for use the property file as per your requirement. You can use it in your dao while you using session factory.
Answer: An alternate approach is you can directly use hibernate.properties file instead of hibernate.cfg.xml.
But if you want to use another file then hibernate.properties file then please refer link given below:
How to read database configuration parameter using properties file in hibernate
Still, if you want to read properties file separate then you can read with normal java code to read properties file from class path or relative file path and set those properties on environment using ConfigurableEnvironment  of spring.
Edited Answer
If you want to read properties file outside of your application (jar) then you can read properties file programmatically from relative file path.
I have provided one answer earlier and that was the same situation for read properties file, You can follow my Edited answer from there.
Spring Boot embedded Tomcat not loading external properties file in ApplicationListener
Now You can use System properties or Environment properties to store properties loaded earlier from relative file path and then it will available any where in the application.
@Autowired
private ConfigurableEnvironment  myEnv;

or
System.setProperty ("propertyName", "propertyValue");


SQLKata Multiple From Sub Selects

Question: I am trying to write the following statement is my desired output:
SELECT TABLE1.COLUMN_1
  FROM (SELECT '0' AS COLUMN_1 FROM DUAL) TABLE1,
       (SELECT '0' AS COLUMN_1 FROM DUAL) TABLE2
 WHERE TABLE1.COLUMN_1 = TABLE2.COLUMN_1;

This is the code SQLKata:
<PackageReference Include="SqlKata" Version="3.2.3" />
<PackageReference Include="SqlKata.Execution" Version="3.2.3" />

using SqlKata;
using SqlKata.Execution;

var q1= new Query("DUAL").Select("'0' AS COLUMN_1");
var q2= new Query("DUAL").Select("'0' AS COLUMN_1");
var q3= new Query().From(q1, "table1")
                   .From(q2, "table2")
                   .Where("table1.COLUMN_1","table2.COLUMN_1")
                   .Select("table1.COLUMN_1")
                   .FirstOrDefault<string>();

This results in:
SELECT TABLE1.COLUMN_1
  FROM (SELECT '0' AS COLUMN_1 FROM DUAL) TABLE2
 WHERE TABLE1.COLUMN_1 = TABLE2.COLUMN_1;

It looks like it the second From overwrites the first from.
Another example:
var phones = new Query("Phones");
var laptops = new Query("Laptops");

var query = new Query().From(phones, "P").From(laptops, "L")

Results, notice Phones is not in the query:
SELECT
  *
FROM
  (
    SELECT
      *
    FROM
      [Laptops]
  ) AS [L]

Comment: Please give more details and what is your desired output.
Comment: Dear EJD would u please let me know the name of package that you are using for building query? which package does  belong to ?
Answer: This is basically an inner join query, so you can rewrite it like this one:
SELECT TABLE1.COLUMN_1
  FROM (SELECT '0' AS COLUMN_1 FROM DUAL) TABLE1 JOIN
       (SELECT '0' AS COLUMN_1 FROM DUAL) TABLE2
 ON TABLE1.COLUMN_1 = TABLE2.COLUMN_1;

and this is the equivalent syntax in SqlKata
var q1 = new Query("DUAL").Select("'0' AS COLUMN_1");
var q2 = new Query("DUAL").Select("'0' AS COLUMN_1");

var query = new Query()
    .From(q1, "table1")
    .Join(
        q2.As("table2"), // note how the As() method is used to alias this sub query
        j => j.On("table1.COLUMN_1","table2.COLUMN_1")
    )
    .Select("table1.COLUMN_1");

SQLKata Multiple From Sub Selects


Simple rings/algebras fail to be division rings/algebras because of zero-divisors?

Question: Is the following statement true/false?

For a non-trivial ring $R$, and a maximal modular ideal $M\subset R$, if $M$ is not one-sided maximal, then the non-invertible elements of the quotient $R/M$ are zero-divisors.

I know if an ideal is left-maximal or right-maximal, then the quotient must be a division ring. But want to understand why this fails when it's only maximal. Do simple rings/algebras fail to be division rings/algebras only because of zero-divisors? I'm aware of this answer, but that only shows an example. Thanks in advance.
Comment: I'm trying to figure out what "maximal ideal not one-sided maximal" is supposed to mean. You're saying it's maximal as a two-sided ideal, not as a one-sided ideal?  And you mean it's modular both as a left and a right ideal?
Comment: @rschwieb Yes. That's what I mean. So $M$ is two-sided maximal. But there is a larger proper one-sided ideal containing $M$. And yes, it is two-sided modular, so the quotient is unital.
Answer:
then the non-invertible elements of the quotient /
are zero-divisors.

No, it doesn't follow. For example, the Weyl algebra is a ring (with identity) without nonzero zero divisors, and it is also a simple ring.  The zero ideal is maximal (and modular of course, as are all ideals in a ring with identity) but not maximal as a left or right ideal.
Comment: Finding, for a given ring, a way to describe the noninvertible elements is going to be as hard as describing the invertible elements. In general, there is no magic expression for either.
Comment: [DaRT query](https://ringtheory.herokuapp.com/search/results/?H=3&H=8&L=63l) for simple domains that aren't division rings.
Comment: Thanks. But then is it possible to modify the OP and makes it correct? Maybe it's true if it's changed to something like, "the non-invertible elements of the quotient is of the form $a+\alpha$, where $a$ is invertible but $\alpha$ is a nonzero zero-divisor"? Or maybe some other form? There must be some relations to zero divisors?
Comment: "$a+\alpha$ where $a$ is invertible and $\alpha$ is a nonzero zero divisor" surely won't work: in the example given above there are no choices for $\alpha$.  In a ring where nonzero zero divisors don't exist, your quest to associate them with elements outside the maximal ideal is going to be fruitless.
Comment: Thanks. Can I understand it as this? We can always think of a ring as a free algebra quotient-ing out some relations. So if the ring has a pair of invertible elements $(a,b)$ such that $ab=ba=1$, it is quotient of the free algebra of some generators quotient out that relations. Similarly if there're zero-divisors $ab=0$, then the ring is the quotient of some free algebra over that relation. So it's always possible to start from some free algebra and choose some relations to quotient out, producing invertibles or zero-divisors. And there's no restriction whatsoever?
Comment: I mean, maybe not free algebra. But a "free ring".
Comment: @user760 Yes: at the very worst, you can treat each individual element of your ring as a free generator in the free ring. If you map these generators back into your old ring with the obvious map, the kernel necessarily contains all the relations needed to describe your original ring.
Comment: So the real efforts should be about understanding the ideals and one-sided ideals of free algebras/rings. I still have a question though. In a free algebra/ring, it seems at no step did we define a "unit". So does every free algebra/ring automatically admits a two-sided modular ideal, and quotient-ing that ideal out generates a unital ring? Maybe I misunderstood something. I mean, you could say the "empty word" is a unit when concatenating with all the other words. But it seems the "empty word" isn't an element?
Comment: @user760 Well I have never dealt with nonunital free algebras, but yes, I imagine that including the empty word would be a way to give it an identity. It could also be defined using just the generators and finite sums of their finite products, without identity too, I suppose.
Comment: If the free algebra we start with is always unital, then we can't produce non-unital algebras after quotient-ing out any ideals. Right?
Comment: @user760 Yes, fair enough.  I guess you do need the unitless construction.


TypeError: list indices must be integers or slices, not NoneType

Question: I have some troubles with the Type Error (TypeError: list indices must be integers or slices, not NoneType)
I just want to do a little hash table with linear probing in python. Therefore I used to make an insert method, a find method and a hash method so far. I have problems with my insert method.
This is my code
    def insert(self, key):

        index = self.hash(key)
        count = 0
        if self.table[index] == None or self.table[index].getValue() == "DELETED":
            self.table[index] = key
            return count + 1
        else:
            inserted = False
            while inserted != True:
                index += 1
                count += 1
                if index == self.size:
                    index = 0
                if self.table[index] == None or self.table[index].getValue() == "DELETED":
                    self.table[index] = key
                    return count

The problem are these two lines
if self.table[index] == None or self.table[index].getValue() == "DELETED":
What should I do?
I need to compare my table index with None.
Has anybody an idea?
Comment: what is `table` ?
Comment: Is `self.table` a list? You can use `None` as a key for dictionaries, but it's not a valid list index.
Comment: Can you please paste your `self.hash` function here.
Comment: from my `def __init__(self, size = 11) ` method `self.table = [None] * self.size` so table is going to be my hashtable
Answer: It looks like your self.hash function is returning None. Since the value of index is None it is not able to find the value in list self.table. Can you write the hash function as well?
Comment: yes, I just had a little mistake in my hash function. Thank!


Why did Bowser kidnap Cappy's sister Tiara?

Question: In Super Mario Odyssey, Bowser kidnaps both Princess Peach and Cappy's sister Tiara. While Bowser kidnapping Peach is to be expected, I don't understand why he kidnapped Cappy's sister.
Tiara doesn't display any special capturing powers like Cappy, nor does Bowser seem to have any grudge against the Cap Kingdom. The only thing kidnapping Tiara does is give Cappy a reason to team up with Mario.
Is it ever explained why Bowser kidnapped Cappy's sister Tiara?
Answer: The storyline of the game is "Bowser steals the fanciest things for his wedding to Peach"; Tiara is presumably a high-value wedding prize for his bride to be. In the next three levels (after Cascade), he steals a dress, bouquet, and ring for Peach was well. The tiara was just the first step in his quest to deck her out in the best duds available.
Source: wedding items section

Why did Bowser kidnap Cappy’s sister Tiara?


Alternative proof for $\zeta\left(2,\frac14\right)=\psi^{(1)}\left(\frac14\right)=\pi^2+8G$

Question: On the German Wikipedia page of the Hurwitz Zeta Function I have come across the following formula

$$\zeta\left(2,\frac14\right)~=~\pi^2+8G\tag1$$

Where $G$ is Catalan's Constant. Even though I was able proving $(1)$ I am dissatisfied with my own attempt since it is heavily relying on several relatives of the Riemann Zeta Functions. However, first of all I will present my own solution. Starting with the series representation of $\zeta(2)$ we get
$$\begin{align*}
\zeta(2)=\sum_{n=1}^\infty \frac1{n^2}&=\frac1{1^2}+\frac1{2^2}+\frac1{3^2}+\sum_{n=1}^\infty\frac1{(4n)^2}+\frac1{(4n+1)^2}+\frac1{(4n+2)^2}+\frac1{(4n+3)^2}\\
&=\frac1{16}\zeta(2)+\sum_{n=0}^\infty \frac1{4(2n+1)^2}+\frac1{(4n+1)^2}+\frac1{(4n+3)^2}\\
&=\frac1{16}\zeta(2)+\frac14\lambda(2)+\sum_{n=0}^\infty \frac1{(4n+1)^2}+\frac12\left[\frac1{(2n+1)^2}-\frac{(-1)^n}{(2n+1)^2}\right]\\
&=\frac1{16}\zeta(2)+\frac14\lambda(2)+\frac12[\lambda(2)-\beta(2)]+\sum_{n=0}^\infty \frac1{(4n+1)^2}\\
\therefore~\sum_{n=0}^\infty \frac1{(4n+1)^2}&=\frac{15}{16}\zeta(2)-\frac34\lambda(2)+\frac12\beta(2)\\
&=\frac{15}{16}\zeta(2)-\frac34\frac34\zeta(2)+\frac12 G\\&=\frac1{16}\pi^2+\frac12 G
\end{align*}$$

$$\therefore~\zeta\left(2,\frac14\right)~=~\sum_{n=0}^\infty\frac1{\left(n+\frac14\right)^2}~=~\pi^2+8G$$

Where $\zeta(s)$ dnotes the Riemann Zeta Function, $\lambda(s)$ the Dirichlet Lambda Function, $\beta(s)$ the Dirichlet Beta Function. Moreover the relation $\lambda(s)=(1-2^{-s})\zeta(s)$ and the well-known values $\zeta(2)=\frac{\pi^2}6$ and $\beta(2)=G$ were used.

I am suspicious about the heavy usage of the whole Zeta Function machinery and I am curious if there exists a shorter and more elegant way of proving $(1)$?

Thanks in advance!
EDIT
As Zacky pointed out within the comments this special value of the Hurwitz Zeta Function can also be interpreted as a particular value of the Trigamma Function since in general we got a the following series expansion of the Polygamma Function
$$\begin{align*}
\psi^{(n)(z)}&=(-1)^{n+1}n!\sum_{k=0}^\infty\frac1{(z+k)^{n+1}}\\
&=(-1)^{n+1}n!\zeta(n+1,z)
\end{align*}$$
So for $n=1$ and $z=\frac14$ it directly follows that
$$(-1)^{1+1}(1!)\psi^{(1)}\left(\frac14\right)=\zeta\left(1+1,\frac14\right)\Rightarrow \psi^{(1)}\left(\frac14\right)=\zeta\left(2,\frac14\right)$$
Comment: Isn't this $\psi_1 \left(\frac14\right)$ (trigamma function)? See here: http://mathworld.wolfram.com/TrigammaFunction.html
Comment: @Zacky This is due the more general fact that $$\psi^{(n)}(z)~=~(-1)^{n+1}n!\zeta(n+1,z)$$ which can be shown directly with the series representation of both functions. But thank I you, I have forgotten about this relation.
Comment: I see, so basically the question is to prove that $\psi\left(\frac14\right) =\pi^2 +8G$, right?
Comment: @Zacky Yes and no. Basically it is the same question, yes even though I am more interested in Zeta Functions at the moment.
Answer: We can use the following representation of the digamma function from here, namely:
$$\psi(s+1)=-\gamma+\int_0^1 \frac{1-x^s}{1-x}dx\Rightarrow \psi_1(s+1)=\int_0^1 \frac{x^{s}\ln x}{x-1}dx$$
Above follows since $\frac{d}{dz}\psi(z)=\psi_1{(z)} $, so we can rewrite our desired value as:
$$\psi_1\left(\frac14\right)=\int_0^1 \frac{x^{1/4-1} \ln x}{x-1}dx$$
Notice that $\frac{d}{dx}\left(4x^{\frac{1}{4}}\right)=x^{\frac14-1}$, so we can easily substitute $x^{\frac14}=t\Rightarrow x=t^4$ to get: $$\psi_1\left(\frac14\right)=16\int_0^1 \frac{\ln t}{t^4-1}dt$$
We might already recall that we saw before something similar, $\int_0^1 \frac{\ln x}{1+x^2}dx=-G$, thus let's try to get there.
$$\frac{1}{x^4-1}=\frac12 \frac{(x^2+1)-(x^2-1)}{(x^2+1)(x^2-1)}=\frac12 \left(\frac1{x^2-1}-\frac{1}{x^2+1}\right)$$
$$\Rightarrow \psi_1\left(\frac14\right)=8\int_0^1\frac{\ln t}{t^2-1}dt -8\int_0^1 \frac{\ln t}{t^2+1}dt=\boxed{\pi^2 +8G}$$
I am pretty sure you can prove that the first integral equals to $\frac{\pi^2}{8}$, but here are found many proofs.
Comment: Well done (+1) This is the kind of answer I had in mind while formulating my question. Okay, to be honest I was not thinking about the Trigamma Function since I had forgotten about this relation but anyway thank you.
Comment: ^_^ Now that I think of it, maybe it was more directly to use  this: https://en.wikipedia.org/wiki/Hurwitz_zeta_function#Integral_representation, but I am more familiar with trigamma function than to Hurwitz's Zeta function.
Answer: Inspired by Zacky's comment on the integral representation of the Hurwitz Zeta Function I have found another pretty straightforward way. First we notice that

$$\zeta(s,q)~=~\frac1{\Gamma(s)}\int_0^\infty \frac{t^{s-1}e^{-qt}}{1-e^{-t}}\mathrm dt\tag1$$

Now substitute $s=2$ and $q=\frac14$ followed by $u=e^{-t}$ to get
$$\mathfrak I=\int_0^{\infty}\frac{te^{-t/4}}{1-e^{-t}}\mathrm dt=\int_0^1\frac{u^{1/4-1}\cdot \log(u)}{u-1}\mathrm du$$
And now we are at the same point from where Zacky deduced the right value via well-known integrals. Hence his method was quite elegant I will not repeat his solution but just refer to it. Basically using $(1)$ does not force us to rely on the Trigamma Function but instead leaves us all along with the Hurwitz Zeta Function and some nice integrals.
Answer: We can use the generalization identity
$$\psi^{(n)}(a)=-\int_0^1\frac{x^{a-1}\ln^n(x)}{1-x}\ dx$$
set $n=1$ and $a=1/4$ we get
$$\psi^{(1)}\left(\frac14\right)=-\int_0^1\frac{x^{1/4-1}\ln(x)}{1-x}\ dx$$
which is the same integral @Zacky got.


Is it possible to horizontally add a QTableWidget to a layout?

Question: I have written a piece of code to print questions side by side with a score table. However when trying the present the table using a QHBoxLayout (if run) the table is not presented, but no error is shown. On the other hand, when using QVBoxLayout, it is shown when I run the code.
Is it possible that I could present the table side by side (horizontally) with the question/answer boxes? Would a splitter work as an alternative and, if so, how could I implement that in my code?
My code is as follows:
import sys, os, random
from PyQt4 import QtCore, QtGui
StudentNames = []
StudentScores = []

class StartTest(QtGui.QMainWindow):
    def __init__(self, questions, parent=None):
        global StudentNames
        global StudentScores
        super(StartTest, self).__init__(parent)
        self.stack = QtGui.QStackedWidget(self)
        self.setCentralWidget(self.stack)
        StudentNames.append('Hamzah Akhtar')
        StudentNames.append('Bob Marley')
        StudentNames.append('John Meadows')
        StudentScores.append(int(0))
        StudentScores.append(int(0))
        StudentScores.append(int(0))
        for index, question in enumerate(questions):
            page = Question(question, self)
            page.submit.clicked[()].connect(
                lambda index=index: self.handleSubmit(index))
            self.stack.addWidget(page)
        self.answers = []

    def handleSubmit(self, index):
        page = self.stack.widget(index)
        answer = page.answer.text()
        # validate submitted answer...
        self.answers.append(answer)
        if index < self.stack.count() - 1:
            self.stack.setCurrentIndex(index + 1)

class Question(QtGui.QWidget):
    def __init__(self, question, parent=None):
        global StudentNames
        global StudentScores
        super(Question, self).__init__(parent)
        self.Table = QtGui.QTableWidget()
        self.Table.setRowCount(3)
        self.Table.setColumnCount(1)
        self.Table.setVerticalHeaderLabels(StudentNames)
        self.Table.setHorizontalHeaderLabels(['Scores'])
        self.question = QtGui.QLabel(question, self)
        self.answer = QtGui.QLineEdit(self)
        self.submit = QtGui.QPushButton('Submit', self)
        form = QtGui.QFormLayout()
        form.addRow(self.question, self.answer)
        layout = QtGui.QVBoxLayout(self)
        layout.addLayout(form)
        layout.addWidget(self.submit)
        hlayout = QtGui.QHBoxLayout(self)
        hlayout.addLayout(layout)
        hlayout.addWidget(self.Table)
        self.setLayout(hlayout)

if __name__ == '__main__':
    User = ''
    app = QtGui.QApplication([])
    questions = [
        'What is 5+5?',
        'What is 45+10?',
        'What is 28+47?',
        'What is 22+13?',
        ]
    window = StartTest(questions)
    window.showFullScreen()
    app.exec_()

Answer: You could set a placeholder widget as the central widget. Then add a horizontal layout and add the widgets to that layout.
centralWidget = QtGui.QWidget(self)
self.setCentralWidget(centralWidget)
mainLayout = QtGui.QHBoxLayout(centralWidget)
self.scoreTable = QtGui.QTableWidget(self)
self.scoreTable.setRowCount(len(StudentNames))
self.scoreTable.setColumnCount(1)
self.scoreTable.setVerticalHeaderLabels(StudentNames)
self.scoreTable.setHorizontalHeaderLabels(['Scores'])
for i, score in enumerate(StudentScores):
    item = QtGui.QTableWidgetItem(str(score))
    self.scoreTable.setItem(i, 0, item)

mainLayout.addWidget(self.stack)
mainLayout.addWidget(self.scoreTable)

Complete example: (tested with PySide but should work the same in pyqt)
import sys, os, random
from PyQt4 import QtCore, QtGui
StudentNames = []
StudentScores = []

class StartTest(QtGui.QMainWindow):
    def __init__(self, questions, parent=None):
        global StudentNames
        global StudentScores
        super(StartTest, self).__init__(parent)

        self.stack = QtGui.QStackedWidget(self)
        StudentNames.append('Hamzah Akhtar')
        StudentNames.append('Bob Marley')
        StudentNames.append('John Meadows')
        StudentScores.append(int(0))
        StudentScores.append(int(0))
        StudentScores.append(int(0))
        for index, question in enumerate(questions):
            page = Question(question, self)
            page.submit.clicked[()].connect(
                lambda index=index: self.handleSubmit(index))
            self.stack.addWidget(page)
        self.answers = []

        centralWidget = QtGui.QWidget(self)
        self.setCentralWidget(centralWidget)
        mainLayout = QtGui.QHBoxLayout(centralWidget)
        self.scoreTable = QtGui.QTableWidget(self)
        self.scoreTable.setRowCount(len(StudentNames))
        self.scoreTable.setColumnCount(1)
        self.scoreTable.setVerticalHeaderLabels(StudentNames)
        self.scoreTable.setHorizontalHeaderLabels(['Scores'])
        for i, score in enumerate(StudentScores):
            item = QtGui.QTableWidgetItem(str(score))
            self.scoreTable.setItem(i, 0, item)

        mainLayout.addWidget(self.stack)
        mainLayout.addWidget(self.scoreTable)

    def handleSubmit(self, index):
        page = self.stack.widget(index)
        answer = page.answer.text()
        # validate submitted answer...
        self.answers.append(answer)
        if index < self.stack.count() - 1:
            self.stack.setCurrentIndex(index + 1)

class Question(QtGui.QWidget):
    def __init__(self, question, parent=None):
        super(Question, self).__init__(parent)
        self.question = QtGui.QLabel(question, self)
        self.answer = QtGui.QLineEdit(self)
        self.submit = QtGui.QPushButton('Submit', self)
        form = QtGui.QFormLayout(self)
        form.addRow(self.question, self.answer)
        form.addRow(self.submit)

if __name__ == '__main__':
    User = ''
    app = QtGui.QApplication([])
    questions = [
        'What is 5+5?',
        'What is 45+10?',
        'What is 28+47?',
        'What is 22+13?',
        ]
    window = StartTest(questions)
    window.show()
    # window.showFullScreen()
    app.exec_()

Comment: How could i edit this to update the QTableWidget every time the submit button is clicked? I.e. Everytime the user clicks the submit button, i wanted the program to add 1 to the score. I know how to do that, but the QTableWidget does not refresh?
Comment: I uploaded the code in a new question here: [link](http://stackoverflow.com/questions/23413244/how-would-i-refresh-the-qtablewidget-when-submit-is-clicked)


OpenLayers3 access to UK weather server

Question: I'm trying to get started with OpenLayers3, to get access to weather data from the UK.
Their Datapoint service has a tiling WMTS server. I'm trying to access the radar/precipitation tiles. Receiving '501 - not implemented' errors.

Their Capabilities doc has ServiceTypeVersion OGC WMTS = 1.0.0, so I override the OL default of 1.3.0. The layer name seems fine too.
The OpenLayers setup generates 3 calls to the server, of the form
http://datapoint.metoffice.gov.uk/public/data/inspire/view/wmts?SERVICE=WMS&VERSION=1.0.0&REQUEST=GetMap&FORMAT=image%2Fpng&TRANSPARENT=true&LAYERS=RADAR_UK_Composite_Highres&key=my_key_goes_here&WIDTH=256&HEIGHT=256&SRS=EPSG%3A4326&STYLES=&BBOX=-180%2C-270%2C180%2C90

Repeated here as plain text (note that my API key has been removed from the URL):
http://datapoint.metoffice.gov.uk/public/data/inspire/view/wmts?SERVICE=WMS&VERSION=1.0.0&REQUEST=GetMap&FORMAT=image%2Fpng&TRANSPARENT=true&LAYERS=RADAR_UK_Composite_Highres&key=my_key_goes_here&WIDTH=256&HEIGHT=256&SRS=EPSG%3A4326&STYLES=&BBOX=-180%2C-270%2C180%2C90
In the Capabilities doc, there is an
Operation name="GetTile"
But there's no GetMap. That would explain the 501 error.
But if I try to force 'gettile', it gives a 400 error - bad request.
Answer: You are confused between TileWMS and ol.source.WMTS. The former is for accessing a WMS server, the latter for a WMTS server.

OpenLayers3 access to UK weather server


Beginners Python. Loops and end function

Question: What I am learning is very basic. I have written a short program from a book I am learning from and I wanted to modify it slightly so that you can loop again and use an end function instead of simple answering once and the program ends. This is what I have:
WhatsMyGrady.py
grade=eval(input("Enter the number of your grade (0-100):"))
while grade !="end":
if grade>=90:
    print("You got an A!:)")
elif grade>=90:
    print("You got a B!")
elif grade>=80:
    print("You got a C.")
elif grade>=70:
    print("You got a D...")
elif grade>=60:
    print("you got an F.")
elif grade<59:
    print("You Fail!")
grade=input("select another grade or enter 'end' to quit")

Traceback (most recent call last):
  File "C:\TheseusP&GS\Python\teaching_your_kids_code\what_my_grade.py", line 4, in
    if grade>=90:
TypeError: '>=' not supported between instances of 'str' and 'int'
this is the error im recieveing.
Comment: 1: `grade = int(input("Enter the number of your grade (0-100):"))`, 2: twice condition `grade >= 90`.
Comment: Do **not** use `eval(input(...))`
Answer: You're comparing a string and an int with >=. Instead, do this.
grade=input("Enter the number of your grade (0-100):")
while grade !="end":
    grade = int(grade)
    if grade>=90:
        print("You got an A!:)")
    elif grade>=90:
        print("You got a B!")
    elif grade>=80:
        print("You got a C.")
    elif grade>=70:
        print("You got a D...")
    elif grade>=60:
        print("you got an F.")
    elif grade<59:
        print("You Fail!")
    grade=input("select another grade or enter 'end' to quit")


how would I access this selector using child/parent notation

Question: Hello how would I access the text object using the child parent css selector notation

ie   $(#mydivID > svg)  would get my svg object which has no class name or id.
how would I get the the text object? would it be $(.x axis > g > text) ? I'm not sure
I'm using d3 but jquery and d3 can get selectors using the similar notation and I figured more people would be familiar with jquery so they might answer the question adequately enough
Answer: The correct CSS selector would be .x.axis > g > text.
EDIT: ajp15243 points out that this would get all the text elements in g elements nested immediately below .x.axis. To get the specific text element highlighted above, use this selector:
.x.axis > g:nth-child(2) > text
Comment: @CQM Note if the first `` tag inside of `.x.axis` also has an immediate child `` tag, you will be selecting that as well. Given the answer's edit, however, that shouldn't be a problem :). It all depends on what you want.
Comment: @ajp15243 and Barney, this put me on the right track, I ended up selecting it like this `d3.select('.x.axis').selectAll('g > text')`
Comment: @CQM If that works, then great. Just be aware that if you add any other nested `` tags anywhere under `.x.axis` with immediate `` child tags, those will be selected too. If you don't do that, then it looks like you're good to go.


RNDocumentPicker: Native module is not available

Question: I followed the directions exactly as described here (https://github.com/Elyx0/react-native-document-picker/issues/94?fbclid=IwAR2Ke7ejhPYaJcT0bS7jTZHbZvXM570C7aHQQRAvHQz56C9qzvf3W1R5SkA) but it's not working. I get this error:
RNDocumentPicker: Native module is not available, make sure you have finished the installation process and rebuilt your app

Error: not opened
at WebSocket.send (/Users/miajohansson/Desktop/bnook/node_modules/ws/lib/WebSocket.js:219:16)
at send (/Users/miajohansson/Desktop/bnook/node_modules/react-native/local-cli/server/util/webSocketProxy.js:26:12)
at WebSocket.debuggerSocket.onmessage (/Users/miajohansson/Desktop/bnook/node_modules/react-native/local-cli/server/util/webSocketProxy.js:48:48)
at WebSocket.onMessage (/Users/miajohansson/Desktop/bnook/node_modules/ws/lib/WebSocket.js:442:14)
at emitTwo (events.js:126:13)
at WebSocket.emit (events.js:214:7)
at Receiver.ontext (/Users/miajohansson/Desktop/bnook/node_modules/ws/lib/WebSocket.js:841:10)
at /Users/miajohansson/Desktop/bnook/node_modules/ws/lib/Receiver.js:536:18
at /Users/miajohansson/Desktop/bnook/node_modules/ws/lib/Receiver.js:368:7
at /Users/miajohansson/Desktop/bnook/node_modules/ws/lib/PerMessageDeflate.js:249:5

When I add DocumentPicker in my code (below), I get a TypeError: Cannot read property 'show' of defined.
import { DocumentPicker, DocumentPickerUtil } from 'react-native-document-picker';

// iPhone/Android
DocumentPicker.show({
      filetype: [DocumentPickerUtil.images()],
    },(error,res) => {
      // Android
      console.log(
         res.uri,
         res.type, // mime type
         res.fileName,
         res.fileSize
      );
    });

I've deleted node_modules and run npm install but I still get this error.
Answer: Please in which installation you are, npm or yarn, the installation wasn't complete. Try to redo yarn add react-native-document-picker --save or npm install react-native-document-picker --save.
Answer: All errors of sort Native module is not available, has to be solved by updating pods and rebuilding the app


In My Razor View jquery does is not work after making ajax call?

Question: I am making a post back to get a partial view using ajax.
I'm using following code.

action method in the controller returns a grid with new values. my problem is that after the ajx call is complete the other jquery events in my page stop working.  code for events

this function selects a row from the grid and puts the selected values in a hidden field.
Also a function to open popups is not working after the ajax call.code for this function.
$(function () {
 $("#DivSearch").dialog({ autoOpen: false, height: "600", width: "600", dialogClass: "myRatingHelp", modal: true });
 $('#bRatingHelperDivSearch').live('click',function () { $('#DivSearch').dialog('open'); });
 $('#DivSearchRating_bOk').click(function () {
 $("#InputAuthorityGridSearch_Rating").val($("#hidRating").val());
 $("#DivSearch").dialog('close');
 });
 $('#DivSearchRating_bCancel').click(function () {
 $("#DivSearch").dialog('close');
 });
 });

these functions works perfectly well before the ajax call but all stop working after the making ajax call.
I'm stuck on this. please help me.
Comment: You need to use event delegation for dynamically create elements. http://api.jquery.com/on/
Comment: You need to use .on() or .live() to bypass dynamicali created content
Answer: The problem is that when the HTML gets replaced, the elements lose their bindings. Bind the events to the body or your #DivSearchGrid'
$('#DivSearchGrid').on("click", "#DivSearchRating_bOk", "function () {
    $("#InputAuthorityGridSearch_Rating").val($("#hidRating").val());
    $("#DivSearch").dialog('close');
 });

or
$('body').on("click", "#DivSearchRating_bOk", "function () {
    $("#InputAuthorityGridSearch_Rating").val($("#hidRating").val());
    $("#DivSearch").dialog('close');
 });


PKCS#11 C_Encrypt fails with Bad Arguments for 128 bit AES key

Question: I generate a 128-bit AES object using "C_CreateObject".
I then do the following to encrypt a piece of data and get a "Bad Argumnents" error on the call to "C_Encrypt" to get the encrypted data length.
char clear[] = "My name is Eric!";
buf_len = sizeof(clear) -1;

rv = pfunc11->C_EncryptInit(session, pMechanism, hObject);

if (rv != CKR_OK)
{
    printf("ERROR: rv=0x%08X: initializing encryption:\n", (unsigned int)rv);
    return false;
}

rv = pfunc11->C_Encrypt(session, (CK_BYTE_PTR)clear, (CK_ULONG)buf_len, NULL, pulEncryptedDataLen);
if (rv != CKR_OK)
{
    printf("ERROR: rv=0x%08X: derror getting encryption data buffer length:\n", (unsigned int)rv);
    return false;
}

What am I doing wrong here ?
Here is my mechanism definition -
CK_MECHANISM myMechanism = {CKM_AES_CBC_PAD, (CK_VOID_PTR)"01020304050607081122334455667788", (CK_ULONG)16};
CK_MECHANISM_PTR pMechanism = &myMechanism;

Comment: Clearly the length of the clear text is not the issue here according to this - https://www.cryptsoft.com/pkcs11doc/v211/group__SEC__12__19__4__AES__CBC__WITH__PKCS__PADDING.html  .. The mechanism CKM_AES_CBC_PAD allows for any input length and will round it up to next block size. What could be the bad argument here ?
Answer: Your pulEncryptedDataLen is probably NULL which causes CKR_ARGUMENTS_BAD.
It is better to use e.g.:
CK_ULONG ulEncryptedDataLen;
...
rv = pfunc11->C_Encrypt(session, (CK_BYTE_PTR)clear, (CK_ULONG)buf_len, NULL, &ulEncryptedDataLen);

The number of bytes sufficient to store encryption result of a single-part encryption gets stored into ulEncryptedDataLen.
Also please note that your way of passing IV value is not correct as "01020304050607081122334455667788" results in an ASCII string (giving IV as 30313032303330343035303630373038 -- which is probably not what you want).
To get correct IV use "\x01\x02\x03\x04\x05\x06\x07\x08\x11\x22\x33\x44\x55\x66\x77\x88" instead.
Good luck!


Html Profil Card align right

Question: I don't understand where I made a mistake, I want this round logo on the right. and I want the header below, but where's my fault?
If we briefly summarize the event, as shown in the pictures ..

Category Title

Clip Title

.video-clip {
    width: 305px;
    height: 265px;
}
.clip-pic img {
    width: 305px;
    height: 180px;
}
.clip-detail {
    background-color: black;
    display: flex;
    margin: 0;
    padding: 0;
}
.clip-logo {
width: 80px;
    height: 80px;
    overflow: hidden;
    border: 5px solid #0b75c9;
    position: relative;
    top: -50px;
    max-width: 100%;
    max-height: 100%;
    border-radius: 50%;
}
.clip-desc {
    flex: 1;
    min-width: 1px;
    position: relative;
}

the image i want

i created
Comment: Can you edit your question to explain the problem a bit more? Your code gives a result like the image you posted - but you *don't* want it to look like the image - is that right? Also, you say you want the round logo on the right and I understand that, but I don't know what you mean by "*normally in the articles*" Can you show us an image of what you *are* trying to do?
Comment: the picture I just uploaded.
Answer: I made a quick remake. I hope this can help you.

.card {
  width: 300px;
  display: flex;
  flex-direction: column;
}

.card-pic img {
  width: 100%;
  height: 100%;
  max-height: 350px;
  object-fit: cover;
}

.card-info-logo {
  position: absolute;
  right: 22px;
  top: -22px;
}

.card-info-logo img {
  width: 40px;
  border-radius: 50%;
  border: 4px solid gray;
}
.card-info {
  position: relative;
  background-color: black;
  height: 100px;
  padding: 15px;
  display: flex;
  flex-direction: column;
}

.card-info-top {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.card-info .title {
  color: lightgray;
  font-size: 14px;
}

.card-info .subtitle {
color: lightgray;
  font-size: 18px;
  padding-bottom: 10px;
}
.card-info-bottom {
  border-top: solid 1px white;
  padding-top: 10px;
  display: flex;
  align-items: center;
  line-height: 1;
  justify-content: space-between;
}
.card-info .card-info-bottom .views{
 color: lightgray;
  font-size: 12px;

}

.card-info .card-info-bottom .date {
 color: lightgray;
  font-size: 12px;
}

This is a title

This is a subtitle

        VIEWS 10K

        yesterday

Comment: I did it last night as a result of myself, but still I will find yours :) thank you.

Html Profil Card align right


missing libgl1-mesa-dri:i386, libgl1-mesa-glx:i386, libc6:i386 how do install ubuntu 12.04

Question: Does anyone know how to install these packages for steam libgl1-mesa-dri:i386, libgl1-mesa-glx:i386, libc6:i386 without it saying that it was unable to locate the packages?
Comment: You do not need to know or find anything. Just run the given command in terminal, [edit] your question and post output there. After that I will give you a command to fix it.
Comment: i meant on steam
Comment: Please [edit] your question and add output of `dpkg -l | grep xserver-xorg-core` terminal command. And I will help you out.
Comment: I need to know which version of xorg is installed.
Comment: that does not work the same as sudo apt-get install libc6:i386 libgl1-mesa-dri-lts-utopic:i386 libgl1-mesa-glx-lts-utopic:i386
Comment: Will you PLEASE post output of `dpkg -l | grep xserver-xorg-core` and I will help you. Or you do not need any help? It won't WORK. It will give information.
Comment: i don't know witch xorg is or were to find it
Comment: there's nothing popping up
Comment: Do not re-type the command, but copy it and paste to terminal. And it is one command, not two.
Comment: all it does is say (precise)jacksepticeye@localhost:~$ like it all ways does
Comment: OK, paste the command there and press Enter.
Answer: Try installing Wine - it resolved the issue for me ;-)
I usually install Wine before Steam and do not get the problem.
After recently completely zapping and reinstalling Ubuntu, I forgot to install Wine and got the same problem with Steam.  After installing Wine the problem disappeared.
Comment: Thank you. This got me over the hump OP was at but then it wouldn't start for a different reason. At that point I did an uninstall and reinstall and finally it worked.
Comment: Wait, I forgot to say that I'm running on Kali. I was trying to start steam by typing `steam` in the console. But that wasn't working. It does work if you run steam from the GUI though. In other words, type "steam" into application finder and open it that way.
Answer: Run this command
sudo apt-get install xserver-xorg-lts-trusty libgl1-mesa-glx-lts-trusty:i386

and reboot.
This will install graphical stack of 12.04.5. It should work.
It looks like you already removed xserver with some wrong commands.
And also try this
 sudo apt-get install ppa-purge
 sudo ppa-purge ppa:xorg-edgers/ppa

Comment: Does it install? What `dpkg -l | grep xserver-xorg-core` shows?
Comment: does not work still
Comment: Did you install anything from xorg-edgers?
Comment: does not install and the dpkg command says dpkg -l | grep xserver-xorg-core
dpkg: warning: ignoring option --foreign-architecture=i386: this architecture cannot be foreign
Comment: I updated the answer.
Comment: it got done and said this Errors were encountered while processing:
 /var/cache/apt/archives/linux-image-3.13.0-53-generic_3.13.0-53.89~precise1_i386.deb
E: Sub-process /usr/bin/dpkg returned an error code (1) what do i do


JQuery Mobile - version conflicts, radiobutton JS refresh

Question: I am getting back to developing with JQueryMobile, which proves fabulous for prototyping mobile apps, but there is a potential version issue I have bumped into:
either the formatting works fine but js-checked radiobuttons do not refresh, or the formatting needs to go out of the window and then the same JS does manage to produce the refresh.I am working on dreamweaver CS6 and cross-checking with js-bin.
Here is the page with working JQM formatting, but the lack of radiobutton self-update functionality.
http://jsfiddle.net/tearex/bh9szuer/

    <title>My Page</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.1/jquery.mobile-1.1.1.min.css" />

My Title

        <fieldset data-role="controlgroup">
    <legend>Choose a pet:</legend>
         <input class="group1" type="radio" name="radio-choice" id="WTEDY_0" value="choice-1" />
         Cat

         <input class="group1" type="radio" name="radio-choice" id="WTEDY_1" value="choice-2"   />
         Dog
</fieldset>

Not sure if the checked status is updated but there is no refresh.
Here is a page with the most recent jqm - and it is not showing jqm formatting at all (the way, this is the case with the page being loaded into chrome, too - up-to-date, on windows 7 64 bit)
http://jsfiddle.net/tearex/bh9szuer/2/

    <title>My Page</title>

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="css/themes/my-custom-theme.css" />
  <link rel="stylesheet" href="css/themes/jquery.mobile.icons.min.css" />
  <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile.structure-1.4.5.min.css" />

My Title

        <fieldset data-role="controlgroup">
    <legend>Choose a pet:</legend>
         <input class="group1" type="radio" name="radio-choice" id="WTEDY_0" value="choice-1" />
         Cat

         <input class="group1" type="radio" name="radio-choice" id="WTEDY_1" value="choice-2"   />
         Dog
</fieldset>

And here is the page making no reference to css at all, and the onload function works properly.
http://jsfiddle.net/tearex/y4a369ps/1/

    <title>My Page</title>

  <meta name="viewport" content="width=device-width, initial-scale=1">

My Title

        <fieldset data-role="controlgroup">
    <legend>Choose a pet:</legend>
         <input class="group1" type="radio" name="radio-choice" id="WTEDY_0" value="choice-1" />
         Cat

         <input class="group1" type="radio" name="radio-choice" id="WTEDY_1" value="choice-2"   />
         Dog
</fieldset>

I have some questions.
    1. How to achieve the radiobutton status change and refresh and retain JQM?
    2. Which version of jqm do you find optimal, or - ideally - how do you make the latest one work?
    3. Side question what is the recommended most compatible web-based jsfiddle equivalent?
Thanks a lot.
Comment: I have found the answer to the JQM conflict with body onload - this has to do with the order in which JQM executed relative to .  A workaround is to replace the function with "unwrapped" JS instructions (http://jsfiddle.net/tearex/784u21do/2/) or to have the function triggered by some user activity. What remains as questions is which is the most universally compatible  - and working - jqm version. I look forward to the answers. Thanks.
Comment: Please see here: https://stackoverflow.com/a/44910517/4845566  and here: [jQuery Mobile "Page" Events – What, Why, Where, When & How?](https://jqmtricks.wordpress.com/2014/03/26/jquery-mobile-page-events/)
Answer: It is time to switch to https:

<link rel="stylesheet" href="css/my-custom-theme.css" />
<link rel="stylesheet" href="css/jquery.mobile.icons.min.css" />
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile.structure-1.4.5.min.css" />
<link rel="stylesheet" href="css/my-custom-styles.css" />


PUT to an array in existing collection

Question: The following is the schema of my API end-point. I want to test a PUT using PostMan, where I add a "skill".
How would you enter the information in Postman so that you are just passing a new "skill" to the model?
<code>{
  "_id": "579a6fa26a0b6484172ae284",
  "firstname": "Max",
  "lastname": "Headron",
      "skills": [
         {"skill":"Can Type", "level":"Great"},
         {"skill":"Can Run", "level":"Good"},
  ]
}
</code>
Would you use dot notation in a form field. So instead of adding "firstname", which is at the top level of the object, you might enter "skills.skill" and the "value".
Hopefully this is a clearer description.
Answer: Just change the body of the request.

See https://www.getpostman.com/docs/requests.
Comment: Hi Erwin. I want to do a PUT into an existing record and insert into the "Contact" array.
Comment: Doesn't that depend on the implementation of the API endpoint?

PUT to an array in existing collection


how to get contact email if available

Question: Hi i am new to android development so pardon me if its silly
i want to get the email and other details of contacts in my phone and store them in JSON
here is my code
can any one help me with other parameters of contacts like email address and other stuff it would be very helpfull.
<code>private void getNumber(ContentResolver cr2) {
    // TODO Auto-generated method stub
    Cursor cur = cr2.query(
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
            null, null);
    while (cur.moveToNext()) {
        try {
            obj = new JSONObject();
            obj.put("name",
                    cur.getString(cur
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
            obj.put("number",
                    cur.getString(cur
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
            arobj.put(a, obj);
            a++;
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    try {
        contactsObj.put("contacts", arobj);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        Toast.makeText(ContactsToPdf.this, "done", 500).show();
        cur.close();
    }
}
</code>
Answer: You're on the good path just keep on adding lines
You can look to the different fields in :
http://developer.android.com/reference/android/provider/ContactsContract.CommonDataKinds.html
<code> Cursor cur = cr2.query(
            ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, null,
            null, null);
    while (cur.moveToNext()) {
        try {
            obj = new JSONObject();
            obj.put("email",cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS)));
            arobj.put(a, obj);
            a++;
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
</code>
Comment: i want to get the email associated with the contact like i have a number that has a email id also how to get that

how to get contact email if available


How to build a specialized installer in VS2010?

Question: I'm looking to build a specialized msi installer, preferably with VS2010 to do the following:

Be able to configure SQL server connection.
Pick the database to be used from the SQl server.
Create database table with specified credentials.
Assign a new DB user a set of permissions.
Also configure the IIS application.

I looked into a default installer project in VS2010 and it has nothing related to dealing with SQL server and IIS. Any idea how can I do all this?
Answer: Visual Studio setup projects do not offer support for SQL scripts and IIS. The best you can do is write some custom actions (using custom code) to handle this during install.
Commercial setup authoring tools offer the most control over SQL scripts and IIS elements. You can find a list here: http://en.wikipedia.org/wiki/List_of_installation_software
You can also try WiX. It has a steep learning curve, but it's free and gets the job done.
Comment: Wix ;) Makes all you need, is fee and the learning curve is NOT steep - if you make .net installers you better kjnow what you do. There are ton of crappy ones around.


Akka: Test scheduled actors using Testkit

Question: I have a parent actor which creates a child actor and the child actor greets parent every minute as below
    class MasterActor extends Actor with ActorLogging {

     override def receive: Receive = {
       case "Greet" =>
         print("Hey child!!")
       case "CreateChild" =>
        context.actorOf(Props[ChildActor])
      }
    }

    class ChildActor extends Actor with ActorLogging {

    import context.dispatcher

    override def preStart(): Unit = {
      super.preStart()
      context.system.scheduler.schedule(Duration("1 minutes").asInstanceOf[FiniteDuration],
        Duration("1 minutes").asInstanceOf[FiniteDuration], context.parent, "Greet")
    }

    override def receive: Receive = {
      case _ =>
        print("child receives something")
      }
    }

I am new to actor system, How can I test schedule scenario using TestKit?
I tried something like below in my test but that is not working
    "Master actor" should {
     "receive a Greet message every minute" in {
      val probe = TestProbe

      val actor = system.actorOf(Props(new Child() {

        import context.dispatcher

        override def preStart() =
          context.system.scheduler.scheduleOnce(Duration("1 seconds").asInstanceOf[FiniteDuration], probe.ref, "Greet")
      }))

      probe.expectMsg("Greet")
     }
    }

Answer: You can read about it at the timing-assertions section in the testing of akka docs. There is the within function that should help you.
For example you can try:
"Master actor" should {
 "receive a Greet message every minute" in {
   within(62 seconds) {
    val probe = TestProbe

    val actor = system.actorOf(Props[Child])
    probe.expectMsg("Greet")
  }
 }
}

What I would do, not to wait so long, is putting the delay timeout in the configuration, and change it to a few millis in the test scenario.


Seeking an intuitive proof that the divisor function $d$ has $d(n) = o(n^\epsilon)$ for all $\epsilon > 0$

Question: It is clear that the number of divisors, d(n) grows alot more slowly than the number line, hence it is intuitive that >0, d(n)=o(n^)
But is there an intuitive way to formulate the proof? We can translate it into a simple-sounding problem:
Suppose we have a group of drummers playing different beats.
The first drummer sets the beat//
The second drummer hits his drum every second beat of the first drummer//
The third hits every third beat//
etc
Now the question is simply: what is the rate at which the drummers' beats coincide increases, relative to the beat set by the first drummer?
This is the same as the divisor function. On the 6th beat the first second and third and sixth drummers play together. On the 12th beat the first, second third fourth sixth and twelfth players hit their drums at the same time.
Obviously, the rate at which the number of drum beats coincide increases a lot more slowly than the number of beats the first drummer has played. But how much more slowly?
Comment: It does require a proof. Once that is done, Ramanujan pointed out that, for any real $\delta > 0,$ there is a maximal value of $\frac{d(n)}{n^\delta}.$ When, for example, $\delta $ is rational, the maximum is attained at just a single value of $n.$ Such an $n$ is called a Superior Highly Composite Number. https://en.wikipedia.org/wiki/Superior_highly_composite_number
Comment: Your problem is in Hardy and Wright, theorem 315 (page 260 in edition 5) and proved in half a page
Answer: It follows from $$\pi(2k)\log 2k\ge \sum_{p\le 2k}\log p= \sum_{p^m\le 2k}\log p+O(k^{1/2}) \\\ge \sum_{p^m\le 2k}\log p \lfloor 2k/p^m\rfloor = \log {2k\choose k} +O(k^{1/2})\ge O(k)$$ that $$n\le e^{rk} \implies \sum_{p| n} 1\le C\frac{\log n}{\log \log n} \implies d(n)\le 2^{C\frac{\log n}{\log \log n}}=n^{c/\log\log n}=O(n^\epsilon)$$
Comment: Thank you @reuns. If I can be honest, I don't think this is an "intuitive" proof, since it is more of a black box (it's very hard for me as a non-professional mathematician to understand this). I'm hoping for something that could be explained to a 12 year old... :  )
Comment: Proofs aside, the result you're asking for, that $d(n)$ is $o(n^\epsilon)$ for all $\epsilon>0$, is somewhat technical in itself. I'm not sure how I'd even explain raising a number to a power between 0 and 1 to a twelve-year-old.
Comment: Thanks Karl - the reason I translated the problem into a very easy-to-understand analogy (which is a perfect analogy) is that I feel like the rate of change of the increase in 'number of beats that coincide' must surely have an easier explanation than the ones currently available.
Comment: Ah yeah, there are certainly intuitive arguments that shed some light on the growth rate of $d(n)$ without fully proving the theorem you mentioned. For example, the *average* value of $d$ over the numbers $1,...,n$ is $\frac 1 1+\frac 1 2+...+\frac 1 n\approx\log n$.
Comment: ok! Can I ask you for a proof/explanation of that? (again, suppose I'm 12...)
Answer: Here's a way to make your intuition more quantitative. Imagine the drummers have been playing for a long time, which you estimate is around $n$ beats, and you're about to start listening. How many drummers will hit the first beat you hear? Drummer 1 will definitely hit it. Drummer 2 hits half of all the beats, drummer 3 hits a third of them, and so on, up through drummer $n$, and the later drummers haven't begun playing. So the average number of hits per beat that we'll hear over the next few beats is approximately $\frac 1 1 + \frac 1 2 + ... + \frac 1 n$, which is approximately $\log n$ (see harmonic series) and grows more slowly than any positive power of $n$.
This idea doesn't yield a proof of the statement you mentioned, though, because the divisor function can exceed this "local average", and the argument above doesn't help us bound that behavior.
Comment: Yeah, the slow growth of $\log n$ is what I was referring to: for every $\epsilon>0$, for sufficiently large $n$, $n^\epsilon>\log n$. $\log n$ is not an upper bound on $d(n)$, but it's its "expected value" or "average value near $n$" in an informal sense (that can be made precise).
Comment: Thanks Karl! When you say 'more slowly' than any positive power of n (or also n) is there a clear way to say how much more slowly? is it d(n) ≈log  ?


In .net does a new thread get created for each System.Thread.Timer object in a process?

Question: I want to execute methods at different intervals and was looking at using the Timer class to schedule this. However, I wanted to understand if the Timer spun up a new thread for each new schedule which could then potentially impact performance of the application
Answer: For System.Threading.Timer:
Short-answer: 90% of the time: no. It uses the Thread Pool to get an existing thread (that isn't doing anything).
Long-answer: Possibly! If all threads in the pool are busy then a new thread will need to be created by the OS and added to the pool and then used by the Timer.
https://learn.microsoft.com/en-us/dotnet/api/system.threading.timer?view=netframework-4.8

Provides a mechanism for executing a method on a thread pool thread at specified intervals. This class cannot be inherited.

For other timer types:

System.Windows.Forms.Timer triggers a new Win32 Window Message to be sent to the Form at a set interval. It does not use a dedicated thread nor a pool thread, instead it uses Win32's SetTimer function.
System.Timers.Timer will also use a pool thread by default (just like System.Threading.Timer) but lets you perform thread synchronization. See https://learn.microsoft.com/en-us/dotnet/api/system.timers.timer?view=netframework-4.8

A single-threaded alternative using coroutines:
I recommend you look at using await Task.Delay instead - as it won't cause a new thread to be used (remember that Tasks are not Threads) - though if you do use Task.Run to run the coroutine in a pool thread then it may run on a new thread:
public static class Foo
{
    public static async Task<Int32> Main( String[] args )
    {
        Task loop30 = this.Every30Seconds();
        Task loop20 = this.Every20Seconds();
        Taks loop10 = this.Every10Seconds();

        await Task.WhenAll( loop30, loop20, loop10 );

        return 0;
    }

    public static async Task Every30Seconds()
    {
        while( true )
        {
            Console.WriteLine("Ping!");

            await Task.Delay( 30 * 1000 );
        }
    }

    public static async Task Every20Seconds()
    {
        while( true )
        {
            Console.WriteLine("Pong!");

            await Task.Delay( 20 * 1000 );
        }
    }

    public static async Task Every10Seconds()
    {
        while( true )
        {
            Console.WriteLine("Pang!");

            await Task.Delay( 10 * 1000 );
        }
    }
}

Comment: You are right when it's a timer from System.Threading namespace. But there are other 3 timers in the .Net. So, if you can write the complete answer it could be great.
Answer: Dai's done a good job of answering the question regarding timers and threads.
I thought I'd give you an alternative way of writing your code. You should use Microsoft's Reactive Framework (aka Rx) - NuGet System.Reactive and add using System.Reactive.Linq; - then you can do this:
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);

EventLoopScheduler els = new EventLoopScheduler();

els.Schedule(() => Console.WriteLine(Thread.CurrentThread.ManagedThreadId));

IObservable<string> pings = Observable.Timer(TimeSpan.Zero, TimeSpan.FromSeconds(30), els).Select(x => "Ping!");
IObservable<string> pongs = Observable.Timer(TimeSpan.Zero, TimeSpan.FromSeconds(20), els).Select(x => "Pong!");
IObservable<string> pangs = Observable.Timer(TimeSpan.Zero, TimeSpan.FromSeconds(10), els).Select(x => "Pang!");

IObservable<string> query = Observable.Merge(els, pings, pongs, pangs);

IDisposable subscription = query.Subscribe(x => Console.WriteLine($"{x} ({Thread.CurrentThread.ManagedThreadId})"));

Console.ReadLine();

subscription.Dispose();
els.Dispose();

The EventLoopScheduler creates a single, dedicated, re-usable thread that you can used until you call .Dispose() on it.
Both Observable.Timer and Observable.Merge allow you to specify that you want to use the EventLoopScheduler to ensure that the code is run on that thread.


How can you hide something from registered users but display it to anonymous users?

Question: This is for Plone 4. It is quite a general problem. I have a form (ploneformgen) that I want anonymous users to see and fill in, but I want to hide it from registered users (i.e., users who have logged in). Similarly, I have a "log in" link in the navigation menu. Obviously, anonymous users should see that, but logged-in users shouldn't have to see it. I've tried many options which I won't detail here (workflows, scripts that change local permission settings, etc.) since none of them have worked. There must be a standard way of doing this, but I can't work out what it is.
Any ideas?
Answer: Untested, but it might work: Products.AutoRole can assign groups and roles to visitors based on their IP, without creating user accounts for them. It also has a switch to only give automatic roles/groups to anonymous users. A rule 255.255.255.255/0 should match all IPs, so all anonymous users get a group, and you can make the form private and visible to that group.
(Note that AutoRole is not IPv6-ready, though, and has caveats regarding user inheritance, particularly: it will de facto disable the admin account, so you should not activate it in your Plone instance, but in the Zope server acl_users, if at all possible.)
Comment: This looks promising, but I think I'm missing something. I installed AutoRole, activated it (through Plone), went to "Properties" tab on "Plone/acl_users/auto_role", and in the "IP filter and roles" field I entered "255.255.255.255/0:GroupThatCanViewForm", where all members of the group "GroupThatCanViewForm" can view the particular form I want anon users to be able to see. However, it doesn't seem to work. Am I missing something? I see that there is an auto_group plugin as well, is that relevant?
Comment: @adam: you need Authentication, Extraction, Groups in the Activate tab; the default install settings are Authentication, Extraction, Roles, maybe it's that.
Answer: Another untested idea.
There's a not a very know product and I never used it in a production environment (but in my tests it works perfectly): collective.subtractiveworkflow (https://pypi.python.org/pypi/collective.subtractiveworkflow) and the use of workflow chain.
In practice you can design a second workflow where View permission will be subtracted from Member roles.
To be honest I'm not 100% sure of how this can work with Anonymous, just because normally you can't define permission for Anon users but not given to other roles. This can be the same in that situation.


How to disable "Contact a Board Administrator"?

Question: The page <code>/forum/memberlist.php?mode=contactadmin</code> leads to this page that allows a guest to spam.
How to completely disable this "Contact a Board Administrator" feature in phpBB 3?

Sample spam message:

Hello Administrator,
The following is an e-mail sent to you through the administration contact
  page on "xxx".
The message was sent from a guest who specified the following contact
  information:
  Name: Barnypok
  E-mail address: firstname.lastname@example.com
  IP Address: 188.143.x.x
Message sent to you follows
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~
zd9hNf Link deleted.
Answer: The solution is to go to ACP (Admin control panel) > Contact page settings > Enable contact page > Disabled.


How to extract a timezone's current time with system.currentTimeMillis()?

Question: public class ShowCurrentTime
{
public static void main(String[] args)
<code>{

 // Obtain the total milliseconds

 long totalMilliseconds = System.currentTimeMillis();

 // Obtain the total seconds

 long totalSeconds = totalMilliseconds / 1000;

 // Compute the current second in the minute in the hour

 long currentSecond = totalSeconds % 60;

 // Obtain the total minutes

 long totalMinutes = totalSeconds / 60;

 // Compute the current minute in the hour

 long currentMinute = (totalMinutes % 60);

 // Obtain the total hours

 long totalHours = totalMinutes / 60;

 // Compute the current hour

 long currentHour = totalHours % 24;

 // Display results

 System.out.println("Current time is " + currentHour + ":" + currentMinute + ":" + currentSecond + "GMT");

}
</code>
}

Running these codes, gives the GMT, how to configure it to get the current time of a certain timezone like GMT +5:30 (IST)?
Answer: times in Java are UTC, if you need to display it in a different timezone you can use the Calendar class and set your desired timezone


adding event handlers on dynamically created WPF controls

Question: I have a WPF application and it is using dynamic WPF controls. How do I add event like button or image OnResize?
Thanks
Comment: what do you mean by adding events?. Do you want something like this button.Click += button_Clicked
Answer: You could hook up an event handler to an event of the Button or Image using the += syntax:
 Image image = new Image();
 image.SizeChanged += (s, e) => { /* handle event */ };


Why is my concrete foundation not plumb?

Question: I have a poured basement foundation on a 1920s home in the pacific northwest (zone 8). We've had a few cold winters, and there are signs of frost heave in the concrete around the house. The walkway, for instance, is all busted out and unlevel.
More urgently, I noticed recently the basement wall is pitched inward, about 1/2" per 4'. Also the forms are not totally level. I did not notice this before (lived here 6 years). Yet, I did not see any evidence of shear or stress fractures in the foundation. there are no cracks or signs of stress. Also the interior walls are not pitched at all.
Is it possible the house has settled with some geologic movement? Or the original pour is off? Is this any sign of danger, and what remediation would be considered?
Comment: It's 100 years old. If the outside of the basement wall slopes, but the inside does not, (which is what I read you to say) it was built that way, and has been that way for 100 years, so it's not "urgent" because you noticed it.
Comment: Can you see the sill and joists? Is the sill still connected to the foundation solidly? It seems unlikely that the wall would have come more than an inch out of true without impacting some structural elements.
Comment: re: _"Is it possible the house has settled with some geologic movement?"_; it's not possible, it's virtually guaranteed, though on a lesser scale than geologic. An inch or so through the wall is fine: as long as some of the bottom of the thick wall overlaps some of the top, it normally won't buckle. 90% of houses aren't plumb; new ones because of chincy foundations, old ones because wind, rain, frost, and age guide long-term unpredictable slow settling.
Comment: Concrete does not bend well so if no cracks, then the pour being off a bit is possible.  Would check carefully for cracks, frost heave and settling usually lead to cracks, some quite small.
Comment: Are you saying it was plumb but not anymore
Comment: There is no "frost heave" in most of the Pacific Northwest, the ground rarely freezes more  than a few inches deep. Soil can settle, though, especially in urban areas. Inadequately braced walls can be pushed over. Underground water flows can also wreak havoc.
Comment: What "forms" are not totally level? Are you talking about a sill plate?
Comment: By "interior walls are not pitched at all," do you mean that there are interior load bearing walls running parallel to the pitching foundation, where these parallel interior load bearing walls are plumb unlike the foundation wall?
Answer: Your pitched foundation wall was probably placed out of plumb. For your problematic concrete flatwork, frost heave is very unlikely the cause in USDA zone 8. Expansive soil, heaving from roots, and installer negligence (like leaving a layer of organics below placed concrete) are more likely root causes.
Expansive soil (or frost heaving soil) doesn't uniformly expand along a whole foundation. There are good spots and bad spots. The differential expansion along the whole foundation causes localized damage analogous to your problematic flatwork's damage.
I have seen earthquake induced liquifaction cause foundation failures, where you could see rigid body movements without localized damage like you've described. It's saturated soils with liquifaction potential, however, so the tiny probability of soil liquifaction being the cause of your pitched wall goes to an even tinier probability if you don't have a high water table.
Go to the corner where your pitched wall meets a perpendicular wall. If your wall has pitched after the concrete was placed, then you should see a wedge-shaped gap at the corner. If there's no such gap, then your foundation wall was probably placed out of plumb. It was probably placed out of plumb.
Comment: *heaving from roots* ...-> *more likely root causes.*


What are the weapons and signs in the kill feed in PUBG?

Question: In a PUBG, the are notifications in the upper right corner that show various things:

player kill and with what weapon "PlayerA [weapon_symbol] PlayerB",
death from an environmental effect (fall, vehicle impact, drowning, etc.),
death from the blue zone,
death from the red zone.

I am particularly interested in the weapon icons. I mostly cannot recognize the DMRs and SMGs clearly.

What is the comprehensive list of these notification "events"?
Is there a setting to show the weapon names instead of icons? If yes, where do I turn it on/off?
Answer:
Is there a comprehensive list of these notification "events"?

There is a list of all weapon icons that you can relate back to the weapons kill feed.
This doesn't include environmental or blue zone deaths but those are unique and aren't really in need of a comprehensive list.

Is there a setting to show the weapon names instead of icons?

There's no way to change the icons into names, only the option to turn the feed on or off. (Settings > Gameplay > UI > Icon Killfeed)
Comment: The first half of this answer is link-only. Please edit relevant information into the answer body in case the page linked is changed or removed.
Comment: @Wrigglenite I know that's preferred, but it seems so tedious for me to copy and paste each individual image :(
Comment: Then this is effectively the same as the existing answer.
Comment: Give me some time to extract the info out and I'll update it :) It's gonna take some time. But this is a different answer because the other is stating that there is no comprehensive list when they do exist.
Answer: You seem to have the icon killfeed feature turned on. Here's how you can turn it off:
To turn off the icon killfeed, simply go to your PUBG in-game settings, and under the "Gameplay" tab, under the "UI" section, you'll see "Icon Killfeed". Simply switch it to "OFF" and you're good to go!

After that, your killfeed will show messages like this:

[attacker] knocked out [victim] with [weapon]
[attacker] killed [victim] with [weapon]

Also,

[player] was heavily injured from [environmental damage]
[player] died from [environmental damage]

And, no. There is no comprehensive list of kill feed notifications.
Comment: "And, no. There is no comprehensive list of kill feed notifications." - There are.
Comment: That wasn't what the question asked...
Comment: @n_plum, if you update your answer tell us about comprehensive list of the killfeed notifications I'll be much helped.


Can the cure for your disease fail?

Question: On Plague INC, once the humans make a cure for your disease, is it possible for it to not work and them have to re-make it?
Answer: No, once the cure is complete the game is essentially over. New infections won't happen, but some will still die off.
Comment: The cure probably does fail several times during the countdown. But when it hits 100% it has been perfected.
Answer: You cannot evolve your disease in any way to make an existing cure ineffective, as far as I know.
Although, with Necro-Virus, It is possible to still win (although very hard) after the cure reaches %100.  Instead of infecting new people, existing zombies kill off healthy people - and some of those become zombies.
Answer: No, the disease cannot become cure-resistant. The only game mode I know of is the Immune Plague, which is an in app purchase and a cheat plague, along with Hidden and Unlimited Plague.
Answer: I have found a way to make a cure fail, and this happened by extreme luck. I was playing fungus on mega brutal, still trying to beat it, and the cure had just hit 100%, and was being distributed. I had recently evolved total organ failure, and was beginning to get DNA points for killing quickly, but not enough DNA to get a genetic reshuffle. I immediately opened up the abilities and symptoms, and devolved things I didn't need. I got exactly enough points for a genetic reshuffle. The cure went down. It had cured some people, and now I was killing way faster than I was infecting. I evolved necrosis, reinfecting everyone that had been cured, and then I won in a matter of time. The cure was at 97% when I won. So I can now say that I beat the cure, even when it was complete.

Can the cure for your disease fail?