text:
Q: Cannot dereference end list iterator I'm currently working on a project about browser histories.  I'm using the STL's list implementation to keep track of the different websites.  I have most of it figured out but I can't seem to resolve the error:

Screenshot; cannot dereference end list iterator.

The website data is contained within my Site objects.
class BrowserHistory {
   private:
      list<Site> history;
      list<Site>::iterator current = history.begin();
   public:
      void visitSite(string, size_t)
      void backButton();
      void forwardButton();
      void readFile(string);
};

void BrowserHistory::visitSite(string x, size_t y)
{
   while (current != history.end()) {
       history.pop_back();
   }
   history.push_back({ x, y });
   current++;
}

void BrowserHistory::backButton()
{
   if (current != history.begin())
       current--;
}

void BrowserHistory::forwardButton()
{
   if (current != history.end())
       current++;
}

void BrowserHistory::readFile(string filename)
{
   string action, url;
   size_t pageSize;
   ifstream dataIn;
   dataIn.open(filename);

   while (!dataIn.eof()) {
       dataIn >> action;
       if (action == "visit") {
           dataIn >> url >> pageSize;
           history.push_back({ url, pageSize });
           current++;
       }
       if (action == "back") {
           current--;
       }
       if (action == "forward") {
           current++;
       }
   }
   dataIn.close();
}

Can anyone explain to me what's wrong? Thanks in advance for any help.

A: When you initialise current, the list is empty.
Adding elements to the list does not suddenly make it a valid iterator, even though it will be different from end.
It looks like you're thinking of iterators as very much like pointers, but they're not.
Iterators are for iterating and should be considered transient, and not stored for later use.
Use a vector, and use an index for current instead of an iterator.
Further, I would rename the "button" functions (what does the history care about buttons?) to "goBack" and "goForward" and use your actual interface when reading:
void BrowserHistory::readFile(string filename)
{
   ifstream dataIn(filename);
   string action;

   while (dataIn >> action) {
       if (action == "visit") {
           string url;
           size_t pageSize;
           if (dataIn >> url >> pageSize) {
               visitSite(url, pageSize);
           }
           else {
               // Handle error
           }
       }
       else if (action == "back") {
           goBack();
       }
       else if (action == "forward") {
           goForward();
       }
       else {
           // Handle error
       }
   }
}


text:
Q: How to enable cache per operation in azure apim Is there any way i can implement via api policy to enable cache per operation in azure ?
I want to enable cache per operation in azure apim. How to do that ?

redpajama_set_name: RedPajamaStackExchange


text:
Q: » in a codeigniter form function How could i use the entity » inside a form in codeignite php form?
Example:
<?php
    echo form_open('pagina/contato');
    echo form_label('Mensagem:', 'mensagem');
    echo form_textarea('mensagem');
    echo form_submit('enviar', 'Enviar mensagem »', array('class' => 'botao'));
    echo form_close();
?>

How do i do to make the entity "»" (&raquo) be printed within the button, in this case instead of the entity name being shown in the button??

A: It sounds like CodeIgniter is escaping the content for you so it ends up doing a double-escape. Try using the "»" character literally in your function call:
echo form_submit('enviar', 'Enviar mensagem »', array('class' => 'botao'));


text:
Q: Python sklearn df issue - Field Cady sample code issue I'm working through Field Cady's "The Data Science Handbook", with sample code here: https://github.com/field-cady/the_data_science_handbook/blob/master/chapter08_classifiers/example.py
I get syntax error from line 23 of this code, namely:
File "<ipython-input-4-02028cc326e3>", line 2
    X, Y = df[df.columns[:3]], (df['species']=='virginica') X_train, X_test,
Y_train, Y_test = train_test_split(X, Y, test_size=.8)
                                                                  ^
SyntaxError: invalid syntax

I've googled around but can't find any answer - if anyone is able to shine any light I'd really appreciate it.
Many thanks
Full code:
from matplotlib import pyplot as plt
import sklearn
from sklearn.metrics import roc_curve, auc
from sklearn.cross_validation import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.naive_bayes import GaussianNB
# name -> (line format, classifier)
CLASS_MAP = {
    'LogisticRegression':
        ('-', LogisticRegression()),
    'Naive Bayes': ('--', GaussianNB()),
    'Decision Tree':
        ('.-', DecisionTreeClassifier(max_depth=5)),
    'Random Forest':
        (':', RandomForestClassifier(
            max_depth=5, n_estimators=10,
            max_features=1)),
}
# Divide cols by independent/dependent, rows by test/ train
X, Y = df[df.columns[:3]], (df['species']=='virginica') X_train, X_test,
Y_train, Y_test = \
    train_test_split(X, Y, test_size=.8)
for name, (line_fmt, model) in CLASS_MAP.items():
    model.fit(X_train, Y_train)
    # array w one col per label
    preds = model.predict_proba(X_test)
    pred = pd.Series(preds[:,1])
    fpr, tpr, thresholds = roc_curve(Y_test, pred)
    auc_score = auc(fpr, tpr)
    label='%s: auc=%f' % (name, auc_score)
    plt.plot(fpr, tpr, line_fmt,
        linewidth=5, label=label)
plt.legend(loc="lower right")
plt.title('Comparing Classifiers')
plt.plot([0, 1], [0, 1], 'k--') #x=y line.  Visual aid
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.show()

A: You have to load the iris dataset first. Here is your updated code.
    from matplotlib import pyplot as plt
    import sklearn
    from sklearn.metrics import roc_curve, auc
    from sklearn.cross_validation import train_test_split
    from sklearn.linear_model import LogisticRegression
    from sklearn.tree import DecisionTreeClassifier
    from sklearn.ensemble import RandomForestClassifier
    from sklearn.naive_bayes import GaussianNB
    # name -> (line format, classifier)
    from sklearn.datasets import load_iris
    import pandas as pd
    data = load_iris()
    df = pd.DataFrame(data['data'], columns=data['feature_names'])
    df['species'] = pd.Categorical.from_codes(iris.target, iris.target_names)

    CLASS_MAP = {
        'LogisticRegression':
            ('-', LogisticRegression()),
        'Naive Bayes': ('--', GaussianNB()),
        'Decision Tree':
            ('.-', DecisionTreeClassifier(max_depth=5)),
        'Random Forest':
            (':', RandomForestClassifier(
                max_depth=5, n_estimators=10,
                max_features=1)),
    }
    # Divide cols by independent/dependent, rows by test/ train
    X, Y = df[df.columns[:3]], (df['species']=='virginica')
    X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=.8)
    for name, (line_fmt, model) in CLASS_MAP.items():
        model.fit(X_train, Y_train)
        # array w one col per label
        preds = model.predict_proba(X_test)
        pred = pd.Series(preds[:,1])
        fpr, tpr, thresholds = roc_curve(Y_test, pred)
        auc_score = auc(fpr, tpr)
        label='%s: auc=%f' % (name, auc_score)
        plt.plot(fpr, tpr, line_fmt,
            linewidth=5, label=label)
    plt.legend(loc="lower right")
    plt.title('Comparing Classifiers')
    plt.plot([0, 1], [0, 1], 'k--') #x=y line.  Visual aid
    plt.xlim([0.0, 1.0])
    plt.ylim([0.0, 1.05])
    plt.xlabel('False Positive Rate')
    plt.ylabel('True Positive Rate')
    plt.show()


text:
Q: How to use datatable for SSRS Report in SSRS Class Library? Hi I created a simple Class in SSRS solution.
Public Class Class1

    Dim table As DataTable = GetTable()
    Function GetTable() As DataTable
        ' Create new DataTable instance.
        Dim table As New DataTable

        ' Create four typed columns in the DataTable.
        table.Columns.Add("Dosage", GetType(Integer))
        table.Columns.Add("Drug", GetType(String))
        table.Columns.Add("Patient", GetType(String))
        table.Columns.Add("Date", GetType(DateTime))

        ' Add five rows with those columns filled in the DataTable.
        table.Rows.Add(25, "Indocin", "David", DateTime.Now)
        table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now)
        table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now)
        table.Rows.Add(21, "Combivent", "Janet", DateTime.Now)
        table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now)
        Return table
    End Function
End Class

can I use this table in my report?
Thank you
ps: I don't want to use report viewer in VB.net project, because I really want to use NATIVE SSRS, so I can design report parameter the regular way.


text:
Q: Search text using strstr function in C I'm making a search program, but it does not output the sentences for my input.
It shows nothing in the end. Just the 'search for:' in the line 1.
#include <stdio.h>
#include <string.h>
char tracks[][80] = {
"I left my heart in Harvard Med School",
"Newark, Newark - a wonderful town",
"Dancing with a Dork",
"From here to maternity",
"The girl from Iwo Jima",
};

void find_track(char search_for[])
{
int i;
for (i = 0; i < 5; i++) {
if (strstr(tracks[i], search_for))
printf("Track %i: '%s'\n", i, tracks[i]);
}
}

int main()
{
char search_for[80];
printf("Search for: ");
fgets(search_for, 80, stdin);
find_track(search_for);
return 0;
}

Using Visual Studio 2010 with C

A: fgets(search_for, 80, stdin);

if you give input heart after you are pressing return key
fgets()  reads newline into search_for
    Now search_for=="heart\n";

remove \n at the end of search_for
   if(search_for[strlen(search_for)-1]=='\n')
      search_for[strlen(search_for)-1]='\0';

   find_track(search_for);

A: Easiest solution is to replace:
fgets(search_for, 80, stdin);

with
fscanf(stdin, "%s", search_for);

With this method, be careful not to enter more than 79 characters in your search though.


text:
Q: Accessing pytest assert message in finalizer I am trying to generate a custom report with pytest and trying to access the assert message generated by pytest, in the case of a failure, in the finalizer of a global fixture in the conftest.py file. I am able to access the status of the test but I am not able to get the error message.
I would like to access the status message in the following way
@pytest.fixture(scope='function',autouse = True)
def logFunctionLevel(request):
    start = int(time.time() * 1000)
    def fin():
        stop = int(time.time())
        fo = open("/Users/mahesh.nayak/Desktop/logs/test1.log", "a")
        fo.write(request.cls.__name__ + "." + request.function.__name__ + " " + str(start) + " " + str(stop) + "\n")

