text:
Q: Как сделать пополнение очереди и отправку задания потокам? Python Такая ситуация возникла, не могу найти решение. Пишу многопоточный парсер, ссылки которые нужно обработать постоянно генерируются. Мне нужно реализовать раздачу этих ссылок потокам. Решил сделать через threading и queue. Написал такой код, для примера. В данном коде мне нужно каким-то образом, понять когда очередь стало пустой, пополнить ее и заставить потоки выполнить над ней какую-то функцию.
import threading
from queue import Queue
import random

class Downloader(threading.Thread):

    def __init__(self, queue):
        """Инициализация потока"""
        threading.Thread.__init__(self)
        self.queue = queue

    def run(self):
        """Запуск потока"""
        while True:

            num = self.queue.get()

            self.output(url)

            # Отправляем сигнал о том, что задача завершена
            self.queue.task_done()

    def output(self, url):
        print(url, threading.current_thread())

def generate():
    number.append(random.randrange(1, 10, 1))

def main(numbers):
    """
    Запускаем программу
    """
    queue = Queue()

    # Запускаем потом и очередь
    for i in range(2):
        t = Downloader(queue)
        t.setDaemon(True)
        t.start()

    #
    for num in numbers:
        queue.put(num)
    # Ждем завершения работы очереди

    queue.join()
    if __name__ == "__main__":
      number = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

      main(number)


text:
Q: real values of $x$ in $\sqrt{5-x} = 5-x^2$.
Calculate the real solutions $x\in\mathbb{R}$ to
$$
\sqrt{5-x} = 5-x^2
$$

My Attempt:
We know that $5-x\geq 0$ and thus $x\leq 5$ and
$$
\begin{align}
5-x^2&\geq 0\\
x^2-\left(\sqrt{5}\right)^2&\leq 0
\end{align}
$$
which implies that $-\sqrt{5}\leq x \leq \sqrt{5}$. Now let $y=\sqrt{5-x}$. Then
$$
\tag1 y^2=5-x
$$
and the equation converts into
$$
\begin{align}
y &= 5-x^2\\
x^2 &= 5-y\\
y^2-x^2 &= 5-x-(5-y)\\
y^2-x^2 &= y-x\\
(y-x)(y+x)-(y-x) &= 0\\
(y-x)(y+x-1) &= 0
\end{align}
$$
So either $y=x$ or $x+y=1$.
Case 1 ($y=x$):
We can plug this into $(1)$ to get
$$
\begin{align}
y^2 &= 5-x\\
x^2 &= 5-x\\
x^2+x-5 &= 0\\
x &= \frac{-1\pm \sqrt{1+20}}{2}
\end{align}
$$
Since $-\sqrt{5}\leq x\leq \sqrt{5}$, the only solution is
$$
x = \frac{-1+\sqrt{21}}{2}
$$
Case 2 ($y=1-x$):
We can plug this into $(1)$ to get
$$
\begin{align}
y^2 &= 5-x\\
(1-x)^2 &= 5-x\\
1+x^2-2x &= 5-x\\
x^2-x-4 &= 0\\
x &= \frac{1\pm\sqrt{17}}{2}
\end{align}
$$
Since $-\sqrt{5}\leq x\leq \sqrt{5}$, the only solution is
$$
x = \frac{1-\sqrt{17}}{2}
$$
So final solution is
$$
x \in \left\{\displaystyle  \frac{1-\sqrt{17}}{2}, \frac{-1+\sqrt{21}}{2} \right\}
$$
Is it possible to solve this problem using geometry? For example, could we use the properties of a half-circle and a parabola?

A: $$
\begin{align}
\sqrt{5-x}&=5-x^2\\
5-x &= \left(5-x^2\right)^2\\
5-x &= x^4-10x^2+25\\
x^4-10x^2+25-5+x &= 0\\
x^4-10x^2+x+20 &= 0\\
(x^2-x-4)(x^2+x-5) &= 0
\end{align}
$$
$$
\begin{align}
x^2-x-4=0 &\vee x^2+x-5=0\\
x=\frac{-(-1)\pm\sqrt{(-1)^2-4\cdot 1 \cdot (-4)}}{2\cdot 1} &\vee x=\frac{-1\pm\sqrt{1^2-4\cdot 1 \cdot (-5)}}{2\cdot 1}\\
x=\frac{1\pm\sqrt{17}}{2} &\vee x=\frac{-1\pm\sqrt{21}}{2}
\end{align}
$$
Two of the $4$ solutions are good:
$$
\begin{align}
x_1 &= \frac{1-\sqrt{17}}{2}\\
x_2 &= \frac{-1+\sqrt{21}}{2}
\end{align}
$$

I don't see the positive thing in using geometry! This is the fastest way.

A: You can see the solutions as the abscissa of the intersection points of the two curves $y=5-x^2$ (a parabola) and $y=\sqrt{5-x}$ (upper half of a parabola). These twoo parabolas intersect at 4 points, but only two of them lie in the $y>0$ half-plane.

redpajama_set_name: RedPajamaStackExchange


text:
Q: what is the difference between "string" == $variable and $variable == "string" in IF statements I am comparing a variable to a string in an "if" statement. There seems to be different results depending on if its $variable == "string" or "string" == $variable.
I don't seem to understand the difference. Any help in understanding would be appreciated.
$template = get_page_template_slug();
if('template.php' == $template || 'template_2.php' == $template  ){
wp_enqueue_style('masorny',
get_stylesheet_directory_uri().'/css/template.css', false, '1.1', 'all');}

vs
$template = get_page_template_slug();
if( $template == 'template.php' ||  $template == 'template_2.php'  ){
wp_enqueue_style('masorny',
get_stylesheet_directory_uri().'/css/template.css', false, '1.1', 'all');}

The first one works correctly the second one just shows up a blank page.


text:
Q: Threads getting into blocked state while doing a host name look up using java.net.InetAddress.getLocalHost Please find below the application/environment details where the problem is seen.

*

*Java Web application deployed on Tomcat 9.0.35 with JRE Version 1.8.0_231-b11

*The application is running in a docker container deployed on Open shift Kubernetes Distribution platform.

I see lot of threads in the application are getting into a BLOCKED state sometimes for few mins. On  thread dump analysis, it was found that java.net.InetAddress.getLocalHost call is taking too much time. Lot of threads are getting stuck here. The host name is fetched for every logger printed in the application.
The issue is  intermittent. But when it occurs, the application/tomcat will go into a paused state which leads to the accumulation of lot of threads. After some time(few seconds), all the blocked threads are unblocked simultaneously. Because of the request concurrency, the application will run out of DB connections which it maintains in the pool leading to issues/slowness/service availability. As a fix, I have made sure to access the host name only once into a static variable and use the same throughout the logging process. I wanted to know the detailed root cause of this issue.

*

*Why this issue is occurring intermittently?

*Is there a problem with DNS look up in this kubernetes environment?

*We are using IPV4 protocol/addresses

*Are there any better approaches/fixes to handle this issue?

Sample below from the thread dump:
 "https-jsse-nio-8443-exec-13" #95 daemon prio=5 os_prio=0 tid=0x00007fccadbba800 nid=0xaf5 waiting for monitor entry 0x00007fcb912d1000
       java.lang.Thread.State: BLOCKED (on object monitor)
        at java.net.InetAddress.getLocalHost(InetAddress.java:1486)
        - waiting to lock <0x00000005e71878a0> (a java.lang.Object)

A: In JDK 8, InetAddress.getLocalHost() works as follows:

*

*Obtain host name as a string via native gethostname call.

*If there was less than 5 seconds since the last host name resolution, return the cached IP address.

*Otherwise resolve the host name:

*

*using JDK built-in lookup cache, which has the default TTL equal to 30 seconds;

*using the system call, which performs an actual DNS lookup (depending on the configuration, the address may be further cached by the OS and DNS servers).

*Cache the resolved local host IP address for 5 seconds.

Steps 2-4 are performed under the global cacheLock. If something goes wrong during this process, all threads calling InetAddress.getLocalHost() will block at this lock - exactly what you observe.
Usually local host name resolution does not end up in a network call, as long as the host address is hard-coded in /etc/hosts. But in your case it seems like the real network requests are involved (whenever TTL expires). And when the first DNS request times out (UDP is not a reliable protocol after all), a delay happens.
The solution is to configure /etc/hosts to contain the name and the address of the local host, e.g.
192.168.1.23   myhost.mydomain

where myhost.mydomain is the same string as returned by hostname command.
Finally, if the host name is not expected to change while the application is running, caching it once and forever on the application level looks like a good fix.

A: To fix the issue, I am loading the hostname only once and caching it during the application start up. I have rolled out this fix to production and we are not seeing the thread blocking issues anymore.

A: Maybe server is going to look using ipv6 and if is not in use you can configure JVM to use only IPV4, to do so add this to the options -Djava.net.preferIPv4Stack=true or if only need ipv6 -Djava.net.preferIPv6Stack=true. This will force JVM to use the right protocol.


text:
Q: Javascript scroll vertically after clicking an image I have a set of buttons that are currently just images with different hover effects defined like so:

And what I want to do with them is scroll down to a different div upon clicking them but I am unsure on how to do this. I found a sample piece of code that works in this scenario here http://jsfiddle.net/ryXFt/3/ but my problem is that I don't know how to apply this to my images that I have created.
This is my failed attempt at trying to get it to work:

However it does not work and I am unsure simply how to get javascript to recognise the image as something to click.

A: your selector is wrong

look at the jquery documentation

A: You need to add an id property to the image:

And access it like this:
$("#homeimg").click(...


text:
Q: Good jquery datagrid that works well with .net (2.0) services I'm trying to find a jquery datagrid which has the following:

*

*Allows to use the scroll bar to fetch the next page of data.

*Is able to handle high volume of data.

*Works with .NET (2.0) services

Thank you

A: You may want to look at this option
http://demos.telerik.com/aspnet-ajax/grid/examples/overview/defaultcs.aspx

A: I don't recommend to load a lot of rows on the same page. It will slow down the page.
I don't recommend you to use the scrollbar to load new rows. There will always be a delay and
several ajax requests will be invoked if the user continues to scroll the bar (and by doing so put load on your server/db).
I've created a grid which can use a "show more" button to load more rows in the table or use a traditional page pager.
It's easy to create custom filtering to let the user to quickly find the wanted rows (It's much better from a users perspective to search/filter than load a large number of rows).
https://github.com/jgauffin/griffin.table


