text:
Q: GWT RPC response header Is there any way to read the header information received by GWT client, on the RPC response?
Response header
Server                 Apache-Coyote/1.1
Set-Cookie             JSESSIONID=3379B1E57BEB2FE227EDC1F57BF550ED; Path=/GWT
Content-Encoding       gzip
Content-Disposition    attachment
Content-Type           application/json;charset=utf-8
Content-Length         209
Date                   Fri, 05 Nov 2010 13:07:31 GMT

I'm particularly interest in identifying when client receives the Set-Cookie attribute on its header.
Is there any way to do that on GWT?
I found that on
com.google.gwt.user.client.rpc.impl.RequestCallbackAdapter<T>

exist the method
public void onResponseReceived(Request request, Response response) { ... }

On the parameter Response seems to have the information I need. The this is, exist some way to get that without "racking" the GWT compiler code?
thanks
JuDaC

A: You may try to override the  RpcRequestBuilder.doSetCallback method and force your service to use it:
MyServiceAsync service = GWT.create(MyService.clas);
((ServiceDefTarget) service).setRpcRequestBuilder(new RpcRequestBuilder() {
    @Override
    protected void doSetCallback(RequestBuilder rb, final RequestCallback callback) {
        super.doSetCallback(rb, new RequestCallback() {

            @Override
            public void onResponseReceived(Request request, Response response) {
                String headerValue = response.getHeader("my-header");
                // do sth...
                callback.onResponseReceived(request, response);
            }

            @Override
            public void onError(Request request, Throwable exception) {
                callback.onError(request, exception);
            }
        });
    }
});

Inspired by http://stuffthathappens.com/blog/2009/12/22/custom-http-headers-with-gwt-rpc/

A: If you declare your async service method to return a RequestBuilder you should be able to set a RequestCallback that will be notified when the Response is received. I haven't tried this myself, but it looks like what you need.


text:
Q: undefined method database::query() in class wrapper Why I get the message Fatal error: Call to undefined method database::query()
when I pass the same code to a class?
here my code:
    class database{
    protected $databaseLink = null;
    function __construct($dbInfo){

        mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
        $this->database = $dbInfo['host'];
        $this->mysql_user = $dbInfo['user'];
        $this->mysql_pass = $dbInfo['pass'];
        $this->mysql_db = $dbInfo['dbname'];
        $this->openConnection();
        return $this->get_link();
    }
    function openConnection(){
      try {
           $this->databaseLink = new mysqli($this->database , $this->mysql_user, $this->mysql_pass, $this->mysql_db);
           $status = $this->databaseLink->set_charset("utf8");
           if ($status === false) {
             //throw new \Database_Exception(self::$dbInstance->error, self::$dbInstance->errno);
           }
      } catch (mysqli_sql_exception $e) {
              if (mysqli_connect_error()) {
                  die('Connect Error (' . mysqli_connect_errno() . ') '
                          . mysqli_connect_error());
              }
          //echo $e->__toString();
      }
    }
    function get_link(){
        return $this->databaseLink;
    }
}
$db = new database($dbInfo);
$query = "SELECT prod_id as id, diction, name as display_name FROM htbl_products ORDER by id LIMIT 10";

$result = $db->query($query); //Fatal error: Call to undefined method database::query()

If I try the code without the class-wrapper like this:
try {
         $db = new mysqli($dbInfo['host'], $dbInfo['user'], $dbInfo['pass'], $dbInfo['dbname']);
         $db->set_charset("utf8");
    } catch (mysqli_sql_exception $e) {

            if (mysqli_connect_error()) {
                die('Connect Error (' . mysqli_connect_errno() . ') '
                        . mysqli_connect_error());
            }
        //echo $e->__toString();
    }

it works.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Asrock motherboard - "Please select the boot device" screen freezes Currently trying to boot my unraid server from usb. Set the boot options to usb as default. When I start I get the screen below which freezes. I cannot drag the mouse or click anything.
Someone an idea what could cause this?
BIOS usb boot screen
Details

*

*Motherboard: ASRock Z270M Pro4

*Bios version: P1.10

*Legacy boot


text:
Q: Continuous linear functional on $c_{00}$ Let $X$ be the space of real sequences having finitely many nonzero terms with $||\  ||_p , 1\leq p \leq \infty$ . Define $f: X\to\mathbb{R}$ by $f(x)=\sum_{j=1}^{\infty} x_j $ for $x=(x_j)  \in X$. Then
$(a)$ $f$ is continous only for $p=1$.
$(b)$ $f$ is continous only for $p=2$.
$(c)$ $f$ is continous only for $p=\infty$.
$(d)$ $f$ is not continous only for any $ p , 1\leq p \leq \infty$.
My attempt:
$X$ is just $c_{00}$ with $||\  ||_p$
For $(c)$ if I take $z_n=(1,1,1,...1,0,0,0,...)$ then $||(z_n)||_\infty=1$ but $f((z_n))=n$ that means norm of $f$ is unbounded means $f$ is not continuous.
For $(a)$ if I take $z_n=(0,0,0,...,1,0,0,0,...)$ $ 1$ at $n^{th}$ place. Then $||(z_n)||_1=1$ but    $f((z_n))=\sum_{j=1}^{\infty} 1 =\infty$ that is norm of $f$ is unbounded. Therefore $f$ can not be continuous. But I don't know how to proceed for $(b)$ and $(d)$. Could you please help me. Thank you very much.

A: The corrrect answer is a): $f$ is continuous only for $p=1$. For $p=1$ we have $|f(x)| \leq \sum |x_i|=\|x\|$ so $f$ is bounded. For $ 1<p<\infty$ consider $x=(1,1,\cdots ,1,0,0...)$ where there are $n$ ones. Then $f(x)=n$. If $|f(x) \leq C\|x\|$ we get $n \leq Cn^{1/p}$ for all $n$ and we get a contradiction by dividing by $n^{1/p}$ and letting $n \to \infty$. For $p=\infty$ your example works.


text:
Q: Get url of tab that called inject-script There is a problem.
I want to get url of tab that called inject-script content.js:
My manifest.json:
{
  "background_page": "background.html",
  "content_scripts": [ {
    "all_frames": true,
    "matches": [ "http://*/*", "https://*/*" ],
    "js": [ "content.js" ],
    "run_at": "document_start"
  } ],
  "description": "Test...",
  "name": "TestExt",
  "permissions": [ "tabs", "http://*/*", "https://*/*" ],
  "version": "0.1.0"
}

My content.js:
document.addEventListener("beforeload", function(event) {
  console.log(document.location.href);
}, true);

Result for link http://ya.ru:
http://ya.ru/
http://kiks.yandex.ru/system/fc06.html
http://suggest.yandex.ru/jquery-1-4-2.crossframeajax.html

but i need to see this
http://ya.ru/
http://ya.ru/
http://ya.ru/

A: Try window.top.document.location.href.


text:
Q: Ruby skip existing record while importing csv My problem is that i have to export an excel sheet save some rows to the database without duplication or redundancy
so i started it with importing CSV instead of XLS then when i finish i might be able to parse the xls
this is my model code:
require 'csv'
class Machine < ActiveRecord::Base
  def self.assign_row(row)
  a, b, c, d = row
  @c = c.slice(1,4)
 Machine.create(name: c, mid: @c)
   end
 def self.import(file)
 CSV.foreach(file.path) do |row|
  machine = Machine.assign_row(row)
    end
  end
 end

Import method in machines_controller
 def import
 count = Machine.import params[:file]
 redirect_to machines_path, notice: "file imported successfully!"
  end

Migration code
 def change
 create_table :machines do |t|
 t.string :name
 t.string :mid
 t.timestamps null: false
 end
  add_index :machines, :name, :unique => true
 end

and the view code
 <%= form_tag import_machines_path, multipart: true do %>
 <%= file_field_tag :file %>
 <%= submit_tag "upload" %>
 <% end %>

routes
  Rails.application.routes.draw do
 resources :errors
 resources :machines do
  collection do
     post :import
    end
   end
  root "machines#index
   end

any thoughts on how to skip duplicated records from saving into database would be appreciated
thanks

A: Unique Identifier:
 To avoid duplicate records saving to database you should maintain a unique identifier other than primary key. This helps you to identify if the record already available in DB, if it is available you can skip that record from saving again.
I guess you can use name in this case, which should be unique for each record in database. write a uniqueness validation in model to implement this.
After changes:
 validates_uniqueness_of  :name

 def self.assign_row(row)
   a, b, c, d = row
   @c = c.slice(1,4)
   machine = Machine.find_by(name: c)
   Machine.create(name: c, mid: @c) if machine.blank?
 end

Hope it helps!!
Thank you.


text:
Q: Cannot start Kafka when start kafka-consumer zookeeper display this:
[2019-01-02 16:34:15,893] INFO Accepted socket connection from /127.0.0.1:51155 (org.apache.zookeeper.server.NIOServerCnxnFactory)
[2019-01-02 16:34:15,893] WARN Exception causing close of session 0x0: null (org.apache.zookeeper.server.NIOServerCnxn)
[2019-01-02 16:34:15,893] INFO Closed socket connection for client /127.0.0.1:51155 (no session established for client) (org.apache.zookeeper.server.NIOServerCnxn)

what happened to it,and how to solve ?
this is all my steps:
wget http://mirror.bit.edu.cn/apache/kafka/2.1.0/kafka_2.12-2.1.0.tgz
tar zxf kafka_2.12-2.1.0.tgz

cat config/zookeeper.properties | grep -Ev '^$|^#' >> config/zk.properties
cat config/server.properties | grep -Ev '^$|^#' >> config/kfk1.properties

bin/zookeeper-server-start.sh config/zk.properties
bin/kafka-server-start.sh config/kfk1.properties

bin/kafka-topics.sh --create --topic maoge --replication-factor 1 --partitions 1 --zookeeper localhost:2181
bin/kafka-console-consumer.sh --bootstrap-server localhost:2181 --topic maoge --from-beginning

