text:
Q: Web of analogies between integers/rationals and finite fields Web of analogies between integers/rationals and finite fields:
$$\mathbb{z} \iff \mathbb{F}_{q}[T]$$
$$\mathbb{z}[X] \iff \mathbb{F}_{q}[T,X]$$
Here $q = p^t$, where $p$ is an odd prime. I am not able to understand what is analogy here ?
Reference : http://www.math.rutgers.edu/~sk1233/courses/ANT-F14/lec10.pdf

A: One of the important analogies is that the ring of integers of the number field $\mathbb{Q}$ is a PID, namely $\mathbb{Z}$, and that the ring of integers of the global field $\mathbb{F}_p(T)$ is again a PID, namely $\mathbb{F}_p[T]$. This is quite important in algebraic number theory. A number field $K$ has characteristic zero, whereas a function field, which is a finite extension of $\mathbb{F}_p(T)$ has characteristic $p>0$. Now many arguments holding for number fields can be applied to function fields, because $\mathbb{F}_p[T]$ is also a PID.
Note that the context of number theory seems appropriate, since the lecture you have linked is called "Number Theory (Fall 2014)".


text:
Q: why new Date() output wrong location? On my machine, mac-os, node v0.8.7, why the GMT+0900
> new Date()
Mon Nov 12 2012 17:23:51 GMT+0800 (CST)
> new Date(553964400000)
Thu Jul 23 1987 00:00:00 GMT+0900 (CST)
>

On my server, ubuntu, node v0.8.6, why it is GMT+0800
> new Date();
Mon Nov 12 2012 17:27:55 GMT+0800 (CST)
> new Date(553964400000)
Wed Jul 22 1987 23:00:00 GMT+0800 (CST)

A: You should check the timezone set on your machine and your server. The OSX machine might be observing daylight savings time whereas the server might not.

A: It's depending on the locale setting and date.
On 1987-Jul, it was DST in Chongqing/Shanghai. So it's UTC+9 for your giving time point.
Unless you give very detailed locale settings, this can't not be explained.
What I'm 100% sure, is the CST thing is wrong, it suppose to be CDT. You may change some other time points to verify my theory.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Averaging all the rows of a massive pyspark dataframe when each row only contain a sparse vector I have a pyspark dataframe with 15 million rows and one column.
Each row contains a sparse vector ( Vectors.sparse from pyspark.ml.linalg) x (vector size is 5000)
I want to obtain a dense vector, containing the mean of all the sparse vectors contained in each row.
I tried the following approach:
from pyspark.ml.stat import Summarizer
result = df.select(Summarizer.mean(df.x)).show(truncate=False)

but it takes hours.
Is there an efficient way to average all the rows of a dataframe, if each row only contains a sparse vector?


text:
Q: Problem with detecting the value of the drop down list on the server (servlet) side Client code is pretty simple:
<form action="DDServlet" method="post">
       <input type="text" name="customerText">
       <select id="customer">
             <option name="customerOption" value="3"> Tom </option>
             <option name="customerOption" value="2"> Harry </option>
       </select>
       <input type="submit" value="send">
</form>

Here is the code on the Servlet
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()){
      String paramName = (String)paramNames.nextElement();  //get the next element
      System.out.println(paramName);
}

When I print out, I only see, customerText, but not customerOption. Any idea why guys? What I hope is, if I select Tom in my option, once I submit, on my servlet I should able to do this: String paramValues[] = request.getParameterValues(paramName); and get back value of 3

A: You need to put the name attribute on the select.  This should fix it up:
<select name="customerOption" id="customer">
    <option value="3"> Tom </option>
    <option value="2"> Harry </option>
</select>

A: The code you are showing, you did getParameterNames. Is that just example or is that the mistake?


text:
Q: Is there a possibility to control the Expando class to not allow adding properties/members under certain conditions? As far as I can tell, the Expando class in Kephas allows adding new members on the fly. Unlike the ExpandoObject in .NET, I noticed it is not sealed, so I could change its behavior, but I don't really know how.
[EDITED]
My scenario is to make the expando readonly at a certain time.

A: Try this snippet:
public class ReadOnlyExpando : Expando
{
    private bool isReadOnly;

    public ReadOnlyExpando()
    {
    }

    public ReadOnlyExpando(IDictionary<string, object> dictionary)
        : base(dictionary)
    {
    }

    public void MakeReadOnly()
    {
        this.isReadOnly = true;
    }

    protected override bool TrySetValue(string key, object value)
    {
        if (this.isReadOnly)
        {
            throw new InvalidOperationException("This object is read only").
        }

        return base.TrySetValue(key, value);
    }
}

For other scenarios you may want to check the LazyExpando class, which provides a way to resolve dynamic values based on a function, also handling circular references exception.


text:
Q: Checkpoint stream data to HDFS clulster I have a HDFS cluster , and it has got two NameNodes.
Usually if a use a HDFS client to save data, it takes care of which NameNode to use if one of these is down.
But in Spark, for checkpointing, the API is: StreamingCOntext.checkpoint("hdfs://100.90.100.11:9000/sparkData").
Here i can only specify one of the NameNode, and if that goes down , Spark has no itelligence to switch to second one.
Can anyone help me here?
Is there a way, Spark can understand the "hdfs-site.xml" (which has the information of both the namenodes) if i place this XML in the classpath.

A: Ok, i found the answer. You can use below syntax to add resources like core-site.xml, hdfs-site.xml etc:
SparkContext.hadoopConfiguration().addResource(ABC.class.getClassLoader().getResource("core-site.xml"));
        SparkContext.hadoopConfiguration().addResource(ABC.class.getClassLoader().getResource("hdfs-site.xml"));


text:
Q: Excel interop range find entire cell contents Is there any way to set this excel flag (match entire cell contents) on by code?
Currently i'm using the following, but it gaves me only partial match
eg. lookin value is 1520 and it finds 651520
or just use in case the findnext method for it?
currentFind = insta.Find(line, Missing.Value, XlFindLookIn.xlValues, XlLookAt.xlPart, XlSearchOrder.xlByRows, XlSearchDirection.xlNext, false, Missing.Value, Missing.Value);

A: Change from XlLookAt.xlPart to XlLookAt.xlWhole.
ref: http://msdn.microsoft.com/en-us/library/office/ff839746%28v=office.15%29.aspx


text:
Q: iOS - Export (100+) files to Google Drive My app works with pictures and annotations files. The annotation files are just XML files containing information for each picture. That way, a user can have for example a dataset of 100 pictures + 100 annotation files.
At some point I want the user to be able to export those files to a cloud service, ideally iCloud or Google-Drive, so that they are available for further processing/work.
The Files App looked the best candidate for this task. The user has already connected their cloud providers in the Files App, and I don't need to worry about almost anything.
 func presentLocationPicker(forExportingFiles urls: [URL]) {
        let documentPicker = UIDocumentPickerViewController(urls: urls, in: .exportToService)
        self.present(documentPicker, animated: true)
 }

I thought it would be easy, but the reality is quite different. The integration of Google Drive with the Files App seems very weak. I have the following problems with Google Drive:
Blocker 1 - When selecting the google drive folder I want to export the files, I get the following system alert: The Operation Can't Be Completed. Couldn't communicate with the helper application

Blocker 2 - When presenting the UIDocumentPickerViewController the list of cloud providers is sometimes greyed out.

Blocker 3 - If directly from the Files App I try to move a folder (with 100 items for example) to Google Drive, it does not work either. Only some files are copied, and not with the original folder structure. Just a mess.
So my first question is: Am I supposed to do something different with UIDocumentPickerViewController to avoid Blocker 1?
Second question is: Is there any other way of exporting multiple files (more than 100) to the user's Google Drive account? I am out of ideas.

A: This is from the Google Drive API page, but I suspect the SDK is beholden to the same limitations.
https://developers.google.com/drive/api/v3/manage-uploads

*

*Simple upload: uploadType=media. For quick transfer of a small file (5 MB or less). To perform a simple upload, refer to Performing a Simple Upload.

*Multipart upload: uploadType=multipart. For quick transfer of a small file (5 MB or less) and metadata describing the file, all in a single request. To perform a multipart upload, refer to Performing a Multipart Upload.

Emphasis mine.
You will likely want to break up your requests to fit within that restriction.


text:
Q: How should I generate documentation for my web service API? I am exposing my API through web service (.asmx). Currently, the only thing available is the  default WSDL help page. While this is immensely helpful, it is not sufficient if my target audience requires a little more hand-holding. For instance, let us say I want to include some examples but still need automatic generation of method signatures etc.
Is there a good semi-automated (automatic method signatures but still be able to provide examples) to achieve this? I am looking for something like this which is also maintainable. Ideally something that helps me modify the default WSDL (I really like that page) would be great. All I need is for the documentation to be automatically available along with the service when it is deployed.
Any suggestions?

A: Maybe easiest way is to use XML documentation comments.
XML Documentation Comments
Using these comment you can automatically generate HTML documentation. For example using Sandcastle or NDoc3:
Build Sandcastle Documentation When Building Visual Studio Project
And after all you can automatically save html documentation into shared location near your service, and it could be easily navigated there using browser. So, all could be near - wsdl + html documentation

A: This is fairly easy. If you decorate all your classes and methods with tripple /// comments then you could generate documentation from it. See here:
http://msdn.microsoft.com/en-us/library/dd233217.aspx
http://www.developerfusion.com/article/84436/documentation-made-easy-with-c-and-xml/

A: Agree with other posters, however I've used NDoc3 with a lot of success. It's quite a bit faster than Sandcastle (which is a very good tool as well). NDoc3 will create .chm, .doc, and .html output.
NDoc3 and Sandcastle both generate MSDN-style documentation.
NDoc3 - http://sourceforge.net/projects/ndoc3/


text:
Q: Why can the web browser render fonts like Open Sans that are not installed on my system? Relating the mechanism which permit a browser to display correctly a text formatted wiht a certain Font-Family, it should be described in this way:
the font-family property lets designers specify a prioritized list of fonts for the browser to use to display content. If the preferred font is not installed on the user's computer, the browser will attempt to use the second font in the list. If the user does not have of the preferred fonts installed, a default font is used to display the content.
In Windows 7 the set of fonts installed on the user's computer font should be viewed in Control Panel > Appearance and Personalization > Fonts.
Now in my installed fonts "Open sans" is not listed, and yet my IE11 are able to correctly reproduce a text formatted in "Open sans".
Where is the repository where IE11 get the "Open sans" font?
Thank you very much

A: Because of @font-face:

The @font-face rule allows for linking to fonts that are
  automatically fetched and activated when needed. This allows authors
  to select a font that closely matches the design goals for a given
  page rather than limiting the font choice to a set of fonts available
  on a given platform.


text:
Q: Understanding a step in a proof on diagnosability of graphs I am currently writing a paper about diagnosability of graphs. For this, I am looking into a paper published in 1967 by Preparata, Metze and Chien called "On The Connection Assignment Problem of Diagnosable Systems".
I am currently working through the proof of Theorem 5 within this paper and there is one step that I just can't understand. In the link above, this step happens right at the top of page 22 with the sentence:

The above stated condition (1) can be met if the number $n$ of units cannot be partitioned in less than $s$ sequences of the given maximum length.