text:
Q: How to add my self-defined node to OPC UA Server using the OPC UA .NET StandardLibrary I am a noob to establish an OPC UA Server using tehe .NET Standardenter link description here
when I want to add the new self-defined node to the OPC Server, it cannot generate the node correctly,below is my code
  public override void CreateAddressSpace(IDictionary<NodeId, IList<IReference>> externalReferences)
    {
        lock (Lock)
        {
            LoadPredefinedNodes(SystemContext, externalReferences);

            // find the untyped Boiler1 node that was created when the model was loaded.
            BaseObjectState passiveNode = (BaseObjectState)FindPredefinedNode(new NodeId(Objects.Boiler1, NamespaceIndexes[0]), typeof(BaseObjectState));
            BaseObjectState passiveNode2 = (BaseObjectState)FindPredefinedNode(new NodeId(SelfDefined.Objects.DefinedModel, NamespaceIndexes[0]), typeof(BaseObjectState));

            // convert the untyped node to a typed node that can be manipulated within the server.
            m_boiler1 = new BoilerState(null);
            m_boiler1.Create(SystemContext, passiveNode);

            m_test1 = new TestVariableState(null);
            m_test1.Create(SystemContext, passiveNode2);

            // replaces the untyped predefined nodes with their strongly typed versions.
            AddPredefinedNode(SystemContext, m_boiler1);
            AddPredefinedNode(SystemContext, m_test1);

            // create a boiler node.
            m_boiler2 = new BoilerState(null);
           m_test2 = new TestVariableState(null);

            // initialize it from the type model and assign unique node ids.
            m_boiler2.Create(
                SystemContext,
                null,
                new QualifiedName("Boiler #2", NamespaceIndexes[1]),
                null,
                true);

            m_test2.Create(
                SystemContext,
                null,
                new QualifiedName("Value #2", NamespaceIndexes[1]),
                null,
                true
                );

            // link root to objects folder.
            IList<IReference> references = null;

            if (!externalReferences.TryGetValue(Opc.Ua.ObjectIds.ObjectsFolder, out references))
            {
                externalReferences[Opc.Ua.ObjectIds.ObjectsFolder] = references = new List<IReference>();
            }

            references.Add(new NodeStateReference(Opc.Ua.ReferenceTypeIds.Organizes, false, m_test2.NodeId));

            // store it and all of its children in the pre-defined nodes dictionary for easy look up.
            AddPredefinedNode(SystemContext, m_boiler2);
            AddPredefinedNode(SystemContext, m_test2);

            // start a simulation that changes the values of the nodes.
            m_simulationTimer = new Timer(DoSimulation, null, 1000, 1000);
        }
    }

m_test1 and m_test2 is defined by me and the boiler is the original node in the BoilerServer. And all the node is generated by the ModelCompiler of the OPCFoundation:enter link description here

A: You wrote that you used the Opc.Ua.ModelCompiler, so I assume that you have generated your own model and added the own classes to the solution.  Did you specified the new namespaces in constructor of BoilerNodeManager?
string[] namespaceUrls = new string[4];
namespaceUrls[0] = Namespaces.Boiler;
namespaceUrls[1] = Namespaces.Boiler + "/Instance";
namespaceUrls[2] = <EnterYourNamespace>;
namespaceUrls[3] = <EnterYourNamespace> + "/Instance";
SetNamespaces(namespaceUrls);

This collection must be extended with your own namespaces and than you have to update the NamespaceIndexes:
BaseObjectState passiveNode2 = (BaseObjectState)FindPredefinedNode(new NodeId(SelfDefined.Objects.DefinedModel, NamespaceIndexes[2]), typeof(BaseObjectState));
//..
m_test2.Create(
  SystemContext,
  null,
  new QualifiedName("Value #2", NamespaceIndexes[3]),
  null,
  true);


text:
Q: Как установить generic-pae ядро на Ubuntu? Я новый пользователь Ubuntu и по-неопытности установил версию x86-x64 версию Ubuntu 18.04 LTS. 4Gb ОЗУ мне мало. Недавно узнал, что можно расширить это значение до 64Gb, если установить ядро generic-pae. Как это сделать?
Или как можно перенести Ubuntu на x64? Сохранив все свои данные?

A: Я не так все понял и сейчас проверить версию системы введя в терминале команду uname -m
Мне вывелось x86_64, что означает, что версия 64-битная и никаких плясок с ОЗУ не нужно проводить, потому что скорее всего битое гнездо для ОЗУ.


text:
Q: Why does it take more time to identify an incorrect password than to identify a correct one? It takes almost two seconds before my linux machine replies the password is incorrect while the correct one gets accepted almost instantaneously.

A: Actually, that's an intentional delay to prevent someone from being able to brute force a bunch of passwords in a short time.


text:
Q: Is it possible to capture the iOS GPU frame time using XCode or XCode Instruments? I am trying to write an automated profiling tool which will use XCode Instruments to load and run an iOS game, and gather profile and timing information about the rendered scene in the game. Specifically I want to know how many milliseconds the scene takes to render on the GPU. From what I can gather about Instruments, I can call it in such a way as it will output profile data to a file, for later examination.
I know that the GPU frametime can be viewed if I run the game from XCode and I can see that on the Performance panel of XCode the frame time of both GPU and CPU is displayed. But I cannot find anyway of accessing this information so that I can write it out to a file for examination later.
Is it possible to capture the iOS GPU frame time using XCode or XCode Instruments?
I am currently using XCode Version 4.6.1, and running a Unity 4 app ( the built in iOS GPU profiler for Unity is wildly inaccurate and useless for my needs ).
Thanks
George


text:
Q: Vectrorized Calls of function handles, which are stored in a cell I would like to know if there is a way to vectorize the calls of different function handles, which are stored in a cell array and have of course input values themselves. I basically have a model, which looks like:
    MyModel=cell(2,1);
    MyModel{1}=@(a,b) a+b;
    MyModel{2}=@(a,b) a-b;
    a=[1,2];
    b=[2,1];
    ModelNumber=[1,2];

Now I would like to call MyModel{ModelNumber(1)} at a(1) and b(1) and MyModel{ModelNumber(2)} at a(2) and b(2). Of course it can be done with a for loop. However, the real thing will take a lot of time, if I use a loop. So is there a way to vectorize the problem in a way that something like
    MyModel{ModelNumber(:)}(a(:),b(:))

works? I already looked at cellfun, but couldn't find an answer.
Thanks in advance!
Ingo

A: As discussed in the comments, simply using cellfun won't increase the performance over a simple for loop. Thus a for loop is the best solution for the generic case you described above.
I would expect a good performance from a for loop in this case, thus if your solution is to slow you may put it into the question and we will see if it could be improved.


text:
Q: Regular expression merge needed I need to check input against a specific pattern (xxxx.xx.xx)
e.g: 1234.12.34, 2.3.5, 22.22,1.0.3
I have made these rules
\d{0,4}
\d{0,4}\.\d{1,2}
\d{0,4}\.\d{1,2}\.\d{1,2}

is there a way to merge the 3 rules into one?
I thought of using the ? operator nested into the later parts but I couldn't figure out the correct syntax
any pointers are appreciated
thanks.

A: You could try the below,
^\d{0,4}(?:(?:\.\d{1,2})?\.\d{1,2})?$

DEMO
? would turn the previous token as optional. And don't confuse ? present in the non-capturing group.
(?:...) called non-capturing group which will do matching only. It won't capture any characters. last ? in this (?:\.\d{1,2})? pattern will turn the whole pattern, ie (?:\.\d{1,2}) as optional.
^ asserts that we are at the start and $ asserts that we are at the end.

A: ^(?:\d{0,4}|\d{0,4}\.\d{1,2}|\d{0,4}\.\d{1,2}\.\d{1,2})$

Try this.See demo.
https://regex101.com/r/aI4rA5/1
| or operator is what you need .


text:
Q: revert constants back from logical to render in the output I want to get this output (first convert data into logical vector then loop via if else to get output based on logical comparison of the vector):
10 2 4 8 11 6 5
 10 equal to normal.
 Caution: 2 is less than normal.
 Caution: 4 is less than normal.
 8 equal to normal.
 11 equal to normal.
 6 equal to normal.
 5 equal to normal.

I tried this:
m3<-c(10,2,4,8,11,6,5)
m3
str(m3)
mu3<-unlist(m3, recursive = TRUE, use.names = TRUE)
n3<-as.numeric(mu3)
n3
str(n3)
dg3<-5
dg3
class(dg3)
dg1<-as.logical(dg3)
dg1
class(dg1)
dg <-(n3 >= 5)
dg
{cat (m3)}
for (r4 in dg) {
    if (r4 == dg.1) {
    cat("\n", r4,"equal to normal.")
    }
    else {
    cat("\n Caution: ", "is less than normal.")
    }
}

but I'm getting:
10 2 4 8 11 6 5
 TRUE equal to normal.
 Caution:  is less than normal.
 Caution:  is less than normal.
 TRUE equal to normal.
 TRUE equal to normal.
 TRUE equal to normal.
 TRUE equal to normal.

A: I think you can replace the whole thing with:
cat(m3, "\n", ifelse(m3 >= 5, paste(m3, "equal to normal.\n"),
                              paste("Caution:", m3, "is less than normal\n")))
#> 10 2 4 8 11 6 5
#>  10 equal to normal.
#>  Caution: 2 is less than normal
#>  Caution: 4 is less than normal
#>  8 equal to normal.
#>  11 equal to normal.
#>  6 equal to normal.
#>  5 equal to normal.


text:
Q: Spark Context Issue with Spring Boot application I wrote a Spring boot application using Apache Spark. It works on my machine perfectly but when I tried to deploy it on a VM (Debian 9 with 4 GO of memory , 2 vCPU and 60 GB of storage) and run it  , it throws this exception : Error initializing SparkContext.
java.lang.IllegalArgumentException: There is already an RpcEndpoint called LocalSchedulerBackendEndpoint.
I added the option : set("spark.driver.allowMultipleContexts", "true") and it didn't work also.
I don't use multiple contexts in my program, here's the code :
public Set<Customer> retrieveCustomers(String a) {
        SparkConf sparkConf = new SparkConf().setAppName("Spring boot app ")
                .setMaster("local[2]")
                .set("spark.driver.allowMultipleContexts", "true") ;

         JavaSparkContext ctx = new JavaSparkContext(sparkConf);

    final List<String> stopWords = getStopWords(ctx).collect();
    List<Tuple2<String, Tuple3<String,String,String>>> collect = getCompanies(ctx).collect();
    a = cleanText(a.substring(0,1000));
    String allTextLowerCase = a.toLowerCase();
    JavaRDD<Customer> words = ctx.parallelize(Arrays.asList(SPACE.split(a)))
            .filter(word -> isNotStopWord(word,stopWords))
            .filter(word -> ! word.trim().isEmpty())
            .map(word -> toDenomination(collect,word,allTextLowerCase))
            .filter(Objects::nonNull);
    Set<Customer> customers = new HashSet<>( words.collect());
    System.out.println("Total found Words :" + customers.size());
    ctx.cancelAllJobs();
    ctx.stop();
    System.clearProperty("spark.driver.port");

}

Do you have any solution for my problem ? why the application has initialized multiple Spark contexts on the server while in localhost , it does not.
Thank you

A: Have you tried to inject the context as another regular Spring Bean instead of the manual instantiation? It should work anyway but I guess that is the proper way of using Spring.
Where are you calling this method from? How many times?
It seems like multiple threads are accessing the method simultaneously.


text:
Q: How to prevent sentry from logging errors while on Django local server? I am trying to prevent Sentry from logging errors to my Sentry dashboard while I'm working on my local server (i.e http://127.0.0.1:8000/). The only time I want sentry to log errors to my dashboard is when my code is in production. How can I go about this? I have tried this below, but it doesn't work:
if DEBUG == True
    sentry_sdk.init(
        dsn=os.environ.get('SENTRY_DSN', None),
        integrations=[DjangoIntegration()],

        # Set traces_sample_rate to 1.0 to capture 100%
        # of transactions for performance monitoring.
        # We recommend adjusting this value in production.
        traces_sample_rate=1.0,

        # If you wish to associate users to errors (assuming you are using
        # django.contrib.auth) you may enable sending PII data.
        send_default_pii=True
    )

