text:
Q: Binding list to params in Pandas read_sql_query with other params I've been trying to test various methods for making my code to run. To begin with, I have this list:
member_list = [111,222,333,444,555,...]
I tried to pass it into this query:
query = pd.read_sql_query(
"""
select member id
    ,yearmonth
from queried_table
where yearmonth between ? and ?
    and member_id in ?
""", db2conn, params = [201601, 201603, member_list])

However, I get an error that says:

'Invalid parameter type.  param-index=2 param-type=list', 'HY105'

So I looked around and tried using formatted strings:
query = pd.read_sql_query(
"""
select member id
    ,yearmonth
from queried_table
where yearmonth between ? and ?
    and member_id in (%s)
""" % ','.join(['?']*len(member_list), db2conn, params = [201601, 201603, tuple(member_list)])

Now, I get the error:

'The SQL contains 18622 parameter markers, but 3 parameters were supplied', 'HY000'

because it's looking to fill in all the ? placeholders in the formatted string.
So, ultimately, is there a way to somehow evaluate the list and pass each individual element to bind to the ? or is there another method I could use to get this to work?
Btw, I'm using pyodbc as my connector.
Thanks in advance!

A: Break this up into three parts to help isolate the problem and improve readability:

*

*Build the SQL string

*Set parameter values

*Execute pandas.read_sql_query

Build SQL
First ensure ? placeholders are being set correctly. Use str.format with str.join and len to dynamically fill in ?s based on member_list length. Below examples assume 3 member_list elements.
Example
member_list = (1,2,3)
sql = """select member_id, yearmonth
         from queried_table
         where yearmonth between {0} and {0}
         and member_id in ({1})"""
sql = sql.format('?', ','.join('?' * len(member_list)))
print(sql)

Returns
select member_id, yearmonth
from queried_table
where yearmonth between ? and ?
and member_id in (?,?,?)

Set Parameter Values
Now ensure parameter values are organized into a flat tuple
Example
# generator to flatten values of irregular nested sequences,
# modified from answers http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python
def flatten(l):
    for el in l:
        try:
            yield from flatten(el)
        except TypeError:
            yield el

params = tuple(flatten((201601, 201603, member_list)))
print(params)

Returns
(201601, 201603, 1, 2, 3)

Execute
Finally bring the sql and params values together in the read_sql_query call
query = pd.read_sql_query(sql, db2conn, params)

A: WARNING! Although my proposed solution here works, it is prone to SQL injection attacks.
Therefor, it should never be used directly in backend code!
It is only safe for offline analysis.
If you're using python 3.6+ you could also use a formatted string litteral for your query (cf https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498)
start, end = 201601, 201603
selected_members = (111, 222, 333, 444, 555)  # requires to be a tuple

query = f"""
    SELECT member_id, yearmonth FROM queried_table
    WHERE yearmonth BETWEEN {start} AND {end}
      AND member_id IN {selected_members}
"""

df = pd.read_sql_query(query, db2conn)

A: query = 'Select count(*) cnt from TBL_DESK_AUDIT  where trunc(DATETIMECREATED) = trunc(sysdate) and DESK_NAME =' + "'"+dataframe_list1[0][0] + "'"
print(query)
df_TBL_DESK_AUDIT = pd.read_sql_query(query, connect);


text:
Q: securing app service connectivity to azure storage we have a blob container with anonymous access (open to internet) and an appservice talking to it.
What are our options of ensuring that only the appservice can talk to this storage endpoint? vnet integration is our last option.
Thanks -nen

A:
What are our options of ensuring that only the appservice can talk to
this storage endpoint?

One option would be to make use of Azure Role Based Access Control (RBAC) Data roles.
For this, first you would assign a managed identity to your App Service and then assign that identity appropriate Azure Storage RBAC data roles.
You would also need to block access to the storage account via access keys or shared access signature so that only your App Service can connect to your storage account using Azure AD authorization.
You can read more about it here: https://learn.microsoft.com/en-us/azure/storage/blobs/assign-azure-role-data-access?tabs=portal.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to redirect a .py file with GET variable to .php using .htaccess I would like to redirect /download.py?fileId=1 to /download.php?fileId=1 using .htaccess. Here's what I've tried without success:
RedirectMatch 301 ^/download\.py(.+) /download.php$1

A: You can use this rule:
RedirectMatch 301 ^/download\.py$ /download.php

Query string is automatically carried over to new URI.


text:
Q: Why can't we use this technique to compare complex numbers? I have heard that you can't compare complex numbers... Well it is true because it's not defined on the real number line, you can't compare imaginary quantities... But I just wanted to know that why can't we compare them using their modulus?
For example, let's say we have two complex numbers:
$$z_1 = 4 + 3i \quad \text{ and } \quad z_2 = 7 + 9i$$
Now we take their modulus,
$$|z_1| = 16 + 9 = 25 \\
|z_2| = 49 + 81 = 130$$
Now we could say that $z_2$ is greater than the first one right?


text:
Q: R: Error: $ operator not defined for this S4 class when using RadAR package I am trying to visualize features that were extracted from a dataset of CT-scans using radiomics. I extracted features using the Pyradiomics library, and now I have a few .csv files.
I found this R Library which can read a dataset and generate images for it. Reading the dataset works according to plan using the input = import_pyradiomics(dir = "/path/to/datadir") command, but when I try to visualize it using for instance plot_correlation_matrix(rdr = input, view_as = "heatmap"), one of the visualization functions, I get the following error:
Error: $ operator not defined for this S4 class
I read about S3 and S4 classes, and I think that [line 160] in the library is where this error occurs first as it attempts to call this '$' operator. I am currently using R version 4.0.2. It seems to me like this issue is caused by this R library relying on an older version of R, but it is relatively up to date. What can I do to resolve this issue? Do I have to go in and manually change the code in the library? Or is there an easier fix, such as casting the S4 class to an S3 class? I feel like I'm missing an easy solution because I'm not familiar with R.
I found a similar question here, but it doesn't answer my specific question. Answers on other questions regarding this topic also do not work for me unfortunately.

A: I am the developer of RadAR, thank you for your interest in our package. The issue was probably related to the use of a different version of the SummarizedExperiment R package. The bug has now been fixed. You can re-install the new version of RadAR from https://github.com/cgplab/RadAR.
For any questions related to RadAR, please refer to the "issues" section of the RadAR github page.


text:
Q: How to add new line in serial port communication vb.net? I open 2 serial port monitors which can send and receive data.
Also I have 2 virtual com ports, com3 and com4.
When I press for example "test" on the one and send it, the other receives it.
If I try to send an other text for example test2 then the other one receives it on a new line.
Example:
test
test2
I wrote a small vb.net program to send and receive data.
My vb.net program on com3 and the other monitor program on com4.
I have a button and inside the button the code:
SerialPort1.Write("test")

If I press the button 1 time the other program shows:
test
If I press it again the other program shows:
testtest
So why with my program the other monitor just merges the text and doesn't add a new line?
I tried
SerialPort1.WriteLine("test")

But that will only print if i press the button twice:
testtest
I even tried + Chr(13) but that will only print <cr> on the other monitor and not a new line..
what is all the others programs doing that my little program is not doing?


text:
Q: changing clicked element's style in array through javascript my html code:

div1

div2

div3

div4

div5

div6

function clickonelement(){
mydiv = document.getElementsByClassName("mydiv");
for(i=0; i<mydiv.length; i++){
mydiv.item(i).style.backgroundColor = "red";
mydiv[this].style.backgroundColor = "#fff";
}
}
css code
.mydiv{width:300px; height:30px;}

I want on onClick event to change clicked element's background to white and other elements background remain red in color but my code
    mydiv[this].style.backgroundColor = "#fff";
is not working. please solve this problem in JavaScript only. I am in basic stage of JavaScript.

A: You need to pass a reference to the element that you want to refer to with this, e.g. onclick="clickonelement(this)":

function clickonelement(elem) {
  mydiv = document.getElementsByClassName("mydiv");
  for (i = 0; i < mydiv.length; i++) {
    mydiv.item(i).style.backgroundColor = "red";
    elem.style.backgroundColor = "#fff";
  }
}

div1

div2

div3

div4

div5

div6

A: This is JS code for your HTML code, you need add addEventListener.
function clickonelement() {
  mydiv = document.getElementsByClassName("mydiv");

  for (var i = 0; i < mydiv.length; i++) {
    mydiv[i].addEventListener('click', function() {
      this.style.backgroundColor = "red";
      this.style.backgroundColor = "#fff";
    });
  }
}

A: Here is just another way of achieving the same functionality.
Objective

*

*To remove inline event handler

*Use loop only once instead of looping over all the matched class name (mydiv) on every click.

Used javascript functions & concepts

*

*querySelectorAll : - Used to select all matched elements with same class that is mydiv. It will return an nodelist containing all matched elements

*forEach:- is an array method which used to loop over list.It accepts three arguments. For this case two will be enough.

*addEventListener:- Is use to attach event to an element

*Closures:These functions 'remember' the environment in which they were created.
Hope this snippet will be useful
//Get all the matched Elements
var matches = document.querySelectorAll("div.mydiv");
//Use an variable to rememeber previous clicked element
var prevIndex = -1; //
// Loop over the list
matches.forEach(function(item,index){
 (function(i){ //  A closure is created
    item.addEventListener('click',function(){
       // if any previous element was clicked then rest it's background
        if(prevIndex !== -1){
         matches[prevIndex].style.background="red";
        }
        // change background of current element
        item.style.background="#fff";
        // update prevIndex
        prevIndex = i;
     })
    }(index))

})

Check this DEMO


text:
Q: Odoo Studio Bug So we created some new custom fields through Odoo Studio by just dragging them into the view. The problem now is that suddenly these fields became BASE Fields instead of custom fields. We were trying to delete them but Odoo didnt let us.

So what can we do in this situation?

A: try to delete the fields and any relationships they have with other fields from the xml


text:
Q: Positioning two D3 plots I am trying to position two plots in a 2 by 1 column using in D3.
The first plot is a scatter plot and the second plot is a histogram. Eventually, the data shown on one will depend on the region selected in the other. Right now, I'm having problems positioning the two plots.
My attempt.
Why do the two plots overlap?
I tried changing the "transform" attribute of the histogram (var histo) to account for the width of the first figure, but that just made the histogram disappear.


text:
Q: an error in runining canopy example in mahout I want to run canopy example in mahout, but I am getting error:

Warning: $HADOOP_HOME is deprecated.
Running on hadoop, using /usr/local/hadoop/bin/hadoop and HADOOP_CONF_DIR=
MAHOUT-JOB: /usr/local/mahout-distribution-0.7/examples/target/mahout-examples-0.7-> job.jar
Warning: $HADOOP_HOME is deprecated.
Exception in thread "main" java.lang.NoClassDefFoundError: com/google/common/io/Closeables
at org.apache.mahout.driver.MahoutDriver.loadProperties(MahoutDriver.java:214)
at org.apache.mahout.driver.MahoutDriver.main(MahoutDriver.java:98)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.hadoop.util.RunJar.main(RunJar.java:160)
Caused by: java.lang.ClassNotFoundException: com.google.common.io.Closeables
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
... 7 more

in case, there is guava-r09.jar in "/usr/local/mahout-distribution-0.7/examples/target/dependency" that including com/google/common/io/Closeables class and its dependency is in pom.xml.
what can I do to solve this error?

A: Unfortunately, Hadoop and Mahout is a mess. You are probably in jar hell.
I don't think it is actually worth to try a lot. Unless you have Google scale data, a non-Mapreduce implementation will likely be much faster. That is: as long as your data fits into memory of a single node, prefer a single-node solution.
In my experiments, a Mahout cluster with 10-15 CPUs would be about 5x slower than a good single CPU implementation. Because all this "framework" and the disk-oriented operation of Hadoop and Mahout come at a substantial cost. So, if your data isn't on the size of terabytes, don't use it.
Now to a more precise answer:
You are in a distributed world. It is not sufficient if this .jar file is avilable on your computer.
Due to the design of Hadoop, it must actually be uploaded to every host that participates in your computation. The mahout command is supposed to take care of this (identifying and uploading all required .jar files), but sometimes it fails to get the classpath right. And unfortunately, the process is a mess and hard to understand or debug.

Warning: $HADOOP_HOME is deprecated.

Take this warning seriously. What is the current way of getting the classpath right?


text:
Q: Why does viewModelScope.launch run on the main thread by default While I was learning coroutines and how to properly use them in an android app I found something I was surprised about.
When launching a coroutine using viewModelScope.launch { } and setting a breakpoint inside the launch lambda I noticed my app wasn't responsive anymore because it was still on the main thread.
This confuses me because the docs of viewModelScope.launch { } clearly state:

Launches a new coroutine without blocking the current thread

Isn't the current thread the main thread ? What is the whole purpose of launch if it doesn't run on a different thread by default ?
I was able to run it on anther thread using viewModelScope.launch(Dispatchers.IO){ } which works as I was expecting, namely on another thread.
What I am trying to accomplish from the launch method is to call a repository and do some IO work namely call a webservice and store the data in a room db. So I was thinking of calling viewModelScope.launch(Dispatchers.IO){ } do all the work on a different thread and in the end update the LiveData result.
viewModelScope.launch(Dispatchers.IO){
    liveData.postValue(someRepository.someWork())
}
So my second question is, is this the way to go ?

A: ViewModelScope.launch { } runs on the main thread, but also gives you the option to run other dispatchers, so you can have UI & Background operations running synchronously.
For you example:
fun thisWillRunOnMainThread() {

    viewModelScope.launch {

        //below code will run on UI thread.
        showLoadingOnUI()

        //using withContext() you can run a block of code on different dispatcher
        val result = novel.id = withContext(Dispatchers.IO) {
            withsomeRepository.someWork()
        }

        //The below code waits until the above block is executed and the result is set.
        liveData.value = result
        finishLoadingOnUI()
    }
}

For more reference, I would say there are some neat articles that will help you understand this concept.
Medium link that explains it really neat.

A: The idea behind main thread being default is you can run UI operations without having to change the context. It is a convention I guess Kotlin coroutine library writers have chosen
Suppose if by default if the launch runs on IO thread then the code would look like this
viewmodelScope.launch {
  val response = networkRequest()
  withContext(Dispatchers.Main) {
    renderUI(response)
  }
}

Suppose if by default if the launch runs on Default thread then the code would look like this
viewmodelScope.launch {
  val response: Response = null
  withContext(Dispatchers.IO) {
     response = networkRequest()
  }
  withContext(Dispatchers.Main) {
    renderUI(response)
  }
}

Since the default launch is on main thread, now you have to do below
viewmodelScope.launch {
  val response: Response = null
  withContext(Dispatchers.IO) {
     response = networkRequest()
  }
  renderUI(response)
}

To avoid the messy code initializing the response with null, we can also make the networkRequest as suspend and wrap the business logic of networkRequest() function in withContext(Dispatchers.IO) and that's how lot of people write their networkRequest() function as well! Hope this makes sense

A:
So my second question is, is this the way to go ?

I would expect two things to be different in your current approach.
1.) First step would be to define the scheduler of the background operation via withContext.
class SomeRepository {
    suspend fun doWork(): SomeResult = withContext(Dispatchers.IO) {
        ...
    }
}