Why is this true?

A: I think I just solved it myself, so I'm just gonna put the answer here:
I ended up reshuffling the proof and using two properties. One is equation (3) from the same proof. The other property is
$$s \ r_{max} \geq n,$$
which is true because we have split $n$ into $s$ segments of maximum length $r_{max}$. Then we can combine the two properties to get (1).


text:
Q: login sql throws java.sql.SQLException: Column Index out of range, 3 > 2 in Spring Security Below codes are Spring Boot login configuration using Spring Boot Security.
First
== application.properties
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost/test?characterEncoding=utf8&serverTimezone=Asia/Seoul
spring.datasource.username = root
spring.datasource.password = password

spring.queries.users-query = SELECT username, password FROM blog_user WHERE username=?
spring.queries.roles-query = SELECT username, role FROM blog_user WHERE username=?

== spring security configuration
@Value("${spring.queries.users-query}")
private String usersQuery;

@Value("${spring.queries.roles-query}")
private String rolesQuery;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // TODO Auto-generated method stub
        auth.jdbcAuthentication().usersByUsernameQuery(usersQuery).authoritiesByUsernameQuery(rolesQuery)
                .dataSource(dataSource).passwordEncoder(passwordEncoder());
}

@Override
protected void configure(HttpSecurity http) throws Exception {
        // TODO Auto-generated method stub
        http.csrf().disable()
            .authorizeRequests()
                .antMatchers("/" ,"/home*", "/js/**", "/css/**", "/icon/**", "/users/login", "/users/register").permitAll()
                .antMatchers("/users*", "/posts/**").hasAnyRole("USER")
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/users/login").defaultSuccessUrl("/")
                .usernameParameter("username").passwordParameter("password")
                .and()
            .logout()
                .invalidateHttpSession(true)
                .clearAuthentication(true)
                .logoutSuccessUrl("/").and()
            .exceptionHandling().accessDeniedPage("/error/403");
}

But login line throws the following exceptions.
Caused by: java.sql.SQLException: Column Index out of range, 3 > 2.
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129) ~[mysql-connector-java-8.0.15.jar:8.0.15]
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.15.jar:8.0.15]

I know this exception is thrown from sql PreparedStatementCallback method. But I am afraid I have no idea where the spring.queris.users-query statement is related with spring security part, so I can fix this preparedstatement parameter. I am a beginner in Spring Security.

A: The problem is that your SQL query is searching for 3 values in 3 different columns and it finds only 2 columns in the selected table. The queries from the application.properties file are the only ones?
I think that this will also help you.
Maybe you can print the entire stacktrace here with the sql statement printed and also the structure of USERS and ROLES tables.


text:
Q: Plugins for logo in wp themes? Is there a plugin where you can upload image "logo" for use in the site's theme rather than the admin area?

A: No, not really. This wouldn't be a plugin since every theme is different. Some themes have this functionality built in, though.

A: There is no plugin that I know of, but you could add this code to your functions.php file. It would accomplish what you're looking for:
// Add a custom logo to the admin pages.  Image _MUST_ be 30x31, located in the theme images folder and named 'admin-logo.gif'.
function admin_logo() {
    $logo = dirname(__FILE__).'/images/admin-logo.gif';
    $logourl = get_bloginfo('template_directory').'/images/admin-logo.gif';

    if (file_exists($logo)) {
        echo '
            <style type="text/css">
                #header-logo { background-image: url('.$logourl.') !important; }
            </style>
        ';
    }
}

add_action('admin_head', 'admin_logo');

The function will check the images folder in your theme for a file named admin-logo.gif, and if found will add a CSS call to the page header to replace the stock WP logo. As mentioned in the comment, the image MUST be 30x31 pixels.

A: The logo is controlled by the theme ... so you'll have to use a theme that offers that option.
Alternatively, you could edit the them to change the logo.

A: +1 on using a theme that supports logos.  Unless you are an experienced developer you really want to do as little editing of CSS and PHP as possible.


text:
Q: Scala Quill error when using infix I run into problem when using Quill's infix operation .
Scala 2.12.4
Quill 2.3.3
import io.getquill._
val ctx = new SqlMirrorContext(PostgresDialect, SnakeCase)
import ctx._

// infix for custom DB operation
implicit class StringQuotes(left: String) {
  def equalTest(right: String): Quoted[Boolean] = quote {
    infix"$left = $right".as[Boolean]
  }
}

case class User(name: String)

object User {
  // normal usage
  def filter1() = quote {
    query[User]
      .filter(
        user => user.name == "Cool"
      )
  }
  //using infix for custom operation
  def filter2() = quote {
    query[User]
      .filter(
        user => user.name equalTest "Cool"
      )
  }
}
//pass, and generates a valid SQL.
ctx.run(User.filter1())

// fail
ctx.run(User.filter2())

The error message is obscure:
java.util.NoSuchElementException: value user
..... too long to show
Error while emitting main.scala

It only indicate filter2 is cause, and doesn't say which line wrong.
Runnable code snippet at Scastie online editor https://scastie.scala-lang.org/superChing/haYVkGLDSlKsOhYlaPdO1w

A: It works without explicit return type Quoted[Boolean] in equalTest function :
def equalTest(right: String) = quote {
    infix"$left = $right".as[Boolean]
}


text:
Q: Apply DataAnnotations via subclass I have a domain model for a project that can be used with multiple data storage endpoints.
I want to use it with DynamoDB.  Dynamo provides object-persistence approach that allows you to annotate properties of a class with structure elements of a DynamoDB collection (i.e. [DynamoDBTable], [DynamoDBHashKey], [DynamoDBLocalSecondaryIndexRangeKey], etc).  I would like to keep my Domain model clean so I do not want to decorate it with these endpoint specific annotations.
I know I could use Dynamo Document Model approach but I like the organization of attaching the attributes to properties.
To satisfy both wants, is there a way to inherit my domain model and apply those dynamo annotations in the sub class?  Or alternatively, is there a way to apply the data annotations programatically?


text:
Q: I can't load devtools in R 3.2.0 I am developping R packages with Rstudio. Until now, I used R 3.1.2 and all worked fine. Recently I have updated R to 3.2.0 version and I have updated the packages too. Now, when loading devtools:
> library(devtools)
Error in inDL(x, as.logical(local), as.logical(now), ...) :
unable to load shared object 'C:/Documents and Settings/cruiz.CREAL/Mis documentos/R/win-library/3.2/git2r/libs/i386/git2r.dll':
LoadLibrary failure:  No se encontró el proceso especificado.

Error: package or namespace load failed for 'devtools'

I have reinstalled devtools and git2r with biocLite and with install.packages and it didn't work. This file already exists and it is on this path.
My R session Info:
R version 3.2.0 (2015-04-16)
Platform: i386-w64-mingw32/i386 (32-bit)
Running under: Windows XP (build 2600) Service Pack 3

locale:
[1] LC_COLLATE=Spanish_Spain.1252  LC_CTYPE=Spanish_Spain.1252
[3] LC_MONETARY=Spanish_Spain.1252 LC_NUMERIC=C
[5] LC_TIME=Spanish_Spain.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
[1] tools_3.2.0

Thank you very much!

A: I suggest the following:

*

*remove.packages(c("git2r", "devtools", "rversions")).

*Use the information from my answer on this post -- R - Error installing Devtools in Windows to reinstall devtools. This should also reinstall the needed dependencies.


text:
Q: Slow issues with Website running Wordpress on Azure I am running a Website with wordpress but I am suffering a slowness issues every three weeks. The website is https://aguadilla.inter.edu/ it is from a University and I am the Webmaster.
Here is GtMetrix report when the website running normal:
https://gtmetrix.com/reports/aguadilla.inter.edu/2XiClnef
Now if I made the test  there is no report, it gave me  the following error:

Analysis Error
An error occurred fetching the page: read timeout
There may be a connectivity issue between your server and the GTmetrix test server. Please login to try testing from another test location or try again later.
Please see our FAQ on how to fix this error.

Please help.
Jossue Morales
jomorales@ag.inter.edu


text:
Q: Access join on first record I have two tables in an Access database, tblProducts and tblProductGroups.
I am trying to run a query that joins both of these tables, and brings back a single record for each product. The problem is that the current design allows for a product to be listed in the tblProductGroups table more than 1 - i.e. a product can be a member of more than one group (i didnt design this!)
The query is this:
select tblProducts.intID, tblProducts.strTitle, tblProductGroups.intGroup
from tblProducts
inner join tblProductGroups on tblProducts.intID = tblProductGroups.intProduct
where tblProductGroups.intGroup = 56
and tblProducts.blnActive
order by tblProducts.intSort asc, tblProducts.curPrice asc

At the moment this returns results such as:
intID | strTitle | intGroup
1     | Product 1 | 1
1     | Product 1 | 2
2     | Product 2 | 1
2     | Product 2 | 2

Whereas I only want the join to be based on the first matching record, so that would return:
intID | strTitle | intGroup
1     | Product 1 | 1
2     | Product 2 | 1

Is this possible in Access?
Thanks in advance
Al

A: This option runs a subquery to find the minimum intGoup for each tblProducts.intID.
SELECT tblProducts.intID
, tblProducts.strTitle
, (SELECT TOP 1 intGroup
   FROM tblProductGroups
   WHERE intProduct=tblProducts.intID
   ORDER BY intGroup ASC) AS intGroup
FROM tblProducts
WHERE tblProducts.blnActive
ORDER BY tblProducts.intSort ASC, tblProducts.curPrice ASC

A: This works for me. Maybe this helps someone:
SELECT
    a.Lagerort_ID,
    FIRST(a.Regal) AS frstRegal,
    FIRST(a.Fachboden) AS frstFachboden,
    FIRST(a.xOffset) AS frstxOffset,
    FIRST(a.yOffset) AS frstyOffset,
    FIRST(a.xSize) AS frstxSize,
    FIRST(a.ySize) AS frstySize,
    FIRST(a.Platzgr) AS frstyPlatzgr,
    FIRST(b.Artikel_ID) AS frstArtikel_ID,
    FIRST(b.Menge) AS frstMenge,
    FIRST(c.Breite) AS frstBreite,
    FIRST(c.Tiefe) AS frstTiefe,
    FIRST(a.Fachboden_ID) AS frstFachboden_ID,
    FIRST(b.BewegungsDatum) AS frstBewegungsDatum,
    FIRST(b.ErzeugungsDatum) AS frstErzeugungsDatum
FROM ((Lagerort AS a)
LEFT JOIN LO_zu_ART AS b ON a.Lagerort_ID = b.Lagerort_ID)
LEFT JOIN Regal AS c ON a.Regal = c.Regal
GROUP BY a.Lagerort_ID
ORDER BY FIRST(a.Regal), FIRST(a.Fachboden), FIRST(a.xOffset), FIRST(a.yOffset);

I have non unique entries for Lagerort_ID on the table LO_zu_ART. My goal was to only use the first found entry from LO_zu_ART to match into Lagerort.
The trick is to use FIRST() an any column but the grouped one. This may also work with MIN() or MAX(), but I have not tested it.
Also make sure to call the Fields with the "AS" statement different than the original field. I used frstFIELDNAME. This is important, otherwise I got errors.