A: There are two ways you can do this:
The first option is to import sys and check for runserver (ref:https://stackoverflow.com/a/49874564/15205504)
import sys

if (len(sys.argv) >= 2 and sys.argv[1] != 'runserver'):
    sentry_sdk.init(
        dsn=os.environ.get('SENTRY_DSN', None),
        integrations=[DjangoIntegration()],

        # Set traces_sample_rate to 1.0 to capture 100%
        # of transactions for performance monitoring.
        # We recommend adjusting this value in production.
        traces_sample_rate=1.0,

        # If you wish to associate users to errors (assuming you are using
        # django.contrib.auth) you may enable sending PII data.
        send_default_pii=True
)

The second option is to specify an environment type in your settings.py. For instance, if your production server is Heroku, you can create an env_type variable in Heroku or your .env file and set it to 'HEROKU', then use it like this:
env_type = os.environ.get('env_type', 'LOCAL')

if env_type == 'HEROKU':
    sentry_sdk.init(
        dsn=os.environ.get('SENTRY_DSN', None),
        integrations=[DjangoIntegration()],

        # Set traces_sample_rate to 1.0 to capture 100%
        # of transactions for performance monitoring.
        # We recommend adjusting this value in production.
        traces_sample_rate=1.0,

        # If you wish to associate users to errors (assuming you are using
        # django.contrib.auth) you may enable sending PII data.
        send_default_pii=True
)

A: Setting the dsn to None will no-op all SDK operations, so your config should work unless you are also setting the SENTRY_DSN variable in your local environment.

A: Try like this:
  if not DEBUG:
    sentry_sdk.init(
        dsn="SENTRY_DSN",
        integrations=[DjangoIntegration()],

        # Set traces_sample_rate to 1.0 to capture 100%
        # of transactions for performance monitoring.
        # We recommend adjusting this value in production.
        traces_sample_rate=1.0,

        # If you wish to associate users to errors (assuming you are using
        # django.contrib.auth) you may enable sending PII data.
        send_default_pii=True
    )


text:
Q: Quais as características e funcionalidades do Apache Struts? Particularmente não conheço como é a estrutura e o funcionamento desse framework, mas pelo que tenho lido sobre o assunto, ele vem sendo muito utilizado no desenvolvimento Web.
Quais as características e funcionalidades do Apache Struts?

A: Denis,
O Apache Struts, tanto o 1, como o 2, é sim, um framework muito utilizado na Indústria. Principalmente como Solução para sistemas que se beneficiem da arquitetura MVC.  Sem dúvida, você encontrará muitos projetos utilizando ele.
Na minha experiência tenho visto muitas aplicações sendo migradas para Spring MVC.
Portanto, posso te dizer que não há mais muitos projetos novos sendo construídos em Struts, pelo menos não nos meios onde estou. Eu também já trabalhei com Struts 1, e posso afirmar que é inferior ao Spring MVC 3.0, pois o último oferece mais funcionalidades e melhor separation of concerns além de um melhor desacoplamento, pois no Struts um é necessário herdar classes, como as ActionForms
As principais vantagens que eu notei ao trabalhar com ele foram:

*

*Uma rica taglib para criação de .JSPs. Haviam muitas tags auto-explicativas que eu pude usar com facilidade, para pelo menos naquela época gerar conteúdo HTML dinâmico

*Renderizar POJOs, mapeando-os diretamente a propriedades descritas em tags dos JSPs, o problema é que eu tinha que escrever classes Adapters pois ele só renderizava FormBeans(classes herdadas de componentes do Struts).

*Me afastou da programação direta com Servlets(Servlet API), pois ele já abstraia essa camada.

*Me permitiou associar páginas com URLs, e essas URLs com Actions, que tem o papel de Controller no Struts( o C do MVC)

Quais as características e funcionalidades do Apache Struts?

Funcionalidades Core

*

*Arquitetura da estrutura conectável que permite que os ciclos de vida
de solicitação possam ser personalizados para cada Action.

*Estrutura de validação flexível que permite que regras de validação
possam ser desacopladas do código da Action.

*Abordagem hierárquica à internacionalização que simplifica a
localização de aplicativos.

*Conversão de tipo automática que mapeia de forma transparente os
valores de HTTP para objetos de dados Java nativos, resolvendo um dos
esforços mais tediosos ao criar aplicações web.

*Motor de injeção de dependência integrado que gerencia o ciclo de
vida e dependências dos componentes.

*Arquivos de configuração modular que usam pacotes e namespaces para
simplificar o gerenciamento de grandes projetos com centenas de
Actions.

*Anotações Java 5 disponíveis(programação declarativa)

Aqui há uma comparação entre a versão 1 e 2:
https://struts.apache.org/docs/comparing-struts-1-and-2.html


text:
Q: count of the fraction of each category I have a dataframe similar to this
ID  category  fraction_0  fraction 1
A    1         1/3         2/3
A    1         1/3         2/3
A    0         1/3         2/3
C    1         0/1         1/1
B    0         1/1         0/1

fraction_0 and fraction_1 are output.
fraction_0 is group by ID, in ID A, how many in category is 0. For take A as an example, in 3 As, there is one zero and two 1s. So fraction_0 is 1/3, and fraction_1 is 2/3.
my code looks as below
df.groupby('ID')['category'].agg(lamda x: x/x.sum())

However, this piece of code does not help me categorize 0 and 1. Anyone knows how to fix this?

A: Use groupby + value_counts with normalize=True to get the fractions. Then we need to reshape and merge the result back to the original.
res = (df.groupby('ID')['category']      # For category within each ID
        .value_counts(normalize=True)    # Calculate %
        .unstack(-1)                     # Each category to a column
        .fillna(0)                       # No occurrences -> 0%
        .add_prefix('fraction_'))        # Modify column names

df = df.merge(res, on='ID', how='left')

  ID  category  fraction_0  fraction_1
0  A         1    0.333333    0.666667
1  A         1    0.333333    0.666667
2  A         0    0.333333    0.666667
3  C         1    0.000000    1.000000
4  B         0    1.000000    0.000000


text:
Q: Azure storage emulator connecting to unknown sql instance I have a "fresh" (I think refurbished) laptop from my employer, where I installed a new instance of the Azure Storage Emulator. This one fails to start with the well known message:

"Error: Unable to start the storage emulator".

In my eventviewer I see the following message:

Login failed for user 'xxxx'. Reason: Failed to open the explicitly
  specified database 'xxxxx'. [CLIENT: local machine]

The thing is, I don't know which server that is (unknown to me and my team), and the username is also unknown. I've searched for quite some time, but I can't find any article where is explained where the connection strings are configured used by the emulator instead of connecting to the emulator. For me, I only need the blob storage, so sql is not even needed, but I can't disable it it seems.
Any tips?

A: It is trying to connect to LocalDb instance. By default (localdb)\MSSQLLocalDb. Make sure you have it up and running. I believe it is connecting via intergated security, thus with your windows account.
In case you would like to point storage emulator to different instance you have to configure it with command
AzureStorageEmulator.exe init /server <SQLServerInstance>
For more info about confiuguration take a look at Use the Azure storage emulator for development and testing

A:
For me, I only need the blob storage, so sql is not even needed, but I can't disable it it seems.

By default, the storage emulator uses a database in Microsoft SQL Server 2012 Express LocalDB. You can choose to configure the storage emulator to access a local instance of SQL Server instead of the LocalDB instance.  For more information, please refer to How the storage emulator works.

For complete info: it is connecting to a localdb but it expects all sorts of databases and accounts which aren't there

Currently, It doesnot support all sorts of databases. The storage emulator connects to SQL Server or LocalDB using Windows authentication.
If you have any ideas, you could give your feedback to Azure team.


text:
Q: CDT marks std::initalizer_list as error My eclipse cdt marks function definitions and function calls that use initializer_lists as error. This happens both on linux and windows even though the path to the include is set and it seems to find it. Now even though it's just mildly annoying I want to get rid of it.
I suspect I have to tell the cdt something like the -std=c++0x I had to tell the compiler to get initializer lists compiled. Anyone have an idea how to fix this?

A: A little late, but here are some workaround steps:

*

*Window > Preferences > C/C++ > Code Analysis

*Select the Invalid Arguments item under Syntax and Semantic Errors.

*Click the Customize Selected... button.

*In the Scope tab, add the file(s) containing the initialization list syntax to the exclusion patterns.

*Click OK/Apply/OK.

*Select the files that show errors, right click > Index > Freshen All Files

The errors should go away then (they did for me).


text:
Q: Accidentally crashed my website in Drupal 7? I was just editing my website, and was playing around with themes. I installed the Bootstrap 3 theme. When I set it to default, the website crashed! .Now i am not able to visit or login to my website .I kept getting this error message:

PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064
  You have an error in your SQL syntax; check the manual that
  corresponds to your MariaDB server version for the right syntax to use
  near '))' at line 1: SELECT n.uid AS uid, n.created AS created FROM
  {node} n WHERE (n.status = :db_condition_placeholder_0) AND (n.type IN
  ()) ; Array ( [:db_condition_placeholder_0] => 1 ) in
  _archive_post_count() (line 385 of /home/eric/public_html/medics/sites/all/modules/archive/archive.module).

Even i am unable to go to admin page.
Please help me!

A: *

*The problem seems to be not in Bootstrap theme, but rather in Archive module. I think that problem is here: AND (n.type IN ())

*Try to clear the cache by visiting www.your-site.com/update.php and them try to open www.your-site.com/admin/modules directly and disable this module.

A: Clear the cache from drush .
1. Go to your folder in terminal.
2. Type drush cc all.
3. If nothing happens then change the theme from Terminal using drush  using
drush vset admin_theme bartik


text:
Q: In Django, how can I get an exception's message? In a view function, I have something like:
try:
    url = request.POST.get('u', '')
    if len(url) == 0:
        raise ValidationError('Empty URL')
except ValidationError, err:
    print err

The output is a string: [u'Empty URL']
When I try to pass the error message to my template (stuffed in a dict, something like { 'error_message': err.value }), the template successfully gets the message (using {{ error_message }}).
The problem is that I get the exact same string as above, [u'Empty URL'], with the [u'...']!
How do I get rid of that?
(Python 2.6.5, Django 1.2.4, Xubuntu 10.04)

A: ValidationError actually holds multiple error messages.
The output of print err is [u'Empty URL'] because that is the string returned by repr(err.messages) (see ValidationError.__str__ source code).
If you want to print a single readable message out of a ValidationError, you can concatenate the list of error messages, for example:
    # Python 2
    print '; '.join(err.messages)

    # Python 3
    print('; '.join(err.messages))

A: If you are importing ValidationError from django.core.exceptions you can simply use messages method as err.messages.
https://github.com/django/django/blob/main/django/core/exceptions.py#L124
If you are importing ValidationError from rest_framework.serializers , there is no messages property for the ValidationError but there is detail property. so you can use err.detail which will give you a dictionary.
In order to concatenate all the error messages as a string, you can use
"".join(["".join(v) for v in err.detail.values()])
or
"".join([k+" - "+"".join(v) for k,v in err.detail.items()])
https://github.com/encode/django-rest-framework/blob/master/rest_framework/exceptions.py#L143

A: A more general way to always know where the message is to call the dir function on your err variable to show you all the attribute of this object.
from that list you can infer where the messages are, in my case (with django 3.2) i found out that the message dict is in an attribute called args.
so to use it (with a print for example)
try:
    url = request.POST.get('u', '')
    if len(url) == 0:
        raise ValidationError('Empty URL')
except ValidationError, err:
    print(err.args) # HERE THE ERROR DICT MESSAGE IS ACCESSIBLE

A: I fixed it by changing ValidationError to BaseException.


text:
Q: Toggle select table columns on/off by using radio buttons (off by default) I have a basic table that should show first name and last name columns only when loaded. The user can toggle the radio buttons to show one extra column at a time. The issue is that the toggling is not working correctly and the user can see multiple extra columns at once. Also, when the table loads, the extra columns aren't hidden. I have this working for checkboxes but when I adjusted for radio buttons it caused these issues.

$('input[type="radio"]').each(function() {
    var inputValue = "table ." + $(this).attr("name");
    $(inputValue).hide();
});

$('input[type="radio"]').click(function(){
    var inputValue = "table ." + $(this).attr("value");
    $(inputValue).toggle();
});

Select a column to show. You can only show one extra column from the options below at a time.

<input type="radio" name="extraCol" id="age" value="age">
Age
<input type="radio" name="extraCol" id="gender" value="gender">
Gender
<input type="radio" name="extraCol" id="hometown" value="hometown">
Hometown
<input type="radio" name="extraCol" id="off" value="off" checked>
Don't show;

    First name
    Last name
    Age
    Gender
    Hometown

    Jill
    Smith
    50
    Female
    Springfield

    Eve
    Jackson
    94
    Female
    South Park

A: You  need to loop through your radio button to hide other columns which are shown using $(this).val() which will give us radio button value and using this we will hide.
Demo Code :

$('input[type="radio"]').each(function() {
 //get the value of radio button
  var inputValue = "table ." + $(this).val();
  $(inputValue).hide();
});

$('input[type="radio"]').click(function() {
//first check all radio hide all other columns
  $('input[type="radio"]').each(function() {

    var inputValue = "table ." + $(this).val();
    $(inputValue).hide();
  });
  //show only the column which is clicked
  var inputValue = "table ." + $(this).attr("value");
  $(inputValue).toggle();
});

Select a column to show. You can only show one extra column from the options below at a time.

<input type="radio" name="extraCol" id="age" value="age">
Age
<input type="radio" name="extraCol" id="gender" value="gender">
Gender
<input type="radio" name="extraCol" id="hometown" value="hometown">
Hometown
<input type="radio" name="extraCol" id="off" value="off" checked>
Don't show;

    First name
    Last name
    Age
    Gender
    Hometown

    Jill
    Smith
    50
    Female
    Springfield

    Eve
    Jackson
    94
    Female
    South Park


text:
Q: SQL, using entered time to find session with most visitors I have a query that I need to write. Lab assistants will enter the information for students coming to the lab for help.  the field are:

Visit_ID, Student_ID, Visit_Date, Time_In, Time_Out, Course, Asst_ID.

There are 3 sessions for time_in entry

*

*Session 1   9-12

*Session 2   12-3

*Session 3   3-6
The query needs to determine which session on the current day had the most visitors. This is what I have so far:
with cte as
 (
  select
      case
        when cast(Time_In as time) >'12:00:00' and cast(Time_In as time) <='15:00:00'  and Visit_Date = cast(GETDATE() as date)then 'Session 2'
        when cast(Time_In as time) >'3:00:00' and cast(Time_In as time)<= '6:00:00' and Visit_Date = cast(GETDATE() as date) then 'Session 3'
        else 'Session 1'
      end session
      /*course*/
    from Lab_Visits2
  ), ctecnt as (
  select session,/* course,*/ count(*) cnt
  from cte
  group by session /*course*/
)
select session, /*course,*/ (cnt)
from (
  select session, /*course,*/ cnt, row_number() over (order by cnt desc) rn
  from ctecnt
  ) t
where rn = 1


text:
Q: Getting SyntaxError when using lightweight-charts in NextJS I'm trying to use the lightweight-charts package in my nextjs project, however when i try to call the createChart function I get this error in my nodejs console.
...\lightweight-charts\dist\lightweight-charts.esm.development.js:7
import { bindToDevicePixelRatio } from 'fancy-canvas/coordinate-space';
^^^^^^

SyntaxError: Cannot use import statement outside a module

Component:
import styled from "styled-components"
import { createChart } from 'lightweight-charts';

const Wrapper = styled.div``

const CoinPriceChart = () => {
  const chart = createChart(document.body, { width: 400, height: 300 });
  return <Wrapper></Wrapper>
}

export default CoinPriceChart

Page:
import styled from "styled-components"
import CoinPriceChart from "../../components/charts/CoinPriceChart"

const Wrapper = styled.div``

const CoinDetailPage = () => {
  return (
    <Wrapper>
      <CoinPriceChart />
    </Wrapper>
  )
}

export default CoinDetailPage

Does someone have an idea what I could do to enable me to use the library within nextjs?
Thank you!

A: That because you are trying to import the library in SSR context.
Using next.js Dynamic with ssr : false should fix the issue :
import styled from "styled-components"
import dynamic from "next/dynamic";
const CoinPriceChart = dynamic(() => import("../../components/charts/CoinPriceChart"), {
  ssr: false
});

const Wrapper = styled.div``

const CoinDetailPage = () => {
  return (
    <Wrapper>
      <CoinPriceChart />
    </Wrapper>
  )
}

export default CoinDetailPage


text:
Q: Is it possible for MediatorLiveData to wait for two livedata too receive an update? As the title says. I have two livedata objects that fetch some data from an API. I want to wait for the two livedata have finished fetching the data before doing some operation on their values.
This is what I have so far:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button myButt;
    private MainViewModel mvw;
    private TextView myView;
    private MediatorLiveData data;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        mvw = new ViewModelProvider(this).get(MainViewModel.class);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myButt = findViewById(R.id.button);
        myView = findViewById(R.id.textview);
        myButt.setOnClickListener(this);

        data =  new MediatorLiveData<>();
        data.addSource(mvw.getAllOrders(), new Observer<Orders>() {
            @Override
            public void onChanged(Orders orders) {
                data.setValue(orders);
            }
        });
        data.addSource(mvw.getAllOrderRows(), new Observer<OrderRows>() {
                    @Override
                    public void onChanged(OrderRows orderRows) {
                        data.setValue(orderRows);

                    }
        });
        data.observe(this, new Observer<Orders>() {
                    @Override
                    public void onChanged(Orders order) {
                        myView.setText(mvw.extractDate(order));
                         //Here i want to manipulate order and orderrows
                        Log.i("livedata" , order.getOrders().toString());
                    }
                });

    }

    @Override
    public void onClick(View view) {
        switch(view.getId()){
            case R.id.button:
                Log.i("button","clicked");
                mvw.updateOrderData(); // calls for new values to be fetched
                mvw.updateOrderRowData();
        }
    }
}