This way, the operation itself runs on a background thread, but you didn't force your original scope to be "off-thread".
2.) Jetpack Lifecycle KTX provides the liveData { coroutine builder so that you don't have to postValue to it manually.
val liveData: LiveData<SomeResult> = liveData {
    emit(someRepository.someWork())
}

Which in a ViewModel, you would use like so:
val liveData: LiveData<SomeResult> = liveData(context = viewModelScope.coroutineContext) {
    withContext(Dispatchers.IO) {
        emit(someRepository.someWork())
    }
}

And now you can automatically trigger data-loading via observing, and not having to manually invoke viewModelScope.launch {}.

A: One of the main reasons it runs on Main thread, is because it's more practical for general use in ViewModel, like murali kurapati wrote. It was a design choice.
It's also important to note that all suspending functions should be "main safe" according to best pracices. That means, that your repository should switch coroutine context accordingly, like so:
class someRepository(private val ioDispatcher: CoroutineDispatcher) {
    suspend fun someWork() {
        withContext(ioDispatcher) {
            TODO("Heavy lifting")
        }
    }
}


text:
Q: WebGL painfully slow on Ubuntu 20.04 LTS TLDR; WebGL running smooth Win10 & previous Ubuntu 18. Now it's really bad.
I'm running a well updated Ubuntu 20.04 on my XPS15 9550.
Since I updated from Ubuntu 18 I recognized WebGL or other graphic intense browser apps run very slow.
Specs;
Core i5-6300HQ CPU @ 2.30GHz
GeForce GTX 960M
Samsung NVMe SSD 500GB

Hardware probe listing GTX960 as "detected" and not "working", Idk...
As a driver I use the proprietary nvidia-driver-450 package.
Running glxinfo|egrep "OpenGL vendor|OpenGL renderer" returns my GTX960M as the active graphic unit. Doing a GPU benchmark with glmark2 returns neat results and shows;
=======================================================
OpenGL Information
GL_VENDOR:     NVIDIA Corporation
GL_RENDERER:   GeForce GTX 960M/PCIe/SSE2
GL_VERSION:    4.6.0 NVIDIA 450.102.04

Running FishGL gives me 2fps.
My very specific question ist; WHY?

A: Wow. Fixed it super easily;

*

*Type chrome://flags in the address bar

*Press Ctrl + f and type " Rendering list ", "Override
software rendering list" should come up, enable it.

*Also check "hardware exeleration" in your chrome settings.

*Restart your browser (console; killall chrome)

-> Enjoy your hardware


text:
Q: Dropwizard. Send Json and make jersey + jackson recognize class i am farley new to jackson and jersey. Have done some programs that uses those libraries. But i have a problem that i cant find a solution for.
  @POST
  @Path("/submit")
  @Consumes(MediaType.APPLICATION_JSON)
  public void submitTicket(Ticket ticket)
  {
    System.out.println("*** SUBMIT A NEW TICKET ***");
    System.out.println("Ticket: " + ticket);
  }

This is in my ticketResource class. I am trying to send json from my webapplication to the server. But i only get error's when trying.
    $('#newTicketSubmit').click(function () {
    var jsonData = [
       {'topic':$('#inputTopic').val()},
       {'priority':$('#inputPriority option:selected').val()},
       {'assigned':$('#inputAssign option:selected').val()},
       {'text':$('#inputText').val()},
       {'solved':0},
       {'date':'No date set'}
    ];

    $.ajax({
        type: 'POST',
        url: '/ticket/submit',
        // The key needs to match your method's input parameter (case-sensitive).
        data: JSON.stringify(jsonData),
        processData: false,
        contentType: 'application/json; charset=utf-8',
        success: function(data){alert(data);},
        failure: function(errMsg) {
            alert(errMsg);
        }
    });
  });

This is how my javascript file looks like. It does call the server. But i am not 100% sure if i am doing everything correctly
public class Ticket {

  public Ticket()
  {
    /* Empty */
  }

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @JsonProperty
  private int id;

  @NotEmpty
  @JsonProperty
  private String topic;

  @NotEmpty
  @JsonProperty
  private String text;

  @NotNull
  @JsonProperty
  private int solved;

  @NotNull
  @JsonProperty
  private int priority;

  @NotNull
  @JsonProperty
  private int assigned;

  @NotEmpty
  @JsonProperty
  private String date;

And lastly here is a snipped of my Ticket class
What i want my project to understand is that when i send something from the javascript app. Then the server would understand how to create a Ticket class from that json data. If i understand everything correctly. That should be possible. But i am doing something wrong somehow.
Any help that could take me on the right path is more than welcome
    com.sun.jersey.spi.container.ContainerResponse: A message body writer for Java class io.dropwizard.jersey.errors.ErrorMessage, and Java type class io.dropwizard.jersey.errors.ErrorMessage, and MIME media type application/octet-stream was not found.
The registered message body writers compatible with the MIME media type are:
*/* ->
  com.sun.jersey.core.impl.provider.entity.FormProvider
  com.sun.jersey.server.impl.template.ViewableMessageBodyWriter
  com.sun.jersey.core.impl.provider.entity.StringProvider
  com.sun.jersey.core.impl.provider.entity.ByteArrayProvider
  com.sun.jersey.core.impl.provider.entity.FileProvider
  com.sun.jersey.core.impl.provider.entity.InputStreamProvider
  com.sun.jersey.core.impl.provider.entity.DataSourceProvider
  com.sun.jersey.core.impl.provider.entity.XMLJAXBElementProvider$General
  com.sun.jersey.core.impl.provider.entity.ReaderProvider
  com.sun.jersey.core.impl.provider.entity.DocumentProvider
  com.sun.jersey.core.impl.provider.entity.StreamingOutputProvider
  com.sun.jersey.core.impl.provider.entity.SourceProvider$SourceWriter
  com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider
  com.sun.jersey.core.impl.provider.entity.XMLRootElementProvider$General
  com.sun.jersey.core.impl.provider.entity.XMLListElementProvider$General
application/octet-stream ->
  com.sun.jersey.core.impl.provider.entity.ByteArrayProvider
  com.sun.jersey.core.impl.provider.entity.FileProvider
  com.sun.jersey.core.impl.provider.entity.InputStreamProvider
  com.sun.jersey.core.impl.provider.entity.DataSourceProvider
  com.sun.jersey.core.impl.provider.entity.StreamingOutputProvider

Stracktrace of exception:
javax.ws.rs.WebApplicationException: com.sun.jersey.api.MessageException: A message body writer for Java class io.dropwizard.jersey.validation.ValidationErrorMessage, and Java type class io.dropwizard.jersey.validation.ValidationErrorMessage, and MIME media type application/octet-stream was not found.
at com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:284)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1510)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:540)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:715)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
at io.dropwizard.jetty.NonblockingServletHolder.handle(NonblockingServletHolder.java:49)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1515)
at org.eclipse.jetty.servlets.UserAgentFilter.doFilter(UserAgentFilter.java:83)
at org.eclipse.jetty.servlets.GzipFilter.doFilter(GzipFilter.java:348)
at io.dropwizard.jetty.BiDiGzipFilter.doFilter(BiDiGzipFilter.java:127)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1486)
at io.dropwizard.servlets.ThreadNameFilter.doFilter(ThreadNameFilter.java:29)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1486)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:519)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1097)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:448)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1031)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:136)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
at com.codahale.metrics.jetty9.InstrumentedHandler.handle(InstrumentedHandler.java:173)
at io.dropwizard.jetty.RoutingHandler.handle(RoutingHandler.java:51)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
at org.eclipse.jetty.server.handler.RequestLogHandler.handle(RequestLogHandler.java:92)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
at org.eclipse.jetty.server.handler.StatisticsHandler.handle(StatisticsHandler.java:162)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
at org.eclipse.jetty.server.Server.handle(Server.java:446)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:271)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:246)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.run(AbstractConnection.java:358)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:601)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:532)
at java.lang.Thread.run(Thread.java:745)

A: Ok so i found a solution for my problem yesterday. The problem was my implementation of the Json data
   var jsonData = {
     'topic':$('#inputTopic').val(),
     'priority':parseInt($('#inputPriority option:selected').val()),
     'assigned':parseInt($('#inputAssign option:selected').val()),
     'text':$('#inputText').val(),
     'solved':0,
     'date':'No date set'
  };

This is a example of a working Json data in javascript.


text:
Q: What regex expression can replace every other word? Given the following sentence: Crazy Fredrick bought many very exquisite opal jewels., what regex expression would allow me to filter out every other word? I am doing my replace like this:
"Crazy Fredrick bought many very exquisite opal jewels.".replace(/regex goes here/gi, "replace string goes here")

So I want to create a regex expression that will turn that sentence into either Fredrick many exquisite jewels. or crazy bought very opal.

A: Could use the following (assumes your words are all matched by \w)
"Crazy Fredrick bought many very exquisite opal jewels.".replace(/(\w+) (\w+)/g, '$1');
-> "Crazy bought very opal."

Replacing $1 with $2 gives you:
"Fredrick many exquisite jewels."

A: Not sure if RegEx is the right tool, but you could split the string by space into an array and then use filter to remove the odd or even elements:
var s = "Crazy Fredrick brought many very exquisite opal jewels";

s.split(/\s+/)
    .filter(function (_, index) {
        return index % 2 !== 0; // only want "odd" words
    }).join(" ");

// yields "Fredrick many exquisite jewels"

A: Not the best solution, but you can try using these regexes:
\b\S+\b\s?(?=((\b\S+\b\s?){2})*\.?$)
\b\S+\b\s?(?=\b\S+\b\s?((\b\S+\b\s?){2})*\.?$)

Explanation and demonstration here: http://regex101.com/r/kR3hS5


text:
Q: Conditional probability and calculation if $P(F|E)=3P(F|E^c)$
$P(E)=0.3$
$P(F)=0.4$
Then $P(E|F)=??$
How do i use the conditional probability equation that has been given in the question

A: From the first equality you wrote,
$$P(F|E) = \frac{P(F\cap E)}{P(E)} = \frac{P(F\cap E)}{.3} = 3P(F|E^{c}) = 3\frac{P(F\cap E^{c})}{P(E^{c})} = 3\frac{P(F\cap E^{c})}{.7} $$
We can rearrange some terms to get
$$P(F\cap E) = \frac{3*.3}{.7} P(F\cap E^{c}) = \frac{9}{7}P(F\cap E^{c})$$
Now, since $P(F) = P(F\cap E) + P(F\cap E^{c})$, substitute the above equality into this one to get
$$\frac{2}{5} = .4 = P(F) = P(F\cap E) + P(F\cap E^{c}) = \frac{9}{7} P(F\cap E^{c}) + P(F\cap E^{c}) = \frac{16}{7}P(F\cap E^{c})$$
Therefore $P(F\cap E^{c}) = \frac{\frac{2}{5}}{\frac{16}{7}} = \frac{14}{80} = \frac{7}{40}$. Now
$$P(F\cap E) = \frac{2}{5} - \frac{7}{40} = \frac{9}{40}$$
By definition, $P(E|F) = \frac{P(E\cap F)}{P(F)}$, which will be $\frac{\frac{9}{40}}{\frac{2}{5}} = \frac{45}{80} = \frac{9}{16}$

A: $P(E)=0.3$
$P(E^c)=1-0.3=0.7$
$P(F)=0.4$
$P(F|E)=3P(F|E^c)$
$P(F\cap E) = 3 \frac{P(F\cap E^c)}{P(E^c)}$
$P(F\cap E) = 3 \frac{P(F)−P(F\cap E)}{P(E^c)}$
Because $P(F\cap E^c)=P(F)−P(F\cap E)$
$P(F\cap E).P(E^c) = 3P(F)− 3P(F\cap E)$
$0.7P(F\cap E) + 3P(F\cap E) = 3×0.4$
$3.7P(F\cap E) = 1.2$
$P(F\cap E)=\frac{1.2}{3.7}$
$P(F\cap E)=0.324$
Hope you now solve for $P(E|F)$


text:
Q: Let Oracle trigger the sequence for ID instead of Hibernate? I have an application that has an Oracle database where each table has a trigger that calls a sequence to get the next ID for that row. How do I configure my domains so that Hibernate doesn't specify the next ID on an insert and just lets Oracle and the trigger handle it?
Previously I had my domains setup to use the sequence generator and this seemed to work. I can't use this on our production systems because the DBA's will not let me grant select privileges to the sequence for Grails. This obviously breaks the generator for Hibernate.

A: There is this Hibernate forum topic, which discusses a custom generator using the generatedKeys from a JDBC insert to retrieve the id: https://forum.hibernate.org/viewtopic.php?t=973262
If that custom generator works for you you should be able use it via:
static mapping = {
    id generator:"jpl.hibernate.util.TriggerAssignedIdentityGenerator"
}

A: You can't, there are following scenarios when using a sequence support database and a autonumber support database:

*

*Sequence Support

*

*Hibernate fetches sequence's next value

*Hibernate sets the fetched value as ID of your entity

*Hibernate persists the entity, with it's ID being set in the query

*Auto-number support

*

*Hibernate persists the entity, without ID value

*Hibernate fetches assigned ID from JDBC driver

As a matter of fact Oracle's driver does not support step 2.2, so Hibernate can't retrieve the last assigned ID (so it can sets it in ID of your entity).


text:
Q: How to get column names from HQL query&result to json with Key as columns How to convert hql query result directly to Json.I tried this one
            Query query=session.createQuery(SQLUtilsConstants.fQuery);
    query.setParameter(StringConstants.TRPID, trId);
    List list=query.list();
            gson = new Gson();
            String jsonStudents = gson.toJson(list);
           System.out.println("jsonStudents = " + jsonStudents);

When i converted.I get a json with list of values without properties.Query result contains data from multiple table .I want to generate result with properties as key and value as output.If query contains customerid and customername then i need a result like this.
      [{"customerid" : "abc", "customername" : "rose"}]

But using above code i getting like this..
          [{"abc", "rose"}]
How can i do this???

A: You should create a Map, how ever you want it. then parse the map into json.

Map<String,WhatEver> newMap = new HashMap<String,WhatEver>();
foreach(WhatEver item: list){
      //create your map how ever you like it to be

}
  String jsonStudents = gson.toJson(newMap);


text:
Q: I get a debuggging assertion failed Line 1662 Can you guys tell me why I get this error.

Debug Assertion Failed!
Program: C:\Widnows\system32\MSVCP100D.dll
File: c:\program files (x86)\microsoft visual studio
11.0\vc\include\xstring
line:1662
Expression: string subscript out of range
For more information on how your program can cause an assertion
failure, see the visual c++ doccumentation on asserts.
Here is the code I found that has been causing the issue. Student for my test case is 30 characters. Also size is 10.
    for (count = 0; count < size; count++)
    {
              answers[count] = student[11 + (2*count)];
    }

I created size by the following method
    string examSize;
    fstream questionNumber;
    questionNumber.open("answers.txt", ios ::in);
    getline(questionNumber, examSize);
    int size = stoi(examSize);

I created answers with the following method.
     vector<char> answers(size,' ');

I created student with a string and it is occupied by a getline function.
      getline(studentAnswers, student);

Also could you guys tell me if there is a way for me to use more pointers in this code?
As of now I tried this method to check for an overflow in students I still get the same
 error
    for (count = 0; count < size; count++)
    {
        cout << student[11 + count];
    }

A: As the comments suggest, "string subscript out of range" means that you are trying to access an element of memory that is not part of the student object. You say you have limited the call to student[11] to student[20]. Are you sure this is in range? Try printing out the variables at each stage of the process, before and after statements that change the variable's value and every time around the loop and see if the data is what you think it should be.
I'm not sure what you are trying to do with this loop, but maybe it would be easier to extract the data you want out of the student array first, and then assign it to the answer array.


text:
Q: Manage component life in vue I'm working on the vuejs, I have the following problems:
- I have a method that receives a list of records through an api rest, it is executed from time to time automatically, the method also has a validation in case the sent token is active, otherwise it redirects to the system login; The detail here is that the method is still running. The way I do the redirection is as follows.
if(error.response.status == 401){
              that.$swal('Su token ha expirado', 'Vuelva a ingresar sus credenciales de acceso.', "info")
              that.$store.dispatch("logout").then(() => {
                that.$router.push("/login");
              });
            }

*

*The list of records has for each item a More Information button, where a Modal component is opened in which videos and audios are displayed, when playing any of them and then closing the modal one continues listening to the audio, so the component follows active.

In both situations it seems that the component is not destroyed or is not deactivated, because it is still running in the background. Please I need guidance regarding this, thanks for your answers and contributions.


text:
Q: sql ranking when 5 users have same points and ranks has to be skipped if users have same rank Rank users with same ranks if they have same points and then skip the rest of the ranks.
For eg: the table below shows that user 5 was first to respond 3 times hence his rank will be above all then user 4 then user1 and the rest? I really appreciate any help.Thanks in advance.
    SELECT  name,
            (select count(*)
             from users u2
             where u2.points > u.points or
                   u2.points = u.points and u2.sno <= u.sno
            ) as rank
    FROM  `users` u GROUP BY  `name` ,  `sno`
ORDER BY CAST(points AS UNSIGNED) DESC;

USERS:
SNO points  first_to_respond   name
1    100   1                    a
2    100   0                    b
3    100   0                    c
4    100   2                    d
5    100   3                    e

A: To get a proper ranking as you are asking for:
SELECT  name,
        (select count(*) + 1
         from users u2
         where u2.points > u.points
        ) as rank
FROM  `users` u;

This counts the number that have more points, and then adds 1 to that value.
If you want to order by some other factor as well, then do something like:
SELECT  name,
        (select count(*) + 1
         from users u2
         where u2.points > u.points or
               u2.points = u.points and u2.first_to_respond < u.first_to_respond
        ) as rank
FROM  `users` u;

(I'm not sure if that second condition should be < or >.)


text:
Q: C++ MFC How to prevent duplicate values in each Ch? I have the following code:
And I would like to select one Ch without the number which has been selected in the other Ch.
For example, in Ch5, "1","2","3","37" can not be selected.
BOOL CMaintenanceHeadDispenserDlg::OnInitDialog()
{
CMaintenanceChildDlg::OnInitDialog();

CRect rc(0, 0, 0, 0);
m_edtDist.Create( NULL, NULL, WS_CHILD|WS_VISIBLE|WS_DISABLED, rc, this, IDC_EDT_MT_HEAD_DISPENSER_DIST );
m_edtDist.SetInputMode( 1 );
m_edtDist.SetInputRange( 999.999, 0.0 );
m_edtDist.EnableRightInputMode( TRUE, 2 );

m_edtOutput.Create(NULL, WS_CHILD|WS_VISIBLE|WS_DISABLED, rc, this, IDC_EDT_MT_HEAD_DISPENSER_OUTPUT);

CDeviceConfigDispenserController* p = CDeviceConfigDispenserController::GetInstance();
SDeviceConfigDispenser d;
p->GetData( d );

m_DispenserChInfoSet.GetChMap(m_mapCh);

for( int i = 0; i < 5; i++ ) {
    m_cmbCh[i].ResetContent();
    m_cmbCh[i].SetScrollCnt(5);
    m_cmbCh[i].SetHitTrace( TRUE );

m_edtCh[i].Create(NULL,NULL,WS_VISIBLE|WS_CHILD|WS_DISABLED,rc,this,IDC_EDT_MT_HEAD_DISPENSER_CH1 + i);
    m_edtCh[i].SetLimitTextNum(32);

    int itemCnt = 0;
    CString strCh;
    for( map<int, CString>::iterator it = m_mapCh.begin(); it != m_mapCh.end(); it++ ) {
        strCh.Format(_T("%d"), it->first);

        m_cmbCh[i].InsertString(itemCnt, strCh);
        m_cmbCh[i].SetItemData(itemCnt, it->first);
        if( d.nUseCh[i] == it->first ) {
            m_cmbCh[i].SetCurSel( itemCnt );
            m_edtCh[i].SetString( it->second );
        }
        itemCnt++;
    }

    m_rdoCh[i].SetCheck( BST_UNCHECKED );
}

 afx_msg LRESULT CMaintenanceHeadDispenserDlg::OnCbxSelchanged(WPARAM wParam, LPARAM lParam)
{
//int j = 0;    //ou
for( int i = 0; i < 5; i++ ) {
    if( m_cmbCh[i].m_hWnd == (HWND)lParam )
    {
        int Cnt = m_cmbCh[i].GetCount();
        if( (int)wParam < Cnt && (int)wParam >= 0) {
            m_cmbCh[i].SetCurSel( (int)wParam );

            int Index = (int)m_cmbCh[i].GetItemData( m_cmbCh[i].GetCurSel() );
            map<int, CString>::iterator it = m_mapCh.find( Index );
            if( it != m_mapCh.end() ) {
                m_edtCh[i].SetString( it->second );
            }
            break;
        }
    }
}


text:
Q: Real time loop issue I am having problem archiving real time loop. While it going to next iteration, it should check the status first for an update (status= 0) before going to next iteration.
status field might be updated somewhere else...
For example:
<?php
$SQL = "SELECT * FROM data WHERE status = 0";
$query = $db->prepare($SQL);
$query->execute();

while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
    print_r($row);
    print("\n\n");
    sleep(5);
}
?>

While php script is running/looping, in mysql console, I quickly did:
UPDATE data SET status = 1

It is still showing all the records even I have updated the status. How can that problem be fixed?

A: The result set is only computed once.  If you want to see intermediate updates, you need to issue another SELECT statement.

A: When you enter the while loop you've long gone fron the DB, you're simply displaying now what was sent back.

A: You must requery the database each time you want to get freash data. Otherwise, you will only re-iterate over the old fetched data.
<?php
$SQL = "SELECT * FROM data WHERE status = 0";

while (true) { // set the condition you need here (eg: time)

    // I don't know PDO enough to know if prepare can be executed out of the loop
    $query = $db->prepare($SQL);

    // re-query the database to get the new statuses
    $query->execute();

    // process the data
    while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
        print_r($row);
        print("\n\n");
    }

    // sleep when all the row have been processed
    sleep(5);
}
?>


text:
Q: Why does GreaterEqual take a long time to evaluate with arrays? Take the following example:
big = RandomReal[1, 10000000];
Head[big >= 0.66] // AbsoluteTiming

(* {0.53489, GreaterEqual} *)

Why does this take a long time to evaluate, given that the expression doesn't actually change?

Update:  Simon Woods points out that the slowdown is due to unpacking.  There is also some strange interaction with ReplaceAll that I do not understand.  Both are demonstrated by the following:
r=RandomReal[1,10000000];

On["Packing"]

Hold[Greater[r,0.5]]/.{x_?ArrayQ:>x}//AbsoluteTiming
Developer`FromPackedArray::unpack: Unpacking array in call to Greater.
{0.497073,Hold[r>0.5]}

Hold[greater[r,0.5]]/.{x_?ArrayQ:>x}//AbsoluteTiming
{0.000017,Hold[greater[r,0.5]]}

ArrayQ[r]//AbsoluteTiming
{3.*10^-6,True}

Note:

*

*big is a large packed array

*big >= 0.66 is the same as GreaterEqual[big, 0.66]

*the result is identical to GreaterEqual[big, 0.66]

This is a problem for my BoolEval package, which has a BoolEval function that transforms the expression big >= x to UnitStep[big - x] to speed up element-wise comparisons.  big >= x takes longer to evaluate than UnitStep[big - x].
Here's a much simplified version of the function:
greatereq[a_, b_] := UnitStep[a-b]
BoolEval[expr_] := expr /. GreaterEqual -> greatereq

A potential solution is
SetAttributes[BoolEval, HoldAll]
BoolEval[expr_] := Unevaluated[expr] /. GreaterEqual -> greatereq

The problem with this is that it will not work with
f[] := big >= 66
BoolEval[f[]]

Such a function would simply be too confusing to use.


text:
Q: How should I start implementing telegram-mtproto without using any packages in nodeJS? I want to implement the telegram-mtproto using nodejs and create a client nodejs telegram app but I don't know how to do this. the api and protocol part in telegram website make me confused and I didn't understand anything from them.
my starting question is how to create a keppalive connection with telegram server?

A: Take a look at How to implement authorization using a Telegram API? it's the most exhaustive answer that exists on the subject. None of the code is in Node but with some effort you'll be able to translate things.


text:
Q: How to change the receiver type(root node) after rebalancing a tree I'm trying to implement a binary tree in Go, but at the moment I'm stuck at the rebalancing of the tree. After rebalancing the root node will most likely be changed. Since the root node is the receiver type I have to change the value where the receiver type points to. The previous root node is used as another node now, which leads to the situation that this node is now also the root node.
func (n *treeNode) rebalance()  {

    sorted := n.traverseTree([]*treeNode{})  //returns a sorted array of *treeNode
    newRoot := innerRebalance(sorted) //the method gives the correct result
    *n = *newRoot//now I have a cyclic reference in the tree

}

The rebalance is called within the add function. I do not want to make the rebalance method public since it is an implementation detail. I want to call the rebalance method within the Add method.
Interface:
type Store interface {
    Add(key string, value string)
    Get(key string) string
    Remove(key string) bool
}

treeNode struct:
type treeNode struct {
    bigger           *treeNode
    smaller          *treeNode
    key              string
    value            string
}

Example
Before rebalance
100(root) --> 150 --> 200
After rebalance
100 <-- 150(root) --> 200
After the assignment to *n
... 150 <-- 150 <-- 150 --> 200
How can I change the receiver type w/o getting a cyclic reference to itself?

A: What you want to change is actually **n, so it can points to another node. You can not do that within the current scope. However, you can wrap the node and set the node outside of the method, and let the node's method returns a root.
For example,
type tree struct {
    root *treeNode
}

func (t *tree) Remove(key string) bool {
    root,ok := t.root.Remove()
    t.root = root
    return ok
}

And change *treeNode.Add to func (*treeNode) Add(string) *treeNode.


text:
Q: Display Hour and Minutes I got two fields in my table which is Hour and Minutes. How do I display it to my report that will look like this format HH:MM?

A: Try this below formula.
ToText(datetime field, "hh:mm")

A:
Right click The Field You Will Get The
->Format Editor
In Date and Time Column you can change the date Format .

A: Try this
Create a formula @Display and write as below
ToText(Hour)+" : "+ToText(Minutes)

A: *

*Add text object to canvas

*drag and drop each field to a text object

*edit the text object and add a ":".

*while in edit mode, right click each field and change its formatting to remove decimal points.


text:
Q: Internet Explorer 11 displays error in app.js (3820,1) file vuejs app, works with other browser My vuejs app works with other browsers well, but in Internet Explorer 11 it just displays a blank page.
The Babel code is not converted. How can I fix that?
I have used Bootstrap and Google charts as plugins.


text:
Q: PHP Simple HTML Dom: Get childNodes nodeValue? a.php:

Point 1

Point 1.1

Point 1.2

                some codes

Reference: link

I would like to get the nodeValue "Point 1" only. In JS, it is:
alert(document.getElementsByTagName("li")[0].childNodes[0].nodeValue);

But I would like to get the nodeValue in PHP (Simple HTML Dom); Here's the code snippet in another PHP page (b.php):
<?php

include('simple_html_dom.php');
$html = file_get_html('http://lifelearning.net63.net/a.php');

// stuck here:
echo $html->getElementsByTagName('ul',0)->getElementsByTagName('li',0)->nodeValue;
//

?>

I have used textContent but it just extracts the content descendents under Point 1. This is not what I want. I only want "Point 1".
Any help is appreciated!

A: Try this:
<?php
include('simple_html_dom.php');
$html = file_get_html('http://lifelearning.net63.net/a.php');
echo $html->find('li[id=pt1] li', 0)->innertext;

Above snippet finds the first (descent to li#pt1)matching li tag and gives your the inner text (content between the text, including all HTML in it, if any).
Have a look at SimpleHTMLDom docs. There are many ways and examples that your can find content (ID, classes, etc) from the HTML output.
SimpleHTMLDom mostly follows jQuery/CSS selectors.
Note that if you do not use innertext method, it returns a SimpleHTMLDom node that you need to process before displaying.
If there were no matching elements, it will return an E_WARNING error message. So make sure your input contain the require elements or make sure the element is present with an isset()

A: With the help of others online, a simpler solution is suggested:
$html = new DOMDocument();
$html->loadHTMLFile('http://lifelearning.net63.net/a.php');
echo $html->getElementsByTagName('li')->item(0)->childNodes->item(0)->textContent; // returns "Point 1"

What I've learnt is that
first, any external library is not required in my case, DOMDocument does the job of getting the HTML DOM of a webpage.
Second, use item() and childNodes. Very much like what it is in JS:
document.getElementsByTagName("li")[0].childNodes[0].nodeValue

But thank you for all your replies.

A: u may looking for this
 <?php  $str2 =     '
 ' ;?>
 <?php  $str2 .=    '

Point 1
 ' ;?>
 <?php  $str2 .=    '
 ' ; ?>
 <?php  $str2 .=    '
Point 1.1
' ; ?>
 <?php  $str2 .=    '
Point 1.2
' ; ?>
 <?php  $str2 .=    '
' ; ?>
 <?php  $str2 .=    '     some codes' ; ?>
 <?php  $str2 .=    '
' ; ?>
 <?php  $str2 .=    '
Reference: link
' ; ?>
 <?php  $str2 .=    '
' ; ?>
 <?php  $str2 .=    '
 ' ; ?>
 <?php  $str2 .=    '
' ; ?>

 <?php

 function getTextBetweenTags($string, $tagname) {
     $pattern = "/<$tagname ?.*>(.*)<\/$tagname>/";
     preg_match($pattern, $string, $matches);
     return $matches[1];
     }

   $txt = getTextBetweenTags($str2, "div");
   echo $txt;
   ?>

   will output : -->  Point 1


text:
Q: Método não inicia na primeira vez (Constructor ou IonViewDidEnter) Tenho uma função que deveria ser carregada e gerar uma lista no momento que a page é carregada, mas não acontece como deveria. Ao clicar na aba referente à tela, não é carregada a função - indo para outra view e clicando novamente, aí é carregado normalmente. A função no caso é a loadHistorico(), está sendo chamada no IonViewDidEnter(), já coloquei no construtor e o resultado foi o mesmo.
import { HistoricoModel } from './../../models/HistoricoModel';
import { Component, Inject } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { AlertController, LoadingController, ToastController } from 'ionic-angular';
import { CaixaModel } from './../../models/CaixaModel';
import { HttpClient } from '@angular/common/http';
import { PaginaBase } from '../../infra/PaginaBase';
import { ICaixaService } from './../../providers-interfaces/ICaixaService';
import { CaixasimpleProvider } from './../../providers/caixasimple/caixasimple';
import { NativeStorage } from '@ionic-native/native-storage';
import { CredenciadoProvider } from '../../providers/credenciado/credenciado';

@Component({
  selector: 'page-credenciado-caixa',
  templateUrl: 'credenciado-caixa.html',
  providers: [
    CaixasimpleProvider,
    CredenciadoProvider,
  ]
})
export class CredenciadoCaixaPage extends PaginaBase {
  foiSubmetido: boolean;
  caixaModel: CaixaModel;
  public currentCred;
  public loader;
  public io = new Array<any>();
  public total = "";
  historicoModel: HistoricoModel[];
  public isEmpty: boolean = false;

  constructor(public navCtrl: NavController,
    public navParams: NavParams,
    public formBuilder: FormBuilder,
    public alertCtrl: AlertController,
    public loadingCtrl: LoadingController,
    public toastCtrl: ToastController,
    @Inject('ICaixaService')
    public caixaservice: ICaixaService,
    private nativeStorage: NativeStorage,
    public http: HttpClient,
    public CaixasimpleProvider: CaixasimpleProvider,
    public CredenciadoProvider: CredenciadoProvider) {
    super({
      formBuilder: formBuilder,
      alertCtrl: alertCtrl,
      loadingCtrl: loadingCtrl,
      toastCtrl: toastCtrl
    })
    this.foiSubmetido = false;
    this.caixaModel = new CaixaModel();
    this.nativeStorage.getItem('idCredenciado')
      .then(
        dados => this.currentCred = (dados.idCredenciado), error => { console.log(error); })
    console.log(this.currentCred);
  }

  ionViewDidEnter() {
    this.loadHistorico();
    this.setIsEmpty();
  }

  setIsEmpty() {
    this.nativeStorage.getItem('idCredenciado').then(
      dados => this.CaixasimpleProvider.getHistoricoForIsEmpty(dados.idCredenciado).subscribe(
        data => {
          const response = (data as any);
          if(response == ""){
            this.isEmpty = true;
          }else{
            this.isEmpty = false;
          }
        }
      ));
  }

  loadHistorico() {
    this.showLoading();
    console.log("currentcred no ionviewdidenter -> " + this.currentCred);
    this.CaixasimpleProvider.getTotalFluxoCaixa(this.currentCred).subscribe(
      data => {
        var retorno = (data as any);
        this.total = retorno[0].soma;
      }, error => {
        this.closeLoading();
        console.log(error);
      });

    this.CaixasimpleProvider.getImputOutput(this.currentCred).subscribe(
      data => {
        const response = (data as any);
        console.log(response);
        this.io = response;
        console.log(this.io);
      }, error => {
        this.closeLoading();
        console.log(error);
      });

    this.CaixasimpleProvider.getHistorico(this.currentCred)
      .subscribe(data => {
        var retorno = (data as any);
        this.historicoModel = retorno;
      }, error => {
        this.closeLoading();
        console.log(error);
      });
    this.closeLoading();
  }

  cadastrarValor(caixaModel: CaixaModel): void {
    this.foiSubmetido = true;
    this.esconderToast();
    const mensagem = "Entrada de valor cadastrada!";
    const mensagemErro = "Ocorreu um erro, tente novamente, não iremos decepcionar :)";

    this.CaixasimpleProvider.cadastrarValor(this.caixaModel)
      .subscribe(dados => {
        this.mostrarToast(mensagem);
      },
        erro => { this.mostrarToast(mensagemErro); });
    this.navCtrl.setRoot(this.navCtrl.getActive().component);
    this.navCtrl.setRoot(this.navCtrl.getActive().component);
  }

  cadastrarValorNeg(caixaModel: CaixaModel): void {
    this.foiSubmetido = true;
    this.esconderToast();
    const mensagem = "Entrada de valor cadastrada!";
    const mensagemErro = "Ocorreu um erro, tente novamente, não iremos decepcionar :)";
    this.caixaModel.valor = "-".concat(this.caixaModel.valor);
    this.CaixasimpleProvider.cadastrarValor(this.caixaModel)
      .subscribe(dados => {
        this.mostrarToast(mensagem);
      },
        erro => { this.mostrarToast(mensagemErro); });
    this.navCtrl.setRoot(this.navCtrl.getActive().component);
    this.navCtrl.setRoot(this.navCtrl.getActive().component);
  }

  showLoading() {
    this.loader = this.loadingCtrl.create({
      content: "Carregando ..."
    });
    this.loader.present();
  }
  closeLoading() {
    this.loader.dismiss();
  }
}

A: Como todas as chamadas são assíncronas o showLoadinge o closeLoading é chamado em sequência e por isso dá a impressão que não está funcionando, você pode colocar um contador e fazer o closeLoading só quando tiver carregado as três requisições, segue abaixo os ajustes em loadHistorico e closeLoading que resolve esse problema:
  loadHistorico() {
    let count = 0;
    this.showLoading();
    console.log("currentcred no ionviewdidenter -> " + this.currentCred);
    this.CaixasimpleProvider.getTotalFluxoCaixa(this.currentCred).subscribe(
      data => {
        count++;
        this.closeLoading(count);
        var retorno = (data as any);
        this.total = retorno[0].soma;
      }, error => {
        count++;
        this.closeLoading(count);
        console.log(error);
      });

    this.CaixasimpleProvider.getImputOutput(this.currentCred).subscribe(
      data => {
        count++;
        this.closeLoading(count);
        const response = (data as any);
        console.log(response);
        this.io = response;
        console.log(this.io);
      }, error => {
        count++;
        this.closeLoading(count);
        console.log(error);
      });

    this.CaixasimpleProvider.getHistorico(this.currentCred)
      .subscribe(data => {
        count++;
        this.closeLoading(count);
        var retorno = (data as any);
        this.historicoModel = retorno;
      }, error => {
        count++;
        this.closeLoading(count);
        console.log(error);
      });
  }

  closeLoading(count) {
    if(count===3) this.loader.dismiss();
  }


text:
Q: 'ToastNotifier' object has no attribute 'classAtom' I ran the code below;
from win10toast import ToastNotifier
toaster = ToastNotifier()
toaster.show_toast("Hello World!!!",
                   "Python is 10 seconds awsm!",
                   icon_path="custom.ico",
                   duration=10)

I am getting below error :
  File "C:\Users\jnp\AppData\Local\Continuum\anaconda3\lib\site-packages\win10toast\__init__.py", line 83, in _show_toast
self.hwnd = CreateWindow(self.classAtom, "Taskbar", style,

AttributeError: 'ToastNotifier' object has no attribute 'classAtom'

A: What was causing this for me was creating multiple instances of ToastNotifier(). Reusing the same instance fixed the error.

A: As mentioned by @InAFlash, The classAtom is returning nothing and the reason is because there is already a registered notification. Messing with the source, I added an exception print to the except block as below:
try:
    self.classAtom = RegisterClass(self.wc)
except Exception as e:
    print(e)

I am running my notifications in threads and when the code comes across this point it prints out the below error:
(1410, 'RegisterClass', 'Class already exists.')

Looking through it I think I found a solution, though it kind of takes away from the idea of "spamming" the notifications. By adding to the self.wc.lpszClassName variable the title, it makes it a different notification. So overall the code should look something like this:
self.wc = WNDCLASS()
self.hinst = self.wc.hInstance = GetModuleHandle(None)
self.wc.lpszClassName = str(f"PythonTaskbar{title}")  # must be a string
self.wc.lpfnWndProc = message_map  # could also specify a wndproc.
try:
    self.classAtom = RegisterClass(self.wc)
except Exception as e:
    print(e)

This solution worked for my scenario so not sure if this is the best fix but I'm rolling with it.
Hope this helps.

A: Looks like the problem is with the source code itself.
if you see the image, if there is an exception happening at self.classAtom = RegisterClass(self.wc) they did not handle it which will leave classAtom variable not declared. That is the cause of your problem. So, to fix it, just make classAtom = "" or some thing. But, this wont actually fix it.

A: Considering the accepted answer might break more things down the line, I'll post this.
It is, as inAFlash mentioned in his comment, a dependency issue. Updating setuptools will fix the problem.
To do so, simply run: python -m pip install setuptools --upgrade


text:
Q: DateTime format to a WPF TextBox I need some help.

*

*My problem is,I have a textbox,I wanna write a correct DateTime form for it with "autostring". For example if i write into my TextBox,I want the program to write a . or a / after year,month automatically (in US DateTime form after 2-2 strings,in Hungarian after 4-2 - I am from Hun). If you can only show me a form in other DateTime like the US-GB-GE or any other country,that won't be a problem at all.Hungarian DateTime would be only a formality in my program.

*I live in Hungary,didn't find any correct DateTime format for my Country. Format in here YYYY-MM-DD and not DD-MM-YYYY. Will it work if i simply reverse it or need to do anything else? I tried it,didn't seem to work,but maybe i did smth wrong.
Please help!

A: Masked entry in a text box in WPF is not done easily.  If it's a requirement that the text box have the slashes or the dashes for the date as the user enters it, I would consider using WPF Toolkit DateTime Picker or the WPF Toolkit Masked Edit Text Box, both of which are available on Codeplex as part of the Extended WPF toolkit.
If you still want to try masked text box editing on your own, here's an example I found that could be modified for a date format of your choice: WPF Masked Text Box


text:
Q: disk usage application How can I get separate assigned path disk usage by crontab job to do it? For example, I would like to find out the path as list as below
ex:
/var/example/attachments/ver003/112/24

/var/example/attachments/ver003/10/13/12

/var/example/attachments/ver003/119/12

How can I use du -sh to got their disk usage by crontab or sh file to output the result?
output: path1:10GB
path2:20MB

path3:850MB

A: Try this:
for i in /var/example/attachments/ver003/112/24 /var/example/attachments/ver003/10/13/12 /var/example/attachments/ver003/119/12; do
    du $i -sh | awk -v p=$i '{print p,":",$1;}'
done


text:
Q: Entity Framework IQueryable I'm having problems querying the entity model to get additional information.
My db has a Program table with a one to many relation with an Events table.  The Entity model generates the relationships just fine, but I'm unable to figure out how to query the model to get the progam object with its events.
I can do this:
var foo = from program in entities.ProgramSet
          where program.StartDate > DateTime.now
          orderby program.StartDate
          select program;

No problems there.  From what I've found on Microsofts Page (Shaping queries with Entity framework): msdn.microsoft.com/en-us/library/bb896272.aspx, if I wanted to get the child objects, I just do the following:
// Define a LINQ query with a path that returns
// orders and items for a contact.
var contacts = (from contact in context.Contact
          .Include("SalesOrderHeader.SalesOrderDetail")
          select contact).FirstOrDefault();

However, there is no .Include or Include  that I can find on the query.
Any suggestion?  I know that I can do a foreach across the results, then run a .Events.Load() on it, but doesn't that force the IQueriable result to execute the sql, instead of optomize it to run only when a .ToList() etc is called on it?
Here is some sample code from my project:
public class ProgramRepository : CT.Models.IProgramRepository
{
    CTEntities db = new CTEntities();

    public IQueryable<Program> FindAllPrograms()
    {

        return db.ProgramSet;
    }
    public IQueryable<Program> FindUpcomingPrograms()
    {

        var programs =  from program in FindAllPrograms()

               where program.StartDate > DateTime.Now
               orderby program.StartDate
               select program;
        return programs;

    }

With the FindUpComingPrograms I would like to have it also include the Events Data. There is a relationship between the Program and Events model.  Program has a List<Events> property, that I would like to fill and return with the IQueryable method.
Thanks again!

A: The Include Function is part of the ObjectQuery object...
I think you are going to need to re-write your query to look something like this:
var contacts = context.Contact.Include("SalesOrderHeader.SalesOrderDetail").FirstOrDefault();

//Not sure on your dot path you might have to debug that a bit

Here is an Article that has some examples...


text:
Q: Bigquery - Data Consistency not guaranteed for external data sources The Google documentation for BigQuery mentions that the service does not guarantee data consistency for external data sources. Changes to the underlying data while a query is running can result in unexpected behavior.
Source: https://cloud.google.com/bigquery/external-data-sources
I am not exactly sure what it means. Can someone describe a situation where this may be problematic? (What happens vs what was the user expecting).

A: You can refer ACID properties (Consistency) of database:

Definition:
The database must remain in a consistent state after any transaction. No transaction should have any adverse effect on the data residing in the database. If the database was in a consistent state before the execution of a transaction, it must remain consistent after the execution of the transaction as well.

Unexpected behavior:
As the data source is heterogeneous (external) – Any changes to the underlying data in the data source while a query is running in BigQuery referring to external data source can result in unexpected behavior.


text:
Q: Errors in Xcode 5 "use of undeclared identifier" I have the following errors in my Xcode project that I can not figure out how to correct it. I tried to save and close Xcode and reopen the project but this is not working. I am getting following message:
use of undeclared identifier'gremoveads'  with the following code.
}
if (buttonIndex==2) {
    bool bPaymentInQueue = NO;
    for (SKPaymentTransaction *transaction in [SKPaymentQueue defaultQueue].transactions) {
        if ([transaction.payment.productIdentifier isEqualToString:gRemoveads]) {
            bPaymentInQueue = YES;
            NSLog(@"Payment already in queue!");
            break;
        }

I am also getting this error.  Use of undeclared identifier 'gunlimitedcoins' with the following code.
if (buttonIndex==0) {
    bool bPaymentInQueue = NO;
    for (SKPaymentTransaction *transaction in [SKPaymentQueue defaultQueue].transactions) {
        if ([transaction.payment.productIdentifier isEqualToString:gUnlimitedCoins]) {
            bPaymentInQueue = YES;
            NSLog(@"Payment already in queue!");
            break;

How do I fix these two undeclared identifier errors?
The full code showing these errors are in the gamestoreviewcontroller.m file
#import "GameStoreViewController.h"
#import "Reachability.h"
#import "SurfSlotMachineAppDelegate.h"

@implementation GameStoreViewController
@synthesize activityIndicatorView;
@synthesize lblLoading;
@synthesize lblProductTitle;
@synthesize txtProductDescription;
@synthesize txtGamecenterDescription;
@synthesize txtRestoreDescription;
@synthesize txtMoreGamesDescription;
@synthesize btnBuyProduct;
@synthesize btnGameCenter;
@synthesize btnRestore;
@synthesize btnReturn;
@synthesize btnMoreGame;
@synthesize activityIndicatorPurchasingView;
@synthesize lblPurchasing;
@synthesize unlockInfoImage;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
 // Custom initialization
 }
 return self;
 }
 */

/*
 // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
 - (void)viewDidLoad {
 [super viewDidLoad];
 }
 */

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];

    //    SurfSlotMachineAppDelegate* del = (SurfSlotMachineAppDelegate*)[UIApplication sharedApplication].delegate;
    //    [del hideADS:YES];

    bErrorOnConnection = NO;
    self.lblProductTitle.hidden = YES;
    self.txtProductDescription.hidden = YES;
    self.txtGamecenterDescription.hidden = YES;
    self.txtRestoreDescription.hidden = YES;
    self.txtMoreGamesDescription.hidden = YES;
    self.btnBuyProduct.hidden = YES;
    self.btnRestore.hidden = YES;
    self.btnGameCenter.hidden = YES;
    self.btnMoreGame.hidden = YES;

    self.lblLoading.hidden = YES;
    self.activityIndicatorPurchasingView.hidden = YES;
    self.lblPurchasing.hidden = YES;
    self.unlockInfoImage.hidden = YES;

    // Check network reachability
    Reachability* reachability = [Reachability reachabilityWithHostName:@"www.google.com"];
    NetworkStatus internetStatus = [reachability currentReachabilityStatus];
    if (internetStatus != ReachableViaWiFi && internetStatus != ReachableViaWWAN) {

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No Internet Connection"
                                                        message:@"You require an internet connection via WiFi or cellular network for connecting to online store"
                                                       delegate:nil
                                              cancelButtonTitle:@"Dismiss"
                                              otherButtonTitles:nil];

        [alert show];
        [alert release];
        bErrorOnConnection = YES;
    }

    if ([SKPaymentQueue canMakePayments])
    {
        [self requestProductData];

    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"In-App Purchases are disabled"
                                                        message:@"Please check your restrictions for In-App Purchases in Settings->General->Restrictions."
                                                       delegate:nil
                                              cancelButtonTitle:@"Dismiss"
                                              otherButtonTitles:nil];
        [alert show];
        [alert release];
        bErrorOnConnection = YES;
    }

    //timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(tick:) userInfo:nil repeats:YES];
    //[timer retain];
}
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error
{
    UIAlertView  *alert = [[[UIAlertView alloc] initWithTitle:@"In-App Store unavailable" message:error.localizedDescription delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] autorelease];

    [alert show];
}
- (void)setMainGameParent:(id) parent {
    mainGameParent = parent;
}