A: You're using zookeeper reference (port 2181) in the console consumer, with bootstrap-server which is incorrect. Kafka consumer used to have --zookeeper option, but has moved away from that config long time back, and now refers to broker for consumer.
The correct command for that would be something like: bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic maoge --from-beginning


text:
Q: How to use starts-with() in xpath to switch to frame using Selenium Can anyone help me understand how i use the following java code in python and selenium:
new WebDriverWait(driver,10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[starts-with(@name, 'a-') and starts-with(@src, 'https://www.google.com/recaptcha')]")));
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("div.recaptcha-checkbox-checkmark"))).click();

I tried using string formatting and couldnt find a way of using starts-with() in python.

A: starts-with() is a xpath function used for finding the web element whose attribute value gets changed on refresh or by other dynamic operations on the webpage. It should remain identical irrespective of the language binding e.g. Java, Python, C#, etc.

The equivalent of the following Java based lines of code:
new WebDriverWait(driver,10).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//iframe[starts-with(@name, 'a-') and starts-with(@src, 'https://www.google.com/recaptcha')]")));
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("div.recaptcha-checkbox-checkmark"))).click();

in Python would be as follows:
WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[starts-with(@name, 'a-') and starts-with(@src, 'https://www.google.com/recaptcha')]")))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.recaptcha-checkbox-checkmark"))).click()


text:
Q: Why isn't my infopath data connection returning all results in the document library? I'm running Infopath 2010 in windows 7. But I'm saving in the format "Infopath 2007 filler form" in order to publish to our sharepoint 2007. I'm trying to create an auto numbering system on a document library.
In order to do this I use a form submit rule to set project_num to the maximum value of project_num in my document library plus one. This works sometimes. When it doesn't work, the "max(@product num)" function returns the project_num value of a seemingly arbitrary document(102, out of 129). When I deleted this document, I got back a value of 103.
So I created a new form, set up a new rule on a 2010 form and got the right result. But when I save it as a 2007 form and fix up the data connections, I get 103 back.
All items in the library have the project_num field are filled in. I tried migrating the document library by saving it as a template in sharepoint. But the new library produces the same results.

A: I've resolved the problem by changing the item limit in the default library view in sharepoint from 100 to 2147483647


text:
Q: JS и TypeError: Cannot read property 'indexOf' of undefined Использую шаблонизатор lodash в своей работе. При подгрузке файла Ajax, содержимое подгружается и код отрабатывается, но консоль выдает ошибку:

Error in event handler for (unknown): TypeError: Cannot read property 'indexOf' of undefined

Подскажите, как можно найти причину данной ошибки?


text:
Q: Spring can't find configuration in path well I'm runnning this code and it cant' find the springconfig4.xml file:
package com.nortal.pirs.test.independant;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test4 {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("/com/nortal/pirs/beans/springconfig4.xml");
        BeanFactory factory = context;
        Test3 instance = (Test3) factory.getBean("Test3");

        instance.run();
    }
}

I mean I was kind of expecting it not to work, because in Java it never works when you try to use a path that is not in your current package. However as many Spring tutorials I've seen, they all show this way of specifying the configuration file.
Now my springconfig4.xml is in my applications' src/com/nortal/pirs/beans folder. So how do I specify it so that it can be found here?
The current Test4 class is located in src/com/nortal/pirs/test/independant folder.
My stacktrace:
    2012-12-09 06:16:15,734 [main] INFO  org.springframework.context.support.AbstractApplicationContext - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@b24044e: startup date [Sun Dec 09 06:16:15 EET 2012]; root of context hierarchy
Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/asm/ClassVisitor
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.<init>(AbstractAutowireCapableBeanFactory.java:121)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.<init>(AbstractAutowireCapableBeanFactory.java:168)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.<init>(DefaultListableBeanFactory.java:167)
    at org.springframework.context.support.AbstractRefreshableApplicationContext.createBeanFactory(AbstractRefreshableApplicationContext.java:195)
    at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:128)
    at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:527)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:441)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at com.nortal.pirs.test.independant.Test4.main(Test4.java:9)
Caused by: java.lang.ClassNotFoundException: org.springframework.asm.ClassVisitor
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 10 more

My springconfig4.xml:
  <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd">

  <context:component-scan base-package="com.nortal.pirs.businesslogic.logic"></context:component-scan>
  <context:component-scan base-package="com.nortal.pirs.test.independant"></context:component-scan>

</beans>

Or is the problem somewhere else maybe?

A: Exception says it is not finding a class, not Spring context xml
Caused by: java.lang.ClassNotFoundException: org.springframework.asm.ClassVisitor
please add asm dependency
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>org.springframework.asm</artifactId>
    <version>3.1.0.RELEASE</version>
</dependency>

A: Your stacktrace points this:
java.lang.ClassNotFoundException: org.springframework.asm.ClassVisitor

You need to download the spring-asm-3.1.2.RELEASE.jar file from the maven repo (supposing that you are using spring 3.1.2) or if you are using maven, edit your pom.xml file and add the next lines:
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-asm</artifactId>
    <version>3.1.2.RELEASE</version>
</dependency>

Also, this line:
ApplicationContext context = new ClassPathXmlApplicationContext("/com/nortal/pirs/beans/springconfig4.xml");

Has an error, the path must not start with a trailing /., so the path to the file becomes: "com/nortal/pirs/beans/springconfig4.xml".
The ClassPathResource javadoc states that it will be removed anyways:

Create a new ClassPathResource for ClassLoader usage. A leading slash
  will be removed, as the ClassLoader resource access methods will not
  accept it.

A: Add spring-asm-3.0.1.RELEASE.jar and spring-expression-3.0.1.RELEASE.jar.

A:
java.lang.ClassNotFoundException: org.springframework.asm.ClassVisitor

Just add the spring-asm-3.1.2.RELEASE.jar file. Place it in your lib folder.

A: For the above problem as mentioned above these jars are missing namely 1.org.springframework.asm-3.0.1.RELEASE-A.jar
2.org.springframework.expression-3.0.1.RELEASE-A.jar
or
Add all the core Jars of Spring so that any new programmer can Run all basic level programs.
There is no need of below line in your program. insted of that you can use context insted of factory in the above program.
BeanFactory factory = context
We usually use ApplicationContext insted of BeanFactory.
Even if you use BeanFactory there will be no effect for the program.

A: Add the Jars which is shown in the Screen short and it will work


text:
Q: javascript loop string comparison headache         console.log(previousCompetitors);
        console.log(competitors);
        if(data.isVisible) {
            var moveIndexTo = [];
            for(var q=0; q<competitors.length;q++) {
                moveIndexTo.push(-1);
            }
            for(var i = 0; i<competitors.length; i++) {
                for(var j = 0; j<previousCompetitors.length; j++) {
                    console.log(competitors[i].name);
                    console.log(previousCompetitors[j].name);
                    if(competitors[i].name === previousCompetitors[j].name) {
                        moveIndexTo[j]= i;
                        break;
                    }
                }
            }
            console.log(moveIndexTo);
        }

I'm slowly going insane trying to figure out what is happening here. I have an array of competitor data that updates in order. They are both arrays and I want to track the changes from the previous ordering.
I console.log the data and can see that the data order has been changed yet every single time the moveIndexTo array ends up being [0,1,2,3,4,5] implying that previousCompetitors an Competitors have equal order. How can they be changed between when I console.log them at the top of the code block to when I perform the string comparison?
Competitors and previousCompetitors take roughly the form
[{name:'name1'},{name:'name2'},{name:'name3'},{name:'name4'},{name:'name5'},{name:'name6'}]
with a lot more going on in each object. So If that was previousCompetitors then competitors would be something like
[{name:'name6'},{name:'name2'},{name:'name3'},{name:'name4'},{name:'name5'},{name:'name1'}].
Note the switch of name1 and name6. So I would expect moveIndexTo to be [5,1,2,3,4,0].

A: Just try this : moveIndexTo[i] = j;
fiddle at : https://jsfiddle.net/c9mbbpjj/


text:
Q: Setting builtin Octopus variables I am trying to update the value of "Octopus.Action.Azure.CloudServicePackageExtractionDisabled" Octopus variable in deploy.ps1 of cloud-service deployment octopus step. But the following does not seem to work. Any suggestions ?
$cloudServicePackageExtractionDisabledpre = $OctopusParameters["Octopus.Action.Azure.CloudServicePackageExtractionDisabled"]
Write-Host "PRE CloudServicePackageExtractionDisabled: $cloudServicePackageExtractionDisabledpre"

Set-OctopusVariable -name "Octopus.Action.Azure.CloudServicePackageExtractionDisabled" -value "True"

$cloudServicePackageExtractionDisabledpost = $OctopusParameters["Octopus.Action.Azure.CloudServicePackageExtractionDisabled"]
Write-Host "POST CloudServicePackageExtractionDisabled: $cloudServicePackageExtractionDisabledpost"


text:
Q: Multiple key press on JavaFX scene How are multiple key events detected in a single scene? I need my program to detect when the space bar and the right arrow keys are pressed simultaneously.
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
    public void handle(KeyEvent ke) {
        if (ke.getCode() == KeyCode.RIGHT) {
            ///
        }

        if (ke.getCode() == KeyCode.LEFT) {
            ///
        }

        if (ke.getCode() == KeyCode.SPACE) {
            ///
        }

        if (ke.getCode() == KeyCode.RIGHT && ke.getCode() == KeyCode.SPACE) {
            // How??
        }
    }
});

The first 3 expressions look for a single key and work fine. The final expression never returns true. I believe only the latest key event is passed to the handler.
I looked at KeyCodeCombination, however this appears to be for use in cases when a key has a modifier key from a specified list (ALT_DOWN, SHIFT_DOWN, etc).
Is there a utility in FX that I can use?