The problem is, I seem to only be able to listen to one of the two live datas. How can I wait for both to finish and then do some operation on both of them?

A: You can write a MergedMediatorLiveData class as follows:
class MergedLiveData<T, K, S>(sourceA: LiveData<T>, sourceB: LiveData<K>, private val mergedCallback: (resultA: T?, resultB: K?) -> S) : MediatorLiveData<S>() {

      private var resultA: T? = null
      private var resultB: K? = null

      init {
        super.addSource(sourceA) {
          resultA = it
          value = mergedCallback(resultA, resultB)
        }
        super.addSource(sourceB) {
          resultB = it
          value = mergedCallback(resultA, resultB)
        }
      }
    }

So your usage will be:
     val sample = MergedLiveData(sourceA = mvw.getAllOrders(), sourceB = mvw.getAllOrderRows())
      { resultA: OrderRows?, resultB: Orders? ->
        // Todo manipulate order and orderRows
      }


text:
Q: Get response time of web client web-flux Just want to know if there is any way to get the response time of web client of spring web-flux?

A: you also have the possibility to use elapsed() for this kind of thing
webClient.get().uri("/bla").retrieve()
     .bodyToMono(String.class)
     .elapsed()  // map the stream's time into our streams data
     .doOnNext(tuple -> log.info("Milliseconds for retrieving {}", tuple.getT1()))
     .map(Tuple2::getT2) // after outputting the measurement, return the data only

Note, that elapsed() elapses the whole reactive stream, so if you're doing something before the webClient... part, you should put an elapsed() before that - this resets the timer.

A: With Spring Boot you have built-in metrics for that. See issue.
If you want to implement your custom stopwatch, you could do something like this:
Mono<String> resultMono = Mono.subscriberContext()
        .flatMap(context -> webClient.get()
                .uri("/foo")
                .retrieve()
                .bodyToMono(String.class)
                .doOnNext(ignored -> log.info("Execution duration is {} ms",
                        System.currentTimeMillis() - context.<Long>get("stopWatch"))))
        .subscriberContext(context -> context.put("stopWatch",
                System.currentTimeMillis()));