- (void)viewWillDisappear:(BOOL)animated {

    [super viewWillDisappear:animated];

    [timer invalidate];
    [timer release];
}

/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];

    self.activityIndicatorView = nil;
    self.lblLoading = nil;
    self.lblProductTitle = nil;
    self.txtProductDescription = nil;
    self.txtRestoreDescription = nil;
    self.txtGamecenterDescription = nil;
    self.txtMoreGamesDescription = nil;
    self.btnBuyProduct = nil;
    self.btnGameCenter = nil;
    self.btnRestore = nil;
    self.btnMoreGame = nil;
    self.btnBuyProduct = nil;
    self.unlockInfoImage = nil;

    mainGameParent = nil;

    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)dealloc {
    [super dealloc];
}

- (IBAction) closePressed:(id) sender {
    [mainGameParent GameStoreClosed];
    [self.view removeFromSuperview];
}

- (IBAction) purchaseUnlock:(id) sender {

    UIActionSheet *Sheet=[[UIActionSheet alloc]initWithTitle:@"Option" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Super Coins",@"Unlock Payouts",@"RemoveAds", nil];
    [Sheet showInView:[UIApplication sharedApplication].keyWindow];

    //[self.view removeFromSuperview];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{

    if (buttonIndex==actionSheet.cancelButtonIndex) {

    }
    if (buttonIndex==0) {
        bool bPaymentInQueue = NO;
        for (SKPaymentTransaction *transaction in [SKPaymentQueue defaultQueue].transactions) {
            if ([transaction.payment.productIdentifier isEqualToString:gUnlimitedCoins]) {
                bPaymentInQueue = YES;
                NSLog(@"Payment already in queue!");
                break;
            }
        }
        if (!bPaymentInQueue) {
            NSLog(@"Adding new payment...");
            SKPayment *payment = [SKPayment paymentWithProductIdentifier:gUnlimitedCoins];
            [[SKPaymentQueue defaultQueue] addPayment:payment];
        }
    }
    if (buttonIndex==1) {
        bool bPaymentInQueue = NO;
        for (SKPaymentTransaction *transaction in [SKPaymentQueue defaultQueue].transactions) {
            if ([transaction.payment.productIdentifier isEqualToString:kPayoutUnlockProduct]) {
                bPaymentInQueue = YES;
                NSLog(@"Payment already in queue!");
                break;
            }
        }
        if (!bPaymentInQueue) {
            NSLog(@"Adding new payment...");
            SKPayment *payment = [SKPayment paymentWithProductIdentifier:kPayoutUnlockProduct];
            [[SKPaymentQueue defaultQueue] addPayment:payment];
        }
    }
    if (buttonIndex==2) {
        bool bPaymentInQueue = NO;
        for (SKPaymentTransaction *transaction in [SKPaymentQueue defaultQueue].transactions) {
            if ([transaction.payment.productIdentifier isEqualToString:gRemoveads]) {
                bPaymentInQueue = YES;
                NSLog(@"Payment already in queue!");
                break;
            }
        }
        if (!bPaymentInQueue) {
            NSLog(@"Adding new payment...");
            SKPayment *payment = [SKPayment paymentWithProductIdentifier:gRemoveads];
            [[SKPaymentQueue defaultQueue] addPayment:payment];
        }
    }
}

- (IBAction) gameCenter:(id)sender {
    SurfSlotMachineAppDelegate* del = (SurfSlotMachineAppDelegate*)[UIApplication sharedApplication].delegate;
    RootViewController *rootViewController = del.viewController;
    [rootViewController showLeaderboard];
}

- (IBAction) restore:(id)sender {
    [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}

- (IBAction) moreGames:(id)sender {
    SurfSlotMachineAppDelegate* del = (SurfSlotMachineAppDelegate*)[UIApplication sharedApplication].delegate;
    [del dispMoreApps];
}

- (void)requestProductData {

    lblLoading.hidden = NO;
    [activityIndicatorView startAnimating];

    SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObject:kPayoutUnlockProduct]];
    request.delegate = self;
    [request start];
}

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
    NSArray *myProducts = response.products;
    NSLog(@"%@",myProducts);
    if ([myProducts count] > 0) {
        SKProduct *product = [myProducts objectAtIndex:0];

        NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
        [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
        [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
        [numberFormatter setLocale:product.priceLocale];
        NSString *priceString = [numberFormatter stringFromNumber:product.price];

        NSLog(@"Title: %@", product.localizedTitle);
        NSLog(@"Desc: %@", product.localizedDescription);
        NSLog(@"Price: %@", priceString);

        self.lblProductTitle.text = product.localizedTitle;
        self.txtProductDescription.text = product.localizedDescription;
        [self.btnBuyProduct setTitle:[NSString stringWithFormat:@"Choose your UPGRADE"] forState:UIControlStateNormal];
        [self.btnGameCenter setTitle:[NSString stringWithFormat:@"Leaderboard"] forState:UIControlStateNormal];
        [self.btnRestore setTitle:[NSString stringWithFormat:@"Restore"] forState:UIControlStateNormal];
        [self.btnMoreGame setTitle:[NSString stringWithFormat:@"More Games"] forState:UIControlStateNormal];

        self.lblProductTitle.hidden = NO;
        self.txtProductDescription.hidden = NO;
        self.txtGamecenterDescription.hidden = NO;
        self.txtRestoreDescription.hidden = NO;
        self.txtMoreGamesDescription.hidden = NO;
        self.btnBuyProduct.hidden = NO;
        self.btnGameCenter.hidden = NO;
        self.btnRestore.hidden = NO;
        self.btnMoreGame.hidden = NO;
        self.unlockInfoImage.hidden = NO;

        [numberFormatter release];
    }

    lblLoading.hidden = YES;
    [activityIndicatorView stopAnimating];

    [request release];
}

- (void)tick:(id)sender {

    bool bPaymentInQueue = NO;
    for (SKPaymentTransaction *transaction in [SKPaymentQueue defaultQueue].transactions) {
        if ([transaction.payment.productIdentifier isEqualToString:kPayoutUnlockProduct]) {

            bPaymentInQueue = YES;
            break;
        }
    }

    if (bPaymentInQueue) {
        [self.activityIndicatorPurchasingView startAnimating];
        self.activityIndicatorPurchasingView.hidden = NO;
        self.lblPurchasing.hidden = NO;
        self.btnReturn.enabled = NO;
        self.btnBuyProduct.enabled = NO;
    } else {
        [self.activityIndicatorPurchasingView stopAnimating];
        self.activityIndicatorPurchasingView.hidden = YES;
        self.lblPurchasing.hidden = YES;
        self.btnReturn.enabled = YES;
        self.btnBuyProduct.enabled = YES;
    }

    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    if ([userDefault objectForKey:KEY_PAYOUTLOCKED] != nil && [userDefault boolForKey:KEY_PAYOUTLOCKED] == NO) {
        [mainGameParent GameStoreClosed];
        [self.view removeFromSuperview];
    }

    if (bErrorOnConnection) {
        [mainGameParent GameStoreClosed];
        [self.view removeFromSuperview];
    }
}
@end

A: You did not declared these:
gRemoveads

and
gUnlimitedCoins

The declarations are missing for these in the scope/block.

A: It looks like the variable "gRemoveads" in the statement "transaction.payment.productIdentifier isEqualToString:gRemoveads" has never been declared or set. From the computer's perspective, this variable doesn't exist. Do you know what this variable is or where it is supposed to be set?
Or are those supposed to be string literals? As in the exact text "gRemoveads". In that case, put it in quotes.


text:
Q: I want to know difference between "delete-orphan" and "all-delete-orphan" cascade styles in hibernate From my understanding,
Cascade= "all"   is equal to cascade="save-update,delete"
and
Cascade= "all-delete-orphan"  is equal to cascade= "save-update,delete-orphan"
is it correct?

A: Here's what the documentation says:

For each basic operation of the Hibernate session - including persist(), merge(), saveOrUpdate(), delete(), lock(), refresh(), evict(), replicate() - there is a corresponding cascade style. Respectively, the cascade styles are named create, merge, save-update, delete, lock, refresh, evict, replicate. If you want an operation to be cascaded along an association, you must indicate that in the mapping document. For example:
   <one-to-one name="person" cascade="persist"/>

Cascade styles my be combined:
   <one-to-one name="person" cascade="persist,delete,lock"/>

You can even use cascade="all" to specify that all operations should be cascaded along the association. The default cascade="none" specifies that no operations are to be cascaded.


text:
Q: File System access from Firefox Extension Is it possbile to create a firefox extendsion to write to files in a windows file system ?

A: Yes, see this page for examples.
Edit
XPCOM and so nsIFile are now legacy technologies :

Use of OS.File is preferred over the examples in this article. Only use these legacy interfaces if OS.File is not available to you.

You can find the new way to go here


text:
Q: Rsync unexprected behavior I have 2 external drives and I want to use rsync to copy the files that have been updated (modified timestamp) in the source directory to a target directory.
The files have the same filename but the timestamp is different i.e. some files have been recently updated but the filename has remained the same.
However,
rsync -rv --ignore-existing --progress /Volumes/vol1/Data/ /Volumes/vol2/Data/
does not do anything. The result is null nothing is transferred.

sending incremental file list
sent 68 bytes  received 12 bytes  160.00 bytes/sec total size is
20,634  speedup is 257.93

How can I solve this?

A: Well, Reading The Fine Manual I find this:
        --ignore-existing       skip updating files that exist on receiver

So by definition, the options you're using are explicitly asking NOT to update already existing files.
I think you simply want to use "-a" (archive) option:
rsync -av --progress /Volumes/vol1/Data/ /Volumes/vol2/Data/


text:
Q: Ng2-translate - Fallback to default language when file doesn't exist I have set up ng2-translate which translates my entire app and I have an en-GB.json file which contains all of my translations. The problem I have now is that if the user's device is set to another language (e.g. 'en-US'), I get 404 errors saying that the file en-US.json doesn't exist.
I have tried this solution https://github.com/ocombe/ng2-translate#how-to-handle-missing-translations but it seems that I would have to set up a default value for every single translation which isn't great.
Is there a way to automatically fall back to using the en-GB.json file if en-US.json (and other language files) doesn't exist?
Thanks for any help.
Edit:
Forgot to mention that I also set a default language like so:
Globalization.getPreferredLanguage().then(
    res => {
      language = res.value;
      self.translate.setDefaultLang('en-GB');
      self.translate.use(language);
    }
  );

A: You could keep a reference to all languages you support in an array and check if the language is inside the array. If it exists, you set the language, if not you set your default language.
const langs = [
    'en-GB',
    'fr-FR',
    'de-DE'
];

let isSupported = this.langs.find(supportedLanguage => supportedLanguage === language);

if(isSupported) self.language.set(language);
else self.language.set('en-GB')


text:
Q: C# Adding objects to listBox and then changing their parameters How can I add new object to listBox and then change their parameters?
I have a class:
public class Triangle
{
    public Triangle(double a, double b, double c): base(a, b, c)
    { }
}

private void button1_Click_1(object sender, EventArgs e)
{
    double a = 3;
    double b = 4;
    double c = 5;

    Triangle t = new Triangle(a, b, c);
    listBox1.Items.Add("Triangle");
}

How can I change length of the sides of this Triangle (new values will be from Textbox) and update this class object?

A: First, you will need to expose the properties on your Triangle class:
public class Triangle
{

    public double SideA { get; set; }
    public double SideB { get; set; }
    public double SideC { get; set; }
    public string Name { get; set; }

    public Triangle(double a, double b, double c, string n)
    {
        SideA = a;
        SideB = b;
        SideC = c;
        Name = n;
    }

    public override string ToString()
    {
        return Name;
    }
}

Note that I have added a Name property that will get displayed by default (because of the ToString() override) in your ListBox.
Then, add your Triangles to the ListBox:
listBox1.Items.Add(new Triangle(1, 2, 3, "One"));
listBox1.Items.Add(new Triangle(1, 2, 3, "Two"));
listBox1.Items.Add(new Triangle(1, 2, 3, "Three"));

And finally, is some other part of your code you will have to first obtain a reference to a Triangle object from the ListBox:
Triangle t = listBox1.SelectedItem as Triangle;
if (t != null)
    t.SideA = 10;

Please note that I'm assuming you want to edit the currently selected Triangle.
Cheers

A: Thank you for your answer, but the problem is that the numer of elements (triangles) in listBox is limitless, so I can't using the name string. It should be dynamic adding after click a button, but after the select element in listbox you can change for example lenght of the sides


text:
Q: Maven site reporting fine for surefire tests, needs extra config for pitest mutationCoverage If I set up the <reporting> section in my pom as follows, I only get the surefire report, while the pitest report fails because it can't find any input.
  <reporting>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-project-info-reports-plugin</artifactId>
        <version>2.9</version>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-report-plugin</artifactId>
        <version>2.19.1</version>
      </plugin>
      <plugin>
        <groupId>org.pitest</groupId>
        <artifactId>pitest-maven</artifactId>
        <version>1.1.10</version>
        <configuration>
          <targetClasses>
            <param>pricingengine.*</param>
          </targetClasses>
          <targetTests>
            <param>pricingengine.*</param>
          </targetTests>
        </configuration>
        <reportSets>
          <reportSet>
            <reports>
              <report>report</report>
            </reports>
          </reportSet>
        </reportSets>
      </plugin>
    </plugins>
  </reporting>

To obtain the input to the pitest report so that it outputs to the site reports, I need to do this first:
mvn compile test-compile org.pitest:pitest-maven:mutationCoverage
Do I have to set up each of these in the <build> section as plugins with executions bound to the pre-site phase to get this to happen? Or is there a simpler solution with another plugin I'm not aware of?

A: The maven-surefire-report-plugin however explicity states, that it invokes the test goal of the default lifecycle. The pitest plugin doesn't. So yes, you have to add the pitest-maven plugin to the build section and bind it to a lifecycle phase, i.e. pre-site. I wouldn't recommend the use of the site lifecycle for that purpose as it is not intended for long-running analysis tasks, but that is up to you.
So the build order is:

*

*build lifecycle

*

*build the module (compile phase)

*run the test (test phase)

*run the mutation coverage (i.e. in verify phase)

*site lifecycle

*

*pre-site (mutationCoverage);

*generate reports

*publish reports

*...

I'd suggest to use a profile so the mutation test is not run on every build and you can activate it when needed (i.e. mvn site-P pit)
<profile>
  <id>pit</id>
  <build>
    <plugins>
        <plugin>
            <groupId>org.pitest</groupId>
            <artifactId>pitest-maven</artifactId>
            <configuration>
                <targetClasses>
                    <param>pricingengine.*</param>
                </targetClasses>
                <targetTests>
                    <param>pricingengine.*</param>
                </targetTests>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>mutationCoverage</goal>
                    </goals>
                    <phase>pre-site</phase>
                </execution>
            </executions>
        </plugin>
    </plugins>
  </build>
</profile>


text:
Q: Perform google search programmatically using keywords Like we go on google and perform google search via keywords.
Can we do such query programaticaly? like
http://www.google.com/search?q=cupertino+american+food

After executing the query we should get all search result details for each link to store in database.
Exactly like some site provide REST api access, so that user can get bunch of results his query.
I don't have seen something like this possible with google or not.

A: Whatever technique you're going to use, Google will block your IP for bot-like search queries. And don't try with TOR proxy because all their IPs are always banned or challenged with captcha.
You have to use Google API in order to be compliant with Google's T&C. Also the result is much much better
https://developers.google.com/custom-search/json-api/v1/overview
The API is free if you have a CSE and has a limit of 100 queries per day. If you need more you'll be billed 5$ per 1000 queries

A: @mahtOrz: Okay, here's some rough code that will deliver a Json back to the console.  Note that the api base search string is different than the one you have which is www.google.com/search?q=cupertino+american+food. You need to use the Google API base URL below. Do you have your APIkey and CxKey? If not, I can walk you through those steps too.
using System;
using System.Text;
using System.Net;
using System.IO;
using System.Web;

namespace GoogleSearchTest1
{
    class Program
    {
        //Google keys
        const string APIKey = "{your key here}";
        const string CSEKey = "{your key here}";
        //base url for the search query
        const string GoogleBaseURL = "https://www.googleapis.com/customsearch/v1?"; //per Google documentation

    public static void Main(string[] args)
    {
        string myQuery = "cupertino american food"; //put what you're searching for here
        string result = submitSearch(myQuery);
        Console.WriteLine(result);
        string dummy = Console.ReadLine();
    }
    public static string submitSearch(string myQuery)
    {
        try
        {
            string final = string.Format(GoogleBaseURL+"key={0}&cx={1}&q={2}",
                HttpUtility.UrlEncode(APIKey),
                HttpUtility.UrlEncode(CSEKey),
                HttpUtility.UrlEncode(myQuery));
            final += "&alt=json";
            WebRequest myRequest = WebRequest.Create(final);
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            Stream myStream = myResponse.GetResponseStream();
            StreamReader myReader = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
            string result = myReader.ReadToEnd();
            myStream.Close();
            myReader.Close();
            myResponse.Close();
            return result;
        }
            catch (Exception e)
        {
            //debug statement
        }
        return null;
    }
}

}

A: use cUrl request, hand in hand with output buffering

A: @user123: I can offer some tips if you can work in C#? The API steps are extensive. Let me know!


text:
Q: extracting DC from audio signal for biasing I've been wondering if there is a simple means of extracting a DC signal from an AC+DC signal for the purpose of providing a small DC supply to a CMOS device.
Essentially the signal I'm considering is a DC microphone bias supplied to an electret microphone. The electret mic will add its own small signal AC, and this will pass through some circuit that requires the DC bias only, leaving the microphone AC undistorted to be passed to another part of the circuit uneffected. The rest of the audio chain is passive, and no external supply is available other than the 2.5V - 5.0V DC microphone bias superimposed with audio AC.
I'd like to add a small CMOS comparator (or similar) that requires a DC supply, and the microphone bias is the only DC source available for the CMOS device supply. Usually removing the DC from a signal is straight forward with a DC block capacitor, but any thoughts how to do this DC extraction simply without effecting the audio signal ??
Cheers, Mike


text:
Q: How to get mysql node in node-red? I've tried npm install node-red-node-mysql and it ran successfully, but when I start node-red, no node like mysql can be found. I'd appreciate it if someone could help me with this.

A: Run the following command in your Node-RED user directory - typically ~/.node-red

npm install node-red-node-mysql

Also

The reconnect retry timeout in milliseconds can be changed by adding a line to settings.js

mysqlReconnectTime: 30000,


text:
Q: Static IP in Sony Camera Remote API I'm planning to integrate the Sony Camera Remote API to use with an Action Cam Mini AZ1. Before doing that, I have serious doubts about the possibility of connecting the camera to a static IP, instead of working in the same Wifi network.
Does anyone knows if that is possible?
Thanks!
Marc

A: Sorry connecting to a static IP is not possible.


text:
Q: python3 elif syntax error Ошибка:
     File "main.py", line 56
    elif datetime.datetime.todaye().isoweekday() == 2:
       ^
SyntaxError: invalid syntax

Код:
@bot.message_handler(commands=['today'])
def send_welcome(message):
    if datetime.datetime.today().isoweekday() == 1:
        bot.reply_to(message, open_file('msg/1.txt')
    elif datetime.datetime.todaye().isoweekday() == 2:
        bot.reply_to(message, open_file('msg/2.txt')
    elif datetime.datetime.todaye().isoweekday() == 3:
        bot.reply_to(message, open_file('msg/3.txt')
    elif datetime.datetime.todaye().isoweekday() == 4:
        bot.reply_to(message, open_file('msg/4.txt')
    elif datetime.datetime.todaye().isoweekday() == 5:
        bot.reply_to(message, open_file('msg/5.txt')

Что я делаю не так?

A: bot.reply_to(message, open_file('msg/1.txt')

Здесь нет закрывающей скобки


text:
Q: How do I use an IF statement to replace NULL value? This is a question from my assignment and I have most of it done just can't get the IF statement to replace the NULL.
Question: Write a SELECT statement that answers this question: What is the total quantity purchased for each product within each category? Return these columns
The category_name column from the category table
The product_name column from the products table
The total quantity purchased for each product with orders in the Order_Items table
Use the WITH ROLLUP operator to include rows that give a summary for each category name as well as a row that gives the grand total.
Use the IF and GROUPING functions to replace null values in the category_name and product_name columns with literal values if they're for summary rows.
My Answer So Far:
SELECT product_name, SUM((item_price - discount_amount) * quantity) AS Total_quanity_purchased

FROM products p

JOIN order_items ori ON p.product_id = ori.product_id

GROUP BY product_name WITH ROLLUP

A: I think your rollup NULL you are referring to is the Product_Name after all categories.  You can probably use an
IF( Product_Name is null, 'All Products', Product_Name )

In lieu of using IF(), the COALESCE() function returns the first non-null value which the above would result in
COALESCE( Product_Name, 'All Products' )

Now, your actual question states to include the categories too, so I would suspect the category too, so you'll need that join too.  So, the modified query would be (including all columns properly table/alias.columnName context.  Get used to it now to prevent ambiguity knowing which column associated with which table.  Especially when you get to using the same table multiple times in the same query.  Use the aliases.
SELECT
      if( c.category_name is null, 'All Categories', c.category_name) Category,
      if( p.product_name is null, 'All Products', p.product_name ) Product,
      SUM(ori.quantity) as Total_Qty_Purchased,
      SUM(( ori.item_price - ori.discount_amount) * ori.quantity)
         AS Total_Purchase_Sales
   FROM
      products p
         JOIN Category c
            on p.category_id = c.category_id
         JOIN order_items ori
            on p.product_id = ori.product_id

   GROUP BY
      c.category_name,
      p.product_name,
      WITH ROLLUP

Finally, your computation of (price - discount) * qty would be a total PRICE, not Total_Quantity_Purchased.... Maybe a TotalPurchaseAmount, but not total Quantity... I added a separate Qty total as well.  You can remove from your final answer, but just to show context.


text:
Q: Compound operators in Dash DataTable front-end filter Is it possible to filter Dash DataTable (dt) columns by compound operators in the front-end? For e.g. I have a column 'NumDays' and  filter by > 6 finds records where 'NumDays' is greater than 6.
But how to filter for ((NumDays > 6) & (NumDays <= 15?)) in front-end? And is there a help-page for query syntax? The official filtering page also seems to have simple operators as filters. Thanks

A: && seems to work for me. I'm using Python 3.6.1. See example code:
style_data_conditional=[
        {
            'if': {
                'column_id': 'avf',
                'filter_query': '{avf} < 10000'
            },
            'backgroundColor': '#ff6961', # red
        },
        {
            'if': {
                'column_id': 'avf',
                'filter_query': '({avf} < 12000) && ({avf} >= 10000)'
            },
            'backgroundColor': 'yellow', # yellow
        },
        {
            'if': {
                'column_id': 'avf',
                'filter_query': '{avf} >= 12000'
            },
            'backgroundColor': '#7CFC00', # green
        },
    ]


text:
Q: Mac OS Two Monitors Chrome YouTube Video Requires Second Click Hey all I'm new to using Macbooks (I'm on the M1 Macbook Air), this is my issue in short: when Chrome isn't in focus on my second monitor, and I try to play a video again by switching focus from my other screen, it doesn't play, but after a second click, then it plays. I know it's a small thing, but because of the frequency of when I do this, it's super annoying. How can I have it play in just one click?
I've also tried double clicking fast, but it instead just maximized the video which I don't want. So I'm stuck actually clicking first, and then waiting the half second before my second click - I switch between the screen really often and pause very often to take notes, so it adds up.
Here's a detailed breakdown if the issue didn't quite make sense:
Given:

*

*I have 2 monitors (1 monitor being the Macbook itself and the other being an external monitor)

*On monitor 1, I have Chrome full screened with a paused video (which is not full screened)

*On monitor 2, I have a Word document that is currently in focus (for taking notes)

When:

*

*I click the video on monitor 1

Then:

*

*The video doesn't play, but requires a second click

I did some googling but couldn't find a relevant answer, ideally this would act like in Windows, where you don't have to click twice with no modification keys pressed. I saw this answer and the command+click does not work either :(