A: Close the application using hot keys.
mac: command + w / esc
windows: alt + F4 / esc
    public class JavaApp {/*inner: public class YourApplication extends Application*/
        public void exit() {
            stage.close();
            System.exit(0);
        }
    }

        KeyCombination keyCombinationMac = new KeyCodeCombination(KeyCode.W, KeyCombination.SHORTCUT_DOWN);
        KeyCombination keyCombinationWin = new KeyCodeCombination(KeyCode.F4, KeyCombination.ALT_DOWN);
        scene.addEventHandler(KeyEvent.KEY_RELEASED, event -> {
            if (keyCombinationMac.match(event)
                    || keyCombinationWin.match(event)
                    || event.getCode() == KeyCode.ESCAPE
                    ) {
                new JavaApp().exit();
            }
        });

from: https://dzone.com/articles/handling-keyboard-sortcuts
final KeyCombination keyComb1 = new KeyCodeCombination(KeyCode.R, KeyCombination.CONTROL_DOWN);
scene.addEventHandler(KeyEvent.KEY_RELEASED, new EventHandler() {
                @Override
                public void handle(KeyEvent event) {
                    if (keyComb1.match(event)) {
                        System.out.println("Ctrl+R pressed");
                    }
                }
            });

scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
 public void handle(final KeyEvent keyEvent) {
   if (keyEvent.getCode() == KeyCode.F5) {
    System.out.println("F5 pressed");
    //Stop letting it do anything else
    keyEvent.consume();
   }
 }
});

A: Try this:
final BooleanProperty spacePressed = new SimpleBooleanProperty(false);
final BooleanProperty rightPressed = new SimpleBooleanProperty(false);
final BooleanBinding spaceAndRightPressed = spacePressed.and(rightPressed);

// How to respond to both keys pressed together:
spaceAndRightPressed.addListener(new ChangeListener<Boolean>() {
    @Override
    public void changed(ObservableValue<Boolean> obs, Boolean werePressed, Boolean arePressed) {
        System.out.println("Space and right pressed together");
    }
});

// Wire up properties to key events:
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
    @Override
    public void handle(KeyEvent ke) {
        if (ke.getCode() == KeyCode.SPACE) {
            spacePressed.set(true);
        } else if (ke.getCode() == KeyCode.RIGHT) {
            rightPressed.set(true);
        }
    }
});

scene.setOnKeyReleased(new EventHandler<KeyEvent>() {
    @Override
    public void handle(KeyEvent ke) {
        if (ke.getCode() == KeyCode.SPACE) {
            spacePressed.set(false);
        } else if (ke.getCode() == KeyCode.RIGHT) {
            rightPressed.set(false);
        }
    }
});


text:
Q: Failed to resolve issue of addition in Javascript everytime variable value is concatenated? Here is my code i m successfully getting dynamic values from code but failed to do addition like this
var abc = 0;
var someValue = 5;
abc += someValue;
var  grandTotalProposalCost = 0;

CODE:
var totalSum = parseFloat(summField.total_mat_sale +summField.total_labour_sale).toFixed(2);
grandTotalProposalCost += totalSum;
alert("summary line 96::::"+grandTotalProposalCost);

Everytime i am getting dynamic values from database in summField.total_mat_sale,summField.total_labour_sale    and i want to get total sum.But failed to do so.........
in alert i am getting summary line 96::::1250.266648.828596.25
Here
totalSum = 1250.26 is the value which i am getting first time then
2nd time totalSum = 6648.82 and
third time totalSum= 8596.25

A: Looks like your values are concatenated as string. Try using parseFloat to parse your value before adding them.
grandTotalProposalCost += parseFloat(totalSum);

Hope this helps


text:
Q: meteor beforeunload doesn't reset mongo I am trying to create a game where when the player closes his window the mongo database is changed to "player1 is inactive".
This is the code I have in main.js:
window.addEventListener('beforeunload', function (e) {
   Games.update({_id : myGuy},{$set:{active : 0}});
  // Cancel the event
e.preventDefault();
  // Chrome requires returnValue to be set
  e.returnValue = '';
});

It works sporadically in Firefox and pretty much never in Chrome. ?I'm thinking maybe meteor might change the local mini mongo but doesn't know to change the mongo on the server? (Just a thought.)

A: In response to  Jankapunkt, the above code is on the client side, but I still have "autopublish" turned on, so that shouldn't be a problem.
In response to Jimish Gamit, thanks for the info. It does indeed seem to be a Chrome bug. I tried the alert box, which didn't seem to help.
window.addEventListener('beforeunload', function (e) {
Games.update({_id : myGuy},{$set:{active : 0}});
 e.preventDefault();
 return "alert"
})

As a work around, I just created a custom aframe component that creates a key that can reset the players to inactive when needed, which is the best I can do I guess.
AFRAME.registerComponent('reset', {
    init: function() {
      document.addEventListener('keydown', (event) => {
      const keyName = event.key;
      if (keyName === 'r') {
                if (Games.findOne()) {
                  var playerId1 = Games.findOne({name: "player1"})._id;
                  var playerId2 = Games.findOne({name: "player2"})._id;
                  Games.update({_id : playerId1},{$set:{active : 0}});
                  Games.update({_id : playerId2},{$set:{active : 0}});
                }
           }
        })
     }
  })


text:
Q: An Eigenvalue of $A^3$ is an Eigenvalue of $A$? Let $A^3$ be a matrix who has a Jordan Normal Form of the following:
$$\left(\begin{matrix}8 & 1 & 0\\0 & 8 & 0\\0 & 0 & 1 \end{matrix}\right)$$
Calculating the characteristic polynomial of this matrix:
$P_x=(\lambda-1)(\lambda-8)^2$
From above I can conclude that $\lambda=1,\lambda=8$ are the only eigenvalues of $A^3$.
Are these eigenvalues, are the eigenvalues of the matrix $A$? How can I know/verify it? Maybe $\sqrt[3]{\lambda}$ is the eigenvalues?
Thanks,
Alan

A: $8$ will not be an eigenvalue of $A$ and $1$ may or may not be (depending upon whether $A$ has complex-valued entries or not). This is because:
Let $M$ be an $n\times n$ matrix with eigenvalue $\lambda$ and corresponding eigenvector $\vec{x}$. Then we have: $A^n\vec{x}=A^{n-1}A\vec{x}=\lambda A^{n-1}\vec{x}=\lambda A^{n-2}A\vec{x}=\lambda^2 A^{n-2}\vec{x}=...=\lambda^n\vec{x}$.
So, $2=8^{1/3}$ will be an eigenvalue for sure. But depending upon the form for $A$, then $1$ or a cube root of unity may be the third eigenvalue.


text:
Q: Communication between Java ME application and C# application using bluetooth I am C# developer which started working in Java lately, never done anything in Java ME. My next project requires to pass simple keypress from phone keyboard to C# application using bluetooth, there are some examples on sending/recieving files over bluetooh, but so little documentation how to pass messages between applications:
I stumbled on 32feet.NET library but provided samples are just poor, and bigger mystery for me is J2ME side of application.
if someone could provide any code samples or just explain some basic stuff and principals of bluetooth communication beetween phone and desktop applications:

*

*what bluetooth service is used for passing messages? Serial port?

*what type of data can is used for communication?

*how is connection kept alive?


text:
Q: PHP form validation preventing empty form submitting I have created a simple form with login session capabiltites, i am using mysqli_connect_errno()  and  added a condition
     if ($_POST['username']=="") {

     $home_url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) .    '/form.html';
     header('Location: ' . $home_url);
     $Err = "Invalid value";
       }

and
     Name

     <input type="text" name="username"class="text">
     <?php echo $Err;?>

but the error message is not showing up  on   empty submit

A: You have mentioned header('Location:'.$home_url); then how could you see the error. Pass the error message in header location
replace your code to
$Err = "Invalid value";
header('Location: ' . $home_url.'?err='.$Err);

and print the error like this
if(isset($_GET['err']))
{
    echo $_GET['err'];
}

A: header('location:' .$home_url?flag=y);

the above line is be be written in php page
<?php if(isset($_REQUEST['flag']) && $_REQUEST['flag'] == 'y'){ echo "valid";} else{ echo "Invalid"; } ?>

the above code is to be written in html page

A: If you write this way
if ($_POST['username']=="") {

     $home_url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) .    '/form.html';
     header('Location: ' . $home_url);
     $Err = "Invalid value";
       }

What will happen your page get redirected from header() function and code below that will never execute. This is something dangling code. so instead of that you need to write as follow
if ($_POST['username']=="") {

     $home_url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) .    '/form.html';
$Err = "Invalid value";
header('Location: ' . $home_url);

       }


text:
Q: Pagination with PrincipalSearcher I need pagination when I use a PrincipalSearcher. I tried using the VirtualListView property of the underlying DirectorySearcher with no avail.
Samplecode:
using System;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Linq;
namespace Testbed
{
    internal class Testbed
    {
        private static void Main(string[] args)
        {
            Works();
            Fails();
            Console.ReadKey();
        }

        private static void Works()
        {
            var entry = new DirectoryEntry("LDAP://server/DC=example,DC=com", @"USERNAME", "PASSWORD");
            var searcher = new DirectorySearcher(entry);

            searcher.SearchScope = SearchScope.Subtree;
            searcher.Filter = "(cn=*)";
            // sort is needed, otherwise DVLV will not work?
            searcher.Sort = new SortOption("cn", SortDirection.Ascending);

            searcher.VirtualListView = new DirectoryVirtualListView(5, 10, 5);
            SearchResultCollection result = searcher.FindAll();
            Console.WriteLine("Works: " + result.Count);
        }