A: You could use the metrics from HttpClient:
HttpClient.create(...
.....
.metrics(true, CustomMetricsRecorder::new);

and:
public class CustomMetricsRecorder implements HttpClientMetricsRecorder {

    @Override
    public void recordDataReceivedTime(SocketAddress remoteAddress, String uri, String method, String status, Duration time) {
      System.out.println("Client metric: " + durationToString(time) + " - DataReceivedTime - " + uri + " " + method.toUpperCase());
    }
    @Override
    public void recordDataSentTime(SocketAddress remoteAddress, String uri, String method, Duration time) {
      System.out.println("Client metric: " + durationToString(time) + " - DataSentTime - " + uri + " " + method.toUpperCase());
    }
    @Override
    public void recordResponseTime(SocketAddress remoteAddress, String uri, String method, String status, Duration time) {
      System.out.println("Client metric: " + durationToString(time) + " - total req+resp - " + uri + " " + method.toUpperCase());
    }
    @Override
    public void recordDataReceived(SocketAddress remoteAddress, String uri, long bytes) {

    }
    @Override
    public void recordDataSent(SocketAddress remoteAddress, String uri, long bytes) {

    }
    @Override
    public void incrementErrorsCount(SocketAddress remoteAddress, String uri) {

    }
    @Override
    public void recordDataReceived(SocketAddress remoteAddress, long bytes) {

    }
    @Override
    public void recordDataSent(SocketAddress remoteAddress, long bytes) {

    }
    @Override
    public void incrementErrorsCount(SocketAddress remoteAddress) {

    }
    @Override
    public void recordTlsHandshakeTime(SocketAddress remoteAddress, Duration time, String status) {
      System.out.println("Client metric: " + durationToString(time) + " - TlsHandshakeTime - " + remoteAddress);
    }
    @Override
    public void recordConnectTime(SocketAddress remoteAddress, Duration time, String status) {
      System.out.println("Client metric: " + durationToString(time) + " - ConnectTime - " + remoteAddress);
    }
    @Override
    public void recordResolveAddressTime(SocketAddress remoteAddress, Duration time, String status) {
      System.out.println("Client metric: " + durationToString(time) + " - ResolveAddressTime - " + remoteAddress);
    }
  }

will print:
Client metric: 00:00.09 - ResolveAddressTime - xxxx.com:443
Client metric: 00:00.69 - ConnectTime - xxxx.com/52.210.218.144:443
Client metric: 00:00.87 - TlsHandshakeTime - xxxx/52.210.218.144:443
Client metric: 00:00.01 - DataSentTime - /xx/xx/v1 POST
Client metric: 00:00.14 - DataReceivedTime - /xx/xx/v1 POST
Client metric: 00:00.122 - total req+resp - /xx/xx/v1 POST


text:
Q: Increase width and height of Bitmap without stretching or recreating For the last few weeks I've been working on a program that creates a bitmap that has a grid on it, which every time I want to change the image, I recreate it with
    gridBMP = New Bitmap(gridColumns * boxWidth, gridRows * boxHeight)
    Dim g As Graphics = Graphics.FromImage(gridBMP)
    Dim p As New Pen(Color.FromArgb(255, 0, 0, 0)) ' Create a new pen, black
    Dim b As New SolidBrush(Color.FromArgb(255, 0, 0, 0)) ' Create a new solid brush, black

    Dim wallPen As New Pen(Color.FromArgb(255, 192, 192, 192)) ' Create a new pen, Grey

    Dim maxWidth As Integer = pb_grid.Width ' Get Max width
    Dim maxHeight As Integer = pb_grid.Height ' Get Max height

    g.Clear(Color.White) ' Make white background

    For i = 0 To gridColumns ' Draw Column lines
        Dim val As Integer = i * boxWidth
        g.DrawLine(wallPen, New Point(val, 0), New Point(val, maxHeight))
    Next

    For i = 0 To gridRows ' Draw Row lines
        Dim val As Integer = i * boxHeight
        g.DrawLine(wallPen, New Point(0, val), New Point(maxWidth, val))
    Next

    ' Draw borders at bottom and right
    g.DrawLine(wallPen, New Point(0, maxHeight), New Point(maxWidth, maxHeight))
    g.DrawLine(wallPen, New Point(maxWidth, 0), New Point(maxWidth, maxHeight))

    drawAll(g, p, b) ' Draw all objects

    pb_grid.Image = gridBMP

    ' Dispose of brush and pen
    p.Dispose()
    b.Dispose()

As you see at the end I set the picturebox image as the bitmap with pb_grid.Image = gridBMP
But is there an easier way to do this? Because currently recreating the image everytime seems to be very intensive and takes a second or two to update the image, which I don't want, I would like it to be near to instant as possible with the form, but I cannot figure out how to 'Increase' the width of the grid, without recreating the whole image, which takes time.
I've tried a background worker, but it's really no difference because the image takes so long anyways.
Any thoughts and suggestions are welcome!
Thanks


text:
Q: How to handle redirect response from a Single Page Application browser only webapp I have Single Page Application, browser only webapp (javascript, no server side).
The user interacts with the application and sets some variables.
Far after the creation of the main index.html page, when the user wants to upload a file, he needs to authenticate with an external service using oauth2 (using "token / implicit grant").
Once authenticated, the authentication service responds with a redirect, possibly to another page (page2).
What should the page2 do to continue the flow of the program?

*

*Should it redirect back to the original main page (this time, with the access token)?

*If so, wouldn't this reload the main page and reset the application and the variables that were set?
Thanks,
Avner

EDIT
Ricardo,
I don't use a specific web platform, just plain javascript.
@charlietfl
I found a general example here that does postMessage between 2 seperate windows and it works ok.
I'm straggling to customize it according to Ricardo's comments, i.e.

*

*make the second window popup

*set a separate HTML file or a "noop" route on your SPA as redirect URL (what is a noop route?)

*poll for that URL in the popup
I found this example that create the popup in the main page (index.html), set the redirect, and poll in order to close the popup.
In my case I set the redirect URL to a new page (auth.html) that does postMessage with the access token back to the main page (index.html).
If the auth.html page is not openned in the browser, should I still expect to receive a message in the main page index.html ?
From what I read for postMessage to work both pages, index.html, auth.html should be opened in 2 separate tabs in the browser.

A: You can use a small popup, which will load the necessary oauth2 endpoint, setting a separate HTML file or a "noop" route on your SPA as redirect URL. You may then poll for that URL in the popup, so you know when to close it (user is done with oauth2 flow).
This strategy is used by libraries like vue-authenticate, react-oauth and satellizer.
Also, depending on the specific service your are trying to authenticate against, you can find official libraries and SDKs that will handle the oauth2 flow automatically.
Last but not least, you could also save the current state of you application in browser storage, redirect to the oauth2 endpoint, and point back to your app as redirect URL. When coming back to your app, the specific route should be able to restore the saved data and resume user experience, with the addition of the oauth2 tokens.


text:
Q: Render result seems partially flipped on miyoo mini I'm trying to port game Freedink https://savannah.gnu.org/git/?group=freedink to Miyoo mini handheld. At the first run I saw this

*

*Splash screen is ok

*In da house: stats is ok but homies are flipped.

*The house collapsed
After some investigations I assumed that the problem is in SDL_BlitSurface function. After I changed this code
      {
    /* Copy splash to the background buffer so that D-Mod can
       start an effect from it (e.g. Pilgrim Quest's burning
       splash screen effect) */

    SDL_BlitSurface(splash, NULL, GFX_lpDDSTwo, NULL);
    SDL_FreeSurface(splash);
      }

    /* Copy splash screen (again) to the screen during loading time */
    SDL_BlitSurface(GFX_lpDDSTwo, NULL, GFX_lpDDSBack, NULL);

    flip_it();
  }

to this:
      {
    /* Copy splash to the background buffer so that D-Mod can
       start an effect from it (e.g. Pilgrim Quest's burning
       splash screen effect) */

    SDL_BlitSurface(splash, NULL, GFX_lpDDSThird, NULL);        //First copy to GFX_lpDDSThird
    SDL_BlitSurface(GFX_lpDDSThird, NULL, GFX_lpDDSTwo, NULL);  //And only then to GFX_lpDDSTwo
    SDL_FreeSurface(splash);
      }

    /* Copy splash screen (again) to the screen during loading time */
    SDL_BlitSurface(GFX_lpDDSTwo, NULL, GFX_lpDDSBack, NULL);

    flip_it();
  }

splash screen also become flipped. My question is simple: is this behavior known and how to fix this?


text:
Q: how to access from android device into remote sql lite web service i have built small app that gets data from remote sql lite server. im using ksoap2 for the android client and netbeans 7.4 for the web service.
my app work just fine on my emulator i get data from the sql throw the ws and into my emulator. the problem is with my mobile device. the app just dont work there. the data dosent transfer from some reason.
i did a little research and I think its because of the ip. im using ip 10.0.2.2:8080 and its probably local ip and my android just cant see it. so, how can he see it?? ive put my public ip and still the device dont get sql data.
can some one please tell my how to make this app work on my mobile?
this is my android code:
   package com.gy.webservice3_3;

import android.os.Bundle;
import android.app.Activity;
import android.content.res.Resources.Theme;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
//add import
//please copy and ...
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
//add import
//add import
import java.util.Hashtable;
import org.ksoap2.serialization.KvmSerializable;

public class Main_WebService3_3_Activity extends Activity {

    EditText et1;
    EditText et2;
    EditText et3;

    Button btn1;
    Button btn2;
    Button btn3;

    private static final String NAMESPACE = "http://myAndroidIt.gy.com/";
    private static final String URL = "http://10.0.2.2:8080/androidWS6_3/androidWS6_3?WSDL";
    private static final String SOAP_ACTION = "http://myAndroidIt.gy.com/getDataFromSql";
    private static final String METHOD_NAME = "getDataFromSql";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main__web_service3_3_);
        et1=(EditText) findViewById(R.id.editText1);
        et2=(EditText) findViewById(R.id.editText2);
        et3=(EditText) findViewById(R.id.editText3);
        btn1=(Button) findViewById(R.id.button1);
        btn2=(Button) findViewById(R.id.button2);
        btn3=(Button) findViewById(R.id.button3);
        btn1.setOnClickListener(btn1Listener);
    //  btn2.setOnClickListener(btn2Listener);

    }

    private OnClickListener btn1Listener=new OnClickListener() {
        @Override
        public void onClick(View v) {
            Thread netWorkThread=new Thread(){
                @Override
            public void run() {
            SoapObject requset=new SoapObject(NAMESPACE,METHOD_NAME);
            PropertyInfo propInfo=new PropertyInfo();
            propInfo.setName("id");
            propInfo.setValue(et1.getText().toString()+"");
            propInfo.setType(PropertyInfo.STRING_CLASS);
            requset.addProperty(propInfo);

            SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
            envelope.setOutputSoapObject(requset);
            envelope.dotNet=false;

            try{
            HttpTransportSE ht=new HttpTransportSE(URL);
            ht.call(SOAP_ACTION, envelope);
            final SoapPrimitive response=(SoapPrimitive)envelope.getResponse();
            final String str=response.toString();
            Main_WebService3_3_Activity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                String []stary=str.split(",");
                et1.setText(stary[0].toString());
                et2.setText(stary[1].toString());
                et3.setText(stary[2].toString());

                }
            });

            }catch (Exception e) {
                Main_WebService3_3_Activity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(Main_WebService3_3_Activity.this, "wsad", Toast.LENGTH_SHORT).show();

                    }
                });

            }
            }
            };
            netWorkThread.start();
        }

    };
    private OnClickListener btn2Listener=new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main__web_service3_3_, menu);
        return true;
    }
    }

thx!


text:
Q: visual studio 2010 last successful build I made some changes to my website, then had to reformat my server, and over two weeks I tried to undo what I did (it was a stupid forum thingy). Obviously I missed something, becuase now I have the dreaded Build Failed With No Error problem.
This is my home server, so no I am not running source control.
After staring at it for a few days, I decided to try somehting. Today I allowed VS to run the last successful build, and it still works.
QUESTION: How can I go back to the last successful build? I don't care about any changes made since it worked. That's really all I need.
THANKS

A: Have you checked to see if you have Previous Versions available?
It sounds like you won't likely be able to recover the source files / project config, though you could certainly attempt to recover the "source" by using tools like ILSpy or .NET Reflector. You can use them to examine the output assemblies, and reconstruct your code if necessary.
As a lesson learned, both Mercurial and Git work wonderfully for versioning home projects - I'd give a slight nod to Mercurial in your case as it works just a tad bit easier on the Windows platform.


text:
Q: IndexError: too many indices for array: array is 2-dimensional, but 3 were indexed I am trying to identify Global Feature Relationships with SHAP values. The SHAP library returns three matrices and I am trying to select the SHAP matrix however, I am getting this error: "IndexError: too many indices for array: array is 2-dimensional, but 3 were indexed".
The code I have is below:
df_score = spark.sql("select * from sandbox.yt_trng_churn_device")

#XGBoost Model
import pickle
from xgboost import XGBClassifier
from mlflow.tracking import MlflowClient
client = MlflowClient()
local_dir = "/dbfs/FileStore/"
local_path = client.download_artifacts

model_path = '/dbfs/FileStore/'
model = XGBClassifier()
model = pickle.load(open(model_path, 'rb'))
HorizonDate = datetime.datetime(2022, 9, 5)
df = df_score
score_data = df.toPandas()
results = model.predict_proba(score_data)
results_l = model.predict(score_data)
score_data["p"]=pd.Series( (v[1] for v in results) )
score_data["l"]=pd.Series( (v for v in results_l) )
spark.createDataFrame(score_data).createOrReplaceTempView("yt_vw_tmp_dev__scores")
spark.sql("create or replace table sandbox.yt_vw_tmp_dev__scores as select * from yt_vw_tmp_dev__scores")

#SHAP Analysis on XGBoost