Any help to access the exception message is appreciated
Thanks
Edit : The answer by Bruno did help. Adding the below lines printed the asserts.
  l = str(report.longrepr)
  fo.write(l)

A: I'm not sure you can access the exception message from a fixture, but you can implement a custom pytest_runtest_logreport hook (untested):
def pytest_runtest_logreport(report):
    fo = open("/Users/mahesh.nayak/Desktop/logs/test1.log", "a")
    fo.write('%s (duration: %s)\n' % (report.nodeid, report.duration))
    fo.close()

Hope that helps.

A: To access the assert message from a fixture you can follow the documentation here :
https://docs.pytest.org/en/latest/example/simple.html#making-test-result-information-available-in-fixtures
Which for your question make something look like that: (untested code)
# content of conftest.py

import pytest

 @pytest.hookimpl(tryfirst=True, hookwrapper=True)
 def pytest_runtest_makereport(item, call):
    # execute all other hooks to obtain the report object
    outcome = yield
    rep = outcome.get_result()

    # set a report attribute for each phase of a call, which can
    # be "setup", "call", "teardown"

    setattr(item, "rep_" + rep.when, rep)

@pytest.fixture
def something(request):
    yield

    # request.node is an "item" because we use the default
    # "function" scope
    error_message= ""
    if request.node.rep_setup.failed:
        print("setting up a test failed!", request.node.nodeid)
        error_message = request.node.rep_setup.longreprtext
    elif request.node.rep_setup.passed:
        if request.node.rep_call.failed:
            print("executing test failed", request.node.nodeid)
            error_message = request.node.rep_call.longreprtext

    fo = open("/Users/mahesh.nayak/Desktop/logs/test1.log", "a")
    if error_message:
        fo.write('%s (duration: %s) - ERROR - %s \n' % (report.nodeid, report.duration,
                                                        error_message))
    else:
        fo.write('%s (duration: %s) - PASSED \n' % (report.nodeid, report.duration))
    fo.close()

The main difference with Bruno Oliveira answer, is that pytest_runtest_logreport is called for each different step of the test ( setup/call/teardown? ), when a fixture can be called only one time at the end of the test.


text:
Q: Unpacked javascript doesn't work I found this script (http://coolersport.info/) and downloaded it. I want change some things in javascript code, so I opened cshout.js (unpacked version) and do changes. I saved it as "cshout.packed.js" (replaced with original packed version).
But now I go to my script index, I can't see any thing, And I see only a white blank page...
Why unpacked version doesn't work? The packed version was create from original unpacked file  (I have same problem with some other scripts...it is an example!)
I debugging it with FireBug. Firebug said:
ajaxCS is not defined
localhost/cshout/cshout.js Line 49
cshout is not defined localhost/cshout
Line 14

A: You will need to use a Javascript debugger such as the Firebug plugin for Firefox and trace down what has broken using that. Without the javascript we can't help in determining the issue.

A: It seems like you have a syntax error in your code (referencing an unknown variable - typo?). If you copy your modified cshout.js to cshout.packed.js and it doesn't work, it means you broke something when you modified the original library.

A: you are looking for problem in wrong place
you need to include ajaxcs.js


text:
Q: choosing time and AM or PM i have an option value for time in main form and another option for am or pm...now what confuses me is how am i going to code it when if example i choese 1 and then pm...how am i goin to call it on the database?i also have to filter the sales reports by time and by pm.. hope someone can help me..thanks

A: You can set AM/PM through capital A or lowercase a depending on your preference of capital AM/PM or lowercase am/pm. As far as your question on how to interact with the database, your time inserted should be unedited, IE you don't want to apply the styling from the date function and insert that into your database as a string because that will prevent you from changing it in the future. Instead create a DATETIME or TIMESTAMP column in your table, and put the date in that, then when you select from the table you can apply styling to fit your needs.
http://dev.mysql.com/doc/refman/5.0/en/datetime.html
http://www.php.net/manual/en/function.date.php

A: From Database to Display
The PHP Function [date()][1] can be used to convert a Unix Timestamp into a Human-Readable form.
<?php
// $time is assumed as a Timestamp from DB or other
echo date( 'g:i:sa, l jS F Y' , $time );
?>
Will Return
3:43pm, Wednesday 25th August 2010

Alternately, you could use the [strftime()][2] which performs a similar role, but has different placeholders (it also lacks the placeholder for "st","nd","th" after the day number). The benefit of this function is that you could include plain text within the format, as all placeholders are prefixed with "%" - so "hello" would not be treated as a placeholder.
<?php
// $time is assumed as a Timestamp from DB or other
echo strftime( '%l:%M:$S%P, %A %e %B %Y' , $time );
?>
Will Return
3:43pm, Wednesday 25 August 2010

Translating User-Entered Data into a Format for the Database
Most databases I have worked with have been pretty intelligent about how they handle timestamps. All you should need to do is, if there are more than one field being used (ie one for hour, one for minutes, one for am/pm), join them together into a single string, and just make sure that the resulting string is of a format able to be parsed by PHP.
The function strtotime() can turn a Human-readable time into a Unix Timestamp, which your database should be able to handle without any problems.
<?php
// $input is the string (joined or solo) containing the Human-readable timestamp
$input = "2010/08/25 3:43pm";
if( ( $out = strtotime( $input ) )===false ){
  echo 'Timestamp "'.$input.'" Unrecognisable';
}else{
  echo $out;
}
?>
Will Return
1282743780

If the string being parsed is not recognisable according to the PHP Date Time Formats, then it will return false.


text:
Q: Which communities (tags(s)) on SO award the most points for Q's/A's? Just out of curiosity, which communities (i.e. tag(s)) on SO award the most points for questions?  How about for answers?  Anecdotally I've found that some communities are more willing to award points than others.  So I was just curious about which community is the most generous and which is the least generous.
As I said...purely out of curiosity.

A: There are a few Stack Exchange data explorer queries that give insight on this:

*

*Most/Least dangerous tags among those with 1000 questions

*Most rewarding tags to answer among those with 1000 questions

*Most lucrative tags
And of course, you can bend the data explorer to your will to figure out what fits your chosen criteria best!


text:
Q: Understanding return with FOREACH Loop I have a for each loop that is looping through an array of data -
foreach ($products as $value){
            $product_id = $correlationId;
            $pid = mysql_escape_string($value['ProductId']);
            $dname = mysql_real_escape_string($value['departmentName']);
            $cname = mysql_real_escape_string($value['categoryName']);
            $pname = mysql_real_escape_string($value['productName']);
            $price = mysql_real_escape_string($value['productPrice']);
            $qty = mysql_real_escape_string($value['productQty']);
            //Insert Product data into DB
            $insert_product = "INSERT INTO product(department_name,category_name,product_name,product_price,product_qty)VALUES('$dname','$cname','$pname','$price','$qty')";
            $insert_result = mysql_query($insert_product);
            if(mysql_insert_id() >  0){
                $response = array('CorrelationId'=>$pid,
                            'Messages'=> array('Has been added.')
                );
                return $response;
            }

        }

I am really looking on information to best return $response without stopping the loop. I would like it to return the data then carry back on with the loop then return the data then carry back on with the loop.
Currently It stops after the first return, obviously becasue the return is breaking it?
Can anyone shed some light for me?
Thanks
Edit - Extra Code added
//Create complex type for StringArray
$server->wsdl->addComplexType(
    'StringArray',
    'complexType',
    'array',
    '',
    'SOAP-ENC:Array',
    array(),
    array(array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'xsd:string[]')),
    'xsd:string'
);
//Create complex type for AddProductResponce
$server->wsdl->addComplexType(
    'AddProductResponse',
    'complexType',
    'struct',
    'all',
    '',
    array(
        'CorrelationId' => array('name'=>'CorrelationId','type'=>'xsd:string'),
        'Messages' => array('name'=>'Messages','type'=>'tns:StringArray'),
    )
);

Im working with a NUSAOP server and thats the complexTypes to handle the responce, I cannot seem to be able to adjust these to help aid the return after the loop

A:         $response[] = array('CorrelationId'=>$pid,
                    'Messages'=> array('Has been added.')
        );

and when the loop ends reutrn it.
        return $response;

The difference is that now $response is an array of arrays.
Is that what you were looking for?


text:
Q: Simple test setup with Selenium WebDriver fails I'm just trying to execute a basic selenium test. Nothing special, just to make sure it works.
BUT is throws an exception.
What could I be doing wrong?
Of course I started the server using: java -jar selenium-server-standalone-2.24.1.jar
import static org.junit.Assert.fail;

import java.util.concurrent.TimeUnit;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Selenium {
    private WebDriver driver;
    private String baseUrl;
    private StringBuffer verificationErrors = new StringBuffer();

    @Before
    public void setUp() throws Exception {
        driver = new FirefoxDriver();
        baseUrl = "http://www.google.de/";
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
    }

    @Test
    public void testSeleniumWeb() throws Exception {
    //empty just for testing
    }
}

Throws:
java.lang.AbstractMethodError: org.apache.crimson.tree.ElementNode2.getTextContent()Ljava/lang/String;
    at org.openqa.selenium.firefox.internal.FileExtension.readIdFromInstallRdf(FileExtension.java:134)
    at org.openqa.selenium.firefox.internal.FileExtension.writeTo(FileExtension.java:61)
    at org.openqa.selenium.firefox.internal.ClasspathExtension.writeTo(ClasspathExtension.java:64)
    at org.openqa.selenium.firefox.FirefoxProfile.installExtensions(FirefoxProfile.java:547)
    at org.openqa.selenium.firefox.FirefoxProfile.layoutOnDisk(FirefoxProfile.java:525)
    at org.openqa.selenium.firefox.internal.NewProfileExtensionConnection.start(NewProfileExtensionConnection.java:74)
    at org.openqa.selenium.firefox.FirefoxDriver.startClient(FirefoxDriver.java:149)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:78)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:128)
    at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:79)
    at de.coconet.soapui.selenium.setUp(selenium.java:15)
    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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:30)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

A: It's nothing to do with your code. You have a classpath problem. Some classes depend on a different version of ElementNode2 than the one found first in your classpath.
If you look at jarfinder you can see that after JDK 1.4, this class is included in the Java runtime (rt.jar).
I suspect that you are using an older version of the JDK than the one that WebDriver was compiled against. WebDriver requires JDK 1.6+.