        private static void Fails()
        {
            var context = new PrincipalContext(ContextType.Domain, "server", "DC=example,DC=com",
                ContextOptions.Negotiate,
                @"USERNAME", "PASSWORD");

            var user = new UserPrincipal(context)
            {
                DisplayName = null,
            };

            var searcher = new PrincipalSearcher(user);
            ((DirectorySearcher) searcher.GetUnderlyingSearcher()).Sort = new SortOption("cn", SortDirection.Ascending);
            ((DirectorySearcher) searcher.GetUnderlyingSearcher()).VirtualListView = new DirectoryVirtualListView(0, 2, 2);
            PrincipalSearchResult<Principal> result = searcher.FindAll();

            Console.WriteLine("Fails: " + result.Count());
        }
    }
}

When I use DirectorySearcher (Method: Works()) directly everything works fine, but with PrincipalSearcher (Method: Fails()) I get teh following exception (sorry for the german text):
Ausnahmefehler: System.Runtime.InteropServices.COMException: Die angeforderte kritische Erweiterung wird vom Server nicht unterstützt.

   bei System.DirectoryServices.SearchResultCollection.ResultsEnumerator.MoveNext()
   bei System.DirectoryServices.AccountManagement.ADEntriesSet.MoveNext()
   bei System.DirectoryServices.AccountManagement.FindResultEnumerator`1.MoveNext()
   bei System.DirectoryServices.AccountManagement.FindResultEnumerator`1.System.Collections.IEnumerator.MoveNext()
   bei System.Linq.Enumerable.Count[TSource](IEnumerable`1 source)

Any solution for this? Is this even possible with PrincipalSearcher?

A: The default pagesize of PrincipalSearcher is set to 265. Try to set it to 0 like this:
((DirectorySearcher) searcher.GetUnderlyingSearcher()).PageSize = 0;

This should enable Pagination. The DirectorySearcher has a default PageSize of 0, which is why it works when you use it directly.


text:
Q: Python - counting nucleotides So I am supposed to devise a program that counts a DNA sequence as well as count the individual base pairs. Here's what I have thus far:
class dnaString (str):
    def __new__(self,s):
        return str.__new__(self,s.upper())
    def length (self):
        return (len(self))
    def getATCG (self,num_A,num_T,num_C,num_G):
        num_A = self.count("A")
        num_T = self.count("T")
        num_C = self.count ("C")
        num_G = self.count ("G")
        return ( (self.length(), num_A, num_T, num_G, num_C) )

    def printnum_A (self):
        print ("Adenine base content: {0}".format(self.count("A")))

dna = input("Enter a dna sequence: ")
x=dnaString(dna)

The program doesn't really do anything, and since I'm just starting out with python, I'm not sure how to fix this so it works. what else should I add? I know it's unfinished.

A: I'm not sure what is the question, but as you are not calling the method ´printnum_A`, nothing is printing. If  you call it like this, it works:
dna = input("Enter a dna sequence: ")
x=dnaString(dna)
x.printnum_A()

Update according to comments
It is not enough to declare the methods of a class, you need also to call then when you need them. Like here for printnum_T:
class dnaString (str):
    def __new__(self,s):
        return str.__new__(self,s.upper())
    def length (self):
        return (len(self))
    def getATCG (self,num_A,num_T,num_C,num_G):
        num_A = self.count("A")
        num_T = self.count("T")
        num_C = self.count ("C")
        num_G = self.count ("G")
        return ( (self.length(), num_A, num_T, num_G, num_C) )

    def printnum_A (self):
        print ("Adenine base content: {0}".format(self.count("A")))

    # here the method is declared
    def printnum_T (self):
        print ("Adenine base content: {0}".format(self.count("T")))

dna = input("Enter a dna sequence: ")
x=dnaString(dna)
x.printnum_A()
# Here I call my method on `x`
x.printnum_T()

A: Does this help? It works in Python 2.7.3 and 3.2.3 that I happen to have installed.
import itertools
import sys

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = itertools.tee(iterable)
    next(b, None)
    if sys.version_info[0] > 2:
        return zip(a,b)
    return itertools.izip(a, b)

class DnaSequence():
    Names = {
        'A' : 'adenine',
        'C' : 'cytosine',
        'G' : 'guanine',
        'T' : 'thymine'
    }
    Bases = Names.keys()

    def __init__(self, seq):
        self._string = seq
        self.bases = { x:0 for x in DnaSequence.Bases }
        self.pairs = { x+y:0 for x in DnaSequence.Bases
                             for y in DnaSequence.Bases }

        for base in seq:
            if base in self.bases:
                self.bases[base] += 1

        for x,y in pairwise(seq):
            pair = x+y
            if pair in self.pairs:
                self.pairs[pair] += 1

    def printCount(self, base):
        if base in DnaSequence.Names:
            print(DnaSequence.Names[base].capitalize() +
                  " base content: " + str(self.bases[base]))
        else:
            sys.stderr.write('No such base ("%s")\n' % base)

    def __repr__(self):
        return self._string

d = DnaSequence("CCTAGTGTTAGCTAGTCTAGGGAT")
for base in DnaSequence.Bases:
    d.printCount(base)

# Further:
print(d)
print(d.bases)
print(d.pairs)

It's a complete example that counts the bases (A, C, G, T) and all occurrences of adjacent pairs (e.g. in ACCGTA, the pairs AC, CC, CG, GT, TA would all be 1, the other 11 possible combinations of the Cartesian product ACGT x ACGT would all be 0).
The counting method used here scans the string once in the constructor, rather than scanning it four times every time getATGC() is called.

A: I think the class can be simplified a bit:
class DnaString(str):
    def __new__(self, s):
        return str.__new__(self, s.strip().upper())

    def __init__(self, _):
        self.num_A = self.count("A")
        self.num_C = self.count("C")
        self.num_G = self.count("G")
        self.num_T = self.count("T")

    def stats(self):
        return len(self), self.num_A, self.num_C, self.num_G, self.num_T

then
dna = raw_input("Enter a dna sequence: ")
d = DnaString(dna)

print(d)
print(d.stats())

gives
Enter a dna sequence: ACGTACGTA
ACGTACGTA
(9, 3, 2, 2, 2)

A: You can do this by using a dictionary to organize and retrieve your counts. For instance:
    DNASeq = raw_input("Enter a DNA sequence: ")

    SeqLength = len(DNASeq)

    print 'Sequence Length:', SeqLength

    BaseKey = list(set(DNASeq)) #creates a list from the unique characters in the DNASeq

    Dict = {}

    for char in BaseKey:
        Dict[char] = DNASeq.count(char)
    print Dict


text:
Q: Word choice: non-school customer I'm working in a company that to date has been selling an educational product to schools. We're now aiming to branch out into selling to private consumers, who want to use the product for their family or some other small group of kids.
What's the best word to describe these non-school customers, that distinguishes them from school customers?
We thought of "consumers", but schools are also consumers. They're not "individuals", since there are multiple users in that group, and they're not necessarily "families" either; they could be a group of friends.

A: Business, Commercial, and Industry are often used to describe non-academic enterprises especially within schools.  But if you talking about 'end-users' then personal or home users might be a better fit?

A: I'm guessing your new market includes home-schoolers, afterschool programs (such as Kumon), and churches.  In that case, perhaps non-institutional would work.  Institutional would apply to schools (including private schools) and school districts; non-institutional would be everyone else.  According to the Oxford Dictionaries:

institutional
ADJECTIVE

*

*Of, in, or like an institution or institutions.
'institutional care'
'an institutional investor'

Hope this helps!

A: You may use consumer or end user

consumer  : A person who buys goods or services for their own use
end user : The person or organization that uses something rather than
an organization that trades in it

please check Cambridge dictionary for consumer and end user


text:
Q: Is there a more elegant solution to getting the inverse of an array of ranges? Let's imagine the following:
You have a line that starts at 1 and ends at 10000.
You're given an array of ranges like [{ start: 5, end: 10 }, { start: 15, end: 25 }]
Given an array of ranges, find the inverse.
For the above example, the inverse would be [{ start: 1, end: 4 }, { start: 11, end: 14 }, { start: 26, end: 10000 }]
Notice how the inverse is basically every other range on our line.
Below is my current solution... Is there a more elegant solution that doesn't have to explicitly deal with the edge cases?
Note, in my code ranges are named regions.
const inverseRegions = (regions) => {

  // If no regions, the inverse is the entire line.
  if (regions.length === 0) {
    return [{ start: 1, end: 10000 }]
  }

  let result = []

  // If the first region doesn't start at the beginning of the line
  // we need to account for the region from the 1 to the start of
  // first region
  if (regions[0].start !== 1) {
    result.push({
      start: 1,
      end: regions[0].start - 1
    })
  }

  for (let i = 1; i < regions.length; i++) {
    const previousRegion = regions[i-1]
    const region = regions[i]

    result.push({
      start: previousRegion.end + 1,
      end: region.start - 1
    })
  }

  // If the last region doesn't end at the end of the line
  // we need to account for the region from the end of the last
  // region to 10000
  if (regions[regions.length - 1].end !== 10000) {
    result.push({
      start: regions[regions.length - 1].end + 1,
      end: 10000
    })
  }

  return result
}

Expected results:
inverseRegions([])
  => [ { start: 1, end: 10000 } ]

inverseRegions([{ start: 1, end: 10 }, { start: 15, end: 20 }])
  => [ { start: 11, end: 14 },
       { start: 21, end: 10000 } ]

inverseRegions([{ start: 5, end: 10 }, { start: 12, end: 60 }, { start: 66, end: 10000 }])
  => [ { start: 1, end: 4 },
       { start: 11, end: 11 },
       { start: 61, end: 65 } ]

inverseRegions([{ start: 8, end: 12 }, { start: 16, end: 20 }, { start: 29, end: 51 }])
  => [ { start: 1, end: 7 },
       { start: 13, end: 15 },
       { start: 21, end: 28 },
       { start: 52, end: 10000 } ]

A: You can use reduce initialized with an accumulator that contains the entire region and then split that last region as you encounter new ranges:

function inverseRegions(ranges) {
  return ranges.reduce((acc, curr) => {
    let prev = acc.pop();
    if (curr.start > prev.start)
      acc.push({start: prev.start, end: curr.start - 1})
    if (prev.end > curr.end)
      acc.push({start: curr.end + 1, end: prev.end});
    return acc;
  }, [{start: 1, end: 10000}])
}

console.log(inverseRegions([{ start: 5, end: 10 }, { start: 15, end: 25 }]));
console.log(inverseRegions([]));
console.log(inverseRegions([{ start: 1, end: 10 }, { start: 15, end: 20 }]));
console.log(inverseRegions([{ start: 5, end: 10 }, { start: 12, end: 60 }, { start: 66, end: 10000 }]));
console.log(inverseRegions([{ start: 8, end: 12 }, { start: 16, end: 20 }, { start: 29, end: 51 }]));

This of course assumes that your intervals are sorted.


text:
Q: How to grab the MathQuill data once user types it in? I am trying to set up a chat that can parse math text, and I think MathQuill does the visuals, but I need to parse what the user types in once they submit it.
I am using the MathQuill editor:

\sqrt[3]{8}=\frac{\sqrt{16}}{2}

shown here:
http://jenseng.github.io/mathquill/demo.html
And I want to grab "\sqrt[3]{8}=\frac{\sqrt{16}}{2}" to parse. I tried
document.getElementById("mathTextBox").innerText

but it includes the toolbar text so I get:
"+Basic
πGreek
⊕Operators
≤Relationships
⇔Arrows
{Delimiters
∞Misc
∧
∨
∪
∩
◇
△
⊖
⊎
⊗
⊕
▽
⊓
⊲
⊔
⊳
⊙
◯
†
‡
≀
∐
3√8=
√16
2 "
Also, I would rather not deal with symbols (ie √) so I want it in the text format (ie \sqrt). The text is also missing a division sign after the sqrt(16).
Any ideas are greatly appreciated! Thanks!

A: They told me in mathquill chat (http://webchat.freenode.net/?channels=mathquill) it is:
$(document.getElementById("mathTextBox")).mathquill('latex')


text:
Q: Variable not changed by AFNetworking GET function I am trying to use an AFNetworking class to retrieve data from a database.  Long story short, the data received from the parameter responseObject is filled with items.  Here is my problem however.  I am trying to copy the results in responseObject into an NSDictionary called results.  I used the following code to get there:
__block NSDictionary *results;

[manager GET:@"http://daneolog.altervista.org/app/getData.php"
  parameters:nil
     success:^(AFHTTPRequestOperation *operation, id responseObject) { results = responseObject;
     NSLog(@"Inside: %@", results); }
     failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"%@", error); }];

NSLog(@"Outside: %@", results);

I tried NSLoging the results dictionary INSIDE the success braces, and everything is a-okay there.
I tried NSLoging the results dictionary OUTSIDE the GET function, and it comes up as (null).
These are my results:
2015-11-12 14:34:34.875 TestApp[4864:258743] Outside: (null)
2015-11-12 14:34:35.242 TestApp[4864:258743] Inside: (
        {
        address = "Sample Address";
    }
)

Now notice the peculiar thing: the outside NSLog is being executed first.  I don't know why this is so.  Can anyone help me on this?  Thanks a bundle.

A: Your code outside the success block is executing before the success block completes that is why results come up as null.  results is on the main thread, and you are not blocking (as is correct with an HTTP request).
You can pass a weak reference to an object, and have that updated.  Or if you absolutely need to wait for the result (login for instance) then you should do it on the main thread.
Here is an example of a weak object:
//results is an object created earlier

__weak NSDictionary *weakResults = results;

[manager GET:@"http://daneolog.altervista.org/app/getData.php"
     parameters:nil
     success:^(AFHTTPRequestOperation *operation, id responseObject) {
             weakResults = responseObject;
             NSLog(@"Inside: %@", results);
     }
     failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             NSLog(@"%@", error);
     }];