from shap import KernelExplainer, summary_plot
sql = """
select d_a.*
from
hive_metastore.sandbox.yt_trng_device d_a
right join
(select decile, msisdn, MSISDN_L2L
from(
select ntile(10) over (order by p desc) as decile, msisdn, MSISDN_L2L
from sandbox.yt_vw_tmp_dev__scores
) inc
order by decile) d_b
on d_a.MSISDN_L2L = d_b.MSISDN_L2L and d_a.msisdn = d_b.msisdn
"""

df = spark.sql(sql).drop('msisdn', 'imei', 'imsi', 'event_date', 'MSISDN_L2L', 'account_id')
score_df = df.toPandas()
mode = score_df.mode().iloc[0]
sample = score_df.sample(n=min(100, score_df.shape[0]), random_state=508502835).fillna(mode)
predict = lambda x: model.predict(pd.DataFrame(x, columns=score_df.columns))
explainer = KernelExplainer(predict, sample, link="identity")
shap_values = explainer.shap_values(sample, l1_reg=False)

# The return of the explainer has three matrices, we will get the shap values one
shap_values = shap_values[ :, :, 0]

I am fairly new to coding but it would be great if someone could give some direction on this


text:
Q: Does the Azure Application Gateway support websockets I've setup an azure application gateway with two backend machines. The gateway has cookie affinity enabled and sockjs is used.
The browser initiates a websocket connection for which it receives an '101 Switching Protocols' response. However there is no communication over the websockets and sockjs falls back to long polling.
Does the azure application gateway support websockets? Is some configuration required to enable websockets?

A: Amit Srivastava [MSFT]:

Websocket support is being worked on and will be available shortly.

Update: I asked what shortly meant: the feature is planned for end May.
Update 2:
Amit Srivastava [amsriva@MSFT] on 12/08/2016

Websocket is now supported on Application Gateway.


text:
Q: NOT EXISTS and NOT IN IN Sql server Hi I'm not sure why it produce different result. could someone let me know what is my mistake?
this query return 2 rows of records
SELECT Prod.bintProductRef FROM Prod_ProfileTbl Prod
WHERE   Prod.intDepartmentRef =4

bintProductRef
--------------------
164475
164476

and this query return 1 row of record
SELECT Prod.bintProductRef FROM Prod_ProfileTbl Prod
        WHERE  intCatRef = 132

bintProductRef
--------------------
164475

NOT EXISTS, when combine the above 2 queries, it should return 164476, but there is no ouput.
SELECT Prod.bintProductRef FROM Prod_ProfileTbl Prod
      WHERE   Prod.intDepartmentRef =4
      AND NOT EXISTS (
        SELECT Prod.bintProductRef FROM Prod_ProfileTbl Prod
        WHERE  intCatRef = 132)

NOT IN, this return 1 row of data , which is 164476 and this is correct.
 SELECT Prod.bintProductRef FROM Prod_ProfileTbl Prod
      WHERE  Prod.intDepartmentRef =4
       AND Prod.bintProductRef NOT IN (
        SELECT  Prod.bintProductRef FROM Prod_ProfileTbl Prod
        WHERE  intCatRef = 132)

A: In your "NOT EXISTS" you do not have any link between your main query and the sub query in the NOT EXISTS.
NOT EXISTS evaluates your subquery, it selects something, therefore "something" exists and your NOT EXISTS will be false and no rows are returned.
If you wish to use EXISTS you'll need to link the two querys together; something like this:
SELECT Prod.bintProductRef FROM Prod_ProfileTbl Prod
WHERE   intDepartmentRef =4
AND NOT EXISTS (
    SELECT 1 FROM Prod_ProfileTbl Prod2
    WHERE  intCatRef = 132 AND prod.intCatRef = prod2.intCatRef)

, but for your purpose, the NOT IN or similar is the better approach.

A: NOT EXISTS (...) means that it will only be true if whatever is in the brackets returns nothing.  As you have shown it does return a row, hence NOT EXISTS is false, hence the AND is false and you won't get any rows returned.

A: SELECT Prod.bintProductRef FROM Prod_ProfileTbl Prod
      WHERE   Prod.intDepartmentRef =4
      AND NOT EXISTS (
        SELECT Prod.bintProductRef FROM Prod_ProfileTbl Prod
        WHERE  intCatRef = 132)

This part of code has a logic and it is than Prod.intDepartmentRef =4  and a query should not exists to return a result. note that two predicates should become true so the where clause become true . but also not that this query :
SELECT Prod.bintProductRef FROM Prod_ProfileTbl Prod
            WHERE  intCatRef = 132

exists an have result so the second predicate become false and you have : true and false ---> false so there is no result to return.


text:
Q: Retrieve client IP in :ranch I'm using :ranch to receive TCP packges in my Phoenix application.
First I created a listener in the server using:
:ranch.start_listener(tcp_echo, ranch_tcp, [{port, 5555}], echo_protocol, [] )

How could I print the client IP in the echo_protocol?

A: Ranch includes a sample echo application.
In echo_protocol.erl, there's an init function that accepts the connection from the client:
init(Ref, Socket, Transport, _Opts = []) ->
    ok = ranch:accept_ack(Ref),
    loop(Socket, Transport).

You can display the client ip address there:
init(Ref, Socket, Transport, _Opts = []) ->
    ok = ranch:accept_ack(Ref),
    {ok, {IpAddress, _}} = inet:peername(Socket),
    io:format("Client ~p~n", [IpAddress]),
    loop(Socket, Transport).

It will appear in a format like:
Client {127,0,0,1}


text:
Q: Write a function that asks the user to enter their name, age and height in meters and then display a customised message using a single print statement name = requestString("Enter your name:")

age = requestNumber("Enter your age:")

height = requestNumber("Enter your height:")

print "Hello", name, "!", "i see that you are", num, "years old", "&", height, "tall"

Its not printing as i want it to print.

A: There is no num vaiable declared.
use age instead of num in

print "Hello", name, "!", "i see that you are", num, "years
  old", "&", height, "tall"

Use
print "Hello", name, "!", "i see that you are", age, "years old", "&", height, "tall"


text:
Q: Loop through Json files and extract specific data I have a bunch of Json files in storage where I can loop through to pick out a set list that meets my criteria. Even though the Json files have different data and structures, they all have 1 thing in common - A Metadata property with the structure like:
"meta": {
    "source": "user1",
    "createdDate": "2018-07-16T16:36:58.6471066+01:00",
    "recordCount": 12
},

I would like to extract the metadata of each file and store the results in a new DTO with the structure:
"data": [
{
    "source": "User1",
    "createdDate": "2018-07-16T16:36:58.6471066+01:00",
    "recordCount":12
},
    {
    "source": "User2",
    "createdDate": "2018-07-15T13:01:23.5611259+01:00",
    "recordCount":18
}
]

At the moment my code looks like this:
foreach (string s in objectType) //objectType is a simple string array for my file criteria
{
    var fileData = storage.GetS3(s, testOrg); //custom method to get file from storage, returns the json file contents using StreamReader. Returns null if no file found

    if (fileData != null)
    {
        var response = JsonConvert.DeserializeObject(fileData);

        //extract metadata from file to populate DTO

    }
}

Any help is appreciated. I am very much a newbie to c# in general so please go easy!
My DTO currently looks like the following but can be changed:
public class FileStatusResponse
{
    [JsonProperty("data")]
    public FileStatusDetail[] Data { get; set; }
}

public class FileStatusDetail
{
    [JsonProperty("source")]
    public string FileType { get; set; }

    [JsonProperty("recordCount")]
    public string RecordCount { get; set; }

    [JsonProperty("refreshDate")]
    public DateTime RefreshDate { get; set; }
}

A: OK I seem to have sorted it with:
var fileStatusList = new List<FileStatusDetail>();
        var storage = new S3Manager();

        foreach (string s in objectType)
        {
            var fileData = storage.GetS3(s, organisationCode);

            if (fileData != null)
            {
                var parsedObject = JObject.Parse(fileData);
                var parsedJson = parsedObject["meta"].ToString();

                var json = JsonConvert.DeserializeObject<Metadata>(parsedJson);

                fileStatusList.Add(new FileStatusDetail
                {
                    source = s,
                    RecordCount = json.RecordCount,
                    RefreshDate = json.CreatedDate

                });

            }

        }

Thanks itsme86 for pointing me in the right direction


text:
Q: Hibernate Criteria on EmbeddedId property throws org.hibernate.QueryException: could not resolve property I'm struggling with a very weird behaviour of Hibernate when using Hibernate Criteria API. I'm using hibernate 4.3.6 Final.
I got a class AnnouncementAttribute like this:
@Entity
@Table(name = "announcement_attribute")
public class AnnouncementAttribute implements Serializable {

    @EmbeddedId
    protected AnnouncementAttributePK id;

    @Column(name = "attribute_value")
    private String attributeValue;
}

and below the AnnouncementAttributePK class:
@Embeddable
public class AnnouncementAttributePK implements Serializable {
    @ManyToOne
    @JoinColumn(name = "attribute_id")
    private Attribute attr;

    @ManyToOne
    @JoinColumn(name = "announcement_id")
    private Announcement announcement;
}

And the Attribute class:
@Entity
@Table(name = "attribute")
public class Attribute implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "attribute_type")
    private Integer attributeType;

    @Column(name = "attribute_name")
    private String attributeName;
}

I ommitted getters/ setters here.
Problem is when I try to access @EmbeddedId property attr via Criteria API:
Criteria ac = session().createCriteria(AnnouncementAttribute.class);
ac.add(Restrictions.and(
                    Restrictions.eq("id.attr.attributeName", "someKey"),
                    Restrictions.eqOrIsNull("attributeValue", "someValue")));

I'm getting:

org.hibernate.QueryException: could not resolve property: id.attr.attributeName of: com.example.app.domain.AnnouncementAttribute

I already tried to create an alias for embeddedId - still no luck.

A: Well, altough I'm not convinced to the solution I found, I'll post it anyways, maybe someone will find it useful or maybe it will be a good subject for further discussion.
I removed @Embedded from AnnouncementAttributePK
public class AnnouncementAttributePK implements Serializable {
    @ManyToOne
    @JoinColumn(name = "attribute_id")
    private Attribute attr;

    @ManyToOne
    @JoinColumn(name = "announcement_id")
    private Announcement announcement;
}

, then in AnnouncementAttribute I've changed @EmbeddedId to combination of @IdClass and @Id:
@Entity
@Table(name = "announcement_attribute")
@IdClass(AnnouncementAttributePK.class)
public class AnnouncementAttribute implements Serializable {

    @Id
    private Attribute attr;
    @Id
    private Announcement announcement;

    @Column(name = "attribute_value")
    private String attributeValue;
}

and finally in the Criteria:
Criteria ac = session().createCriteria(AnnouncementAttribute.class)
            .createAlias("attr", "atrib");
ac.add(Restrictions.and(
                    Restrictions.eq("atrib.attributeName", "someKey"),
                    Restrictions.eqOrIsNull("attributeValue", "someValue")));

After those changes everything works just fine. I got no clue why... I'll further investigate it anyway, because it's at least weird. Maybe it has something to do with a fact that my application is running in Spring Context, using LocalContainerEntityManagerFactoryBean and spring-data-jpa, and a org.hibernate.Session object is obtained by unwraping EntityManager ? :
@PersistenceContext
private EntityManager entityManager;

and session:
private Session session(){
    return entityManager.unwrap(Session.class);
}

A: try
Criteria ac = session().createCriteria(AnnouncementAttribute.class)
.createAlias("id", "id")
.createAlias("id.attr", "idAttr")
.add(Restrictions.and(
                    Restrictions.eq("idAttr.attributeName", "someKey"),
                    Restrictions.eqOrIsNull("attributeValue", "someValue")));