A: Create a new query, qryFirstGroupPerProduct:
SELECT intProduct, Min(intGroup) AS lowest_group
FROM tblProductGroups
GROUP BY intProduct;

Then JOIN qryFirstGroupPerProduct (instead of tblProductsGroups) to tblProducts.
Or you could do it as a subquery instead of a separate saved query, if you prefer.

A: It's not very optimal, but if you're bringing in a few thousand records this will work:

*

*Create a query that gets the max of tblProducts.intID from one table and call it qry_Temp.

*Create another query and join qry_temp to the table you are trying to join against, and you should get your results.


text:
Q: Applicative for a user defined type I'm trying to write Applicative for this type
data Choice a = ColumnA a | ColumnB a

I wrote a Functor instance:
instance Functor Choice where
  fmap f (ColumnA a ) = (ColumnA (f a) )
  fmap f (ColumnB a ) = (ColumnB (f a) )

Now I want to write Applicative where ColumnB is considered "a correct value" and ColumnA is considered to be some kind of an error.
I tried
instance Applicative Choice where
    pure             =  ColumnB
    ColumnB f  <*>  r  =  fmap f r
    ColumnA f  <*>  _  =  ColumnA  f   --- this does not work

How can I make it work ?

A: If ColumnA is considered some kind of error, you can not let it wrap an a value. Indeed. The idea of (<*>) is that it takes a Choice (x -> y) and Choice x, and returns a Choice y. But if you have a ColumnA that wraps a function of type x -> y, and you have at the right hand a Choice x, then it thus should return a Choice y, not a Choice x.
What you could do is define a type with two type parameters, for example:
data Choice a b = ColumnA a | ColumnB b
then you only perform a mapping over the ColumnB b data constructor:
instance Functor (Choice a) where
    fmap _ (ColumnA e) = ColumnA e
    fmap f (ColumnB x) = ColumnB (f x)
and then we can define an Applicative instance as:
instance Applicative (Choice a) where
    pure = ColumnB
    ColumnB f <*> ColumnB x = ColumnB (f x)
    ColumnA e <*> _ = ColumnA e
    _ <*> ColumnA e = ColumnA e
Such instance for a Functor and Applicative however already exist: this is how it is defined on the Either data type.

A: Let's rename your data constructors to express your intent properly, as
data Choice a = Bad a | Good a

Your Functor instance keeps the taint on the values,
instance Functor Choice where
  fmap f (Bad  x)  =  Bad  (f x)
  fmap f (Good x)  =  Good (f x)

so let's just do the same for the Applicative, without being skimpy with our clauses:
instance Applicative Choice where
    pure              x  =  Good    x     -- fmap f == (pure f <*>) is the Law
    Good f  <*>  Good x  =  Good (f x)
    Good f  <*>  Bad  x  =  Bad  (f x)
    Bad  f  <*>  Good x  =  Bad  (f x)
    Bad  f  <*>  Bad  x  =  Bad  (f x)

As was pointed in the comments, this interprets Choice a as isomorphic to Writer All a, meaning, Choice a values are really just like (Bool, a) with (False, x) corresponding to Bad x and (True, x) corresponding to Good x. Naturally we only consider values to be Good if everything in their provenance was Good as well.