//when the success block finishes the results object will be populated

If you wanted to block i.e. do it on the main thread you could use:
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

However, if the response doesn't come back, your app hangs.


text:
Q: i cant find charms bar on my Lenovo ideapad A10 I bought ideapad last week and have been battling to find charms bar to access windows.I am sure they said the device comes pre_installed with Windows8.I have tried swiping from all the corners of this device.  Please help!

A: There's a setting called Disable Edge Swipes that may be of help. Try this:
Navigate to Control Panel | Hardware and Sound | Mouse | Device Settings | Settings
It could also be located here:
Navigate to Control Panel | Mouse | UltraNav | TouchPad Settings | Application Gestures | Edge Swipes | then check the status of "Enable Edge Swipes"

A: Swipe from the right if using a touchscreen but not the corner. If you use a mouse you move the mouse to the bottom right corner and then slowly move the mouse up; this will show the charms bar.


text:
Q: Why is some code run on the "Time-limited test" thread instead of the main thread? I have some tests. I notice that sometime my log messages indicate that the code is running on the main thread. Other log messages indicate that the code is running on the "Time-limited test" thread. Many of my tests have a timeout specified.
00000  Time-limt WARNING start gtp2: (a model-18 (0,1) ...
00001  Time-limt WARNING                response2: = A1
00002       main WARNING                   named threads!  ...
Edit 1. The "Time-limited test" thread is started by FailOnTimeout() (please see below). The elapsed time in milliseconds is give as well as the timeout time (200 ms.). I have a few hundred tests that are similar but only a dozen or so timeout on me. In all cases the elapsed time is less than the timeout value for the test.
These tests start up one to five threads, run some test, and then try to shutdown gracefully by interrupting and joining.

00000  Time-limt  SEVERE not main! 'Time-limited test' 1.491111 ms.
200 ms. in controller.GTPBackEnd.startGTP()
controller.GTPBackEnd.startGTP(GTPBackEnd.java:50)
controller.ABothTestCase.testBothGenmoveTrue(ABothTestCase.java:39)
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
Method)
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.base/java.lang.reflect.Method.invoke(Method.java:568)
org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
org.junit.internal.runners.statements.FailOnTimeout$CallableStatement.call(FailOnTimeout.java:299)
org.junit.internal.runners.statements.FailOnTimeout$CallableStatement.call(FailOnTimeout.java:293)
java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)

A: This will be an artifact of the code that you are testing.  The message refers to a "time-limt" (sic) thread.  That spelling error is a big clue1 that the thread doesn't belong to the JUnit test framework.
So, my guess is that the application code that you are testing creates a thread and names it "time-limt".  That thread generates log messages.  Some test (running on the "main" thread) calls the application code (on the "main" thread) ... which interacts with the "time-limt" thread ... which produces the log messages.
In short, those messages are not direct evidence that the test are running on different threada.

1 - If you doubt my inference, download the source code for the version of JUnit you are using, and search for the string time-limt.  I could be wrong.


text:
Q: Instantiation error in argument 2 of (>)/2 So im trying to define natural numbers so far i did this:
 1 nat(0).                        % 0 zero is a natural, can be a stoping case
 2 nat(X):- 0>X , !,fail.         %if is less then zero then its not a natural.
 3 nat(X):- nat(Z), X is Z+1.     %if its bigger than zero do recursively for the number-1

When i do this it gives me  "Instantiation error in argument 2 of (>)/2", so he can't instantiate X in line 2 but if take out the fail he does the comparation (>) fine and has no problem instantiating X , so why he complains if i put the fail?

A: If you want to generate natural numbers, you can do it without using cuts or the fail/0 control construct. For example:
nat(Nat) :-
    next_integer(0, Nat).

next_integer(I, I).
next_integer(I, K) :-
    J is I + 1,
    next_integer(J, K).

Sample call:
| ?- nat(Nat).

Nat = 0 ? ;
Nat = 1 ? ;
Nat = 2 ? ;
Nat = 3 ?
...

But this predicate will not work if instead you want to test if a term is a natural number. For example, the following call will result in a stack overflow in most Prolog systems (as we cannot generate a negative integer by incrementing from zero):
| ?- nat(-3).

If you are using a Prolog system providing a CLP(FD) library, you can use a better definition:
nat(Nat) :-
    Nat #>= 0,
    next_integer(0, Nat).

next_integer(I, I).
next_integer(I, K) :-
    J is I + 1,
    next_integer(J, K).

And then use the same predicate for generating and testing. For example, using SWI-Prolog and library(clpfd):
?- nat(Nat).
Nat = 0 ;
Nat = 1 ;
Nat = 2 ;
Nat = 3
...

?- nat(-3).
false.

Without using a constraints library, you will need to write something like:
nat(Nat) :-
    (   var(Nat) ->
        next_integer(0, Nat)
    ;   integer(Nat), Nat >= 0
    ).


text:
Q: how to read numbers and text from camera in android? I'm working on android application and it should allow users to take photos using camera and the application reads the text and numbers in the photo.
I don't know where to start from android studio. is there any good suggestion on github that could help me???
thanks in advance.

A: You can try to use OpenCV library. Its abbreviature is Open Computer Vision Library. It has a reputation similar to OpenGL. There must be articles about yor issue in which library is ised. It can be linked static or dynamic using runtime application called OpenCV Manager (available in Google Play). You can use it both in Java and C++ code. Hope, it helps
PS i have an own example of it use.
https://github.com/androidovshchik/ProhibitingSignDetector

A: As others said OpenCV or OCR is the way to go.
Google maintains one OCR library called as "Tesseract" (reminds me of Avengers :P).
To make the job little easier there is a fork of Tesseract called as Tess-Two
It combines some other useful tools like Leptonica (image processing library). Build instructions are given on the Readme file.
To get started you can check out very easy to use OCR library
Easy OCR Library Android which uses Tess-Two under the hood.
Again usage instructions are in the Readme file. It is already built so you don't need to build Tess-Two.