A: A workaround is to add the nested id columns as columns as well with insert and update as false. So you have a read-only mapping of the embeddedId that you can use in criteria without any problems.


text:
Q: Simple Content Switching with JQuery and CSS I have several divs of class wrap. Each has several divs of class content. How can I automatically switch out the content that is showing using jquery and css?

    ...

...

...

A: I'm thinking you want something like this?:
http://jsfiddle.net/Btcue/
CSS:
.is-not-showing {

  display: none;

}

JS:
$( ".wrap > .content" ).toggleClass( "is-not-showing" );

A: How bout simply:
$('.is-not-showing').hide()
function switch() {
    $('.is-not-showing, .is-showing').toggle();
}


text:
Q: eventListener for hashChange I am trying to add an event listener for my page in ReactJS. I have added it to componentDidMount(). But the is only triggered for the initial page load.
How can I get it trigger whenever there is a change in the address bar.
componentDidMount:function(){

        window.addEventListener("hashchange", console.log('hashchange1'));
        $(window).bind("hashchange", console.log('$ - hashchange'));
        window.onhashchange =  console.log('hashchange3');
        ReactDOM.findDOMNode(this).addEventListener('hashChange',console.log('ReactDOM - hashchange'));
    },

I've tried several different ways to get it to work, but they all work only on the first load. What am I doing wrong?
Thanks.

A: You're just executing the console.log in every case, and adding its return value as the listener. You need to pass a function as an event listener, for example:
window.addEventListener("hashchange", e => console.log('hashchange1', window.location.hash ));

https://jsfiddle.net/ku6okrp2/
EDIT to make it look more obvious using ES5:
window.addEventListener("hashchange", function(e){
  console.log('hashchange1', window.location.hash )
});


text:
Q: Derive explained sum of squared from beta May I ask, how should I calculate $$SSE=\sum_{i=1}^n(\hat{y}-\bar{y})^2$$
given
$$\beta=-0.094=\frac{\sum(x_i-\bar{x})(y_i-\bar{y})}{\sum(x_i-\bar{x})^2}$$
$$intercept=1.9781$$
and
$\bar{x}=4.9817$,$\bar{y}=1.512, N=100, \sum x^2=2505.8313, \sum xy=750.9786, \sum (y_i-\bar{y})^2=0.9217$

A: First of all, it is SSR, and using regression coefficient estimates, we can calculate estimated target values: $\hat y_i = \hat \beta x_i+\hat \beta_0$, then substitute into the formulation of SSR:
$$\begin{align}\text{SSR}&=\sum_{i=1}^n(\hat y_i-\bar y)^2=\sum_{i=1}^n \hat y_i^2 -2 \bar y\sum_{i=1}^n \hat y_i+\underbrace{\sum_{i=1}^n \bar y^2}_{\text{known}}\end{align}$$
For the second term, we have:
$$\sum_{i=1}^n \hat y_i=\hat\beta\sum_{i=1}^n x_i+\sum_{i=1}^n\hat \beta_0=\hat \beta n\bar x+n\hat \beta_0$$
And, for the third term:
$$\sum_{i=1}^n\hat y_i^2=\hat \beta^2\sum_{i=1}^nx_i^2+2\hat\beta\hat\beta_0\sum_{i=1}^n x_i+\sum_{i=1}^n\hat\beta_0^2$$
which is composed of all known terms.
If you want SSE, just substitute above SSR from SST, which is $\sum (y_i-\bar y)^2$ .


text:
Q: Python issues with specific outlook email Can anyone give me advice for this issue? I am not getting any error messages and don't know where to start.
I made a program that checks emails in an Outlook inbox for pdf attachments from a list of senders, then saves the attachments to a folder. You put in a starting date and choose how many days you want to search through. There is a line in the code to show all emails being checked even if they aren't related to the sender/s for debugging. It has been working fine for months, until recently I got an email from ebay that contains an emote of a packed cardboard box in the subject line, and this specific email causes the program to misbehave.
Here's an example of the erroneous output - I've put in zero to search for 'any sender' from a list, and chosen a date range like always. The first Attribute Error is caused by an undeliverable message (which is not considered class 43 'mail' by outlook). You can see that the first normal mail item in the date range gets checked, with the subject line etc displayed, but then the next message is the ebay email, which is way outside the date range. The program skips over several days without checking any other emails in that range and ends the search. Same thing happens if I disable the display of every email in output (all emails still get read by the program, but there is a line to display only relevant ones).
There seems to be some issue with that specific email - Ebay is not one of the senders in the list the program checks for attachments, and even if I have a date range of zero days it will still show that email from a week ago as the last email checked. The only thing that seems unique about it is the cardboard box emote in the subject line, there is nothing else about it that stands out to me.
Here is the output:
Choose a sender (blank to exit): 0
Enter a starting search date in format dd-mm-yyyy (blank to exit): 05-05-2020
Enter how many days previous to search through: 3
Your search starts from 2020-05-05 00:00:00 and ends on 2020-05-02

Searching for any sender
Searching...
Attribute error (not class 43 mail) for item at mainChoice0() - .MessageClass REPORT.IPM.Note.NDR - Class 46
Looking at [...], WordPress has been updated on [...]. 2020-05-05
Looking at  ORDER DELIVERED: 10x Capacitive Stylus Pen Tou… 2020-04-28
Reached end of date range: final message -  ORDER DELIVERED: 10x Capacitive Stylus Pen Tou… 2020-04-28

If I move the problematic email to a different inbox then my program will correctly check emails across the whole date range I entered.
It gets weirder, because if put in a date range that would include that particular ebay email, then it DOES NOT appear in the output, while OTHER ebay emails which include emotes like a truck or a ticked box DO get checked by the program.
Looking at  ORDER UPDATE: 10x Capacitive Stylu... 2020-04-22
Looking at FAILED Schemus mail synchronization 2020-04-22
Attribute error (not class 43 mail) for item at mainChoice0() - .MessageClass REPORT.IPM.Note.NDR - Class 46
Attribute error (not class 43 mail) for item at mainChoice0() - .MessageClass REPORT.IPM.Note.NDR - Class 46
Looking at Active Directory Sync Failure 2020-04-21
Looking at ✅ ORDER CONFIRMED: 10x Capacitive Stylu... 2020-04-21

Below is the block of code for collecting attachments:
def mainChoice0(): #COLLECT ATTACHMENTS
        #Choose sender from menu.
        senderNum = input("Choose a sender (blank to exit): ")
        if senderNum == "":
            mainChoiceDisplay0 = False
            topMenu() #Return to main menu
        else:
            senderNum = int(senderNum)

        senderChoice = listSender[senderNum]

        ####Determine search range by date
        startDate = input("Enter a starting search date in format dd-mm-yyyy (blank to exit): ")
        if startDate == "":
            mainChoiceDisplay0 = False
            topMenu()

        #strptime will convert startDate from a string to a usable date
        startDate = datetime.datetime.strptime(startDate, "%d-%m-%Y")
        searchRange = int(input("Enter how many days previous to search through: "))
        searchDate = startDate.date() - datetime.timedelta(days = searchRange)
        print("Your search starts from", startDate, "and ends on", searchDate, "\n")

        #SEARCH ANY SENDERS
        if senderNum == 0:
            print("Searching for any sender")
            print("Searching...")

        #LOOK AT INBOX CONTENTS
            for msg in reversed(itcontents): #reversed() looks at most recent received email first based on date

                #while mainChoiceDisplay0 == True:

                    try:

                        ###!!! uncomment this to see details about every email even if they aren't relevant to the search  !!!####
                        print("Looking at", msg, msg.SentOn.date())

                        #msg.Sender is sender name, msg.SenderEmailAddress is the address.
                        if ( (str(msg.SenderEmailAddress) or str(msg.Subject) or str(msg.Sender) or str(msg.SentOnBehalfOfName)) in senderDict and (msg.SentOn.date() >= searchDate and msg.SentOn.date() <= startDate.date())):
                            check += 1

                            print(check, "messages from", msg.SenderEmailAddress, "on", msg.SentOn.date()) #show number of messages from relevant senders

                            for x in msg.Attachments:
                                if str(".pdf").casefold() in str(x): #casefold() checks upper or lower case combinations e.g PDF pdf Pdf
                                    x.SaveAsFile("C:\\Users\\"+emailUser+"\\Desktop\\Invoices from Outlook\\" + str(msg.SentOn.date()) + str(msg.SenderEmailAddress) + x.FileName)
                                    print("Saved attachment", x, "from", str(msg.Sender()), "on", str(msg.SentOn.date()))
                                    #break
                                    #Stop searching inbox earlier than searchDate

                        nextMail() #Look at the next most recent email, repeat until end of date range

                        #Final message to indicate end of search, with subject line and date of the final message.
                        if msg.SentOn.date() < searchDate:
                            print("Reached end of date range: final message -", msg, msg.SentOn.date(), "\n")
                            mainChoiceDisplay0 = False
                            topMenu()

                    except UnicodeEncodeError: #unsupported characters
                        print("Subject line could not be parsed", msg, msg.SentOn.date())
                        #continue

                    except OverflowError: #caused by invalid or very old date e.g 01-01-0000
                        print("Date calculation caused an overflow error, possibly because you entered a very old date e.g 01-01-0000 at mainChoice0()")
                        #break

                    except AttributeError: #The email was the wrong class for the attribute msg.Sender or you tried to use an attribute that doesn't work for that method
                        print("Attribute error (not class 43 mail) for item at mainChoice0() - .MessageClass", msg.MessageClass, '- Class', msg.Class)
                        pass

                    except ValueError:
                        print("Invalid input caused a value error in mainChoice0().")

A: Instead of iterating over all items and checking separate property every time you need to use the Find/FindNext or Restrict methods of the Items class. Read more about thses methods in the following articles:

*

*How To: Retrieve Outlook calendar items using Find and FindNext methods

*How To: Use Restrict method in Outlook to get calendar items


text:
Q: MySQL DUMP as CSV I've looked around and nothing seems to work:
$file = '/path/to/file.csv';
$cmd = 'mysqldump DATABASE TABLE > '.$file.' --host=localhost --user=USER --password=PASS';
$cmd .= ' --lock-tables=false --no-create-info --tab=/tmp --fields-terminated-by=\',\'';
exec($cmd);

Everything I try creates an empty CSV file.  Any ideas?  Thanks much.

A: I found a way to accomplish this using mysql via command line --
        $file = '/path/to/file.csv';
        if(is_file($file))
            unlink($file);
        $sql = 'SELECT * FROM database.table';
        $cmd = 'mysql --host=localhost --user=USER --password=PASS --quick -e \''.$sql.'\' > '.$file;
        exec($cmd);

A: Try SQLYog, works like a charm.
Here is a link to a download of the free community version
http://www.softpedia.com/progDownload/SQLyog-Community-Edition-Download-82252.html
Then all you have to do is right click on the table in question, and go export, and select CSV etc...
If your looking for the code how to do it, then look in the history tab after you export the table and see what code was executed.

A: what happens when you do:
    mysqldump DATABASE TABLE > /path/to/file.csv [snipped the rest of the command] from the command line?
Does it work?
Your last line try:
$cmd .= " --lock-tables=false --no-create-info --tab=/tmp --fields-terminated-by=','";

the single quotes don't get escaped in a single quoted string.

A: The > '.$file.' redirection should be the last (or first) part of the command