text:
Q: Patterns for "flexible" queries without ORM? I am working on a new project in which I am ordered not to use ORM. The software operates on one main model class that has some collection and complicated object fields.
The different operations in the software will only need some of the fields to be populated and may query for the main model based on different conditions.
This requirement would be trivial to implement with an ORM, but I am struggling to design a persistence layer without it.
The main issue is the ridiculous amount of duplication among the SQL queries in the DAOs and lack of safeguards against accessing fields are not loaded.
What kind of patterns do people use to write the model classes and the DAOs without ORMs?
I have looked at less ORM-ish tools that might be allowed like MyBatis but they seems to focus on automating the mapping, which is not a big issue for me...


text:
Q: Litespeed doesn't optimize my all pictures google pagespeed gives "need optimization for news" for my website:
https://cutt.ly/DmoA3UU
I can't click bulk button more.Why, how can I solve it?
here is the panel

A: I did not see such a suggestion for your site from the google page speed. The screenshot you provided shows there's no more image left that needs to be optimized.
You can verify if images are being optimized from the Media>library, and show them in list mode.
I'd recommend the following things for your site optimization.

*

*HTTP/3 is not working may be due to the firewall

*

*Check Tool: https://http3check.net/?host=https%3A%2F%2Fbclinico.helvatica.com%2F

*Follow https://docs.litespeedtech.com/cp/cpanel/quic-http3/#open-udp-port-443-at-the-firewall to fix the firewall issue.

*Optimize image in WebP version and turn on the WebP replacement

*

*https://docs.litespeedtech.com/lscache/lscwp/imageopt/#create-webp-versions

*If no conflict, try to combine the JS files to reduce the page requests

*Your node is located in Turkey. If most of your visitors come from the AU region, I'd recommend you to have CDN integrated to reduce the network latency. E.g.

*

*https://quic.cloud/

*https://www.cloudflare.com/


text:
Q: CountdownTimer and exiting the Activity I have made a game module in which a user is granted a minute to answer the questions and then an intent is called to show the result ,my problem is when I exit the activity in the middle, it still shows the result for the time completed on the game no matter on what activity I am.
My code for timer is
class MyCount extends CountDownTimer{
    public MyCount(long millisInFuture, long countDownInterval) {
    super(millisInFuture, countDownInterval);
    }
    @Override
    public void onFinish() {

        Intent finish= new Intent(QuestionScreen.this,ResultScreen.class);
        finish.putExtra("noofques", Integer.toString(totalquestions));
        finish.putExtra("correct", Integer.toString(score));
        startActivity(finish);
        overridePendingTransition( R.anim.slideinleft, R.anim.slideoutleft);
    }
    @Override
    public void onTick(long millisUntilFinished) {
        if(millisUntilFinished>60000)
        timerview.setText((millisUntilFinished/(1000*60))+1 +" minutes left");
        else
        {
        timerview.setText(millisUntilFinished/1000 +" seconds left");
        }
    }
    }

and code for exiting the game in middle is
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
        alertbox.setMessage("Do you really want to quit");
        alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1) {
                Intent info = new Intent(QuestionScreen.this,com.preciselabs.mental_skills.MenuScreen.class);
                info.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                finish();
                startActivity(info);
                overridePendingTransition( R.anim.slideinright, R.anim.slideoutright);
                }
        });
        alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface arg0, int arg1) {
           }
        });
        alertbox.show();
    return true;
    }
    return super.onKeyDown(keyCode, event);
    }

any solution to my problem will be greatly appreciated

A: use belove code when you exit activity..
  mCount.cancel();
  mCount=null;

and a boolean in onfinish() for   startActivity(finish);


text:
Q: disable next button after 1 click swiper I have a doubt because the documentation is not very clear, I want to click on the next button on the right side and go back with the left button, because here in my code, it can go to the next one and come back with the next button I would like just 1 click to go to the side and the other button to go back my EXAMPLE:
I AM USING SWIPER TO DO THE ACT:
var swiper = new Swiper(".slide-content", {
  slidesPerView: 3,
  spaceBetween: 25,
  loop: true,
  centerSlide: 'true',
  fade: 'true',
  grabCursor: 'true',
  slidesPerGroup: 3,
  pagination: {
    el: ".swiper-pagination",
    clickable: true,
    dynamicBullets: true,
  },
  navigation: {
    nextEl: ".swiper-button-next" ,
    prevEl: ".swiper-button-prev",
  },

  breakpoints:{
      0: {
          slidesPerView: 1,
      },
      520: {
          slidesPerView: 2,
      },
      950: {
          slidesPerView: 3,
      },
  },
});

                                                            <video id="vdd1" class="vdd1" src="/static/aaa/videodr.mp4" controls>

Seu navegador não suporta o vídeo. aqui está um link para o video instantâneo.

                                                            </video>

                                                                    <ion-icon class="pll1"  name="play-circle-outline"></ion-icon>

                                                            <video id="vdd2" class="vdd2" src="/static/aaa/vd2.mp4" controls>

Seu navegador não suporta o vídeo. aqui está um link para o video instantâneo.

                                                            </video>

                                                                    <ion-icon class="pll1"  name="play-circle-outline"></ion-icon>

                                                            <video id="vdd3" class="vdd3" src="/static/aaa/vd3.mp4" controls>

Seu navegador não suporta o vídeo. aqui está um link para o video instantâneo.

                                                            </video>

                                                                    <ion-icon class="pll1"  name="play-circle-outline"></ion-icon>

A: Simple, my friend, just disable the loop, so your next will no longer work, I believe that's it.
**  loop: false, **
var swiper = new Swiper(".slide-content", {
  slidesPerView: 3,
  spaceBetween: 25,
  loop: false,
  centerSlide: 'true',
  fade: 'true',
  grabCursor: 'true',
  slidesPerGroup: 3,
  pagination: {
    el: ".swiper-pagination",
    clickable: true,
    dynamicBullets: true,
  },
  navigation: {
    nextEl: ".swiper-button-next" ,
    prevEl: ".swiper-button-prev",
  },

  breakpoints:{
      0: {
          slidesPerView: 1,
      },
      520: {
          slidesPerView: 2,
      },
      950: {
          slidesPerView: 3,
      },
  },
});


text:
Q: Oracle Query to fetch right rows base on my I have sample date like below. I need to pick up the specific values (i.e) if column type values "st/cm" are similar to type column values "s/p" for columns id,name and value, then pick "s/p" rows as shown below
id   name  text  value  type   date type
123  tan   abc   98     st     2017-06-09
123  tan   abc   98     st     2017-06-09
123  tan   a     98     s      2017-06-09 --pick this
123  tan   a     98     s      2017-06-09 --pick this
124  pan   ndc   97     cm     2017-06-09
124  pan   ndc   97     cm     2017-06-09
124  pan   b     97     p      2017-06-09 --pick this
124  pan   b     97     p      2017-06-09 --pick this

Expected Output:here the below columns are similar for type "ST/CM" compared to   "S/P" rows, so we pick "S/P" rows
    id   name  value  type   date type
    123  tan    98     st     2017-06-09
    123  tan    98     st     2017-06-09
    123  tan    98     s      2017-06-09 --pick this
    123  tan    98     s      2017-06-09 --pick this
    124  pan    97     cm     2017-06-09
    124  pan    97     cm     2017-06-09
    124  pan    97     p      2017-06-09 --pick this
    124  pan    97     p      2017-06-09 --pick this

A: If you're looking for all s / p rows that have at least two st / cm rows with the same identifiers, you could just use count():
SELECT date_type from mytable t1 WHERE t1.type in ('s', 'p') AND
    (SELECT count(*) from mytable t2 where t2.id = t1.id and t2.name = t1.name
     and t2.value = t1.value and t2.type = DECODE(t1.type, 's', 'st', 'p', 'cm')) > 1;

or, if it's enough to have a single match, you can use EXISTS()
SELECT date_type from mytable t1 WHERE t1.type in ('s', 'p') AND
    EXISTS (SELECT 1 from mytable t2 where t2.id = t1.id and t2.name = t1.name
     and t2.value = t1.value and t2.type = DECODE(t1.type, 's', 'st', 'p', 'cm'));


text:
Q: Referencing previous value in cell (R) I have the following data.frame:
head(data.c)

     mark high_mark mark_cum
      5        0        0
      7        1        1
      7        1        2
      NA       0        2
      7        1        3
      7        1        4

As there are NAs I need to construct an additional column of normal sequence from 1:length(mark). However, if it is NA vector cell has to take a previous value. So it must look like this:
     mark high_mark mark_cum mark_seq
      5        0        0       1
      7        1        1       2
      7        1        2       3
      NA       0        2       3
      7        1        3       4
      7        1        4       5
      NA       0        4       5

A: 1) cumsum  This solution uses the fact that each mark_seq element equals the cumulative number of non-NA elements in mark at that point.
transform(data.c, mark_seq = cumsum(!is.na(mark)))

giving:
  mark high_mark mark_cum mark_seq
1    5         0        0        1
2    7         1        1        2
3    7         1        2        3
4   NA         0        2        3
5    7         1        3        4
6    7         1        4        5
7   NA         0        4        5

data.c <- read.table(text = Lines, header = TRUE)

2) na.locf Here is a second solution using seq_along and na.locf (from zoo).  It creates a sequence the same length as the number of non-NA elements in mark and uses replace to put them in the spots where the non-NA elements exist.  Then na.locf is used to fill in the NAs with the prior values.
library(zoo)

transform(data.c, mark_seq=na.locf(replace(mark, !is.na(mark), seq_along(na.omit(mark)))))

3) mark_cum It was not stated in the question how the input column mark_cum is constructed but in the sample output in the question the mark_seq column equals the mark_cum column plus 1 so if that is always the case then an easy solution is:
transform(data.c, mark_seq = mark_cum + 1)

Note: We used this as the input:
Lines <- "mark high_mark mark_cum
      5        0        0
      7        1        1
      7        1        2
      NA       0        2
      7        1        3
      7        1        4
      NA       0        4"


text:
Q: Any ways to detect CSS changing? I have this tags:

Then I have a javascript lib that changes font-size of the
 tag, but
 has its own CSS. Then text in
 does not change. I just want resizing font-size of
 affecting
. I cannot change the javascript lib nor the html structure. So, I think that it would be good to have something like
$('div').bind('css-change', function (){
    $('h1').css('fontSize',$('div')Text.css('fontSize'));
})