A: I made a package for deriving Applicative for sum types:idiomatic.
Choice can be biased towards the left or the right, if it is biased towards the left then ChoiceA is the pure constructor and combining A an B defects to ChoiceB:
{-# Language DerivingVia #-}
{-# Language DerivingStrategies #-}
{-# Language DeriveGeneric #-}
{-# Language DataKinds  #-}

import Generic.Applicative
import GHC.Generics

data Choice a = ColumnA a | ColumnB a
  deriving
  stock (Show, Generic1)

  -- pure :: a -> Choice a
  -- pure = ColumnA
  --
  -- liftA2 :: (a -> b -> c) -> (Choice a -> Choice b -> Choice c)
  -- liftA2 (·) (ColumnA a) (ColumnA a') = ColumnA (a · a')
  -- liftA2 (·) (ColumnA a) (ColumnB b)  = ColumnB (a · b)
  -- liftA2 (·) (ColumnB b) (ColumnA a)  = ColumnB (b · a)
  -- liftA2 (·) (ColumnB b) (ColumnB b') = ColumnB (b · b')
  deriving (Functor, Applicative)
  via Idiomatically Choice '[LeftBias Id]

and right-bias means ChoiceB is the pure constructor and combining A an B defects to ChoiceA:
  -- pure :: a -> Choice a
  -- pure = ColumnB
  --
  -- liftA2 :: (a -> b -> c) -> (Choice a -> Choice b -> Choice c)
  -- liftA2 (·) (ColumnA a) (ColumnA a') = ColumnA (a · a')
  -- liftA2 (·) (ColumnA a) (ColumnB b)  = ColumnA (a · b)
  -- liftA2 (·) (ColumnB b) (ColumnA a)  = ColumnA (b · a)
  -- liftA2 (·) (ColumnB b) (ColumnB b') = ColumnB (b · b')
  deriving (Functor, Applicative)
  via Idiomatically Choice '[RightBias Id]


text:
Q: free cmd/powershell replacement with normal copy paste I don't know why, but I hate pressing ctrl+v and getting ^V in the powershell and cmd windows.
I always do it and then I have to back space it, out find my mouse, then right click, and select paste.   Grrrrrrrrrrrrrr
Is there a (free) fix to this?  Some way to say, hey, I want ctrl+V to work like the other 99.999999% of the applications out there!

A: Easy with Autohotkey:
#IfWinActive ahk_class ConsoleWindowClass
^v::
SendInput {Raw}%clipboard%
return

Save that with an "ahk" extension and run it.

A: You can turn on Quick Edit mode in CMD and Powershell, this makes right mouse click into a paste (no menu fly out).

*

*Right click on the top of your shell window (either CMD or powershell)

*select Properties

*check the box for Quick Edit.

Re do the steps but select Defaults in step 2, to make sure you will have the setting permanently.

A: You can try:

*

*Console2

*Powershell

*TCCLE the free version

A: You can use PowerShell ISE. It uses the usual Windows Shortcuts

A: I haven't tried this but:
http://pscx.codeplex.com/
There's a command for getting clipboard:
http://pscx.codeplex.com/SourceControl/changeset/view/73549#53777
You could perhaps add this to a Ctrl+V menu item and see if it works out.


text:
Q: STL vector vs list: Most efficient for graph adjacency lists? Lists consume most of their time in allocating memory when pushing_back. On the other hand, vectors have to copy their elements when a resize is needed. Which container is, therefore,  the most efficient for storing an adjacency list?

A: I don't think this can be answered with absolute certainty. Nonetheless, I'd estimate that there's at least a 90% chance that a vector will do better. An adjacency list actually tends to favor a vector more than many applications, because the order of elements in the adjacency list doesn't normally matter. This means when you add elements, it's normally to the end of the container, and when you delete an element, you can swap it to the end of the container first, so you only ever add or delete at the end.
Yes, a vector has to copy or move elements when it expands, but in reality this is almost never a substantial concern. In particular, the exponential expansion rate of a vector means that the average number of times elements get copied/moved tends toward a constant -- and in a typical implementation, that constant is about 3.
If you're in a situation where the copying honestly is a real problem (e.g., copying elements is extremely expensive), my next choice after vector still wouldn't be list. Instead, I'd probably consider using std::deque instead1. It's basically a vector of pointers to blocks of objects. It rarely has to copy anything to do an expansion, and on the rare occasion that it does, all it has to copy is the pointers, not the objects. Unless you need the other unique capabilities of a deque (insert/delete in constant time at either end), a vector is usually a better choice, but even so a deque is almost always a better choice than a list (i.e., vector is generally the first choice, deque a fairly close second, and list quite a distant last).

1. One minor aside though: at least in the past, Microsoft's implementation of `std::deque` had what I'd consider sort of a defect. If the size of an element in the `deque` is greater than 16, it ends up storing pointers to "blocks" of only a single element apiece, which tends to negate much of the advantage of using `deque` in the first place. This generally won't have much effect on its use for an adjacency list though.

A: The answer depends on use-case.
P.S. @quasiverse - vectors call realloc when the memory you "::reserve", implicitly or explicitly, runs out
If you have a constantly changing adjacency list (inserts and deletes), a list would be best.
If you have a more or less static adjacency list, and most of the time you are doing traversals/lookups, then a vector would give you the best performance.

A: STL containers are not rigidly defined, so implementations vary.  If you're careful you can write your code so that it doesn't care whether it's a vector or a list that's being used, and you can just try them to see which is faster.  Given the complexity of cache effects, etc., it's nearly impossible to predict the relative speeds with any accuracy.

A: You can add third option to this comparison: list with specialized allocator.
Using allocators for small objects of fixed size may greatly increase speed of allocation/deallocation...

A: This tutorial site recommends using an array of lists or I guess you can use a vector of list elements instead:  array of lists adj list


text:
Q: Shiro / CDI inject security principal works on Glassfish but not on Wildfly I'm porting some code from Glassfish 4.1 to Wildfly 10 and am having problems somewhere between Shiro / CDI and java.security.Principal.
import java.security.Principal;
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;

// simple user interface
public interface User {
  public String getId();
}

// user bean
@Named("user")
@SessionScoped
public class UserBean implements User, Serializable {

  private Principal principal;

  @Inject
  private void initialise(Principal principal) {
    this.principal = principal;
  }

  @Override
  public String getId() {
    return principal.getName();
  }

}

// auth filter runs after shiro filters
public class AuthFilter implements javax.servlet.Filter {

  @Inject
  private User user;

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    log.debug("doFilter: user={}", user.getId());
    ...
  }

}

What happens is:

*

*The user requests a secure page.

*Shiro intercepts and redirects to the login page.

*User enters credentials (username = admin) and submits page.

*Shiro authenticates and redirects to original page.

*Auth filter is invoked, and logs user principal name.

The problem is that in Glassfish, the principal name logged is the (correct) name submitted from the login page. Wildfly however still appears to have the anonymous user. Looking at the logs, they are identical for both systems, including the 4th line where Shiro validates the user id: Authentication successful for token ... admin. Only the last line is different:
-- both
[org.apache.shiro.realm.AuthenticatingRealm] AuthenticationInfo caching is disabled for info [admin].  Submitted token: [org.apache.shiro.authc.UsernamePasswordToken - admin, rememberMe=false (127.0.0.1)].
[org.apache.shiro.authc.credential.SimpleCredentialsMatcher] Performing credentials equality check for tokenCredentials of type [[C and accountCredentials of type [java.lang.String]
[org.apache.shiro.authc.credential.SimpleCredentialsMatcher] Both credentials arguments can be easily converted to byte arrays.  Performing array equals comparison
[org.apache.shiro.authc.AbstractAuthenticator] Authentication successful for token [org.apache.shiro.authc.UsernamePasswordToken - admin, rememberMe=false (127.0.0.1)].  Returned account [admin]
[org.apache.shiro.subject.support.DefaultSubjectContext] No SecurityManager available in subject context map.  Falling back to SecurityUtils.getSecurityManager() lookup.
[org.apache.shiro.mgt.DefaultSecurityManager] Context already contains a session.  Returning.
[org.apache.shiro.subject.support.DefaultSubjectContext] No SecurityManager available in subject context map.  Falling back to SecurityUtils.getSecurityManager() lookup.
[org.apache.shiro.web.servlet.SimpleCookie] Added HttpServletResponse Cookie [rememberMe=deleteMe; Path=/tools; Max-Age=0; Expires=Sun, 01-May-2016 10:24:02 GMT]
[org.apache.shiro.mgt.AbstractRememberMeManager] AuthenticationToken did not indicate RememberMe is requested.  RememberMe functionality will not be executed for corresponding account.

-- glassfish
[com.example.servlet.AuthFilter] doFilter: user=admin

-- wildfly
[com.example.servlet.AuthFilter] doFilter: user=anonymous

The Java EE 7 Tutorial seems to say what I'm trying to do is valid:

Whenever the injected principal is accessed, it always represents the
  identity of the current caller.

So I'm a bit lost as to what is failing here.
Thanks,

A: Try using:
@Resource Principal principal;
instead.
https://docs.oracle.com/javaee/7/tutorial/cdi-adv004.htm


text:
Q: Use categorical variable vs create dichotomous variable for each one? I would like to know whether I should/shouldn't split a categorical variable into separate dummy variables for an OLS regression.
For example, I am regressing income on education using data from the Basic Feb 2016 data set from the U.S. Census Current Population Survey.
The dataset has a variable for highest level of education coded as follows:
-1 - not in universe
31 - Less than 1st grade
32 - 2nd, 3rd, or 4th grade
...
38 - 12th Grade No Diploma
39 - High School Grad-Diploma Or Equiv (GED)
40 - Some College But No Degree
41 - Associate Degree-Occupational/Vocational
42 - Associate Deg.-Academic Program
43 - Bachelor''s Degree(ex: BA, AB, BS)
44 - MASTER''S DEGREE(ex: MA, MS, MEng, MEd, MSW)
45 - Professional School Deg(ex: MD, DDS, DVM)
46 - DOCTORATE DEGREE(ex: PhD,EdD)

In my regression I would use an indicator variable to represent each group, and I would drop one group.
But, I could also make a dichotomous variable for each group and include each one in the regression. This sort of makes sense because a person can have a PhD and not a Masters.
Which should I do and why? Are there other variables where it should be different?

A: To add to what Aksakal mentioned in the answer above:

*

*"Dummy variable," and "indicator variable," both refer to the same thing†

*When you enter dummy variables into a regression model, you need to
drop one group to serve as the reference category.  The reason you
need to drop one group is because you will get perfect
collinearity
if you don't.  Some statistical packages will automatically drop one
variable from your model in the event of perfect collinearity.

*In reality, you may want to collapse some of the groups in your
analysis, because having all of the categories in there may not be
meaningful.  For example, if your reference group is "less than
first grade," someone who has a 2nd, 3rd, or 4th grade education is
probably not going to be that much different from someone with less
than first grade education in the grand scheme of things (OK, the
person may be able to read and do maths better, but how much
difference would that really translate to?).

*Be careful with your interpretation.  You mentioned above that "But, I could also make a dichotomous variable for each group and include each one in the regression. This sort of makes sense because a person can have a PhD and not a Masters." I took a quick look at the CPS survey instrument on the U.S. Census website.  Based on the way the education question was asked, you cannot interpret including the "Doctorate degree" dummy variable as "a person can have a PhD and not a Masters," because that's not what the question is intended to capture.  It simply asks the highest level of education, so some of the people who have doctorates in your sample also have master's degrees.  The question does not distinguish those with multiple advanced degrees vs. those with single degrees.

*Make sure you control for age if you're using Census data.  A 16
year old person who is still in high school in 11th grade is
probably going to have different income from a 32 year old person
who only has an 11th grade education and did not complete high
school or have a GED.

†For point #1, I originally had included "dichotomous variable" and "binary variable" in the list. User ttnphns commented in my original post and correctly pointed out that I was sloppy in lumping these two types of variables with dummy and indicator variables.  Dummy and indicator variables are special cases of dichotomous/binary variables in which the alternatives are coded as 0 or 1.  Of course, dichotomous and binary variables can have other coding besides 0/1, 1/2 is a popular alternative coding scheme, and I have seen 1/3 used in my datasets.  I have edited my post to remove "dichotomous variable" and "binary variable" from the list.

A: It's the same thing what you call dichotomous and indicator (dummy) variable. In both cases you have to drop one category.
In your case there is a natural base category:

-1 - not in universe

A: What you have is an ordinal and not just a categorical variable. You can encode it as binaries but probably will lose important information. The one you have has an integer equivalent - years in school. Maybe you'll get better results if you encode it as continuos based on this number.


text:
Q: javac compiling returns missing package During compiling my project with javac in command line promp it returns many errors and the first one is : package javax.jms does not exists.
Even though there are no problems in Eclipse with the import statment or anything.
The project is located in :
D:/Workspace/MessageQueingChat
I run from  D:/Workspace/MessageQueingChat:
javac src/model/Chat.java
Thanks!


text:
Q: A right-continuous non-decreasing process is cadlag? Consider a measureable process $A:\mathbb{R}_+\times \Omega\rightarrow \mathbb{R}$ such that $t\mapsto A_t$ is a right-continuous non-decreasing process.
Then is it true that $A$ is cadlag?


text:
Q: try to add a new column as foreign key in existing table with data and existing data manipulation A very simple example. I have web API with  a table in the database
Employees
---------
Id
---------
Name

and for example, I have 50 records.
Now I have to Implement a feature to add extra info about the department. Because I have one to many relationships the new database schema is with department id
Employees           Department
----------         -----------
Id                  Id
---------           -----------
Name                Name
---------
DepartmentId

for this, I run the query (i use SQL server)
alter table Employees add constraint fk_employees_departmentid
foreign key (DepartmentId) references Department(Id);

But now I have some issues to handle
1)Now I have the 50 existing records without departmentId. However, I must add manually this value? What is the best practice? For 50 records it is possible but for 2000 records and more?
2) when I add departmentId column I set this column to have null values(is correct?), but as a foreign key, I don't want to allow null values. Can I change it or how can I handle it?

A:
1)Now I have the 50 existing records without departmentId. However, I must add manually this value? What is the best practice? For 50 records it is possible but for 2000 records and more?

It depends. You could set up a new department for "unassigned" and assign them all to that; you could send out a spreadsheet to HR saying "the following employees don't have an assigned department; what department are they in? ps; don't remove the EmployeeID column from the sheet before you send it back; i need it to update the DB". It's very much a business contextual question, not a technical one. X thousand records is easy to handle.. It'll just take a bit of time to work through if you (or someone else) is doing it manually. This information is likely to be available somewhere else; you could perhaps send a list out to all department heads saying "are any of these guys yours? Please remove all the names you don't have in your team from this spreadsheet and send it back to me" then update the DB based on what you get back
As this is a one time operation you don't need anything particularly whizz for it - you can just get your Excel sheet back and in an empty column put:
="UPDATE emp SET departmentID = 5 WHERE id = " & A1

And fill it down to generate a bunch of update statements, copy the text into your query tool and hit go; don't need to get all fancy loading the sheet into a table, doing update joins etc - just hacky style sling together something in excel that will write the SQL for you, copy/paste/run. If HR have sent back the sheet with a list of department names, then put the dept name and id somewhere else on the sheet and use VLOOKUP or  XLOOKUP to turn the name into the department number, then compose your SQL based on that

2) when I add departmentId column I set this column to have null values(is correct?), but as a foreign key, I don't want to allow null values. Can I change it or how can I handle it?

Foreign keyed columns are allowed to have NULL values - it isn't the FK that imposes a "No Nulls" restriction, it's the nullability of the column (alter the column to departmantid INT NOT NULL) that imposes that. A FK references a primary key and the primary key may not be null (or in some DB, at most one record can have a [partly] null PK), but you could just leave those departments null. If you do alter the column to be not null, you'll need to correct the NULL values first or the change will fail


text:
Q: How to drag and drop 2D UI image on 3D Game object and then instantiate 3D game object at the position where we dropped Our 2D UI image? I have a cube in my scene so what I want is to drag and drop a 2d UI image of wrench tool over the cube and as soon as I drop that image on 3d cube the wrench prefab must be instantiated there.
Here is an image showing what I need

I am using below code to drag my UI Image around the scene but dont know how to drop this on 3D Cube and instantiate a wrench prefab
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class wrench : MonoBehaviour {

    public bool Dragging = false;
    public bool collision = false;
    Vector3 position;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

    }

    public void BeginDrag(){
        position = gameObject.transform.position;
        Dragging = true;
    }

    public void Drag(){
        transform.position = Input.mousePosition;
    }

    public void Drop(){
        if (!collision) {
            gameObject.transform.position = position;
        }
        Dragging = false;
    }
}

A: usually on stack overflow you should add some information about what you did and show some code so we can help figure out what is the problem in your approach. People won't write all the code for you without knowing what your project currently look like.
That being said, if you don't have anything to show yet and just wonder where to start, here are an idea:
You can get the position of the mouse in the world, and shoot a ray from it. Then check if this ray hits and object. like this:
if (Input.GetMouseButtonUp(0))
{
    ray = Camera.main.ScreenPointToRay(Input.mousePosition);

    if (Physics.Raycast(ray, out hit))
    {
        Debug.Log(hit); // Find a way to figure out what object you hit
    }
}


text:
Q: Missing Projects in eclipse Server Installed Eclipse Galileo with Java EE IDE and configured Tomcat-6. There are several projects in workspace which i am not able to deploy with tomcat.
I right-click on Tomcat (in the Servers view) -> Add and remove... -> a window appears in which there are two textbox
1. available and 2. Configured.
i can not see any project in available text-box, Why ? is there anything i am missing to install/configure? Please see below the image

A: Your project are not typed as web app otherwise you would have a little globe on project.
Check your project facets


text:
Q: Elegant way of encapsulating behaviour that depends on the combination of involved objects? In want to check whether two items collide in space. For that purpose both items are represented by some simplified geometric shapes - for simplicity lets assume these shapes can only be circles, polygons and lines. The items can be represented by any of these shapes and the collision-detection needs to be able to handle any of the possible combinations. I want to find a strategy that involves minimal code duplication and allows adding further shapes in the future.
My approach is the following:
public class Item{

   private Collidable bounds;

   public boolean checkCollision(Item target){
       return bounds.checkCollision(target.getBounds());
   }
}

Where Collidable is the interface for any geometric shape and a possible shape would look like:
public class Circle implements Collidable{

   public boolean checkCollision(Collidable target){
      if(target instanceof Cirlce){
         //Algorithm for circle-circle collision
      }else if(target instanceof Line){
         //Algorithm for circle-line collision
         //...
      }else{
         return false;
      }
   }
}

This however yields a lot of code duplication (the same circle-line collision algorithm would need to be repeated in the Line class) and does not seem elegant. I looked into different design patterns in search of a solution, but only ended up with this strategy-like solution. What would be a better approach here?