text:
Q: Google Chrome extension - integrate with Google Calendar How can a Chrome extension alter the Google Calendar event editing UI?
I see that, for example, the Moxtra extension has managed to inject UI including a button just below the location. According to their YouTube video they added a button to fill out the event description although when I installed Moxtra this no longer seems to work.
Stepping back from this a bit, it occurs to me that editing the Google Calendar page seems like something that could easily get messed up by future changes to Google Calendar. Perhaps it is better to edit the event description from the extension's own UI? If so, how can that be done?
Thanks.

A: It can be done with content scripts and modification of the DOM.
They probably check Event edit page for specific selectors and try to insert their own elements in the page, if they found it.
So, if UI of Google Calendar will change, extensions like Moxtra will be probably also broken.
You are right about the edit of the description - it's safer. But you still need to get a description field and change a content of it. There is no 100% safe way to do it and don't break on the change of UI.


text:
Q: How do call custom function on elements I am aware of Jquery events click,focus,focusout . How do call my own custom function and get that elements inside function for e.g
       <input type="text" class="pinBox" placeholder="Enter your pin here.">

        $('.pinBox').initialize();

As soon as one execute this there should be a function call which must invokes founction likes below.
     function initialize(){
var element = $(this);
$(element).after('<input type="password" maxlength="1" autocomplete="off" class="form-control pincode-input-text first" tabindex="30">'+
'<input type="password" maxlength="1" autocomplete="off" class="form-control pincode-input-text second" tabindex="31">                    '+
'<input type="password" maxlength="1" autocomplete="off" class="form-control pincode-input-text third" tabindex="32">                    '+
'<input type="password" maxlength="1" autocomplete="off" class="form-control pincode-input-text fourth" tabindex="33">);                 '

}

similarly on $('.pinBox').disableInputBox(); there should be function like . function disableInputBox(){//whatever i want.}

A: $.fn.initialize = function() {
    // below for example I have given a css property to give you idea how you can refer the element by this to play jquery code with.
    this.css( "color", "green" );
    return this;    // By returning `this`, will allow you to attach further jquery functions after calling this `initialize` function to the element
}

$( ".pinBox" ).initialize().addClass( "my-class" );

As you can see here, I have applied initialize function to  and then added one more jquery function addClass.

A: You can add your custom functions to jQuery using $.fn or jQuery.fn

function initialize(){
  console.log('Element text is :', $(this).text());
}

jQuery.fn.printText = initialize;

$(function(){
  $('span').each(function(index, span){
    $(span).printText();
  })
});

1
2
3
4
5

You can also pass your element as an argument

function printText(el){
  console.log('Element text is :', $(el).text());
}

$(function(){
  $('span').each(function(index, span){
    printText(span);
  })
});

1
2
3
4
5

Which to use?

*

*Any function added to jQuery will be lost if another jQuery is loaded. Libraries like jqLite and few others also use $ and overrides it. In such case, you will loose your function.

*Any custom function accessing element as argument can be very useful and can be exported to a utility. Such function can be made generic and can be used freely, but you will have to load the file to make them available. You might also have to add handling, if your function has to be specific for certain elements.

A: It depends on when you want the function to be executed... It could be on page load, or binded on a event, in the next code a few examples:
// on page load:
$(function() {
   initialize();
});

// on event binding:
$('.classname').on('click', function() {
  initialize();
});

Note, if the function should do something with the object, you need to pass it... for example:
$(function() {
   initialize(  $('.pinBox') );
});
function initialize( elem ){
   elem.after( ... );
};

Or if the event is always on the same object:
$(function() {
   initialize();
});
function initialize(){
     $('.pinBox').after( ... );
};


text:
Q: Noob question: Keras shapes are incompatible I'm a student in datascience and I'm trying to work with deep learning. The model I have is as follows:
Model: "sequential_32"

Layer (type)                 Output Shape              Param #
=================================================================
conv2d_26 (Conv2D)           (None, 27, 27, 32)        288
_________________________________________________________________
max_pooling2d_12 (MaxPooling (None, 13, 13, 32)        0
_________________________________________________________________
dense_13 (Dense)             (None, 13, 13, 128)       4224
_________________________________________________________________
dropout_6 (Dropout)          (None, 13, 13, 128)       0
_________________________________________________________________
dense_14 (Dense)             (None, 13, 13, 10)        1290
=================================================================
Total params: 5,802
Trainable params: 5,802
Non-trainable params: 0
_________________________________________________________________

Now I'm trying to fit some data into it with the following code:
print(x_train.shape)
print(x_test.shape)
result = model.fit(x_train, y_train,
          batch_size=batch_size,
          epochs=epochs,
          verbose=1,
          validation_data=(x_test, y_test))

Which outputs the following:
(60000, 28, 28, 1)
(10000, 28, 28, 1)
# some error codes followed by:
ValueError: Shapes (32, 10) and (32, 13, 13, 11) are incompatible

I feel like it really is an easy mistake to fix but I just can't see it. Any help and/ or explanation is welcome!

A: Yes, Thymen's response helped me. Thank you. The model now looks like this:
Model: "sequential_35"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
conv2d_29 (Conv2D)           (None, 27, 27, 32)        160
_________________________________________________________________
max_pooling2d_15 (MaxPooling (None, 13, 13, 32)        0
_________________________________________________________________
flatten (Flatten)            (None, 5408)              0
_________________________________________________________________
dense_17 (Dense)             (None, 128)               692352
_________________________________________________________________
dropout_8 (Dropout)          (None, 128)               0
_________________________________________________________________
dense_18 (Dense)             (None, 10)                1290
=================================================================
Total params: 693,802
Trainable params: 693,802
Non-trainable params: 0
_________________________________________________________________


text:
Q: login authentification in c i need to find a way to create an authentication app in c
but it can't display the result it only shows a *
it also stores the password in the file so that it can also access it after complete execution
i have'nt tried much code to do it
#include <stdio.h>

void main()
{
 char password[10], username[10], ch;
 int i;

 printf("Enter User name: ");
 gets(username);
 printf("Enter the password < any 8 characters>: ");
 for (i = 0; i < 8; i++)
 {
            ch = getchar();
            password[i] = ch;
            ch = '*' ;
            printf("%c", ch);
 }
        password[i] = '\0';
 /*  Original password can be printed, if needed */
 printf("\n Your password is :");
 for (i = 0; i < 8; i++)
 {
            printf("%c", password[i]);
 }
}

A: It is impossible in standard C. You need some implementation-defined terminal libraries. Here you have an example for Linux:
#include <termios.h>
#include <unistd.h>

char *readPassword(char *buff, const size_t maxLength)
{
    size_t cLength = 0;
    int ch;
    while((ch = fgetc(stdin)) != EOF && ch != '\n')
    {
        printf("\b*");
        buff[cLength++] = ch;
        if(cLength == maxLength - 1) break;
    }
    buff[cLength] = 0;
    return buff;
}

int main(void)
{

    static struct termios savedterm, term;

    tcgetattr( STDIN_FILENO, &savedterm);
    /*now the settings will be copied*/
    term = savedterm;

    term.c_lflag &= ~(ICANON);

    tcsetattr( STDIN_FILENO, TCSANOW, &term);

    char password[10];
    readPassword(password, sizeof(password));
    tcsetattr( STDIN_FILENO, TCSANOW, &savedterm);
    printf("\nPassword is: \"%s\"", password);
}

If your terminal support non echo input you can disable it term.c_lflag &= ~(ICANON | ECHO); and you will not need '\b'


text:
Q: How to avoid exit from fullscreen on browser when refresh page? Is there method to avoid exit from fullscreen when a web page gets refreshed?
What i tried so far
I've used javascripts toggleFullScreen() function via onclick Handler on a button to set view on fullscreen mod.
But when the page got refreshed (using F5 key) it will exit from fullscreen mod. As I noticed in browsers (press f11 to fullscreen), when refresh while in fullscreen mod it doesn't get exit from fullscreen mod.
Question:

Is there any option to stop exiting fullscreen mod in case of a refresh if it got triggerd manually using toggleFullScreen()?


text:
Q: Why does location.replace in a .then function does not allow me to send data to firestore? I have some functions in an even listener function (click event). Inside of it, I have a function that sends data to firestore when the 'place order' button is clicked. I have a .then function that alerts the user with 'your order has been placed' after the data is sent to firestore. This works great, but when I add another .then function after the alert function to switch to another page once the alert window is closed, the data never gets sent to firestore.

var placeOrderButton = document.getElementsByClassName('placeOrderBtn')
 for (var i = 0; i < placeOrderButton.length; i++) {
     var button = placeOrderButton[i]
     button.addEventListener('click', placeOrderClicked)
 }

 function placeOrderClicked(event) {
     var y = year.getFullYear();
     var m = month.getMonth();
     var d = day.getDate();
     var h = hours.getHours();
     var m = minutes.getMinutes();
     var s = seconds.getSeconds();
     var mm = milliseconds.getMilliseconds();

     var orderID = ("" + y + m + d + h + m + s + mm);

     localStorage.setItem('processedOrderID', orderID);

     //getting and sending data to order
     db.collection('shoppingSession').doc(localStorage.getItem('seshID')).collection('inCart').get().then(function (querySnapshot) {
         querySnapshot.forEach(function (doc) {

             var idName = doc.id;
             var title = doc.data().title;
             var qty = Number(doc.data().qty);
             var price = Number(doc.data().price);
             var itemTotal = qty * price;
             var orderTotal = 90.00;
             var thiss = orderTotal.toFixed(2);

             addingPrices.push(itemTotal);

             //moving data to orders table for cooks
             db.collection('orders').doc(orderID).collection('inCart').add({
                 title: title,
                 price: price,
                 qty: qty
             });

         });

     }).then(function () {
         alert("Processing your order...");

     }).then(function () {
         location.assign("index.html");
     });

     // remember that this inside an onclick event

 }; //end of onlick event


text:
Q: Need a functions that adds (adm)/(mod) if current user is admin/moderator right after their username When a moderator/admin leaves a comment I want them to stand out and not be like any other comment. I have this piece of code so far but I dont think will do any good
<?php $current_user_is_a_mod = current_user_can( 'edit_others_posts' );if ( $current_user_is_a_mod ) echo '(mod)'; ?>

A: You can ask for roles with current_user_can() too:
current_user_can( 'administrator' )

or
current_user_can( 'editor' )

There is no built-in role moderator.


text:
Q: Incorrect badge icons? I was browsing Aviation.SE site when I noticed "+10" on the reputation dialog.  I clicked on the achievements icon in the top nav bar to see what I got that rep for.  It was for a answer on Stack Overflow, but that's irrelevant.  Also in the drop-down achievements panel were listed a couple of my recent badges from SO - but with an icon for the Aviation.SE - see the screenshot below.

Of course, there's a site icon indicating which site the badges were for, yet I was confused for a second when I saw a little plane badge.
So, is this a slight oversight/bug or an intended behavior?


text:
Q: Find and replace character from the string I have one table in that one column of varchar type I want to replace all data which have '?' with '-' for every row.
For example I have following data
Substance Abuse Facility ? Outpatient
Substance Abuse Facility ? Inpatient

and result should be
Substance Abuse Facility - Outpatient
Substance Abuse Facility – Inpatient

Can someone help me to form this query, only '?' should be replace with '-'.

A: Use REPLACE:
UPDATE MyTable SET mycolumn = REPLACE ( mycolumn , '?' , '-' )