A: i could give suggest about how i would do that if i needed to .
first of all you need to photo the picture only black and white  .
then cheack the min black pixels in row that will define a letter .(you dont want any shadow to recognize as potential letter.
try and learn progress (any camera have diffrent resulution so it need to be some % of the picture row pixels.)
after that evrey letter have diffrent shape so you need to do for loop 5 times in diffrent angel until you get to the third gap of black rows.
after that some huge switch and if to get to the right letter need to do big research about the gap inside the letter proportion.
to have a little dataBase could help if you wanted to get more then one font .
again i not sure its the right way but that what i would do.
have fun :)

A: You may try to find some Optical Character Recognition (OCR) library for Java
Check Java OCR, tess-two, Aprise. And explore stackoverflow searching other OCR solutions.
Implementing your own OCR lib may be very difficult so think is it really necessary for your task.


text:
Q: Prolog, gender with if_then_else I would like to say that if he is a father he is a male else is a female
father(pedro-i,beatriz(1347)).
father(pedro-i,joão(1349)).
father(pedro-i,dinis(1354)).
father(pedro-i,joão_grão_mestre_da_ordem_de_avis).
mother(constança(1320),luis).
mother(constança(1320),maria(1342)).

% I want to say that if is the father then is male else is a female

IF_then_else(X,Y,Z) :- father(X,Y),male.
IF_then_else(X,Y,Z) :- female.

A: A first remark: predicates and functors start with a lowercase letter, not an uppercase: uppercases are used for variables.
You seem to miss the point that predicates in Prolog do not return a value. They can only succeed, or fail (in that sense they "return" a boolean). The way to provide (non-boolean) output is by using unification.
Here you can do this by putting the literal in the head like:
if_then_else(X,Y,male) :- father(X,Y).
if_then_else(X,Y,female).
But now there is another problem: Prolog backtracks. So it means that even if the first clause succeeds, it will try the second clause. So pedro-i will both be male and female. You can solve this problem by putting a guard on the second clause that says that the clause succeeds if Prolog cannot prove that there is a father(X,Y) relation. Something like:
if_then_else(X,Y,male) :- father(X,Y).
if_then_else(X,Y,female) :- \+ father(X,Y).
But this can result in a computationally expensive problem: it is possible that it takes a long time to prove that there is a father(X,Y). relation, and if there is no such relation, failing to prove so will take even more time (because Prolog needs to check all branches). It might even result in an infinite loop to do so. In this case you can use a cut (!). If you reach a cut, Prolog will not attempt to find results in the following clauses of the predicate. So you can write:
if_then_else(X,Y,male) :- father(X,Y), !.
if_then_else(X,Y,female).
Alternatively you can use Prolog's if-then-else structure and use explicit unification:
if_then_else(X,Y,Z) :-
    (  father(X,Y)
    -> Z = male
    ;  Z = female
    ).


text:
Q: How do I add methods to nodejs supertest module? I'm trying to add some convenience methods to https://github.com/visionmedia/supertest. So far the only way I was able do it is by adding them directly to the module source code in lib/test.js:
Test.prototype.expectHeaders = function (a)
{
  for (var header in a)
  {
    this._asserts.push(this._assertHeader.bind(this,
    {
      name: '' + header,
      value: a[header]
    }));
  }

  return this;
};

I tried via util.inherits and prototype.__proto__ but every attempt ends with "expectHeaders is not a function" exception.
Here is my latest attempt:
var supertest = require('supertest'),
  util = require('util');

var SccTest = function()
{
};

SccTest.prototype.__proto__ = supertest.prototype;

SccTest.expectHeaders = function (a)
{
  for (var header in a)
  {
    this._asserts.push(this._assertHeader.bind(this,
    {
      name: '' + header,
      value: a[header]
    }));
  }

  return this;
};

util.inherits(SccTest, supertest);
module.exports = SccTest;

How can I properly add methods to Test prototype?

A: if you want inherited from supertest object, you don't need to point your prototype to supertest manually. you can just call util.inherites method :
var supertest = require('supertest'),
    util = require('util');

var SccTest = function(){
};
util.inherits(SccTest, supertest);

SccTest.prototype.expectHeaders = function (a){
  ...
};
module.exports = SccTest;

A: Ok, this code should be helpful.
   var supertest = require('supertest'),
      util = require('util');
    var SccTest=function (arguments) {
      var sccTest = {}
      sccTest.__proto__ = supertest(arguments)
      sccTest.expectHeaders = function (a)
      {
        for (var header in a)
        {
          this._asserts.push(this._assertHeader.bind(this,
          {
            name: '' + header,
            value: a[header]
          }));
        }
        return this;
      };
      return sccTest;
    }


text:
Q: Timer on Location Manager Is it possible to invoke didUpdateLocationsinside the Timer ? I mean..
_timer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(_:didUpdateLocations:)), userInfo: nil, repeats: true)

Is that going to work ? If yes then it is going to update location every 10 seconds ?

A: You can't invoke didUpdateLocations. If you want frequent updates, your best choice is the Standard location service:

The standard location service is most appropriate for apps that
  deliver location-related information directly to the user but it may
  be used by other types of apps too. To start the service, configure
  the desiredAccuracy and distanceFilter properties of the location
  manager and then call the requestLocation(), startUpdatingLocation(),
  or allowDeferredLocationUpdates(untilTraveled:timeout:) method. Never
  specify an accuracy value greater than what you need. Core Location
  uses the accuracy value you specify to manage power better. A higher
  degree of accuracy requires more precise hardware like GPS, which
  consumes more power.

https://developer.apple.com/reference/corelocation/cllocationmanager

A: Your callback selector has to have a different signature:
class MyClass {

    func startTimer() {
        _timer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(MyClass.timerCallBack(_:)), userInfo: nil, repeats: true)
    }

    // ...

    func timerCallBack(timer: Timer) {
        // Here you go.
    }
}