Any ways to have something like .bind('css-change') ?

A: Afaik there is no event that is triggered on css change...
Why not change the css of the
 via JS and set it to inherit the font-size?
$('h1').css('fontSize','inherit');

A: jQuery has implemented in version 1.4.3: cssHooks
$.cssHooks["someCSSProp"] = {
    get: function( elem, computed, extra ) {
      // handle getting the CSS property
    },
    set: function( elem, value ) {
      // handle setting the CSS value
    }
};


text:
Q: how to save docker image for later installation? There is a docker image I need to load on station which is not connected to the internet
(i.e I can't use docker pull command)
So on the station which is connected to the internet, I want to download the docker image and copy it to the other station (which is not connected to the internet) and run it.
How can I do it this?

A: You can use the docker save command to save one or more images to a tar archive.
More info here-> https://docs.docker.com/engine/reference/commandline/save/
On the system with internet
$ docker pull <image>
$ docker save <image> > <image>.tar

Then copy this .tar file to a usb, and use docker load to unpack it on the other station.


text:
Q: Slice every string in list in Python I want to slice every string in a list in Python.
This is my current list:
['One', 'Two', 'Three', 'Four', 'Five']

This is the list I want for result:
['O', 'T', 'Thr', 'Fo', 'Fi']

I want to slice away the two last characters from every single string in my list.
How can I do this?

A: You can do:
>>> l = ['One', 'Two', 'Three', 'Four', 'Five']
>>> [i[:-2] for i in l]
['O', 'T', 'Thr', 'Fo', 'Fi']

A: x=['One', 'Two', 'Three', 'Four', 'Five']
print map(lambda i:i[:-2],x)  #for python 2.7
print list(map(lambda i:i[:-2],x)) #for python 3

A: Use a list comprehension to create a new list with the result of an expression applied to each element in the inputlist; here the [:-2] slices of the last two characters, returning the remainder:
[w[:-2] for w in list_of_words]

Demo:
>>> list_of_words = ['One', 'Two', 'Three', 'Four', 'Five']
>>> [w[:-2] for w in list_of_words]
['O', 'T', 'Thr', 'Fo', 'Fi']


text:
Q: Approximate countable union of open intervals by a finite covering of open intervals. Given an open interval $I=(a, b)\subset \mathbb R$ for some $a, b\in \mathbb R$ and a countable union of its open subintervals $U=\bigcup\limits_{i=1}^\infty J_i$ such that $\sum\limits_{i=1}^\infty L(J_i)<\infty$($L(J_i)$ is the length of the interval $J_i$), for any $\epsilon>0$ can we choose an finite union of open subintervals $K=\bigcup_{i=1}^n K_i\subset I$ and an integer $N$ such that $$\bigcup\limits_{i=N+1}^\infty J_i\subset K\text{ and } \left| L(K)-\sum_{i=N+1}^\infty L(J_i)\right|<\epsilon?$$
I came up with this question when I was attempting to prove a problem in real analysis, and this would finish the proof if it is true.

A: Let $(q_i)$ be an enumeration of the rationals in $I$. Any such enumeration has the property that the tails of $(q_i)$ are always dense in $I$. (Any point of $I$ is the limit of a sequence of distinct rationals - a subsequence of $(q_i)$. But a tail of $(q_i)$ will contain a tail of the subsequence.)
Let $\epsilon > 0$ and let $$J_i = (q_i - \epsilon 2^{-i-1}, q_i + \epsilon 2^{-i-1})\cap I$$
Then $L(J_i) \le \epsilon 2^{-i}$, so for any $N > 0,$ $$\sum_{i>N} L(J_i) \le \sum_{i>N} \epsilon 2^{-i} = \epsilon 2^{-N} < \epsilon$$
By choosing $\epsilon$ small enough, we can make $\sum_{i} L(J_i)$ as small as we please. In particular, make it smaller than $\frac{b-a}2$.
Because $(q_i)_{i > N} \subseteq \bigcup_{i>N}J_i$ is dense in $I$, any finite union of open intervals $K_N \subseteq I$ containing $\bigcup_{i>N}J_i$ can miss at most a finite number of points of $I$, so $L(K_N) = b-a$, a fixed value with respect to $N$. Therefore, for all $N$,$$\left| L(K_N)-\sum_{i>N} L(J_i)\right| > \frac {b-a}2$$


text:
Q: Groupings Expanded I'd like to be able to keep groupings expanded without needing to expand them each time.  That is, I want the expanded groupings to be the default when a user opens the page.  Can this be done?

A: Edit your view and in the "Group By" section, select the Expanded option for this property : "By default, show groupings:"


text:
Q: PostgreSQL - SQL function to loop through all months of the year and pull 10 random records from each I am attempting to pull 10 random records from each month of this year using this query here but I get an error "ERROR: relation "c1" does not exist
"
Not sure where I'm going wrong - I think it may be I'm using Mysql syntax instead, but how do I resolve this?
My desired output is like this

Month
Another header

2021-01
random email   1

2021-01
random email 2

total of ten random emails from January, then ten more for each month this year (til November of course as Dec yet to happen)..
With CTE AS
(
    Select  month,
            email,
            Row_Number() Over (Partition By month Order By FLOOR(RANDOM()*(1-1000000+1))) AS RN
    From    (
            SELECT
                    DISTINCT(TO_CHAR(DATE_TRUNC('month', timestamp ), 'YYYY-MM')) AS month
                    ,CASE
                      WHEN
                      JSON_EXTRACT_PATH_TEXT(json_extract_array_element_text (form_data,0),'name') = 'email'
                      THEN
                      JSON_EXTRACT_PATH_TEXT(json_extract_array_element_text (form_data,0),'value')
                      END AS email
            FROM  form_submits_y2 fs
            WHERE fs.website_id IN (791)
            AND month LIKE '2021%'
            GROUP BY 1,2
            ORDER BY 1 ASC
            )
)
SELECT  *
FROM CTE C1
LEFT JOIN
     (SELECT RN
            ,month
            ,email
     FROM CTE C2
     WHERE C2.month = C1.month
     ORDER BY RANDOM() LIMIT 10) C3
ON C1.RN = C3.RN
ORDER By month ASC```

A: You can't reference an outer table inside a derived table with a regular join. You need to use left join lateral to make that work

A: I did end up finding a more elegant solution to my query here via this source from github :
SELECT
month
,email
FROM
(
    Select  month,
            email,
            Row_Number() Over (Partition By month Order By FLOOR(RANDOM()*(1-1000000+1))) AS RN
    From    (
            SELECT
                    TO_CHAR(DATE_TRUNC('month', timestamp ), 'YYYY-MM') AS month
                    ,CASE
                      WHEN JSON_EXTRACT_PATH_TEXT(json_extract_array_element_text (form_data,0),'name') = 'email'
                      THEN JSON_EXTRACT_PATH_TEXT(json_extract_array_element_text (form_data,0),'value')
                      END AS email
            FROM  form_submits_y2 fs
            WHERE fs.website_id IN (791)
            AND month LIKE '2021%'
            GROUP BY 1,2
            ORDER BY 1 ASC
            )
) q
WHERE
  RN <=10
ORDER BY month ASC


text:
Q: How to get all users at once with a GraphQL query? List 101 Users with GraphQL
Why I can not get all users at once while using PostGQL?
It just returns first 100 users while using GraphQL but works fine with a GET request.
GraphQL Query

    {
      users(limit: 101, sort: "username") {
        id
        username
      }
    }

Result

Using Get Method returns full set!
I can get the full data set by GET /users?_limit=-1 if I use GET
NOTE: using limit: -1 does not work either.
{
  users(limit: -1) {
    id
    username
  }
}

*

*Strapi Version:3.4.1

*Operating System: Windows, Ubuntu

*Database: Mysql, PostgreSQL

*Node Version: 14.15.3

*NPM Version: 6.14.9

*Yarn Version: 1.22.5

A: The default amountLimit for the GraphQL plugin is 100. You can change this limit as stated here


text:
Q: Return value isn't returning double with two decimal places This question goes towards both my class method and my test cases. I have tried searching it up and implemented some of the methods I found online, but in my test case, it shows as Expected: 10.0  Actual: 11.0 when I want it to show Expected: 10.00  Actual: 11.00 with trailing zeros.
It works if it's a number that's not zero, so Expected: 12.33 Actual: 12.33 is good.
My issue is mainly with trailing zeros.
code in class method:
public Double average(int[] scores) {
        double average = Arrays.stream(scores).average().orElse(0.00);
        String format = String.format("%.2f", average);

        for (int num : scores) {
            if (num < 0) throw new ArithmeticException("scores must be positive");
        }

        return Double.parseDouble(format);
    }

test case: I originally had a double value (10.00) but changed it to a BigDecimal and then converted it to a double to see if it would work, but ig not.
public void testSingleAverage() {
        int[] nums = {11};

        BigDecimal expected = new BigDecimal(10.00).setScale(2);
        Double result = exercise.average(nums);
        Double value = expected.doubleValue();

        assertEquals(value, result);
    }

Thank you in advance for the help <3
Edit: I'm not able to return a String or BigDecimal(even tho its much simpler). Its required to be a double value.

A: There is no way to force a double to have trailing zeros. If you take a look at the Double class you will see that there is no concept of precision or scale included (like there is for the BigDecimal class).


text:
Q: Extending HTML5 tags collection As you know HTML5 introduced  some new html tag, like footer,header, ...
What prevent us from using a lot of other new tag and apply shiv to these new tags? (from functional, behavior, style, structure, ... viewpoints)
I want use following code (more semantic, concise and readable, a step forward Web 3.0):

<book>
    <title>
        My Title
    </title>
</book>

instead of using following traditional (!) code:

        My title

A: This seems to be a use case for RDFa. Actually, there is a very similar example in the RDFa specification. Here is what you can do (I know, it's more verbose than what you propose but who said that more semantics means more conciseness?)

    <title>Title of the web page</title>

      My title

Here, you are saying that there is an entity of type bibo:Book (you need to define a namespace which refer to a vocabulary, here the Bibliography ontology) and this entity has a dc:title (again, the property is defined in the Dublin Core vocabulary).
You can see that I'm using CSS2 selectors to format the book as appropriate.

A: <title> is already an element in HTML. Do you know what happens if you do this in all HTML consumers? In IE8 and earlier for example?
Even if you restrict yourself to elements that don't currently exist in HTML, how can you prevent an element of the same name being invented in the future, with behaviour in browsers that breaks your page?

A: What you want can be done in raw XML...
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet href="main.css" type="text/css"?>
<Root>
  <book>
    <title>
      My Title
    </title>
  </book>
</Root>

and main.css:
book {
    display: block;
    color: red;
}

book title {
    display: inline-block;
    font-weight: bold;
}

Concise enough?

A: Using your own tags works well up to a point, and it sounds tempting. However, you are not adding any meaning (semantics) that way; an invented tag has no defined meaning, and pretending that the tag name is descriptive of meaning is an illusion.
Custom tags have several problems. But your simple example also demonstrates extended usage of tags that are defined in HTML specifications. Who knows what will happen if a document contains several title elements, or a title element outside its  "legal" scope, the head element? Who knows what search engines will think about it?
The point is that title is defined in HTML and browsers treat it in their ways, which cannot be controlled by you. If the browser decides to take a misplaced title element as if it were standard-conformingly in the head and therefore uses it in certain ways (e.g., in top bar or tab control), what can you do about it? If it even overrides a standard-conforming title element, what do you do?
If you just use custom tags, you might decide to ignore the IE problem (which cannot be completely solved using JavaScript, because JavaScript might be disabled). But you would still be using something that may crash tomorrow when some browser vendor starts supporting an extended tag and it happens to have the same name as your tag (but different meaning). And <book> is a good candidate for that. It might even make its way to HTML specs some day; HTML5 drafts already have
.
Your style sheet might override any default presentation describable in CSS today, but browsers might use extended CSS features or might use presentational features not describable in CSS. And new tags might have default functionality that surprises you and can hardly be anticipated now.


text:
Q: method is started when launched So, I have a gameOver() method that should when oval goes out of bounds abort game but, as soon as I start the game it runs the gameOver method. I've been looking over it for a while trying different things. I think what stood out to me is removing the abort sequence the game runs mostly as it should after, popup is closed and that if I replace game.gameOver(); with ya = -1 the ball bounces off the wall.
gaveOver()
public void gameOver(){
    JOptionPane.showMessageDialog(this, "Game Over", "Game Over", JOptionPane.YES_NO_OPTION);
    System.exit(ABORT);
}

move()
package com.edu4java.minitennis1;

import java.awt.Graphics2D;
 import java.awt.Rectangle;

public class Ball {
private static final int DIAMETER = 30;
int x = 0;
int y = 0;
int xa = 1; // Represent the speed in which the ball is moving
int ya = 1; // Represent the speed in which the ball is moving
private Game game;

public Ball(Game game){
    this.game=game;
}

/*
 * If xa=1, the ball moves to the right, one pixel every round of the Game Loop,
 * if xa=-1, the ball moves to the left.
 * If ya=1 moves the ball down and
 * If ya=-1 moves the ball up.
 */

void move(){
    if (x + xa < 0) // Makes left bounds
        xa = 3; // Moves the ball right
    if (x + xa > game.getWidth() - DIAMETER) // Makes right bounds
        xa = -3; // Moves the ball left
    if(y + ya < 0) // Makes top bounds
        ya = 3; // Moves ball down

    if(y + ya > game.getHeight() - DIAMETER) // Makes bottom bounds
        game.gameOver();

    if (collision()){ // Makes collision with Racquet
        ya = -3;
        y = game.racquet.getTopY() - DIAMETER;
    }
    x = x + xa;
    y = y + ya;
}

private boolean collision(){
    return game.racquet.getBounds().intersects(getBoundsBall());
}

public void paint(Graphics2D g){
    g.fillOval(x, y, DIAMETER, DIAMETER);
}

public Rectangle getBoundsBall(){
    return new Rectangle(x, y, DIAMETER, DIAMETER);
}

}

The problems has been resolved I just went back and rewrote the move() method and replaced it with
void move(){
     if(x + xa < 0)// Makes left bounds
         xa = 1;// Moves the ball right
     if(x + xa == game.getWidth() - DIAMETER)// Makes right bounds
         xa = -1;// Moves the ball left
     if (y + ya < 0)// Makes top bounds
         ya = 1;// Moves ball down
     if(y + ya == game.getHeight() - DIAMETER){ // Makes bottom bounds
        ya = 0;// Moves ball up
        xa = 0;
        game.gameOver();
     }

Sometimes all you need to do is go back.

A: You have answered your question yourself I think. Assuming there are no further calls to your gameOver() method than the one that's in your move() method, than gameOver is called from this if block:
if(y + ya > game.getHeight() - DIAMETER)
    game.gameOver();

Which means that (y + ya) is greater than (game.getHeight() - DIAMETER). Since I don't know what your variables are supposed to be I can only guess that there might be a problem with your initial values,etc.
Try stepping through your program with a debugger and it will be much easier to see the problem and understand what's going on.


text:
Q: CBLite Android - Get values in second level Using CBLite Android, and storing docs (similar to Android Grocery Sync example) like this:
{
     "check" : true,
     "created_at" : "2014-02-25T10:16:46.026Z",
     "text" : "Soap",
     "prices":[  { "date" : "2014-02-25" , "value" : 12 }  ]
}

I get value in "text" field as shown in the documentation:
...
Document document = row.getDocument();
String text = ((String)document.getCurrentRevision().getProperty("text"));
...

But, How should I do to get the value in, for example, "value" field?
Thanks.

Edit:
Getting documents
 API reference

A: Search in the doc to something which allow you to get an array, then read the array to get value.


text:
Q: Move Focus to Next Cell on Enter Key Press in WPF DataGrid using MVVM design pattern? I'm writing a simple wpf application which contains datagrid. I'm following MVVM design pattern. When the app is initially run, an empty row will be added to the datagrid and I'm focusing the 1st cell of the 1st row by default.
I need following things to be done and I need it to be done with MVVM design pattern.

*

*When you hit "Enter" key, move focus to next cell

*When the focus is set to the last cell of the grid and user hit the "Enter" key again, new empty row should be added to the grid and focus should be added to the 1st cell of the new row.

I found some similar questions like this(ex : this) but none o f them explains how to do this using MVVM design pattern and my 2nd point above is not included in those posts.
Item.cs class is as below.
public class Item
{
    public string ItemCode { get; set; }
    public string ItemName { get; set; }
    public double ItemPrice { get; set; }

    public Item(string itemCode,string itemName, double itemPrice)
    {
        this.ItemCode = itemCode;
        this.ItemName = itemName;
        this.ItemPrice = itemPrice;
    }
}

ItemsViewModel.cs class as below.
public class ItemsViewModel : INotifyPropertyChanged
{
    private List<Item> _items;

    public List<Item> ItemsCollection
    {
        get { return this._items; }
        set
        {
            _items = value;
            OnPropertyChanged(nameof(ItemsCollection));
        }
    }

    public ItemsViewModel()
    {
        this.ItemsCollection = new List<Item>();
        this.ItemsCollection.Add(new Item("", "", 0));
    }

    #region INotifyPropertyChanged Implementations

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    #endregion
}

Following DataGridBehavior.cs class will handle focus of the 1st cell when the app initialization.
public static class DataGridBehavior
{
    public static readonly DependencyProperty FocusFirstCellProperty = DependencyProperty.RegisterAttached(
        "FocusFirstCell", typeof(Boolean), typeof(DataGridBehavior), new FrameworkPropertyMetadata(false, new PropertyChangedCallback(OnFocusFirstCellChanged)));

    public static void SetFocusFirstCell(DataGrid element, Boolean value)
    {
        element.SetValue(FocusFirstCellProperty, value);
    }

    public static Boolean GetFocusFirstCell(DataGrid element)
    {
        return (Boolean)element.GetValue(FocusFirstCellProperty);
    }

    private static void OnFocusFirstCellChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        DataGrid element = (DataGrid)d;
        if (element.IsLoaded)
        {
            TextBox textBox = FindVisualChild<TextBox>(element);
            if (textBox != null)
                Keyboard.Focus(textBox);
        }
        else
        {
            RoutedEventHandler handler = null;
            handler = (ss, ee) =>
            {
                DataGrid dataGrid = (DataGrid)ss;
                TextBox textBox = FindVisualChild<TextBox>((DataGrid)ss);
                if (textBox != null)
                    Keyboard.Focus(textBox);
                dataGrid.Loaded -= handler;
            };
            element.Loaded += handler;
        }
    }

    private static T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(obj, i);
            if (child != null && child is T)
                return (T)child;
            else
            {
                T childOfChild = FindVisualChild<T>(child);
                if (childOfChild != null)
                    return childOfChild;
            }
        }
        return null;
    }
}

Items.xaml user control is as below.
<UserControl x:Class="WpfApp2.Items"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:local="clr-namespace:WpfApp2"
         mc:Ignorable="d"
         d:DesignHeight="450" d:DesignWidth="800">
<Grid>
    <StackPanel Orientation="Vertical">
        <TextBlock>Search</TextBlock>
        <TextBox Text="{Binding Description}" />
        <DataGrid x:Name="grdItems" ItemsSource="{Binding ItemsCollection}" AutoGenerateColumns="False" ColumnWidth="*"
                  local:DataGridBehavior.FocusFirstCell="True">
            <DataGrid.Columns>
                <DataGridTemplateColumn Header="Item Code">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <TextBox x:Name="txtItemCode" Text="{Binding ItemCode}"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTemplateColumn Header="Item Name">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <TextBox x:Name="txtItemName" Text="{Binding ItemName}" />
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTemplateColumn Header="Price">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <TextBox x:Name="txtItemSellingPrice" Text="{Binding ItemPrice}"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </StackPanel>
</Grid>

MainWindow.xaml is as below
<Window x:Class="WpfApp2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApp2"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Grid>
    <local:Items/>
</Grid>

A: This Working Properly
dvSalesEntryDataGrid.PreviewKeyDown += Datagrid_PreviewKeyDown;

add Datagrid PreviewKeyDown event
if (e.Key == Key.Enter)
            {
   if (Keyboard.FocusedElement is UIElement elementWithFocus)
                {
                    switch (dvDataGrid.CurrentCell.Column.DisplayIndex)
                    {
                            case 1:
                            DataGridRow currentrow5 = dvDataGrid.ItemContainerGenerator.ContainerFromItem(dvDataGrid.CurrentItem) as DataGridRow;
                            elementWithFocus.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                            break;
                            case 2:
                            DataGridRow currentrow5 = dvDataGrid.ItemContainerGenerator.ContainerFromItem(dvDataGrid.CurrentItem) as DataGridRow;
                            elementWithFocus.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                            break;
                            case n:
                            if (dvDataGrid.ItemsSource is ObservableCollection<DetailinfoModel> itemsSourcelast)
                            {
                                DataGridRow currentrow35 = dvDataGrid.ItemContainerGenerator.ContainerFromItem(dvDataGrid.CurrentItem) as DataGridRow;
                                var newItem = new DetailinfoModel();
                                itemsSourcelast.Add(newItem);

                                dvDataGrid.SelectedItem = newItem;
                                Dispatcher.BeginInvoke(new Action(() =>
                                {
                                    DataGridRow newRow = dvDataGrid.ItemContainerGenerator.ContainerFromItem(newItem) as DataGridRow;
                                    DataGridCell cell = Helper.Helper.GetCell(dvSalesEntryDataGrid, newRow, 1);
                                    if (cell != null)
                                        dvDataGrid.CurrentCell = new DataGridCellInfo(cell);
                                }), DispatcherPriority.Background);
                                }
                            break;                               break;
                            default:
                            DataGridRow CurrentRowsdeault = dvDataGrid.ItemContainerGenerator.ContainerFromItem(dvDataGrid.CurrentItem) as DataGridRow;
                            elementWithFocus.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                            break;

          }
  }

}


text:
Q: Getting error Object reference not set to an instance of an object I'm trying to copy the data from sql table "checkin "  to auto fill in on a form in a textbox  .. on a button click
DataSet ds = null;

private void button8_Click(object sender, EventArgs e)
{
    tblNamesBS.DataSource = ds.Tables[0];
     textBox2.DataBindings.Add(new Binding("Text", tblNamesBS,"GuestName"));
}

A: ds starts off as null, and you show no code that would make ds anything other than null. Thus indeed, ds.Tables[0] will explode with a NullReferenceException.
Make ds something non-null.

A: You cant use ds before setting it to an object....
Therefore, this call is invalid ds.Tables[0]; -> You are trying to acces Tables from ds, when ds is null

A: Like the other guys said you need to instantiate ds before you can use it.
DataSet ds = new DataSet();


text:
Q: How to load image files to gtk.gdk.Pixbuf from stream? I have a file picture.jpg, i'm reading it to memory
f = open('picture.jpg', 'rb')
pic = f.read()
f.close()

How can I convert pic to gtk.gdk.Pixbuf?
I know that there is gdk_pixbuf_new_from_stream() but it appears to be missing from pyGTK :/

A: You can use a Pixbuf loader:
loader = gtk.gdk.PixbufLoader('jpeg')
loader.write(pic)
loader.close()

pixbuf = loader.get_pixbuf()


text:
Q: find maximum area of effect overlap on a 2d grid I'm hoping to write a program to help me optimize on a 2d grid.  In this grid, there are "blocks" which have a range that determines its area of effect.  Many blocks can be placed on the grid.  Each block may take up more than 1 tile, but is always square.  I want to find out the maximum amount of times the area of effect can overlap a single XY position.
I need to figure this out for 36 combinations (4 block types - 1x1, 2x2, 3x3, and 4x4, and ranges 1-9)
The area of effect is always in a square pattern.  In the example below, the letters are the blocks, and the numbers are where the area of effect is.  A is a 1x1 block that has an area of effect of 1.  B is a 1x1 block with an area of effect of 2.  And C is a 2x2 block with an area of effect of 1.
X X X X X
X 1 1 1 X
X 1 A 1 X
X 1 1 1 X
X X X X X

X X X X X X X
X 2 2 2 2 2 X
X 2 2 2 2 2 X
X 2 2 B 2 2 X
X 2 2 2 2 2 X
X 2 2 2 2 2 X
X X X X X X X

X X X X X X
X 1 1 1 1 X
X 1 C C 1 X
X 1 C C 1 X
X 1 1 1 1 X
X X X X X X

I can put as many blocks on the grid as I want, and I want to find out how many times the area of effect overlaps a target tile.  For example, if I have an A tile (1x1 with 1 range), I maximize the area of effect by surround the target T.  So the answer here would be 8.
X X X X X
X A A A X
X A T A X
X A A A X
X X X X X

Anyone know how I can figure this out for the other combinations?  Thanks!

A: What you need is some form of spatial partitioning so that it is easy to find the blocks that affect a particular position. Googling 'tree algorithms' should give you an idea on the various ways to partition the space, but the general idea is:
for each block
  addblock (root, block)

addblock (node, block)
  if block fits inside node
    if there are child nodes
      for each child
        addblock (child, block)
    else
      add block to node by dividing into area occupied by block and areas not occupied by block, moving any blocks at this node into all new child nodes
  else
    if there are child nodes
      for each child
        addblock (child, block)
    else
      add block to node block list

Then, to find the number of blocks covering a square, search the tree for the node covering the given square and then see how many blocks are in that node.

A: What you want is a space-filling-curve like a Z-Curve or a Hilbert-Curve and then instead to compute the index convert it to a quadtree-key for each tile. A sfc reduce the 2D-problem to a 1D problem. Then with the new key you want to perform a DFS or BFS to look for overlapping tiles. I've wrote a class for sfc in php at phpclasses.org ( hilbert-curve ). You are welcome to download.


text:
Q: Photoshop JSX script - Close Photoshop How do I close photoshop using its javascript scripting language. (I am automaticly scripting a great deal of things, and I notice that for one reason or another, some of the ram is not releasing with each new task. My hopes are that after X ammount of operations, I will fully close photoshop, to free up the ram.. which it is eating up all of my 8 gigs, and after which then opens photoshop help and causes a huge failure (actually, to be honest it fills up my hard drive with junk till I get a "hard drive is full" message... (I think it is dumping the ram into virtual ram on my hard drive?)... what a mess)Thanks!!

A: I've looked into the Photoshop JSX DOM a bit and couldn't find any magic function to delete temporary files.
The closest thing to your needs was purging caches:
app.purge(PurgeTarget.ALLCACHES);

but that doesn't help much. I tried to find a way to call a .bat file from JSX, but couldn't find anything yet, also, you are unable to delete Photoshop temporary files from the system if you have Photoshop running, event though all documents might be closed.
Put this in a bat file to clear your temp folder. it might help you save a few seconds, but I don't think I can help much.
cd %homepath%\Local Settings\Temp
del * /f /s /q /a r h

If you can automate the process of generating a psd, closing photoshop, clearing temp and repeating for next, that's great. If not, borrow an external hdd from a friend or buy one and set photoshop's scrath disk to that. It might save you a lot more time and headaches than trying to get around it. Photoshop may eat a of resources, but if it gets the job done, 'pay the tribute' and get it done fast. On the long run it will pay off.

A: this will close Photoshop:
 executeAction(app.charIDToTypeID('quit'), undefined, DialogModes.NO);

before that you may want to loop through documents and close them all
 var q = app.documents.length;
 for (var i = 0; i < q; i++) {
      var desc7 = new ActionDescriptor();
      desc7.putEnumerated( charIDToTypeID( "Svng" ), charIDToTypeID( "YsN " ), charIDToTypeID( "N   " ) );
      executeAction( charIDToTypeID( "Cls " ), desc7, DialogModes.NO );
 }

A: Photoshop uses a file on disk for temporary storage, so that it doesn't have to keep everything in memory. This file is by default created on the startup drive, but as you seem to have too little free space on that drive you should change the settings so that it creates the file on a disk with more free space.


text:
Q: Mocha sinon.spy always showing function call 0 times I am new to mocha/chai. I am trying to write the unit test case for following scenario. I want to test whether "callchildfunc" and "childfunc2" is called or not upon calling "parent()" function.
I have read the fundamental and what I understood is if you are spying on any function then just put assert on that function to check if that function is called or not. Means in above script file If i will spy on "childfunc2" and "callchildfunc" function then I don't need to call here in test file since it is already called in script file under parent function. Please correct my understanding if I am wrong.
This is my script.js file
// script.js

function childfunc2(){
    console.log("child function without return");
}
function callchildfunc(var1, var2){
   return var1 + var2;
}
function parent(x){
   var getreturnval = callchildfunc(x, 1);
   console.log(getreturnval);
   childfunc2();
}

This is my test file.
//scenario 1

describe('Test for parent() function ', function(){
   it('should make parent call ', function(){

        var spy1 = sinon.spy(window, 'callchildfunc');
        var spy2 = sinon.spy(window, 'childfunc2');
        parent(2);
        expect(spy1).to.have.been.called();
        expect(spy2).to.have.been.called();
        // or
        sinon.assert.calledOnce(spy1);
        sinon.assert.calledOnce(spy1);

    });
});

After running the test always I am getting this error.
AssertError: expected childfunc2 to be called once but was called 0 times

Also If I change the test file and call the spy function then it will work.
var spy1 = sinon.spy(window, 'callchildfunc');
var spy2 = sinon.spy(window, 'childfunc2');
parent(2);
// After addding these below 2 lines.
window.childfunc2();
window.callchildfunc();

Any help?

A: // Script.js

module.exports= {
childfunc2:function(){
    console.log("child function without return");
},
callchildfunc:function(var1, var2){
   return var1 + var2;
},
parent:function(x){
   var getreturnval = this.callchildfunc(x, 1);
   console.log(getreturnval);
   this.childfunc2();
}
};

// Test.js
var sinon= require('sinon'), expect=require('chai').expect
var r= require('./functests')
describe('Test for parent() function ', function(){
   it('should make parent call ', function(){
        var spy1 = sinon.spy(r, 'callchildfunc');
        var spy2 = sinon.spy(r, 'childfunc2');
        r.parent(2);
//        expect(spy1).to.have.been.called();
  //      expect(spy2).to.have.been.called();
        // or
        sinon.assert.calledOnce(spy1);
        sinon.assert.calledOnce(spy1);

    });
});

// Screenshot


text:
Q: Find Co-ordinates of squares edge defined by angle from center I'm trying to find the co-ordinates of an edge of a square from an imaginary line from the centre of the square that goes out on a variable angle. Where that line intercepts with the edge of the square is the co-ordinates I need.
For example sake, the square is 50px X 50px the center co-ordinates are (10,10) and the angle of the line from the center is on a 45 degree angle clockwise, the end of this line should not extrude the square and I'm trying to find the x,y co-ordinates of the end of this line.
What am I using this for, I want to be able to rotate a liner gradient fill in a rect() as you would do so in photoshop. I'm also not wanting to use a library as I'm trying to "reinvent the wheel" as I find it the best way to learn for my own sake.
I'm doing this in Javascript.
Thanks in advance for any help

A: You have to subdivide the rectangle if four sectors, then determine in which sector your line lies. One way to do that is checking the angle value with 90°, 180° and 270° using plain if statements.
Once you have the angle's sector, you have to compare the line's angle against the rectangle's diagonal angle, so you could determine the edge your line is colliding with.

Once you've determined the collision edge you get one of the collision coordinates for free (left-x, right-x, top-y or lower-y), the another coordinate can be obtained using trigonometry (the tangent relation).
You'll end up with two basic cases in every sector, one takes the opposite leg for the right triangle that forms for the collision with one of the vertical edges and the other takes the adjacent leg. Here is an example for the first sector (the upper right quadrant)
if (lineAngle < rectDiagAngle) {

    // For this collision you have the x coordinate, is the same as the
    // right edge x coordinate
    colX = rectX + rectW;

    // Now you need to find the y coordinate for the collision, to do that
    // you just need the opposite leg
    oppositeLegLength = Math.tan(lineAngle) * (rectW / 2);
    colY = rectCenterY - oppositeLegLength;

} else {
    // The line collides with the top edge

    // For this collision you have the y coordinate, is the same as the
    // top edge y coordinate
    colY = rectY;

    // Now you need to find the x coordinate for the collision, to do
    // that you just need the adjacent leg
    adjacentLegLength = (rectH / 2) / Math.tan(lineAngle);
    colX = rectCenterX + adjacentLegLength;
}

This fiddle takes the angle, calculates the collision point and then draws a line from the rectangle center to the collision point.


text:
Q: \NewDocumentCommand: Why can't I put args on an own line? I encountered a peculiarity concerning \NewDocumentCommand arguments.
In a case where I had real long names in the arguments, I wanted to put
them each on its own line. The first ones are OK, the 2 last ones are
problematic, as shown in the MWE. Is this the normal behaviour or is it a
bug or am I doing something stupid?
\documentclass{article}
\usepackage{xparse}
%                           12  3        4          56
\NewDocumentCommand\TestArg{st+ O{\empty}D(){\empty}mD()%
                              {\empty}O{\empty}}{%
%                                     7
\noindent
3: #3 \\
4: #4 \\
5: #5 \\
6: #6 \\
7: #7
}
\begin{document}
\TestArg[Three](Four){Five}(Six)[Seven]
\par\vspace{2\baselineskip}
\TestArg
[Three]
(Four)
{Five}
(Six)
[Seven]
\end{document}

A: you can not have white space before optional arguments that follow the last mandatory argument so this works.
\documentclass{article}
\usepackage{xparse}
%                           12  3        4          56
\NewDocumentCommand\TestArg{st+ O{\empty}D(){\empty}mD()%
                              {\empty}O{\empty}}{%
%                                     7
\noindent
3: #3 \\
4: #4 \\
5: #5 \\
6: #6 \\
7: #7
}
\begin{document}
\TestArg[Three](Four){Five}(Six)[Seven]
\par\vspace{2\baselineskip}
\TestArg
[Three]
(Four)
{Five}%
(Six)%
[Seven]
\end{document}

This is by design so that (like the optional arguments in amsmath) you do not get mis-interpretation in things like
.... 25\\
[foo] & 26 \\

where [foo] is intended to be the data in the array cell, not an argument to \\

A: With the latest release of xparse, you will find that the b is picked up as you expect. We have refined the treatment of trailing optional arguments such that spaces can be allowed or forbidden:
\documentclass{article}
\usepackage{xparse}
\NewDocumentCommand\TestArgOne{m O{x}}{%
  1: #1, 2: #2
}
\NewDocumentCommand\TestArgTwo{m!O{x}}{%
  1: #1, 2: #2
}

\begin{document}

\TestArgOne{a}[b]

\TestArgOne{a} [b]

\TestArgTwo{a}[b]

\TestArgTwo{a} [b]

\end{document}

As you will see,  \TestArgOne grabs the [b] as an optional argument whether or not there is a space. In contrast, for \TestArgTwo I have used the syntax !O{x}, where the ! means that the optional argument has to follow immediately with no space. This controllable behaviouris useful as depending on the use case, a space may or may not make sense. (The classic example is \\[...], which is used in math mode and where a space or newline before the [ means something very different.)

A: Let's consider a simpler example:
\documentclass{article}
\usepackage{xparse}

\NewDocumentCommand\TestArg{mO{x}}{%
  1: #1, 2: #2
}

\begin{document}

\TestArg{a}[b]

\TestArg{a} [b]

\end{document}

This produces

You can clearly see that in the second case [b] is not recognized as an optional argument; instead, the default value x is used and [b] is printed separately, with a space in front of it.
A new line counts as a space, so it's not a surprise if also
\TestArg
{a}
[b]

produces the same result.
This was a precise choice when the interface of xparse was developed. The team followed the example of amsmath that doesn't allow spaces in front of optional arguments to \\, because of the infamous
\left[\begin{array}{cc}
1 & 2 \\
[1] & [2]
\end{array}\right]

that raises an error, because [1] is mistaken for the optional argument to \\. Instead
\begin{bmatrix}
1 & 2 \\
[1] & [2]
\end{bmatrix}

works flawlessly.
The input \TestArg{a} [b] is deemed ambiguous. There were two choices, the team followed the path of considering [b] not an optional argument.
You get the same behavior with
\documentclass{article}
\usepackage{xparse}

\NewDocumentCommand\TestArg{mD(){x}}{%
  1: #1, 2: #2
}

\begin{document}

\TestArg{a}(b)

\TestArg{a} (b)

\end{document}

In my opinion, one should never define macros with seven arguments. In your case two are for the variants, four are optional and one is mandatory.
A key-value interface would be much better:
\TestArg[
  var-a=true,
  var-b=false,
  opt-A=Three,
  opt-B=Four,
  opt-C=Six,
  opt-D=Seven,
]{Five}

By the way, {\empty} does not specify an empty default value: if tested with \tl_if_empty:nTF{#3}, a missing first optional argument would make LaTeX follow the false branch.


text:
Q: Writing the correct rspec test I am a little new to writing tests with rspec and I am trying to figure out how to correctly write this test for this definition. The definition simply searches for the user, and if they are already added, it will not return them. The definition works, I just want to correctly test it.
Here's what I've got in the controller:
class SearchController < ApplicationController
  ROWS = 9
  def name_search
    page = params[:page].present? ? params[:page] : 1
    query = params[:query].present? ? params[:query] : params[:'search-keywords']
    approved_user_ids = Approval.where(user_id: logged_in_user.id).pluck(:approved_user_id)
    search_results = User.where(['name LIKE :query OR operator_id LIKE :query', { query:
                                 "%#{query}%" }]).where.not(id: approved_user_ids).order(:name)
    page_count = (search_results.count / ROWS.to_f).ceil
    paginated_search_results = search_results.limit(ROWS).offset(ROWS * (page.to_i - 1))
    respond_to do |format|
      format.html do
        if request.xhr?
          render partial: 'layouts/search_results_modal', locals: { search_results: paginated_search_results,
                                                                    page_count: page_count, page: page, query: query
                                                                  }, layout: false, status: 200
        end
      end
    end
  end
end

and in the test:
context 'when a user is added' do
  subject { controller.name_search }
  let(:approved_user) { double(map: double) }

  before do
    allow(controller).to receive(:logged_in_user).with(no_args).and_return(logged_in_user)
    allow(User).to receive(:where).and_return(empty_collection)
  end

  it "name search receieves correct results" do
    expect(Approval).to receive(:where).with( { user_id: logged_in_user.id } ).and_return(approved_user)
    expect(User).to receive(:where).with('name LIKE ? OR operator_id LIKE ?', "%#{ query }%", "%#{ query }%")
    subject
  end
end

Am I on the right path for writing a test for this? Any idea how I can correctly test this definition "name_search"?


text:
Q: How does Gulp know when an asynchronous dependent task is complete (specifically, 'gulp-connect')? Learning Gulp, I see this simple example that runs a second task after a first is complete:
var gulp = require('gulp');
var connect = require('gulp-connect');

// First task
gulp.task('connect', function() {
    // No callback is provided to Gulp to indicate when the server is connected!
    connect.server();
});

// Second task runs after the first task 'completes'
gulp.task('open', ['connect'], function() {

    // v v v
    // Question: since no callback is provided to indicate when 'connect' completes,
    // how does Gulp know when to run this task?

    // Some task here...
});

My question is straightforward.
I think that the connect.server() task must be asynchronous, so that somewhere in its implementation is:
http.createServer(function(request, response) {
    // Presumably, before the first request can be received,
    // there must be an asynchronous delay while the server initializes

    /// ...handle HTTP requests here...
});

I assume that there is an asynchronous delay before the first request can be received in that first task - and only when requests are ready to be received should the first task be considered 'complete', so that Gulp can run the second task.
Given this, how does Gulp know that the server is fully connected and receiving requests so that it knows to run the second task?
I do not see a callback provided to Gulp that can be used by Gulp as a trigger to indicate that the next task is ready to run.

A: In this case, I don't believe you could be 100% sure for 2 reasons.
The first is that you're not passing a callback to your connect task.
The second is that you're not using a callback in your server.listen()
Gulp allows tasks to pass a callback in to the task function for explicit signaling that a task is complete.
You could do something like this
gulpfile
gulp.task('connect', function(done) {
    connect.server(function() {
        return done();
    });
});

server
module.exports = function(callback) {
    let server = http.createServer();
    let port = process.env.PORT || 3000;

    // all of your routes and server logic

    server.listen(port, function() {
        console.log('listening on ' + port);
        if (callback)
            return callback;
    });
}


text:
Q: Can you delete the missing values before the analysis of a time series dataset? The question is: Can I delete all the rows of a certain id because of its missing data, before the data analysis? To be more specific I will give the context and the specific problem:
Context
I have a daily time series dataframe from 1960 to 2018, where each observation is a measurement of precipitation, temperature, and level related to 133 rivers (the ids are the rivers). So, for each river, I will have all the measurements needed, for a given day, in a given year, between 1960 and 2018. I need to predict the river level.
I did this missing value plot to get some insights (the lower the percentage, the lower is the data for that flow in that year):

The inputs
There are three insights from this plot that concern me in order to delete or not delete missing values (and when):

*

*There is an increasing number of distinct rivers per year since 1960.

*2018 has a lot of missing data (which is because all the data stops at March of that year).

*You have some rivers without data for the last 35 years (83 to 87 rivers in the plot, for example). And you have some rivers without data for the last 10, 5, or 2 years (you can see a lot of rivers with 2017 and 2018 data missing in the graph).

The problem
Should I consider all the rivers data for prediction even of those rivers that don't have data for the last X years? Because it doesn't make sense to predict the next year without the data of the last X years (but I do have the data of 1980 to 2000, for example). If I should consider it, what kind of methodology should I use to predict, if is there any?. If I shouldn't consider it, should I delete it? If I should delete it, when should I delete it? Before or after the data analysis for prediction? For example, before or after analyzing the distributions? (in order to group the rivers to impute the missing values as they have different distributions, but I could find a way to group similar distributions). It makes sense to me to delete them before the analysis, as the noise for prediction will be lower as the data for the analysis will be consistent with the data for prediction.
However, if I don't delete them at all I will have more data if I want to see some overall analysis (i.e. the trend from 1960 to 2018 will be a more "representative trend"). Deleting after, in terms of prediction (and insights for feature selection) it will increase the noise as the data for analysis will be different to the data for prediction (as I will have deleted complete data for some rivers).
Besides, I'm thinking of making the assumption that if the river doesn't have data from the last 3 years, the station measuring the river is not operative. But again, if the station is not operative, should I consider its data for overall analysis/insights?.

A: On the one hand, you should not be deleting anything. Information is power. On the other hand, I am highly skeptical about your ability to perform missing data imputation for the missing river-days. It is not clear how different rivers are related, and missing data imputation adds value only if different variables (rivers) are highly co-dependent. What you can do, however, is writing a parametric model for all the rivers. In this model

*

*different rivers are allowed to be correlated,

*any particular river is described by, say, an ARIMA process with unique parameters.

Then, you can estimate the model using the version of Full Information Maximum Likelihood (FIML) for time series. You would need to look up a standard reference on FIML and read it carefully. In a nutshell, FIML does the following.

*

*The log-likelihood function has only terms corresponding to non-missing values.

*All non-missing values are used in at least one term (of the log-likelihood).

*Suppose, in time series $X_j$, values $X_j(t)$ and $X_j(t+3)$ are marked but values $X_j(t+1)$ and $X_j(t+2)$ are missing. Then the log-likelihood function contains term

$$
... + \log(f_{M,3}(X(t+3) | X(t))) + ...
$$
where $f_{M,3}(X(t+3) | X(t))$ is the model-implied conditional density of $X_j(t+3)$ given $X_j(t)$. You see that we are skipping missing cells $X_j(t+1)$ and $X_j(t+2)$.

A: I would leave all of the data in, but then I would dig through to make sure there were not patterns misleading my data (e.g., that all of the new rivers are smaller because the state has been adding monitoring sites but already had the major rivers covered).
The other caveat is that you may need to use precipitation in the preceding X days as a predictor. In that case, you would need to delete the first X days each time observations start or be able to determine the precipitation from some other source (e.g., if that is from a local weather station that was recording, even though the river monitor was not).


text:
Q: Efficient Way to Buffer Polyline (Numerically) I am looking for a way to buffer a polyline in C#, with the purpose of creating a polygon.
However, what I am after is not a graphical solution but a numerical one. Several topics, such as Create a Polygon around a Polyline like a Buffer, suggest ways to do this but the solutions presented seem to be graphical without an indication on whether the solution can be converted into a numerical one.
Can anyone recommend an efficient way to do this operation numerically? Is there a way to get the result for GetWidenedPathGeometry() as a set of polygon coordinates?


text:
Q: Javascript, TypeError: "function" is not a function I have this little problem... in this code if I define only start() everything works, but when I declare time(), i got the error:
"TypeError: start is not a function". Where is the problem??
Here the code,

//start
function start(){

 //removes title and start boxes
 var body=document.getElementsByTagName("body")[0];
 var start_box=document.getElementById("start_box");
 var title_box=document.getElementById("title_box");
 body.removeChild(start_box);
 body.removeChild(title_box);

 //creates stats box
 var stats_box=document.createElement("div");
 stats_box.id="stats_box";
 var time=document.createElement("p");
 time.id="time";
 var points=document.createElement("p");
 points.id="points";
 stats_box.appendChild(points);
 stats_box.appendChild(time);
 body.appendChild(stats_box);

 //creates play box
 var play_box=document.createElement("div");
 play_box.id="play_box";
 body.appendChild(play_box);

}

//time
function time(){
 var time=document.getElementById("time");
 for(x=30,x>=0,x--){
  time.innerHTML("Time:"+x);
 }
}
<!DOCTYPE HTML>

  <title>PICK 'EM ALL</title>
  <link rel="stylesheet" href="pta.css" type="text/css">

PICK 'EM ALL

START

A: Issue is with for loop, it should be semi-colon instead of comma
for(x=30;x>=0;x--){
        time.innerHTML("Time:"+x);
    }


text:
Q: Why does a process get blocked if a thread waits for I/O in many to one mapping Why does a multi-threaded process using a user level thread library get blocked when one of its threads waits for an I/O? This makes sense, but when I think more, a question pops up. Can the user level thread library not schedule another thread?

A: OS can schedule only the processes(or jobs) , it in no way knows about the threads within a program and cannot schedule them as it wants.
when a part of the process ( here the thread which got blocked due to i/o) gets blocked for i/o operation, the os suspends the entire process , since the os deals only with the processes (not threads within the process).
As in the many to one model , there is only a single kernel , the process whose thread was blocked cant be executed until the blocked thread resumes.
whereas in a many to many or one to one model, each kernel runs its piece of code and is unaware of the threads blocked in the other kernels.

A: There's two types of thread. OS threads, and green threads (which is what I think you're talking about).
OS threads are scheduled by the operating system, and one will not block another (at least not on any OS you're likely to come across these days) unless you deliberately introduce something to synchronise them (e.g. Semaphores).
Green threads, where a process schedules different paths of execution for itself, will block unless the scheduler is clever enough provide (and therefore catch) all potentially blocking function calls and use them as a scheduling opportunity. This is also closely related to cooperative multitasking.
So the answer is yes, but only if written that way. Threads in Python famously were not written this way, read up on the GIL, and so would cause no end of problems. Python may have fixed this now.


text:
Q: Maximize sum of squares Lets say that I know that $n$ values $x_i$ sums up to $\mu$:
$$
\mu=\sum_{i=1}^n x_i
$$
 I also now that $0\leq x_i\leq 1$ for all $i=1\cdots n$.
I want to find an upper bound as tight as possible for the sum of their squares $\sum_{i=1}^n x_i^2$ as a function of $\mu$ and $n$.
I know that in general $\sum_{i=1}^n x_i^2 \leq (\sum_{i=1}^n x_i)^2=\mu^2$, but in this case if $\mu=n$ because of the costraints it results $\sum_{i=1}^n x_i^2=n=\mu<\mu^2=n^2$ which is too loose for what I need.
Any ideas?

A: You want as many of the $x_i$ to be $1$ as possible.  If you have $0 \lt x_1,x_2 \lt 1$ you can increase $x_1^2+x_2^2$ by increasing the larger and decreasing the smaller.  So the maximum sum of squares will be $\lfloor \mu \rfloor + (\mu-\lfloor \mu \rfloor)^2$ as long as $\mu \lt n$.  If $\mu \gt n$ there is no solution.


text:
Q: Scaling of horizon chart on R I have just started to learn R and I have created a horizon chart using R.
However, the axes are not appearing properly. Is there any way which I could make the chart bigger and easier to see?
This is the chart I created using horizonplot from the latticeExtra package.:

require(latticeExtra)

horizonplot(data, horizonscale = 10, colorkey = TRUE, layout = c(1, 27))

Thanks in advance for any help given!


text:
Q: Refile and 'aws-sdk' V2 gem getting Missing Region Error I am using the latest version of the refile gem to upload images to AWS and it's working fine. when I try to test my app with rspec i get this error:
/aws-sdk-core/plugins/regional_endpoint.rb:34:in `after_initialize': missing region; use :region option or export region name to ENV['AWS_REGION'] (Aws::Errors::MissingRegionError)
Gemfile:
gem "refile", require: "refile/rails"
gem "refile-mini_magick"
gem "refile-s3"
refile.rb
require 'refile/simple_form'
require "refile/s3"
aws = {
access_key_id: ENV['AWS_ACCESS_KEY_ID'],
secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'],
region: ENV['AWS_REGION'],
bucket: ENV['AWS_BUCKET']
}
Refile.cache = Refile::S3.new(prefix: "cache", **aws)
Refile.store = Refile::S3.new(prefix: "store", **aws)
I tried setting a new initializer aws.rb:
require 'aws-sdk'
Aws.config.update({
  region: 'us-west-2',
  credentials: Aws::Credentials.new('akid', 'secret')
})
but it did not work.
10x for your help!

A: found the answer:
just add to your initializers/refile.rb:
require "refile/s3"
require 'refile/simple_form'

if Rails.env.production?
  aws = {
    access_key_id: ENV['AWS_ACCESS_KEY_ID'],
    secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'],
    region: ENV['AWS_REGION'],
    bucket: ENV['AWS_BUCKET']
  }

  Refile.cache = Refile::S3.new(prefix: "cache", **aws)
  Refile.store = Refile::S3.new(prefix: "store", **aws)
end

A: It looks like your code is looking for the AWS_REGION value as an environment variable. Have you verified that the value for AWS_REGION is being set in your environment before running your tests? You can see if it's set in bash by doing the following:
env | grep AWS_REGION

If it's not set, then just need to set the variable like so (again in bash):
export AWS_REGION="us-west-2"