A: Use the Visitor pattern to restore information of type of the Collidable.
The circle can not know which figure is being checked for a collision, but the figure knows it. Let's find it out by double dispatching.
You can rename these methods, but the meaning should remain the same. You can also mark these methods as internal so that they can not be called in a different context.
You can delegate methods of checking specific pairs to an external static class in order to avoid code duplication.
public interface Collidable {
    boolean checkCollision(Collidable target);
    boolean visit(Collidable collidable);
    boolean accept(Circle circle);
    boolean accept(Line line);
}

public static class CollisionChecks {
    public static boolean check(Circle a, Circle b) { return false; }
    public static boolean check(Circle a, Line b) { return false; }
    public static boolean check(Line a, Line b) { return false; }
}

public class Line implements Collidable {
    @Override
    public boolean checkCollision(Collidable target) {
        return target.visit(this);
    }

    @Override
    public boolean visit(Collidable collidable) {
        return collidable.accept(this);
    }

    @Override
    public boolean accept(Circle circle) {
        return CollisionChecks.check(circle, this);
    }

    @Override
    public boolean accept(Line line) {
        return CollisionChecks.check(this, line);
    }

}

public class Circle implements Collidable {
    @Override
    public boolean checkCollision(Collidable target) {
        return target.visit(this);
    }

    @Override
    public boolean visit(Collidable collidable) {
        return collidable.accept(this);
    }

    @Override
    public boolean accept(Circle circle) {
        return CollisionChecks.check(this, circle);
    }

    @Override
    public boolean accept(Line line) {
        return CollisionChecks.check(this, line);
    }
}

A: Maybe your collision detection doesn't belong to the shape classes. Instead, you could implement a set of collision algorithm classes, one for each combination of shapes. Then the code only lives in one place.
You would need some way of choosing the right algorithm. You could keep them in a map of maps keyed by shape name, or inject only the relevant ones into each shape.
Now when a shape has to decide if it's colliding with another shape, it finds the right collision algorithm and asks that for an answer.


text:
Q: How can I configure logback to rollover based on time or size, with an absolute max on total number of files? Apologies if this is seen as a duplicate. This question is very similar but not the same. I'm interested in controlling the overall number of files (really I want to control the total size used for all logs).
I want the following from log back:

*

*For the current file, roll over every 12 hours or the file hits 100MB.

*No matter what, don't use more than 600MB of space total (I could also say this like: don't have more than 5 backup files).

The first point seems easy. I'm aware of TimeBasedRollingPolicy, and I know I can limit the per file size, but that's not enough. I need a way of limiting the total number of log files, not just the total number of time periods.

A: It's been a long time and someone asked for the code so I thought I would post it as an answer. I haven't tested it but it should serve as a reasonable example.
/**
 * Extends SizeBasedTriggeringPolicy to trigger based on size or time in minutes
 *
 * Example:
 *   <triggeringPolicy class="com.foo.bar.TimeSizeBasedTriggeringPolicy">
 *       <MaxFileSize>10MB</MaxFileSize>
 *       <RolloverInMinutes>35</RolloverInMinutes>
 *   </triggeringPolicy>
 *
 * This would rollover every 35min or 10MB, whichever comes first. Because isTriggeringEvent()
 * is only called when a log line comes in, these limits will not be obeyed perfectly.
 */
public class TimeSizeBasedTriggeringPolicy<E> extends SizeBasedTriggeringPolicy<E> {
     private long MILLIS_IN_A_MINUTE = 60 * 1000;

     private long rolloverPeriod;
     private long nextRolloverTime;

     @Override
     public void start() {
         nextRolloverTime = System.currentTimeMillis() + rolloverPeriod;
         super.start();
     }

     @Override
     public boolean isTriggeringEvent(File activeFile, final E event) {
         long currentTime = System.currentTimeMillis();
         boolean isRolloverTime = super.isTriggeringEvent(activeFile, event) ||
                 currentTime >= nextRolloverTime;

         // Reset the rollover period regardless of why we're rolling over.
         if (isRolloverTime) {
             nextRolloverTime = currentTime + rolloverPeriod;
         }

         return isRolloverTime;
     }

     public long getRolloverInMinutes() {
         return rolloverPeriod / MILLIS_IN_A_MINUTE;
     }

     public void setRolloverInMinutes(long rolloverPeriodInMinutes) {
         this.rolloverPeriod = rolloverPeriodInMinutes * MILLIS_IN_A_MINUTE;
     }
 }


text:
Q: macOS accessibility: can't move focus to "Finder wants to make changes" password prompt/window using keyboard I tried Googling for a solution to this issue but can't find one. When deleting certain files/folders, Finder will pop up a window prompting me to enter my password. If another app/window steals the focus before I can enter my password, I am unable to get the focus back to the password prompt window using the keyboard.
In System Preferences > Keyboard > Shortcuts > Keyboard, I have all shortcut options enabled for keyboard access and moving focus, and the button for "all controls" is selected for the "Full Keyboard Access" option.
I've tried using ⌃+F4,  ⌃+F6, and  ⌘+`, but none of these seem to allow me to move the keyboard focus to this window.
Please help. This can be a very frustrating problem for those who have difficulty using a mouse, particularly anyone with Parkinson's or other mobility issues. Thank you.


text:
Q: Error with `QObject` subclass and copy constructor: `QObject::QObject(const QObject&) is private` The following compile errors is what I have:
/usr/lib/qt-3.3/include/qobject.h: In copy constructor Product::Product(const Product&):
/usr/lib/qt-3.3/include/qobject.h:211: error: QObject::QObject(const QObject&) is private
Product.h:20: error: within this context
HandleTCPClient.cpp: In member function int Handler::HandleTCPClient(int, std::string, std::string):
HandleTCPClient.cpp:574: note: synthesized method Product::Product(const Product&) first required here
HandleTCPClient.cpp:574: error:   initializing argument 1 of std::string productDetails(Product)
/usr/lib/qt-3.3/include/qobject.h: In member function Product& Product::operator=(const Product&):
Product.h:20:   instantiated from void std::vector<_Tp, _Alloc>::_M_insert_aux(__gnu_cxx::__normal_iterator<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer, std::vector<_Tp, _Alloc> >, const _Tp&) [with _Tp = Product, _Alloc = std::allocator<Product>]
/usr/lib/gcc/i386-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_vector.h:610:   instantiated from âvoid std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = Product, _Alloc = std::allocator<Product>]â
HandleTCPClient.cpp:173:   instantiated from here
/usr/lib/qt-3.3/include/qobject.h:212: error: QObject& QObject::operator=(const QObject&) is private
Product.h:20: error: within this context
/usr/lib/gcc/i386-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/vector.tcc: In member function void std::vector<_Tp, _Alloc>::_M_insert_aux(__gnu_cxx::__normal_iterator<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer, std::vector<_Tp, _Alloc> >, const _Tp&) [with _Tp = Product, _Alloc = std::allocator<Product>]:
/usr/lib/gcc/i386-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/vector.tcc:260: note: synthesized method âProduct& Product::operator=(const Product&) first required here
make: *** [HandleTCPClient.o] Error 1

Part of my HandleTCPClient.cpp Line 574:
            Product tempProduct;// temporary Product storage variable
            tempProduct.setHandler(this);
...

            else if (output[1] == '5') // description
            {
                output.erase(0,2); // erase the sequence numbers
                tempProduct.description = output;
    LINE 574            output = productDetails(tempProduct); // obtain client given information about selling product
            }

Product.h::
#include <string>
#include <qtimer.h>
#include "HandleTCPClient.h"
#ifndef PRODUCT_H
#define PRODUCT_H
#include <qobject.h>
#include <qgl.h>

class Handler;

//Define ourselves a product class
class Product : public QObject
    {

        Q_OBJECT

        void startTimer();

    public:
        Product();

        string seller, itemName, description, highestBidder;
        double price, min, buyingPrice, currentBid;
        int time;
        bool isSold;
        Handler *handler;

        void setHandler(Handler *h);

    public slots:
        void setProductToSold();

    };

#endif

Product.cpp::
#include <string>
using std::string;

#include "Product.h"

Product::Product()
{
    seller = "";
    itemName = "";
    price = 0.00;
    min = 0.00;
    buyingPrice = 0.00;
    time = 0;
    description = "";
    highestBidder = "None";
    currentBid = 0.00;
}

void Product::setHandler(Handler *h)
{
    handler = h;
}

Thanks for all the help =)

A: Copying is not allowed for QObject descendants...
See http://lists.trolltech.com/qt-interest/2001-02/thread00123-0.html
Your productDetails() function takes its parameter by value, making a copy necessary. Change it to take a const reference instead.

A: Product is a subclass of QObject, which cannot be copied. Your code is attempting to copy it somewhere (perhaps in productDetails(tempProduct)) and this causes the error. Perhaps you could pass it to your function by const reference instead; or perhaps some redesign of your program is needed.
Your compiler is telling you that the copy constructor of QObject is private, so it cannot be called by any function that is not a method of the base class. Qt has designed it to work that way.
One reason that Qt disables copying of QObjects is that it manages the memory of the children of a QObject. When a QObject gets deleted, so do all of its children. This would be impractical to do properly if the QObject was copyable.

A: On line 574 you are trying to pass one of these items to the productDetails function. You don't show it, but I imagine that this function either takes a value. So the compiler is trying to create a brand new object to pass it, but that's not permitted by the library, which has intentionally set the copy constructor to be private.
Make a new object explicitly, or fix the called function.


text:
Q: Form Fill Rest of the Page pylatex I have the following pylatex cod:
import pylatex as pl
from pylatex.utils import NoEscape
from pylatex import Command
from pylatex import Package
from pylatex import Figure
import os

videoNumber = 1
slideNumber = 5

class Form(pl.base_classes.Environment):
    """A class to wrap hyperref's form environment."""

    _latex_name = 'Form'

    packages = [pl.Package('hyperref')]
    escape = False
    content_separator = "\n"

geometry_options = {
    "head": "1pt",
    "margin": "0.2in",
    "bottom": "0.2in",
    "includeheadfoot": False}
doc = pl.Document(geometry_options=geometry_options)

with doc.create(Figure(position='h!')) as slide_pic:
                slide_pic.add_image("1.jpg",width=NoEscape("\linewidth"))

dirname = os.getcwd()
filename = os.path.join(dirname, 'Text And Slides\\' + str(videoNumber) + '\\Text\\' + str(slideNumber))
with open(filename+".txt", 'r',encoding="utf8") as myfile:
    text=myfile.read().replace('\n', '')
doc.append(text)
doc.append(NoEscape(r"\newcommand\measurepage{\the\dimexpr\pagegoal-\pagetotal-\baselineskip\relax}"))

with doc.create(Form()):
    doc.append(Command('noindent'))
    doc.append(Command('TextField',
               options=["name=multilinetextbox", "multiline=true",
                        NoEscape("width=\linewidth"),NoEscape("height=\measurepage")],
               arguments=''))

doc.generate_tex(str(slideNumber))
doc.generate_pdf(str(slideNumber))