(Maybe contain some syntax errors; currently don't have Xcode at hand)


text:
Q: Fetching multiple event details in Office 365 I need to fetch information related to eventId from office 365 for multiple events.
Is there a way I can get that info in a single REST call?
I want specific events only (based on eventId's only)

A: A batch request may be what you are looking for.
See json Batching Documentation for more information
Keep in mind that batching is currently limited to 20 requests per message (known issues)
Example:
You will need to send a POST Message to the batch endpoint
https://graph.microsoft.com/v1.0/$batch

inside the body you will need to include your requests:
Note: do not include the server url (https://graph.microsoft.com/v1.0/) in the url property or the request will fail with "BadRequest - Invalid request Uri".
Request-Body:
  {
      "requests": [
        {
          "id": "1",
          "method": "GET",
          "url": "/me/calendarview?startdatetime=2018-03-01T18:31:34.206Z&enddatetime=2018-03-12T18:31:34.206Z"
        },
                {
          "id": "2",
          "method": "GET",
          "url": "/me/events/{someEventId}"
        },
      ]
}

When the server has processed all requests an response array containing the results will be sent back:
Server-Response:
  {
    "responses": [
            {
        "id": "2",
        "status": 200,
        "headers": {
            "OData-Version": "4.0",
            "Content-Type": "application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false;charset=utf-8",
            "ETag": "W/\"Z+ICSvkiAfZX7XWQAZ6IH==\""
        },
        "body": {
           // the event object
        }
    },
        {
            "id": "1",
            "status": 200,
            "headers": {
                "OData-Version": "4.0",
                "Content-Type": "application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false;charset=utf-8"
            },
            "body": {
                "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users('aUserID')/calendarView",
                "value": [
                  // list of  found event-objects
                ]
            }
        }
    ]
}


text:
Q: Python, mongo + spider monkey Ok, so this isn't exactly a question that I expect a full answer for but here goes...
I am currently using a python driver to fire data at a mongo instance and all it well in the world. Now I want to be able to pull data from mongo and evaluate each record in the collection. Now I need to pass in to this evaluation a script that will look at the row of data and if a condition is met return true i.e.
(PSUDO CODE)
foreach(row in resultSet)
 if(row.Name=="Chris) return true

return false

Now the script that I use to evaluate each item in the row should be sandboxes somehow with limited functionality/security privileges.
In other words the code will be evaled, and I dont want it to have rights to i.e. include external libraries, call remote servers or have access any files on the server etc...
With this in mind I know that mongo uses something called spider monkey (which I gather is a JS evaluator) to write queries. I wonder would it be possible to take the result of a mongo call and pass it to an evaluated javascript function using spider monkey (somehow) to achieve what I am after? If so would this be safe enough.
To be honest, Im writing this question and I realize its sounding a lot like one of those "please help, how to code the world" type questions but any pointers would be helpful.

A: Have you looked at $where clauses in MongoDB? Seems like those would pretty much give you exactly what you're looking for. In PyMongo it would look something like:
db.foo.find().where("some javascript function that will get applied to each document matched by the find")


text:
Q: Improve DataTable performance when modifying class of cell I'm very satisified using jquery DataTables, but I have found one situation where I need to boost performance. I'm updating the class of a cell depending on the data. To do this I'm using the render function and creating an api instance from the settings to get hold of the cell via the api. Is there a better way for doing this?
{
        "data": "statusText", "className": "status",
        "render": function (data, type, full, meta) {
            switch (type) {
                case "display":
                    var api = new $.fn.dataTable.Api(meta.settings);
                    var td = api.cell({ row: meta.row, column: meta.col }).node();
                    switch (full.status) {
                        case Status.Saved:
                            $(td).addClass("status-saved");
                            break;
                        case Status.Sent:
                            $(td).addClass("status-sent");
                            break;
                        default:
                            $(td).addClass("status-saved");
                    }
                    return full.statusText;
                case "sort":
                    return full.status;
                default:
                    return full.statusText;
             }
        }
    }

A: One possibility I can see is that If you somehow manage to get api and td out of render function. Because that looks like heavy operation.
and make td like below, probably that will work.
var td = $(api.cell({ row: meta.row, column: meta.col }).node());

Further more what you can do is to use vanillaJS instead of addClass

A: Found out that the rowCallback (documentation here) method is better than the render method. In rowCallback we have access to the DOM row and don't have to new up api instance and lookup the cell. I still use jQuery and addClass to set the class. Will try plain vanilla instead of jQuery to try to improve performance even more. As suggested by @shyammakwana.me


text:
Q: Unexpected token '<' when using grunt to compile .js script files to index.html I'm currently using grunt to inject application script files into index.html, and I've configured it as follows:
scripts: {
        options: {
          transform: function(filePath) {
            filePath = filePath.replace('/client/', '');
            filePath = filePath.replace('/.tmp/', '');
            return '<script type="text/javascript" src="' + filePath + '"></script>';
          },
          starttag: '<!-- injector:js -->',
          endtag: '<!-- endinjector -->'
        },
        files: {
          '<%= yeoman.client %>/index.html': [
              ['{.tmp,<%= yeoman.client %>}/{app,components}/**/*.js',
               '{.tmp,<%= yeoman.client %>}/template/js/*.js',
               '{.tmp,<%= yeoman.client %>}/scripts/components/sidebar/*.js',
               '{.tmp,<%= yeoman.client %>}/scripts/components/modal/modalEffects.js',
               '{.tmp,<%= yeoman.client %>}/scripts/components/input/inputFiller.js',
               '{.tmp,<%= yeoman.client %>}/scripts/socket.js',
               '!{.tmp,<%= yeoman.client %>}/scripts/app.js',
               '!{.tmp,<%= yeoman.client %>}/{app,components}/**/*.spec.js',
               '!{.tmp,<%= yeoman.client %>}/{app,components}/**/*.mock.js']
            ]
        }
      },

Which generates the following HTML:
<!-- injector:js -->
 <script type="text/javascript" src="template/js/SmoothScroll.js"></script>
 <script type="text/javascript" src="template/js/bootstrap.js"></script>
 <script type="text/javascript" src="template/js/bootstrap.min.js"></script>
 <script type="text/javascript" src="template/js/jquery.1.11.1.js"></script>
 <script type="text/javascript" src="template/js/jquery.isotope.js"></script>
 <script type="text/javascript" src="template/js/landio.min.js"></script>
 <script type="text/javascript" src="template/js/main.js"></script>
 <script type="text/javascript" src="template/js/modernizr.custom.js"></script>
 <script type="text/javascript" src="template/js/owl.carousel.js"></script>
 <script type="text/javascript" src="scripts/components/sidebar/classie.js"></script>
 <script type="text/javascript" src="scripts/components/sidebar/modernizr.custom.js"></script>
 <script type="text/javascript" src="scripts/components/sidebar/sidebarEffects.js"></script>
 <script type="text/javascript" src="scripts/components/modal/modalEffects.js"></script>
 <script type="text/javascript" src="scripts/components/input/inputFiller.js"></script>
 <script type="text/javascript" src="scripts/socket.js"></script>
 <!-- endinjector -->

The app ends up working perfectly on localhost. However, when deployed on AWS, I see the following in my console:

Has anyone encountered this issue before?


text:
Q: How do you get the soapUI maven plugin to fail safe? AFAIK, the maven failsafe plugin fails safe because it has separate goals for running the tests and failing the build based on the tests.  These are designed to be bound to the integration-test and verify goals respectively.  This allows post-integration-test bound goals to run (shutting down the build) before the build fails.
My question is, how do I do this with the maven-soapui-plugin?  I thought I could simply specify <testFailIgnore>true</testFailIgnore> in my soapui plugin config and then call the failsafe plugin verify goal, but that isn't working.  I don't think I'm not sure if I'm getting a summary file out of the soapui plugin or not.  I keep getting Expected root element 'failsafe-summary' but found 'testsuite' Here is a snippet of the POM:
<plugin>
    <groupId>eviware</groupId>
    <artifactId>maven-soapui-plugin</artifactId>
    <version>4.0.0</version>
    <configuration>
        <junitReport>true</junitReport>
        <exportAll>true</exportAll>
        <outputFolder>${project.build.directory}/surefire-reports</outputFolder>
        <testFailIgnore>true</testFailIgnore>
        <printReport>true</printReport>
    </configuration>
    <executions>
        <execution>
            <id>FailingTest</id>
            <phase>integration-test</phase>
            <goals>
                <goal>test</goal>
            </goals>
            <configuration>
                <projectFile>${basedir}/testData/soapui-integration-tests.xml</projectFile>
                <host>localhost</host>
            </configuration>
        </execution>
    </executions>
</plugin>

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-failsafe-plugin</artifactId>
    <version>2.9</version>
    <executions>
          <execution>
           <phase>verify</phase>
            <id>verify</id>
            <goals>
              <goal>verify</goal>
            </goals>
            <configuration>
              <summaryFiles>
                <summaryFile>${project.build.directory}/surefire-reports/TEST-TestSuite_1.xml</summaryFile>
              </summaryFiles>
            </configuration>
        </execution>
    </executions>
</plugin>

Is there something wrong with my POM or is this a bad approach?  Are there any better approaches?

A: AFAIK maven-failsafe-plugin can only verify success status of tests run by maven-failsafe-plugin and not by maven-soapui-plugin. It does that by reading test summary report file (failsafe-summary.xml) which has specific format.
maven-soapui-plugin could be adjusted to separate running tests from verifying test success status, to support running post-integration-test tasks (stop server, undeploy artifacts, etc.) before verification. Create a support ticket for this to soapUI guys.
Maybe even maven-failsafe-plugin, it's verify mojo, could be extended to allow specifying different test report format (JUnit style reports are supported by soapUI) or even an xpath expression which would be used by maven-failsafe-plugin to determine if there were failed tests or not. Create a support ticket for this on maven-failsafe-plugin issue tracker.
Until those extensions are supported, and you need to do tasks on post-integration-test phase you can use soapUI JUnit integration and have maven-failsafe-plugin run those soapUI JUnit tests.

A: I am trying this solution, and it doesn't work.
But I have found one.
To obtain de tests report of SOAPUI tests in Jenkins, I using the failsafe plugin with this configuration in the pom.xml of my Soap tests folder :
<build>
    <plugins>
        <plugin>
            <groupId>eviware</groupId>
            <artifactId>maven-soapui-plugin</artifactId>
            <version>2.6.1</version>
            <configuration>
                <projectFile>${basedir}/soap_project_tests.xml</projectFile>
                <outputFolder>${filePath.reports.soap}</outputFolder>
                <testFailIgnore>true</testFailIgnore>
                <junitReport>true</junitReport>
                <exportwAll>true</exportwAll>
                <printReport>true</printReport>
            </configuration>
            <executions>
                <execution>
                    <id>run-soap-integration-test</id>
                    <phase>integration-test</phase>
                    <goals>
                        <goal>test</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-failsafe-plugin</artifactId>
            <version>2.11</version>
            <configuration>
                <reportsDirectory>${filePath.reports.soap}</reportsDirectory>
                <printSummary>true</printSummary>
                <argLine>-Xmx512m</argLine>
            </configuration>
            <executions>
                <execution>
                    <id>soap-integration-test-verify</id>
                    <phase>post-integration-test</phase>
                    <goals>
                        <goal>integration-test</goal>
                        <goal>verify</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

The tests cases status are up to Jenkins.

A: There is an open source extension of the soapui plugin which has a separate test-verify goal for exactly this purpose.
https://github.com/redfish4ktc/maven-soapui-extension-plugin
The following example shows the required configuration:
https://github.com/redfish4ktc/maven-soapui-extension-plugin/blob/master/src/it/test-verify_goal/one_failing_project/pom.xml


text:
Q: ntheorem not placing marker on next line Hi does anyone have a solution to this:
\documentclass[12pt,reqno,a4paper,draft]{article}
\usepackage[margin=3.cm,heightrounded]{geometry}
\usepackage{mathtools,amsmath,amssymb}
\usepackage[amsmath,thmmarks]{ntheorem}
\theoremseparator{.}
\theoremstyle{nonumberplain}
\theoremheaderfont{\itshape}
\theorembodyfont{\normalfont}
\theoremsymbol{\enspace\ensuremath{\Box}}
\newtheorem{proof}{Proof}
\begin{document}
\begin{proof}
  Blah
  \begin{equation*}
    blah
  \end{equation*}
  which always hold a an normal almost contact
  metric structure (see [1, Lemma~2.1]).
\end{proof}
\end{document}

as can be seen the box overflows the line instead of being moved to the next line. The text one the last line span the full text width.

A: If you allow (but discourage) a line break and allow the symbol to go flush right it seems to work better in this case:
\theoremsymbol{\nolinebreak[1]\hspace*{.5em plus 1fill}\ensuremath{\Box}}


text:
Q: Getting array name from plist as tableview labels in swift This is my plist file
<plist version="1.0">
<dict>
<key>Complete</key>
<dict>
    <key>Autonomic Nervous System</key>
    <array>
        <string>Cholinergic</string>
        <string>Anticholinergic</string>
    </array>
    <key>Peripheral Nervous System</key>
    <array>
        <string>Central relaxants </string>
        <string>Peripheral relaxants </string>
    </array>
</dict>
<key>Chap</key>
<array>
    <string>Autonomic Nervous System</string>
    <string>Peripheral Nervous System</string>
</array>
</dict>
</plist>

I am able to get chapter names only when I store it as string under a different key "chap".
Here is the code.
override func viewDidLoad() {
    super.viewDidLoad()
    let path = Bundle.main.path(forResource: "xml", ofType: "plist")
    let dict = NSDictionary(contentsOfFile: path!)
    chapters = dict!.object(forKey: "Chap") as! [String]
    ansTopics = dict!.object(forKey: "Complete") as! Array<String>

}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return ansTopics.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "mainPage", for: indexPath)
    cell.textLabel?.text = ansTopics[indexPath.row]
    return cell
}

How do I get the array names as strings and pass it on to tableview elements?  Also, how do I index the topics (stored as strings) for the corresponding chapters for the second table view?
Currently, the ansTopics returns a signal SIGABERT error.

A: The problem is that your key Complete contains Dictionary not the Array of String. So ansTopics should be declare as [String: Any].
ansTopics = dict!.object(forKey: "Complete") as! [String: Any] //or Dictionary<String, Any>

It is batter if you use if let or guard to get value from Dictionary instead of force wrapping it.
if let dict = NSDictionary(contentsOfFile: path!), let arrays = dict.object(forKey: "Complete") as? [String: Any] {
    ansTopics = arrays
}

Edit: You need to declare one instance property of type array of string name chapter and initialized it with keys of dictionary and later use that array with your tableview.
var ansTopics = [String:Any]()
var chapters = [String]()

Now initialized chapters like this way.
if let dict = NSDictionary(contentsOfFile: path!), let arrays = dict.object(forKey: "Complete") as? [String: Any] {
    self.ansTopics = arrays
    self.chapters = self.ansTopics.keys.sorted()
}


text:
Q: Add Custom User Field (Dropdown) in Moodle Hi I need to add Custom User Field (Dropdown) in Moodle. I know I can add it through https://docs.moodle.org/24/en/User_profile_fields and https://docs.moodle.org/dev/User_profile_fields
I went ahead with above method and added dropdown accordingly. However, when I see it in database, {user_info_field} it shows only one row with my select fields seperated by new line. Screenshot is listed.

I want these params to be appear in separate rows. Because, I've few development in pipeline which involves creation of custom invoicing plugin that allows to store pricing for each university.

A: That is how dropdown fields store their options in Moodle - all the values, separated by newlines.
If you want a list of possible values, retrieve  mdl_user_info_field.param1 then use explode("\n", $fieldvalue).

A: I Used in built cohort system to categorized users in different University.  Here I didn't have to create custom profile field.
For invoicing plugin, I will manipulate same cohorts (in my case University) by creating local plugin which adds tables to database field. Thank you all for your help.


text:
Q: data not written in CSV stored in s3 I am using Python boto3 to create and upload a csv file as follows
s3 = boto3.client('s3')
    with open('/tmp/test.csv', mode='w') as csv_file:
        fieldnames = ['emp_name', 'dept', 'birth_month']
        writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerow({'emp_name': 'John Smith', 'dept': 'Accounting', 'birth_month': 'November'})
        writer.writerow({'emp_name': 'Erica Meyers', 'dept': 'IT', 'birth_month': 'March'})
        response = s3.upload_file('/tmp/test.csv', 'my-bucket', 'test.csv')

This creates a file test.csv in the S3 bucket but its empty. There are no errors, any idea?

A: I'll suggest you to use smart-open instead of s3.upload_file. It will help you with simple files operations.
In your case you can easily do:
from smart_open import open
import boto3

s3_session = boto3.Session()

with open('s3://my-bucket/my-folder/my_file_name.csv', 'w',
          transport_params={'session': s3_session}) as fout:
    fout.write('my,row,1\n')
    fout.write('my,row,2\n')

It also support some compression format, simply specifing the extension desidered (.gz for example), you'll not think about compression/encoding ecc


text:
Q: Mariadb 10.3 on debian segfaults Somehow my mariadb-server crashed. Since then it just segfaults. I tried innodb_force_recovery all the way up to 6, nothing changed. The errorlog is really not helpful. Any idea what i could try?
Im using Debian 10 with mariadb 10.3.27-0+deb10u1
2021-05-07 16:06:12 0 [Note] InnoDB: Using Linux native AIO
2021-05-07 16:06:12 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2021-05-07 16:06:12 0 [Note] InnoDB: Uses event mutexes
2021-05-07 16:06:12 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
2021-05-07 16:06:12 0 [Note] InnoDB: Number of pools: 1
2021-05-07 16:06:12 0 [Note] InnoDB: Using SSE2 crc32 instructions
2021-05-07 16:06:12 0 [Note] InnoDB: Disabling background log and ibuf IO write threads.
2021-05-07 16:06:12 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
2021-05-07 16:06:12 0 [Note] InnoDB: Completed initialization of buffer pool
2021-05-07 16:06:12 0 [Note] InnoDB: innodb_force_recovery=6 skips redo log apply
210507 16:06:12 [ERROR] mysqld got signal 11 ;
...

Thread pointer: 0x0
Attempting backtrace. You can use the following information to find out
where mysqld died. If you see no messages after this, something went
terribly wrong...
stack_bottom = 0x0 thread_stack 0x49000
/usr/sbin/mysqld(my_print_stacktrace+0x2e)[0x55c56d01491e]
/usr/sbin/mysqld(handle_fatal_signal+0x54d)[0x55c56cb432ed]
/lib/x86_64-linux-gnu/libpthread.so.0(+0x12730)[0x7f4186447730]
/usr/sbin/mysqld(+0x980aba)[0x55c56cd23aba]
/usr/sbin/mysqld(+0xa4d668)[0x55c56cdf0668]
/usr/sbin/mysqld(+0xa525ca)[0x55c56cdf55ca]
/usr/sbin/mysqld(+0xa52644)[0x55c56cdf5644]
/usr/sbin/mysqld(+0xaa1db2)[0x55c56ce44db2]
/usr/sbin/mysqld(+0xaa2cba)[0x55c56ce45cba]
/usr/sbin/mysqld(+0xa86491)[0x55c56ce29491]
/usr/sbin/mysqld(+0x4ddaf3)[0x55c56c880af3]
/usr/sbin/mysqld(+0x9111e4)[0x55c56ccb41e4]
/usr/sbin/mysqld(_Z24ha_initialize_handlertonP13st_plugin_int+0x68)[0x55c56cb459d8]
/usr/sbin/mysqld(+0x5dbf69)[0x55c56c97ef69]
/usr/sbin/mysqld(_Z11plugin_initPiPPci+0x98a)[0x55c56c9800ea]
/usr/sbin/mysqld(+0x51cb55)[0x55c56c8bfb55]
/usr/sbin/mysqld(_Z11mysqld_mainiPPc+0x3f9)[0x55c56c8c67c9]
csu/libc-start.c:342(__libc_start_main)[0x7f41859f109b]
/usr/sbin/mysqld(_start+0x2a)[0x55c56c8b9c8a]
The manual page at https://mariadb.com/kb/en/how-to-produce-a-full-stack-trace-for-mysqld/ contains
information that should help you find out what is causing the crash.
Writing a core file...
Working directory at /var/lib/mysql
Resource Limits:
...

This is my my.cnf
[mysqld]
general_log=1
innodb_force_recovery = 6
log_warnings=6
log_error = /var/log/mysql/error.log
general_log_file = /var/log/mysql/general.log
innodb_file_per_table=1
character_set_server = utf8mb4

EDIT: I reinstalled mariadb using apt, deleted any config except the my.cnf before that. Changed nothing. When i copy the datadir to a fresh install with just mariadb, mariadb segfaults on the new machine too.


text:
Q: Using npgsql with CockroachDB and .Net Core I successfully used npgsql (Npgsql.EntityFrameworkCore.PostgreSQL) to connect to PostgreSQL database. I have heard that same EF provider works well with CockroachDB. I am trying with it but need help to define connection string for CockroachDB. For PostgreSQL I have used following connection string:
optionsBuilder.UseNpgsql(@"Host=localhost;Database=<database>;Username=postgres;Password=<password>");

Does anybody know what should a connection string look like if I wish to connect it to CockroachDB?

A: The connection string you mentioned is almost correct, you just need to add Port=26257 as CockroachDB runs on a dedicated port.
If the Cockroach nodes are running securely, you'll also need to specify the Security and Encryption parameters.
You can find sample code to use npgsql to talk to CockroachDB in the docs, including the important "retry logic" section.


text:
Q: Comparing Points of graph to a line in chart vb.net I have a chart which contains a graph and line as reference. I want to test if there's 9 consecutive points are on the same side with respect to the reference in other words if they have greater or smaller value y of the line.So i tried to make a compare y-values of points with y-value of my reference line by using the function Findbyvalue but that didn't give me any result this is my code:
Any ideas; thank you in advance
     Dim index As Integer = 0
    'Find first point with a Y1 value of 13.
    Dim dataPoint As DataPoint = Chart1.Series("Rend").Points.FindByValue(13, "Y1", index)
    While Not (dataPoint Is Nothing)
        dataPoint.Color = Color.FromArgb(255, 128, 128)
        'Find all other data points with a second Y1 value 10.
        index += 1
        dataPoint = Chart1.Series("Rend").Points.FindByValue(13, "Y1", index)
          If index = 8 Then
            Exit While
          End If
    End While

A: I found the solution which is too simple : copy the Yvalues of the graph to an array and then make any test you want on the array.
 Dim yArray(Chart1.Series("Rend").Points.Count) As Double
    Dim temp() As Double
    For i = 0 To Chart1.Series("Rend").Points.Count - 1
        temp = Chart1.Series("Rend").Points(i).YValues
        yArray(i) = temp(0)
    Next


text:
Q: MySql attach multiply group to user I got a users table and movies table, each user could watch more then one movie.
Now I want to find all the users who watched particular movie,
How should my tables looks like in MySql?

A: To do this, you need 3 tables. The first two are users and movies, they would, in a very basic form, look like this:
user
  id
  name

movie
  id
  title

Since many users can watch many movies and the same movie can be watched by multiple users, there's a many-to-many relationship there. To define such a relationship in MySQL, you need a third table called a join table, that knows which user watched which movie (I called this user_movies but you might want to go with a different name):
user_movies
  user_id
  movie_id

To know who watched a movie called Spaceballs, you need a query like this:
SELECT u.name FROM user u
  JOIN user_movies um ON um.user_id = u.id
  JOIN movie m ON um.movie_id = m.id
    WHERE m.title = 'Spaceballs'