Which creates this tex file:
\documentclass{article}%
\usepackage[T1]{fontenc}%
\usepackage[utf8]{inputenc}%
\usepackage{lmodern}%
\usepackage{textcomp}%
\usepackage{lastpage}%
\usepackage[head=1pt,margin=0.2in,bottom=0.2in,includeheadfoot=False]{geometry}%
\usepackage{graphicx}%
\usepackage{hyperref}%
%
%
%
\begin{document}%
\normalsize%

\begin{figure}[h!]%
\centering%
\includegraphics[width=\linewidth]{1.jpg}%
\end{figure}

%
Now in this particular case where we have equal populations we can distinguish different regimes. This picture is on the title page of the first edition of Peter Hore's book. First of all it shows the spectra that we see as a function of the exchange rate. You will note that this is a logarithmic scale for example this corresponds to one jump per second while this corresponds to a thousand jumps per second and of course we can go all the way to 100000 per second. This corresponds generally speaking to an increasing temperature. There are other ways of course of changing the speed of a chemical reaction but temperature is certainly one way of doing it. At low temperatures we have slow rates and at slow rates we can actually distinguish the chemical shifts of site A and site B as we have in previous examples. In these simulations they happen to be separated by a difference in chemical shifts that is 50 Hz and which elsewhere is called delta nu with a lower case delta. So that's the abstract notation for the difference in chemical shifts delta nu is equal to nu zero of site B minus nu zero of site A. Now what is interesting is that if we increase the temperature or otherwise increase the interchange rate then the lines begin to broaden and more surprisingly they tend to move closer together. It turns out that the distance between these broad humps is smaller than the distance between the two narrow peaks at low temperature. They get broadened to the point that we see almost no signal and then they turn up as a single hump the two lines appear merged together into a single hump a phenomenon that we call âcoalescenceâ in our trade. More remarkably the single line which is initially rather broad will become narrower and narrower as the exchange rate increases while at the same time we end up with an average chemical shift which is simply half{-}way between the two chemical shifts of the separate sites.%
\newcommand\measurepage{\the\dimexpr\pagegoal-\pagetotal-\baselineskip\relax}%
\begin{Form}
\noindent
\TextField[name=multilinetextbox,multiline=true,width=\linewidth,height=\measurepage]{}
\end{Form}%
\end{document}

However when I try to convert it to pdf, I get the following error:
CalledProcessError                        Traceback (most recent call last)
 in ()
     46
     47 doc.generate_tex(str(slideNumber))

---> 48 doc.generate_pdf(str(slideNumber))
~\Anaconda3\lib\site-packages\pylatex\document.py in
  generate_pdf(self, filepath, clean, clean_tex, compiler,
  compiler_args, silent)
      231             try:
      232                 output = subprocess.check_output(command,
  --> 233                                                  stderr=subprocess.STDOUT)
      234             except (OSError, IOError) as e:
      235                 # Use FileNotFoundError when python 2 is dropped
~\Anaconda3\lib\subprocess.py in check_output(timeout, *popenargs,
  **kwargs)
      334
      335     return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
  --> 336                **kwargs).stdout
      337
      338
~\Anaconda3\lib\subprocess.py in run(input, timeout, check,
  *popenargs, **kwargs)
      416         if check and retcode:
      417             raise CalledProcessError(retcode, process.args,
  --> 418                                      output=stdout, stderr=stderr)
      419     return CompletedProcess(process.args, retcode, stdout, stderr)
      420
CalledProcessError: Command '['latexmk', '--pdf',
  '--interaction=nonstopmode', '5.tex']' returned non-zero exit status
  12.

A: The \measurepage macro doesn't produce correct output amidst a paragraph. To get the correct output you should put a \par (or a blank line) right before the \begin{Form} environment. The following LaTeX document produces correct output:
\documentclass{article}%
\usepackage[T1]{fontenc}%
\usepackage[utf8]{inputenc}%
\usepackage{lmodern}%
\usepackage{textcomp}%
\usepackage{lastpage}%
\usepackage[head=1pt,margin=0.2in,bottom=0.2in,includeheadfoot=False]{geometry}%
\usepackage{graphicx}%
\usepackage{hyperref}%
%
%
%
\begin{document}%
\normalsize%

\begin{figure}[h!]%
\centering%
\includegraphics[width=\linewidth]{example-image-duck}%
\end{figure}

%
Now in this particular case where we have equal populations we can distinguish different regimes. This picture is on the title page of the first edition of Peter Hore's book. First of all it shows the spectra that we see as a function of the exchange rate. You will note that this is a logarithmic scale for example this corresponds to one jump per second while this corresponds to a thousand jumps per second and of course we can go all the way to 100000 per second. This corresponds generally speaking to an increasing temperature. There are other ways of course of changing the speed of a chemical reaction but temperature is certainly one way of doing it. At low temperatures we have slow rates and at slow rates we can actually distinguish the chemical shifts of site A and site B as we have in previous examples. In these simulations they happen to be separated by a difference in chemical shifts that is 50 Hz and which elsewhere is called delta nu with a lower case delta. So that's the abstract notation for the difference in chemical shifts delta nu is equal to nu zero of site B minus nu zero of site A. Now what is interesting is that if we increase the temperature or otherwise increase the interchange rate then the lines begin to broaden and more surprisingly they tend to move closer together. It turns out that the distance between these broad humps is smaller than the distance between the two narrow peaks at low temperature. They get broadened to the point that we see almost no signal and then they turn up as a single hump the two lines appear merged together into a single hump a phenomenon that we call âcoalescenceâ in our trade. More remarkably the single line which is initially rather broad will become narrower and narrower as the exchange rate increases while at the same time we end up with an average chemical shift which is simply half{-}way between the two chemical shifts of the separate sites.%
\newcommand\measurepage{\the\dimexpr\pagegoal-\pagetotal-\baselineskip\relax}%
\par % <---- This line added
\begin{Form}
\noindent
\TextField[name=multilinetextbox,multiline=true,width=\linewidth,height=\measurepage]{}
\end{Form}%
\end{document}

Your python code should therefore include this \par in the document:
import pylatex as pl
from pylatex.utils import NoEscape
from pylatex import Command
from pylatex import Package
from pylatex import Figure
import os

videoNumber = 1
slideNumber = 5

class Form(pl.base_classes.Environment):
    """A class to wrap hyperref's form environment."""

    _latex_name = 'Form'

    packages = [pl.Package('hyperref')]
    escape = False
    content_separator = "\n"

geometry_options = {
    "head": "1pt",
    "margin": "0.2in",
    "bottom": "0.2in",
    "includeheadfoot": False}
doc = pl.Document(geometry_options=geometry_options)

with doc.create(Figure(position='h!')) as slide_pic:
                slide_pic.add_image("1.jpg",width=NoEscape("\linewidth"))

dirname = os.getcwd()
filename = os.path.join(dirname, 'Text And Slides\\' + str(videoNumber) + '\\Text\\' + str(slideNumber))
with open(filename+".txt", 'r',encoding="utf8") as myfile:
    text=myfile.read().replace('\n', '')
doc.append(text)
doc.append(NoEscape(r"\newcommand\measurepage{\the\dimexpr\pagegoal-\pagetotal-\baselineskip\relax}"))
doc.append(NoEscape(r"\par")) # <---- This line added

with doc.create(Form()):
    doc.append(Command('noindent'))
    doc.append(Command('TextField',
               options=["name=multilinetextbox", "multiline=true",
                        NoEscape("width=\linewidth"),NoEscape("height=\measurepage")],
               arguments=''))

doc.generate_tex(str(slideNumber))
doc.generate_pdf(str(slideNumber))


text:
Q: Failed to Compile error - Unexpected token This is a React app - Here is my code:
NewsContext.js
import React, { createContext, useEffect, useState } from "react";
import axios from 'axios'

export const NewsContext = createContext()

export const NewsContextProvider = (props) => {
    const [data, setData] = useState([])
    const apikey = "e25c25eb946e48779021963c288ce5cc";

    useEffect(() => {
        axios
            .get(
                'https://newsapi.org/v2/everything?q=tesla&from=2021-06-21&sortBy=publishedAt&apiKey=${apiKey}'
            )
            .then(response => setData(response.data))
            .catch(error => console.log(error));
    }, [data]);

    return (
        <NewsContextProvider props={data}>
            {props.children}
        </NewsContextProvider>,;
    );
};

But when I run it I get this error:
Copy of error
./src/NewsContext.js
SyntaxError: C:\Users\HP\Documents\GitHub\newsfinder-app\src\NewsContext.js: Unexpected token (22:31)
20 |
21 |             {props.children}

22 |         ,;
|                                ^
23 |     );
24 | };

A: This code works for me:
import React, {createContext, useEffect, useState} from "react"
import axios from "axios"

export const NewsContext = createContext()

export const NewsContextProvider = (props) => {
  const [data, setData] = useState([])
  const apikey = "e25c25eb946e48779021963c288ce5cc"

  const apiUrl = `https://newsapi.org/v2/everything?q=tesla&from=2021-06-21&sortBy=publishedAt&apiKey=${apikey}`

  useEffect(() => {
    axios
      .get(
        apiUrl
      )
      .then(response => setData(response.data))
      .catch(error => console.log(error))
  }, [data, apiUrl])

  return (
    <NewsContextProvider props={data}>
      {props.children}
    </NewsContextProvider>
  )
}

and in the index.js just do:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import {NewsContextProvider} from "./NewContextProvider"

ReactDOM.render(
  <React.StrictMode>
    <NewsContextProvider>
      <App />
    </NewsContextProvider>

  </React.StrictMode>,
  document.getElementById('root')
);

A: From what I understood from your code is, there are two errors

Remove the ,; from return block

And use backticks instead of single quotation. It's called Template Literals

And the Last one is Passing the data in array in useEffect, it'll cause an infinite loop when the component will render, just pass an empty array, it means it will run only once when the component mounts

  axios
  .get(
    `https://newsapi.org/v2/everything?q=tesla&from=2021-06-
     21&sortBy=publishedAt&apiKey=${apiKey}`)
// should be backticks
  .then(response => setData(response.data))
  .catch(error => console.log(error));

And In useEffect
const apiRequest = () =>{
 const apikey = "e25c25eb946e48779021963c288ce5cc";
        axios
            .get(
                `https://newsapi.org/v2/everything?q=tesla&from=2021-06-21&sortBy=publishedAt&apiKey=${apiKey}`
            )
            .then(response => setData(response.data))
            .catch(error => console.log(error));
}
useEffect(() => {
        apiRequest();
    }, []); // you should not pass data,
// as it will cause an infinitie loop in the useEffect, just pass empty array to avoid the loop

So the Code will look like
import React, { createContext, useEffect, useState } from "react";
import axios from 'axios'

export const NewsContext = createContext()

export const NewsContextProvider = (props) => {
    const [data, setData] = useState([])
    //const apikey = "e25c25eb946e48779021963c288ce5cc";

    const apiRequest = () =>{
        const apikey = "e25c25eb946e48779021963c288ce5cc";
        axios
            .get(
                `https://newsapi.org/v2/everything?q=tesla&from=2021-06-21&sortBy=publishedAt&apiKey=${apiKey}`
            )
            .then(response => setData(response.data))
            .catch(error => console.log(error));
     }

     useEffect(() => {
        apiRequest();
    }, []);

    return (
        <NewsContextProvider props={data}>
            {props.children}
        </NewsContextProvider>
    );
};


text:
Q: How to sort dates by Month & Day in Kotlin i have a date with format date = 01-06-2021. I sort it by using list.sortedBy { it.date } kotlin function .
But it gives me like this
01-06-2021
01-07-2021
01-08-2021
02-06-2021
02-07-2021
02-08-2021

i need to sort like below
01-06-2021
02-06-2021
01-07-2021
02-07-2021
01-08-2021
02-08-2021

Sort it by month instead of by day.
Do i need to split the whole date with day , month ,year and then sort? It has lot of data to be done, these comes from firebase realtime database. Any suggestion?

A: list.sortedBy { it.date } will not work because date is in string format. You have to convert string to date like following"
list.sortedBy {
            val sdf = SimpleDateFormat("dd-MM-yyyy")
            sdf.parse(it.date).time
        }

A: What you're trying to achieve can simply be done by the Date object itself, since the default class declaration has already implemented Comparable<Date> in your desired way:
list.sorted()

You can also sort your dates based on their epoch millis:
list.sortedBy { it.time }


text:
Q: I send message by kafka-producer in multi-threads, but message loss occurred I'm using kafka-producer and sending data to topic 'test-topic' that consist of replication-factor 3 and partitions 1 in kafka-cluster(consisting of three brokers).
I created five thread. each thread sent 10,000 messages(each message size is 4000 bytes).
i expected latest offset 50,000 but actually 44,993.
about 5,000 messages loss occurred.
Why did message loss occur? Below my codes... (KAFKA-VERSION 1.1.0)

KafkaMessageSender.class

public class KafkaMessageSender {
    private final static Logger logger =
 LoggerFactory.getLogger(KafkaMessageSender.class);
    private Properties props;
    private KafkaProducer<String, String> producer;
    private String topic;
    private AtomicInteger count;

    public KafkaMessageSender(AtomicInteger count, String bootstrapUrls, String topic) {
        logger.info("KafkaMessageSender initializing...");
        this.topic = topic;
        this.count = count;
        props = new Properties();
        props.put(ProducerConfig.ACKS_CONFIG, "1");
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapUrls);
        props.put(ProducerConfig.BATCH_SIZE_CONFIG, 16384); //16384
        props.put(ProducerConfig.RETRIES_CONFIG, 3);
        props.put(ProducerConfig.LINGER_MS_CONFIG, 5);
        props.put(ProducerConfig.ACKS_CONFIG, "all");
        props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 33554432);
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        producer = new KafkaProducer<>(props);
        logger.info("KafkaMessageSender initializing end");

    }

    public void sendMessages() {
        producer.send(new ProducerRecord<String, String>(topic, Messages.MSG_4K)); //Messages.MSG_4K indicates 4000bytes message
        count.getAndIncrement();
        logger.info("count : "+count.get());
    }
}

KafkaMessageSenderMain.class

public class KafkaMessageSenderMain {

    private final static Logger logger = LoggerFactory.getLogger(KafkaMessageSenderMain.class);

    final static String bootstrap_url = "ism1.solulink.co.kr:9092,ism2.solulink.co.kr:9092,ism3.solulink.co.kr:9092";
    final static String topic = "test-topic"; //topic name
    final static AtomicInteger count = new AtomicInteger(0);
    final static int MAX_LOOP = 10000; //message sending count
    final static int MAX_THREAD = 5;  //created number of threads

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        ExecutorService executorService = Executors.newFixedThreadPool(MAX_THREAD);
        for(int i = 0; i < MAX_THREAD; i++) {
            executorService.execute(() ->{
                    KafkaMessageSender sender = new KafkaMessageSender(count, bootstrap_url, topic);
                    for(int j = 0; j < MAX_LOOP; j++) {
                        sender.sendMessages(); //send message
                    }
            });
        }

        executorService.shutdown();
        try {
            boolean flag = executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
            long endTime = System.currentTimeMillis();
            long procTime = (endTime - startTime);
            logger.info("all Threads is shutdown? : "+flag);
            logger.info("processTime : " + ((double)procTime/(double)1000L)+"sec");
        } catch (InterruptedException e) {
            logger.error("awaitTermination exception",e);
        }
    }
}

Result

Result image

A: Can you modify and run your code as below to see what the error is ?
producer.send(new ProducerRecord<String, String>(topic, Messages.MSG_4K), new Callback() {
        public void onCompletion(RecordMetadata metadata, Exception e) {
            if (e != null)
                e.printStackTrace();
        }
});


text:
Q: Variable only highlighted in declaration? (Emacs c++-mode) In emacs (23.3.1, GNU) i have set a theme (doesn't matter which i use this issue persists). While in C++ mode when i declare  a variable the variable is highlighted (this case white) but upon calling that variable again in my program it will not be highlighted white as it was upon declaration. Any ideas why this happens and how to fix it? Thanks in advance. Here is an example although there is obviously no color:
int num; <------- would be white

 cout << "The number is: " << num << endl; <-------- here it would not be white,

 just regular foreground color?

A: That is because it is quite difficult for Emacs to tell that the num in the second statement is a variable without doing a full syntactic parse of the buffer. In theory, Emacs is capable of doing that (see e.g. here), but most modes use regular expressions for keyword highlighting. That implies some limitations on what can be achieved, but is often preferred by mode programmers for its simplicity (oh, well, all is relative).
You may consider this a weakness of the general purpose text editor that Emacs is, when compared to more specialized IDEs that often do full parsing to provide intelligent error messages, support flexible code browsing and suggest quick fixes for bugs.
If you want to dive deeper into Emacs syntax highlighting, check out Font Lock and in particular font-lock-keywords, but be warned that it is a complex matter.


text:
Q: Sound is not played instantly I have a react project with a socket connection to a server. When a message is received, a sound (ping) should play. This is my code:
    socket.on('order', (data) => {
      let order = JSON.parse(data);
      dispatch({ type: 'PUSH_ORDER', payload: { order } });
      const audio = new Audio('/admin/assets/ping.wav');
      audio.play();
    });

When an order is received, it's pushed to the redux store and displayed, and the 'ping' sound is played. The problem is, it sometimes takes up to 5 seconds before the ping sound is played, even though the order is already on the screen.
It's for a pub where people can order through their online menucard.
Is there a possibility, like a callback or so, that when an order is received, the sound is played, and AFTER the sound is played, the order is pushed to the redux store. Something like this:
    socket.on('order', (data) => {
      let order = JSON.parse(data);
      const audio = new Audio('/admin/assets/ping.wav');
      audio.play(() => {
        // callback function when sound has played
        dispatch({ type: 'PUSH_ORDER', payload: { order } }););
      });


text:
Q: Regex to accept 7 to 10 digit number with dashes in between the number I would need help on regex for accepting any 7 digit to 10 digit number (no decimals) along with hyphen or spaces in between any where in the digit.
For example ,
Below are valid scenarios
0123456789
000-25-392-93
0-1-2-3-4-5-6-7-8-9
0 1-2 3-4 5-6 7

Could some be able provide the best regex to accept this ?

A: Try this regex:
^\d(?:[- ]*\d){6,9}$

*

*^\d starting with a digit.

*(?:[- ]*\d){6,9} followed by another digit with any amount of - or whitespaces inbetween, repeat 6 to 9 times, so 7 to 10 digits in total.

*$ end of string.

See the test case

const texts = [
  '0123456789',
  '000-25-392-93',
  '0-1-2-3-4-5-6-7-8-9',
  '0 1-2 3-4 5-6 7'
];

const regex = /^\d(?:[- ]*\d){6,9}$/;

console.log(texts.map(text => regex.test(text)));

A: ^(?:\d[- ]?){7,10}$ could also work.

*

*\d  for the digit.

*[- ] for the character after the number

*? for checking if there is one space or - after the last number

*{7,10} checks if it is between 7 and 10

Try it out:
https://regex101.com/r/Yx7iQ8/1

A: Here is one way to do that.

const numbers = [
  "0123456789",
  "000-25-392-93",
  "0-1-2-3-4-5-6-7-8-9",
  "0 1-2 3-4 5-6 7",
  "01234" ,          // not valid
  "33300409383850",  // not valid
  "123abc456def78"   // not valid
];

const valid = numbers.filter(num => {
  // count numerical digits by stripping out any non numerical characters
  //const len = num.replace(/\D/g, "").length;  // removes non numerical digits
   const len = num.replace(/[\s\-]/g, "").length;   // removes dashes and spaces

  // now we will only accept elements where their digit count is between 7 and 10
  return len > 6 && len < 11;
});

console.log(valid);


text:
Q: circuitikz 0.8.3 nigfete; undefined controle sequence I'm using circuitikz to draw a circuit with an NMOSFET and like to use the nigfete node defined in circuitikz. When I try to compile my code I'm getting multiple undefined conrol sequence and Missing number errors. Since I'm allready using the newest ciruitikz version (0.8.3) and in all related problemsI could find updating the package fixed the problem I started this question.
Here are the first 5 errors:

! Undefined control sequence.\pgf@sh@bg@nigfete ...gftransformationadjustments\pgfsetcolor {\pgfkeysvalu... \draw (0,0) node [nigfete] {};
! Undefined control sequence.\drawfetcore #1-> \pgftransformationadjustments\pgfpathmoveto {\pgfpoint {... \draw (0,0) node [nigfete] {};
! Undefined control sequence. ...pgfverticaltransformationadjustment.5\pgflinewidth \draw (0,0) node [nigfete] {};
! Missing number, treated as zero.p \draw (0,0) node [nigfete] {};
! Undefined control sequence. ...fhorizontaltransformationadjustment.5\pgflinewidth \draw (0,0) node [nigfete] {};

The MWE I created this errors with is:
\documentclass{article}
\usepackage{circuitikz}
\begin{document}
\begin{circuitikz}
    \draw (0,0) node [nigfete] {};
\end{circuitikz}
\end{document}

However if I replace "nigfete" in the MWE with "op amp" or "gm amp" it compiles just fine.
For compiling I use the "latex + dvips + ps2pdf + view pdf" chain of TexMaker.
Last but not least here is the line with the circuitikz version from the log file:

Package: circuitikz 2017/05/28{} The CircuiTikz circuit drawing package version
0.8.3

Thanks to everyone who helps me!

A: Updating pgf/tikz to a version > 3 did the trick. (Forgot to look into the requirements of circuitikz after I had updated it.)
Thanks to sistlind.


text:
Q: 250000 Grouped products in Magento I've started working on a new Magento webshop which has roughly 250000 different products. Each product can have different conditions (new, used, damaged, etc., each with their own price.). Magento doesn't seem to have a method to implement this at the moment. Of those 250000 products, there are about 150000 different conditions in stock and another 150000 conditions which aren't in stock but do have a price (which can be put on the wishlist).
Some numbers: 1500 categories, drop down attributes (country) with > 300 options, integer attributes (year). Starting with two websites 6 languages each.
I've thought out two solutions to solve this problem:
Grouped / Simple product structure
We create a grouped product which is the container product, each condition will be a different simple product. We'll relate these products to the grouped product.
The nice thing about this solution is that is pretty easy to implement, we'll have to import the data in the correct way and all the information is exactly presented in the way we want.
New Product type
We create a new product type which can have multiple conditions, each with their own inventory. On checkout the inventory is substracted. The problem with this is that implementing the CatalogInventory model in this way probably is difficult and building a whole product type is time consuming and bugprone in general.
The advantage of this solution is this that there will be about 2-2.5x times less products in the system.
Others
Are there any other options to solve this? Maybe there is a module that does all this?
In conclusion: Of course I prefer the first solution but can Magento handle that? Does anyone have experience with this much Grouped Products? The system will have about 550000 products (grouped + simple) products in the system, what will be the performance implications of this? What happens when the site grows and we'll have twice the amount of products?

A: Without knowing more details I'd lean towards using a new product type or just adding the feature independently of product types if you have a use for configurable products (I definitely wouldn't try to duplicate the configurable product type). I'd disable inventory management and use some additional tables which hold individual item inventory with the per-item conditions and maintain a separate inventory that way. Use events and overrides to control the CatalogInventory stock status as needed. Creating new products constantly which are largely duplicates seems like a hassle worth avoiding if this is a long-term endeavor that needs to scale.
However, the Grouped/Simple method might be a viable short-term solution and appropriate if the project is in it's early stages and can't afford a huge initial expenditure. If well-planned, a script should be able to convert all of the old grouped/simple products into your new product type when ready to launch.


text:
Q: If cassandra version is 2.2.12 at that time cqlsh is working, after updating latest version of cassandra (3.11.2v) cqlsh not working I am new to cassandra database.if my cassandra version is 2.2.12 at that place cqlsh is working without any issues and it is connected.
after i updated my cassandra db 3.11.2 version, cqlsh is not connected throwing error

Connection error: ('Unable to connect to any servers', {'127.0.0.1': error(111, "Tried connecting to [('127.0.0.1', 9042)]. Last error: Connection refused")})

after again i Downgrade my cassandra version cqlsh is working.
here why my latest cassandra cqlsh is not working.
Please help me,
Thank you

A: Ran the netstat command and got the following output:
below command is working for me check it once.
netstat -an | grep 9042 tcp 0 0 ::ffff:10.1.22.10:9042 :::* LISTEN The above output indicated that we are listening on port 9042 and IP address 10.1.22.10.

However, the error clearly showed that cqlsh was trying to connect to 127.0.0.1 by default. So we were getting "connection refused" error.
Modified the cqlsh command to connect to the IP address 10.1.22.10 and re-ran it as follows and we were able to connect to Cassandra database successfully.


text:
Q: The factory was called but did not return an instance I started learning ZF-2.2 but have a problem with ServiceManager.
module.config.php
'service_manager' => array(
    'abstract_factories' => array(
        'Zend\Cache\Service\StorageCacheAbstractServiceFactory',
        'Zend\Log\LoggerAbstractServiceFactory',
),

module.php
public function getServiceConfig(){
    return array(
        'invokables' => array(
            'PostDataMapper' => 'student\Model\PostDataMapper',
        ),
        'factories' => array(
            'PostIdentityMap' => function ($sm) {
        }),
    );
}

student\src\student\Model\PostDataMapper.php
    namespace student\Model;

    class PostDataMapper{

      private $dbcon="postgresql";
      protected $dbcon1 ="put";

    }

student\src\student\Model\PostIdendityMap.php
class PostIdentityMap {

    private $datamapper;

    public function __construct(PostDataMapper $pdm) {
        $this->datamapper = $pdm;
    }
}

If i tried like this
$pim = $this->getServiceLocator()->get('PostIdentityMap');

---------------------------------------------

Zend\ServiceManager\Exception\ServiceNotCreatedException
C:\wamp\www\school\vendor\zendframework\zendframework\library\Zend\ServiceManager\ServiceManager.php:911

The factory was called but did not return an instance.
#0 C:\wamp\www\school\vendor\zendframework\zendframework\library\Zend\ServiceManager\ServiceManager.php(1029): Zend\ServiceManager\ServiceManager->createServiceViaCallback(Object(Closure), 'postidentitymap', 'PostIdentityMap')
#1 C:\wamp\www\school\vendor\zendframework\zendframework\library\Zend\ServiceManager\ServiceManager.php(601): Zend\ServiceManager\ServiceManager->createFromFactory('postidentitymap', 'PostIdentityMap')
#2 C:\wamp\www\school\vendor\zendframework\zendframework\library\Zend\ServiceManager\ServiceManager.php(561): Zend\ServiceManager\ServiceManager->doCreate('PostIdentityMap', 'postidentitymap')
#3 C:\wamp\www\school\vendor\zendframework\zendframework\library\Zend\ServiceManager\ServiceManager.php(503): Zend\ServiceManager\ServiceManager->create(Array)
#4 C:\wamp\www\school\module\student\src\student\Controller\BlogController.php(37): Zend\ServiceManager\ServiceManager->get('PostIdentityMap')
#5 C:\wamp\www\school\vendor\zendframework\zendframework\library\Zend\Mvc\Controller\AbstractActionController.php(83): student\Controller\BlogController->postAction()
#6 [internal function]: Zend\Mvc\Controller\AbstractActionController->onDispatch(Object(Zend\Mvc\MvcEvent))
#7 C:\wamp\www\school\vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php(468): call_user_func(Array, Object(Zend\Mvc\MvcEvent))
#8 C:\wamp\www\school\vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php(207): Zend\EventManager\EventManager->triggerListeners('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure))
#9 C:\wamp\www\school\vendor\zendframework\zendframework\library\Zend\Mvc\Controller\AbstractController.php(117): Zend\EventManager\EventManager->trigger('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure))
#10 C:\wamp\www\school\vendor\zendframework\zendframework\library\Zend\Mvc\DispatchListener.php(114): Zend\Mvc\Controller\AbstractController->dispatch(Object(Zend\Http\PhpEnvironment\Request), Object(Zend\Http\PhpEnvironment\Response))
#11 [internal function]: Zend\Mvc\DispatchListener->onDispatch(Object(Zend\Mvc\MvcEvent))
#12 C:\wamp\www\school\vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php(468): call_user_func(Array, Object(Zend\Mvc\MvcEvent))
#13 C:\wamp\www\school\vendor\zendframework\zendframework\library\Zend\EventManager\EventManager.php(207): Zend\EventManager\EventManager->triggerListeners('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure))
#14 C:\wamp\www\school\vendor\zendframework\zendframework\library\Zend\Mvc\Application.php(309): Zend\EventManager\EventManager->trigger('dispatch', Object(Zend\Mvc\MvcEvent), Object(Closure))
#15 C:\wamp\www\school\public\index.php(17): Zend\Mvc\Application->run()
#16 {main}

A: When you use a closure as a service factory you will need to ensure you create and return the instance you require.
For example
public function getServiceConfig(){
    return array(
        'invokables' => array(
            'PostDataMapper' => 'student\Model\PostDataMapper',
        ),
        'factories' => array(
        'PostIdentityMap' => function ($sm) {
           return new Model\PostIdendityMap();
         }),
    );
}

Considering the object has no constructor; You could move the definition to the invokables configuration key. This means the service manager will create the instance for you (without the need for a factory).
public function getServiceConfig(){
    return array(
        'invokables' => array(
            'PostDataMapper'  => 'student\Model\PostDataMapper',
            'PostIdentityMap' => 'student\Model\PostIdendityMap',
        ),
    );
}

Also; Try to follow the ZF2 skeleton application naming conventions - The 'student' directory should be capitalized.


text:
Q: how to select lat | long | name with given "polygon(,,,)" in postgis python My table in postgis is this with name samplecol:
vessel_hash   | name_city | station | speed |  latitude   |  longitude  | course | heading |        timestamp         |                      the_geom
--------------+-----------+---------+-------+-------------+-------------+--------+---------+--------------------------+----------------------------------------------------
 103079215239 |newyork    | 841     | 5     | -5.41844510 | 36.12160900 | 314    | 511     | 2016-06-12T06:31:04.000Z | 0101000020E61000001BF33AE2900F424090AF4EDF7CAC15C0
 103079215239 |washangton | 3008    | 0     | -5.41778710 | 36.12144900 | 117    | 511     | 2016-06-12T06:43:27.000Z | 0101000020E6100000E2900DA48B0F424042C3AC61D0AB15C0
 103079215239 |paris      | 841     | 17    | -5.42236900 | 36.12356900 | 259    | 511     | 2016-06-12T06:50:27.000Z | 0101000020E610000054E6E61BD10F42407C60C77F81B015C0
 103079215239 |room       | 841     | 17    | -5.41781710 | 36.12147900 | 230    | 511     | 2016-06-12T06:27:03.000Z | 0101000020E61000004D13B69F8C0F424097D6F03ED8AB15C0
 103079215239 |pensilvenia| 841     | 61    | -5.42201900 | 36.13256100 | 157    | 511     | 2016-06-12T06:08:04.000Z | 0101000020E6100000CFDC43C2F71042409929ADBF25B015C0
 103079215239 |jorjia     | 841     | 9     | -5.41834020 | 36.12225000 | 359    | 511     | 2016-06-12T06:33:03.000Z | 0101000020E6100000CFF753E3A50F42408D68965F61AC15C0

Output query will must be like this:
name_city  |  latitude   |  longitude
-----------+-------------+----------
newyork    |-5.41844510  | 36.12160900
pensilvenia|-5.42201900  | 36.13256100
jorjia     |-5.41834020  | 36.12225000

My code is this:
poisInpolygon = """SELECT samplecol.latitude,samplecol.name_city samplecol.longitude
FROM samplecol
WHERE ST_Contains(samplecol.the_geom,('POLYGON((-15.0292969 47.6357836, -15.2050781 47.5172007,
-16.2597656 29.3821751, 35.0683594 26.1159859, 38.0566406 47.6357836, -15.0292969 47.6357836))'));"""

cursor.execute(poisInpolygon)
exists1 = cursor.fetchall()
count1 = 0;
for ex1 in exists1:
   count1 = count1+1
   print ex1,"\n"
   print "points", count1

I try this code and query but return 0. What is problem? What is the correct query?

A: I believe it is the classic misplace of long,lat. Based on your data sample, if we create the_geom using longitude, latitude your points land somewhere in Tanzania and therefore far away from your polygon:
SELECT ST_SetSRID(ST_MakePoint(longitude,latitude),4326) FROM samplecol
UNION ALL SELECT 'SRID=4326;POLYGON((-15.0292969 47.6357836, -15.2050781 47.5172007,
-16.2597656 29.3821751, 35.0683594 26.1159859, 38.0566406 47.6357836, -15.0292969 47.6357836))'::geometry;

If we switch the order to latitude,longitude your points land close to Gibraltar and the geometries do overlap:
SELECT ST_SetSRID(ST_MakePoint(latitude,longitude),4326) FROM samplecol
UNION ALL SELECT 'SRID=4326;POLYGON((-15.0292969 47.6357836, -15.2050781 47.5172007,
-16.2597656 29.3821751, 35.0683594 26.1159859, 38.0566406 47.6357836, -15.0292969 47.6357836))'::geometry;

So my guess is that you stored longitude and latitude values in the wrong columns ;)