text:
Q: Selenium Marionette driver UnreachableBrowserException upon second launch I'm currently playing around with the Selenium Marionette WebDriver. In my application, I want to open multiple Marionette drivers sequentially. Basically something like this:
MarionetteDriver driver = new MarionetteDriver();
// do some stuff
driver.quit();

// a while later

driver = new MarionetteDriver();
// do some stuff
driver.quit();

Now I'm facing the problem, that only the first Marionette instance can be successfully started and for each later attempt, I'm getting the following exception. The problem happens every time and the used port always changes, so there is obviously no port conflict.
Exception in thread "main" org.openqa.selenium.remote.UnreachableBrowserException: Could not start a new session. Possible causes are invalid address of the remote server or browser start-up failure.
Build info: version: '2.48.2', revision: '41bccdd10cf2c0560f637404c2d96164b67d9d67', time: '2015-10-09 13:08:06'
System info: host: 'qqilihq.local', ip: '192.168.1.2', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.11.2', java.version: '1.7.0_71'
Driver info: driver.version: MarionetteDriver
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:641)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:247)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:232)
    at org.openqa.selenium.firefox.MarionetteDriver.run(MarionetteDriver.java:84)
    at org.openqa.selenium.firefox.MarionetteDriver.<init>(MarionetteDriver.java:73)
    at org.openqa.selenium.firefox.MarionetteDriver.<init>(MarionetteDriver.java:45)
    at MyMainClass.main(MyMainClass.java:131)
Caused by: org.openqa.selenium.WebDriverException: org.apache.http.conn.HttpHostConnectException: Connect to localhost:41886 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused
Build info: version: '2.48.2', revision: '41bccdd10cf2c0560f637404c2d96164b67d9d67', time: '2015-10-09 13:08:06'
System info: host: 'qqilihq.local', ip: '192.168.1.2', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.11.2', java.version: '1.7.0_71'
Driver info: driver.version: MarionetteDriver
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:91)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:620)
    ... 6 more
Caused by: org.apache.http.conn.HttpHostConnectException: Connect to localhost:41886 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused
    at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:151)
    at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:353)
    at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:380)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184)
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88)
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:71)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:55)
    at org.openqa.selenium.remote.internal.ApacheHttpClient.fallBackExecute(ApacheHttpClient.java:143)
    at org.openqa.selenium.remote.internal.ApacheHttpClient.execute(ApacheHttpClient.java:89)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:142)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:82)
    ... 7 more
Caused by: java.net.ConnectException: Connection refused
    at java.net.PlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:579)
    at org.apache.http.conn.socket.PlainConnectionSocketFactory.connectSocket(PlainConnectionSocketFactory.java:74)
    at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.    java:134)
    ... 20 more

Any pointers appreciated!

A: After digging a little deeper, I came to the following findings which eventually solved my issue:

*

*Marionette resp. wires uses two ports (see wires --help); a marionette-port and a webdriver-port:
Usage:
    ./wires [OPTIONS]

WebDriver to marionette proxy.

optional arguments:
  -h,--help             show this help message and exit
  -b,--binary BINARY    Path to the Firefox binary
  --webdriver-host WEBDRIVER_HOST
                        Host to run webdriver server on
  --webdriver-port WEBDRIVER_PORT
                        Port to run webdriver on
  --marionette-port MARIONETTE_PORT
                        Port to run marionette on
  --connect-existing    Connect to an existing firefox process

When running multiple MarionetteDrivers simultaneously, both ports have to be different from the already running instance obviously. However, when using the default constructor new MarionetteDriver() the marionette-port remains constant (and is not determined based on some free port). We used some workaround (see below) for the GeckoDriverService.Builder to always pick two randomly-chosen available ports.

*The current (version 2.48.2) GeckoDriverService has an empty implementation of waitUntilAvailable() (which should check, if the WebDriver is ready to go). Sporadically, this lead to the UnreachableBrowserException posted above.
To circumvent these issues, we did something like this at the end:
// determine free ports for Marionette and WebDriver
final int marionettePort = PortProber.findFreePort();
final int webDriverPort = PortProber.findFreePort();
// override, as GeckoDriverService provides no direct way to set the Marionette port
GeckoDriverService.Builder builder = new GeckoDriverService.Builder() {
    @Override
    protected ImmutableList<String> createArgs() {
        Builder<String> argsBuilder = ImmutableList.builder();
        argsBuilder.addAll(super.createArgs());
        argsBuilder.add(String.format("--marionette-port=%d", marionettePort));
        return argsBuilder.build();
    }
};
builder.usingPort(webDriverPort);
builder.usingDriverExecutable(pathToDriver);
GeckoDriverService driverService = builder.build();
try {
    driverService.start();
} catch (IOException e) {
    throw new IllegalStateException("Could not start the GeckoDriverService", e);
}
try {
    // keep checking the WebDriver port via Socket until it's available;
    // as far as I could tell, there is nothing more "high level", e.g. REST API
    waitUntilReady(webDriverPort, TimeUnit.SECONDS.toMillis(30));
} catch (InterruptedException e) {
    // ignore
}
return new MarionetteDriver(driverService, capabilities);

A: You need to handle the binary required by Marionette. You can do it by hand (download the binary on your own and export the proper variable), or you can do it automatically using WebDriverManager. Simply add the following dependency:
<dependency>
   <groupId>io.github.bonigarcia</groupId>
   <artifactId>webdrivermanager</artifactId>
    <version>1.6.0</version>
</dependency>

And then, in your code call to:
FirefoxDriverManager.getInstance().setup();

A: Mostly UnreachableBrowserException happens when Selenium couldn't find the required exe of the driver. Since you haven't put driver capabilities setup, I am assuming the following steps will solve your issue.
As per Mozilla MDN link Marionette is set as a DesiredCapability
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
// Set Marionette on so the Grid will use this instead of normal FirefoxDriver
capabilities.setCapability("marionette", true);

WebDriver driver = new RemoteWebDriver(capabilities);

Also, Marionette executable is added to the path (In Windows):

Adding the executable to the PATH
Selenium will try use the executable in the path. You will need to add it to the path using the following.

Finally, another SO question where UnreachableBrowserException issue is handled.

A: I had similar issue, solved by creating overridden instance of MarionetteDriver with overridden builder implementation. Accepted answer is more elegant solution though. Did have much time to deep into the root cause
public static class CustomBuilder extends org.openqa.selenium.firefox.GeckoDriverService.Builder {

    @Override
    protected GeckoDriverService createDriverService(File exe, int port, ImmutableList<String> args, ImmutableMap<String, String> environment) {
        try {
            return new GeckoDriverService(exe, port, args, environment) {
                @Override
                protected void waitUntilAvailable() throws MalformedURLException {
                    logger.info("Waiting until avaliable");
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                    }
                    super.waitUntilAvailable();

                    logger.info("Finished waiting until avaliable");
                }
            };
        } catch (IOException e) {
            throw new WebDriverException(e);
        }
    }
}


text:
Q: Exporting zipped folder only with csv content 1.I am using Oracle and the idea is to use python script to export tables as zipped folder containing csv file which holds my data.
2.Additionaly: Is it possible to save this data in csv per columns. For example, I have 4 columns and all of them are stored in 1 column in csv.
see this image
This is my script:
import os
import cx_Oracle
import csv
import zipfile

connection = cx_Oracle.connect('dbconnection')
SQL = "SELECT * FROM AIR_CONDITIONS_YEARLY_MVIEW ORDER BY TIME"

filename = "sample.csv"

cursor = connection.cursor()
cursor.execute(SQL)
with open (filename, 'r') as output:
   writer = csv.writer (output)
   writer.writerow([i[0] for i in cursor.description])
   writer.writerows(cursor.fetchall())
air_zip = zipfile.ZipFile("sample.zip", 'w')
air_zip.write(filename, compress_type=zipfile.ZIP_DEFLATED)

cursor.close()
connection.close()
air_zip.close()

Code I did exports me separately both csv and zipped folder with proper csv file inside and I want to keep exporting this zipped folder only!
Both sample.zip containing sample.csv as expected and sample.csv generated at the same time.

A: There are a list of problems:

*

*The .csv file is not properly formatted (a row is seen as a single record (string) instead of a sequence of records):

*

*Looking (blindly) at the code and tools (csv.writer, cx_Oracle) documentation, it seems correct

*When noticing that the file is opened with Excel, I remembered that at some point I had a similar issue. A quick search yielded [SuperUser]: How to get Excel to interpret the comma as a default delimiter in CSV files?
. And this was the culprit (the .csv file looks fine in an online viewer / editor)

*Code "exporting" both .csv and .zip files (I don't know what export means, I assume generate - meaning that after running the code, both files are present):

*

*The way of getting around this is by deleting the .csv file after it was archived into the .zip file. Translated into code that would mean adding at the end of the current script snippet:
os.unlink(filename)

As a final observation (if one wants to be pedantic), the lines that close the cursor and the databbase could be moved just after the with block or before air_zip creation (there's no point keeping them open while archiving).

redpajama_set_name: RedPajamaStackExchange


text:
Q: approximating exponential integral for resource constrained environment What would be the best way of calculating or approximating the exponential integral function for implementing in a highly resource constrained device? I would like to try out the approximating function in C or Matlab first if possible

A: There is a C function for calculating the exponential integral function here http://www.mymathlib.com/functions/exponential_integrals.html.
I'm not sure if it meets your resource constraints, but the source has no dependencies other than math.h and float.h, which you hopefully have available on your device.


text:
Q: dataproc cluster on google cloud My understanding is that running a Dataproc cluster instead of setting up your own compute engine cluster is that it takes care of installing the storage connector (and other connectors). What else does it do for you?

A: The most significant feature of Dataproc beyond a DIY cluster is the ability to submit Jobs (Hadoop & Spark jars, Hive queries etc.) via an API, WebUI and CLI without configuring tricky network firewalls and exposing YARN to the world.
Cloud Dataproc also takes care of a lot of configuration and initialization such as setting up A shared Hive Metastore for Hive and Spark. And allows specifying Hadoop, Spark, etc. properties at boot time.
It boots a cluster in ~90s, which in my experience is faster than most cluster setups. This allows you to tear down the cluster when you are not interested and not have to wait tens of minutes to bring a new one up.
I'd encourage you to look at a more comprehensive list of features.


text:
Q: kendoUI templating type="text/x-kendo-template" required? More of an "out of curiosity question", when creating a kendoUI external (script) template, they say to use this syntax:

One of the things I dislike about this type is that the html / etc comes out all black (in Visual Studio).
I've noticed that if I change it to the more typical: type="text/html" the HTML is colorful, and at least will be able to show html structure mistakes, missing comma's/quotes, etc etc. All the usual stuff.


text:
Q: Why use "HEAD:master" instead of just "master" in a "git push origin" I am synching multiple git repositories. It's challenging; I can sync just the diffs easily, but if I want to sync changes I need to do pulls and pushes, and (sometimes) resolve the conflicts locally.
Sometimes, when I do a git push, git tells me to use:
git push origin HEAD:<name-of-remote-branch>

which usually becomes:
git push origin HEAD:master

However, this also works:
git push origin master

So what's the difference? Why do I need the HEAD: ?

A: When you run
git push origin X:Y

What happens is that you push something locally named X to the remote name Y. HEAD is an alias for whatever is currently checked out. If you currently have master checked out, then this is equivalent to
git push origin master:master

If you have a different branch checked out, you get different behavior. You do not need HEAD and I would avoid using it when pushing.
If you omit :master and just run:
git push origin master

It will use master as the default branch name on the remote, unless you have configured it differently.

A: Would this be more clearly worded as:
If you omit master: and just run:
git push origin master
It will use master as the default branch name on the local, unless you have configured it differently.


text:
Q: Ошибка в загрузке файла unity c# Всем привет, такая проблема, сделал загрузку музыки под андройд(проверял на пк все работает отлично) на андройде(redmi, miui самая новая) выбивает ошибку и в папке скачивания в андройде появляется файл название.mp3 но весит он 0кб, а должен 7.24мб
вот код скачивания:
client.DownloadFileAsync(new Uri(_url), Application.persistentDataPath + "/save" + $"/{_filename}.mp3");
(_filename - рандомные числа от 1 до 1000)
ошибка на скрине.


text:
Q: TornadoFx TabPane - Side = left and label rotate style
*

*.tab-container {
      -fx-background-color: transparent;
      -fx-rotate: 90;    }

how do convert to tornadofx? My Tab header label need to be aligned when side.Left.Please help on this

A: TornadoFX doesn't make any changes to the TabPane container, so exactly the same CSS and properties would work for a TornadoFX application. I think you meant .tab-pane instead of .tab-container though. If you want to write the same using type safe CSS, it would be:
tabPane {
    backgroundColor += Color.TRANSPARENT
    rotate = 90.deg
}


text:
Q: Create-reac- app command is not working properly and hang at a point I am trying command npx create-react-app folder name. but it stuck after saying installing react and other things.
Screenshot of the issue -

I have the latest version of node and npm.

A: Try uninstalling npm and re-install it, or try updating your node js.


text:
Q: Client and server with different Locale - fallback mechanism I have jboss server running with fr_CH locale and application client running with de_CH locale. I have two bundles - messages.properties(root) and messages_fr_CH.properties. It is strange, but while being on server side, ResourceBundle.getBundle("bundleLocation", new Locale("de","CH")) returns bundle for fr_CH locale instead of root bundle.
Only thing I could think of is that on server side Locale.getDefault() is "fr_CH", but if I get it right, due to concept of graceful degradation standard java fallback mechanism should not care about it...
any other thoughts what the problem might be?
Thanks,
Jan

A: You are correct, this behaviour is because of default locale. Look at javadoc ResourceBundle.getBundle:

getBundle uses the base name, the specified locale, and the default
  locale (obtained from Locale.getDefault) to generate a sequence of
  candidate bundle names. If the specified locale's language, country,
  and variant are all empty strings, then the base name is the only
  candidate bundle name. Otherwise, the following sequence is generated
  from the attribute values of the specified locale (language1,
  country1, and variant1) and of the default locale (language2,
  country2, and variant2):

baseName + "_" + language1 + "_" + country1 + "_" + variant1
baseName + "_" + language1 + "_" + country1
baseName + "_" + language1
baseName + "_" + language2 + "_" + country2 + "_" + variant2
baseName + "_" + language2 + "_" + country2
baseName + "_" + language2
baseName

So your case is baseName + "_" + language2 + "_" + country2


text:
Q: How to access Azure IOT HUB data at AWS side I have a vendor that publishes the sensor data on Azure IOT HUB, we want to access this data from our application which is deployed on AWS. Is there any possibility we use some data share service OR a gateway service that helps to access the data from Azure IOT HUB to AWS side?

A: As @user565 mentions, for near real-time, you can use directly the IoT Hub compatible EventHub endpoint (Built-in endpoint) or you can use routing to forward the messages to an Storage Account, Event Grid, or other Event Hub.
Using a full featured Event Hub allows you to use Kafka client applications / libraries to read from. Check Use Azure Event Hubs from Apache Kafka Applications


text:
Q: Best Microcontroller for .net? What is the Best Microcontroller for .net ?
(best = popular, good value, has many I/0, able to get support)

A: The porting kit for the .NET Micro Framework directly supports AT91, BF537, Cortex-M3, LPC22XX, LPC24XX, MC9328, PXA271 and SH2.  Get the data-sheets from their manufacturers to see what you like.


text:
Q: Proper formatting of Command Substitution I am trying to add the currently playing song if there is one to my ZSH prompt. I'm using a JXA command osascript -l JavaScript -e "Application('Music').currentTrack.name()". I am trying to assign it to a variable. and then echo that command.
precmd() {
  SONG=$( echo -e osascript -l JavaScript -e "Application('Music').currentTrack.name()" )
  LEFT=echo $SONG
  RIGHT="$(dracula_time_segment) $(battery_pct_prompt)"
  RIGHTWIDTH=$(($COLUMNS-${#LEFT}))
}

I've tried a number of variations eg: echo inside and outside the expression and various flags.

A: You don't need echo at all, as demonstrated by your later command substitutions when setting RIGHT; command substitution just takes a command and executes it.
SONG=$(osascript -l JavaScript -e "Application('Music').currentTrack.name()")
LEFT="$SONG"

You could combine the previous two commands; SONG isn't needed.
LEFT=$(osascript ...)


text:
Q: Uniform convergence and Riemann integral; from compact $0I want to know an idea about how to start with this problem:
Let be $g, f_n, \forall n \in \mathbb{N}$ well-defined functions in $(0, \infty)$, and Riemann integrable in every compact subset $[t, T]$ where $0 < t < T < \infty$. In addition, $f_n$ converges uniformly to a function $f$ and $|f_n| \leq g$ in every compact subset of $[0, \infty]$. If we have that:
$\int_0^{\infty}g(x)dx < \infty$
Proove that $\lim_{n \rightarrow \infty} \int_0^{\infty}f_n(x)dx = \int_0^{\infty}f(x)dx$
I am supposed to solve this problem without using directly any theorem about Measure Theory (like the Dominated Convergence Theorem, which has similarities with this exercise), only using facts about convergence of functions.
My problem is that I can't find a way to start. I know that if $f_n$ are Riemann integrable in a certain subset and they converge uniformly to a function $f$ in t his subset then f is Riemann integrable in this subset and I can put the limit inside or outside the integral. The problem is that I know it for every interval $[t,T]$ but they are talking about $(0, \infty)$, and this generalization is non-trivial and here the function $g$ has to help me but I don't know how to use the bound that they give me.
Thanks :)

A: Consider the difference $\int f_n(x)dx-\int f(x)$. You want to try and make a claim that $|f_n(x)-f(x)|<\epsilon$ for all $x$ when $n$ is big enough but you don't quite have this. Instead, use the fact that $g$ is integrable. This means that $\int_c^\infty g(x)dx$ can be made arbitrarely small as $c$ goes to infinity. So now write:
$$\left|\int_0^\infty f_n(x)dx-\int_0^\infty f(x)dx\right|\leq \int_0^c|f_n(x)-f(x)|dx+2\int_c^\infty g(x)dx$$
where you can now use the fact that $|f_n(x)-f(x)|<\epsilon$ on $[0,c]$ for large enough $n$.


text:
Q: Connection already closed I'm using Grails 2.5.3 and Tomcat7 and after 8 hours of app deployment our logs start blowing up with connection already closed issues. A good assumption is that MySql is killing the connection after the default wait time of 8 hrs.
By way of the docs my pool seems to be configured correctly to keep the idle connections open but it doesn't seem to be the case.
What might be wrong with my connection pool setting?
dataSource {
  pooled = true
  url = 'jdbc:mysql://******.**********.us-east-1.rds.amazonaws.com/*****'
  driverClassName = 'com.mysql.jdbc.Driver'
  username = '********'
  password = '******************'
  dialect = org.hibernate.dialect.MySQL5InnoDBDialect
  loggingSql = false
  properties {
    jmxEnabled = true
    initialSize = 5
    timeBetweenEvictionRunsMillis = 10000
    minEvictableIdleTimeMillis = 60000
    validationQuery = "SELECT 1"
    initSQL = "SELECT 1"
    validationQueryTimeout = 10
    testOnBorrow = true
    testWhileIdle = true
    testOnReturn = true
    testOnConnect = true
    removeAbandonedTimeout = 300
    maxActive=100
    maxIdle=10
    minIdle=1
    maxWait=30000
    maxAge=900000
    removeAbandoned="true"
    jdbcInterceptors="org.apache.tomcat.jdbc.pool.interceptor.StatementCache;"

  }
}

hibernate {
  cache.use_second_level_cache=true
  cache.use_query_cache=true
  cache.region.factory_class = 'org.hibernate.cache.ehcache.EhCacheRegionFactory'
}

Also, I have confirmed that the dataSource at runtime is an instance of  (org.apache.tomcat.jdbc.pool.DataSource)
UPDATE 1 (NOT FIXED)
We think we may have found the problem! We were storing a domain class in the http session and after reading a bit about how the session factory works we believe that the stored http object was somehow bound to a connection.  When a user accessed the domain class form the http session after 8 hours we think that hibernate stored a reference to the dead connection.  It's in production now and we are monitoring.
UPDATE 2 (FIXED)
We finally found the problem.  Removing removeAbandoned and removeAbandonedTimeout resolved all our problems.  We're not entirely sure why this resolved the issue as our assumption was that these two properties exist to prevent exactly what was occurring. The only thought is that our database was more aggressively managing the abandoned connections. It's been over 4 weeks with no issues.

A: I've had this issue with a completely different setup.  It's really not fun to deal with.  Basically it boils down to this:

*

*You have some connection somewhere in your application just sitting around while Java is doing some sort of "other" processing.  Here's a really basic way to reproduce:
Connection con = (get connection from pool);
Sleep(330 seconds);
con.close();

*The code is not doing anything with the database connection above, so tomcat detects it as abandoned and returns it to the pool at 300 seconds.

*Your application is high traffic enough that the same connection (both opened and abandoned in the above code) is opened somewhere else in the application in a different part of code.

*Either the original code hits 330 seconds and closes the connection, or the new code picks up the connection and finished and closes it.  At this point there are two places using the same connection and one of them has closed it.

*The other location of code using the same connection then tries to either use or close the same connection

*The connection is already closed.  Producing the above error.
Suggested route to fix:
Use the setting logAbandoned="true" to find where the connections are being abandoned from.

A: Our url usually looks alike:
url = "jdbc:mysql://localhost/db?useUnicode=yes&characterEncoding=UTF-8&autoReconnect=true"

Check out also encoding params if you don't want to face such an issue.

A: (see update 2 on question)
Removing removeAbandoned and removeAbandonedTimeout resolved all our problems.  Someone may want to provide a more detailed answer on why this did because we are not entirely sure.


text:
Q: Comparison of innerHTML with JQuery I am trying to change
 background according to its contact (innerHTML) but I cant get it to work.

just a test number1

just a test number2

just a test

<button>Execute</button>

I expected only the last
 background to change but nothing happens, why is that?

A: There is no innerHTML property on a jQuery object, so $("p").innerHTML === "just a test" will always be false.
You could use .html() instead, but that would always return the data from first element that matched the selector, so it would still always be false.
Even if that wasn't the case, $("p").css("background","yellow"); would set the background of all the paragraphs.

You need to loop over all the elements and test each one in turn.

$(document).ready(function() {
  $("button").click(function() {
    $("p").each(function(index, paragraph) {
      var $p = $(paragraph);
      if ($p.html() === "just a test") {
        $p.css("background", "yellow");
      }
    });
  });
});

just a test number1

just a test number2

just a test

<button>Execute</button>

A: InnerHtml is a JavaScript property, it does not belong in jQuery.
You need to change this:
 $("p").innerHTML === "just a test"

to this:
 $("p").html() === "just a test"

Secondly selector p is quite big, expecially that you are not calling it form any element, but in global scope. I would advise to use some sort of class or id, if it is possiblem.
Thirdly I would go with such fix to your algoritm:
$("p").each(function(){
   var el = $(this);
   if(el.htlm() === 'just a test'){ // could change for regexp (bevare of white characters)
      el.css("background","yellow")
   }
});

This way for every p element that inner html is 'just a test' you will change background color.


text:
Q: How to execute linux command of helm using ansible modules? I'm running this command:
- name: Save to tmp/charts
  shell: '{{helm_cli_path}}/helm --kubeconfig {{kube_config}} install {{install-name}} {{helm_chart}}/ --dry-run --debug > {{charts_dir}}/{{install_name}}.yaml'

to store helm gerenated yamls using shell module for all helm charts, which is a generalization of this command:
helm1 install <chart-name> <chart-path> --dry-run --debug > tmp/<chart-name>.yaml

But I'm getting error:

fatal: [console.sb]: FAILED! => {"msg": "The task includes an option
with an undefined variable. The error was: Unable to look up a name or
access an attribute in template string ({{helm_cli_path}}/helm
--kubeconfig {{kube_config}} install {{install-name}} {{helm_chart}}/ --dry-run --debug > {{charts_dir}}/{{install_name}}.yaml).\nMake sure your variable name does not contain invalid characters like '-':
unsupported operand type(s) for -:

I have made sure that all variables in {{ }} are correct and defined at correct places.
Please suggest me the correct yaml task description / suitable ansible module to be used here.


text:
Q: How to Compare Two Tables by value I need to compare these tables. First compare by value and make the difference. Second if not exist so show not exist. If you see the image attached. In second table there is two persons with same info but different age, and in first table there is one person with same info like in second table. I need to show not exist in first table. I need result to look like image attached

    const firstArr = [
        { partNo: '1',name: 'Per', age: '35'},
        { partNo: '3',name: 'Tom', age: '27'},
        {partNo: '6', name: 'Alex',age: '18'}
    ]
    const secondArr = [
        { partNo: '1', name: 'Per', age: '33'},
        { partNo: '3', name: 'Tom', age: '27'},
        { partNo: '6', name: 'Alex', age: '18'},
        { partNo: '6',  name: 'Alex', age: '22'}
    ]

let table1 = `<table><tr><th>PartNo</th><th>Name</th><th>Age</th></tr>`
let table2 = `<table><tr><th>PartNo</th><th>Name</th><th>Age</th></tr>`

for (let i = 0; i < firstArr.length; i++) {
for (let j = 0; j < secondArr.length; j++) {
    table1 += `<tr><td>${firstArr[i].partNo}</td><td>${firstArr[i].name}</td><td>${firstArr[i].age}</td></tr>`
    table2 +=  `<tr><td>${secondArr[j].partNo}</td><td>${secondArr[j].name}</td><td>${secondArr[j].age}</td></tr>`
}
}
table1 += `</table>`
table2 += `</table>`
document.getElementById('firstTable').innerHTML = table1
document.getElementById('secondTable').innerHTML = table2

''''''''

A: What is happening is that your loop for the second array is within the first one

You can use forEach  it will get less messy

const firstArr = [{
    partNo: '1',
    name: 'Per',
    age: '35'
  },
  {
    partNo: '3',
    name: 'Tom',
    age: '27'
  },
  {
    partNo: '6',
    name: 'Alex',
    age: '18'
  }
]
const secondArr = [{
    partNo: '1',
    name: 'Per',
    age: '33'
  },
  {
    partNo: '3',
    name: 'Tom',
    age: '27'
  },
  {
    partNo: '6',
    name: 'Alex',
    age: '18'
  },
  {
    partNo: '6',
    name: 'Alex',
    age: '22'
  }
]

let table1 = `<table><tr><th>PartNo</th><th>Name</th><th>Age</th></tr>`
let table2 = `<table><tr><th>PartNo</th><th>Name</th><th>Age</th></tr>`

firstArr.forEach(element => table1 += `<tr><td>${element.partNo}</td><td>${element.name}</td><td>${element.age}</td></tr>`);

secondArr.forEach(element => table2 += `<tr><td>${element.partNo}</td><td>${element.name}</td><td>${element.age}</td></tr>`);

table1 += `</table>`
table2 += `</table>`
document.getElementById('firstTable').innerHTML = table1
document.getElementById('secondTable').innerHTML = table2

''''''''

Or if you still want to use a for loop you can simply get your loop out of the second one

const firstArr = [{
    partNo: '1',
    name: 'Per',
    age: '35'
  },
  {
    partNo: '3',
    name: 'Tom',
    age: '27'
  },
  {
    partNo: '6',
    name: 'Alex',
    age: '18'
  }
]
const secondArr = [{
    partNo: '1',
    name: 'Per',
    age: '33'
  },
  {
    partNo: '3',
    name: 'Tom',
    age: '27'
  },
  {
    partNo: '6',
    name: 'Alex',
    age: '18'
  },
  {
    partNo: '6',
    name: 'Alex',
    age: '22'
  }
]

let table1 = `<table><tr><th>PartNo</th><th>Name</th><th>Age</th></tr>`
let table2 = `<table><tr><th>PartNo</th><th>Name</th><th>Age</th></tr>`

for (let i = 0; i < firstArr.length; i++) {
  table1 += `<tr><td>${firstArr[i].partNo}</td><td>${firstArr[i].name}</td><td>${firstArr[i].age}</td></tr>`

}
for (let j = 0; j < secondArr.length; j++) {
  table2 += `<tr><td>${secondArr[j].partNo}</td><td>${secondArr[j].name}</td><td>${secondArr[j].age}</td></tr>`
}

table1 += `</table>`
table2 += `</table>`
document.getElementById('firstTable').innerHTML = table1
document.getElementById('secondTable').innerHTML = table2

''''''''


text:
Q: jquery does not work in my code <?php while(the condition here) {
$honeyid = $row['id'];
?>
    <form action="<?=$website_url;?>/writecomment.php" name="writecomment" method="post" id="writecomment<?php echo $honeyid; ?>">
    <fieldset style="margin:3px; padding:3px; <?php if( $loggedin == "yes" ) { ?>width:410px;<?php } else { ?>width:360px;<?php } ?> background-color:#EEEEEE; border:1px solid #EEEEEE;">
    <?php if( $loggedin == "yes" ) { ?><section_write style="float:left; padding:0px 3px; margin:0px 3px;">
    <?php
                    $users2 = mysqli_query($con, "SELECT avatar, fullname FROM users WHERE username = '$_SESSION[username]'");
                    $user2 = mysqli_fetch_array($users2);
                        if (strlen($user2['avatar']) == 0) {
                            $img = 'http://placeimg.com/90/90/nature';
                        } else {
                            $img = $website_url . '/assets/img/avatars/'. $user2['avatar'];
                        }
                    ?>
    <a href="<?=$website_url;?>/user/<?php echo urlencode($_SESSION['username']); ?>">
    <img src="<?= $img; ?>" width="30px" height="35px" title="<?= $user2['fullname']; ?>" border="0" />

    </section_write><?php } ?>
    <textarea style="width:350px;height:23px" name="contectcomment" id="contectcomment<?php echo $honeyid; ?>"></textarea>

    <?php if( $loggedin == "yes" ) { ?><input type="checkbox" value="1" id="commentanonim<?php echo $honeyid; ?>" name="commentanonim" checked="checked" style="margin:3px; padding:3px;" /><label for="commentanonim<?php echo $honeyid; ?>">Anonymously   <?php } ?><input type="submit" value=" Comment "  class="comment_submit" name="dergokomentin" id="dergokomentin<?php echo $honeyid; ?>" /><input type="hidden" name="tbhidkoment" value="<?php echo $honeyid; ?>" />
    </fieldset>
    </form>

<?php } ?>

Ok, this is my code. I am trying to make a comment system and what I want to achieve is, when the user clicks the button "Comment", I want to clean the textarea and load the other page as it is written in the code. But it doesn't work! I have been working on this for 4 hours and still no clue. Any idea why this does not work?
Thanks


text:
Q: Translating address label issue in Magento 1 This is my string, which I would love to translate:
<input type="text" placeholder="<?php echo $this->__('Street Address %s', $_i); ?>" title="<?php echo $this->quoteEscape($this->__('Street Address %s', $_i)) ?>" name="billing[street][]" id="billing:street<?php echo $_i ?>" value="<?php echo $this->escapeHtml($this->getAddress()->getStreet($_i)) ?>" class="input-text <?php echo $_streetValidationClass ?>" />

These are my tries from my theme csv file:
"Mage_Customer::Street Address 1","RUE"
"Mage_Customer::Street Address 2","Numéro"
"Mage_Customer::Street Address 3","Boîte"
"Mage_Customer::Street Address 4","Addition"
"Mage_Checkout::Street Address","RUE"
"Mage_Checkout::Street Address 2","Numéro"
"Mage_Checkout::Street Address 3","Boîte"
"Mage_Checkout::Street Address 4","Addition"
"Street Address","RUE"
"Street Address 2","Numéro"
"Street Address 3","Boîte"
"Street Address 4","Addition"

"Street Address %s","RUE"

Interesting about using the last one. It translates me all of the address labels into RUE. Inline translations were not used. The core_translate table is empty. Any other idea how should I translate my strings ?
Thank you

A: Use this
"Street Address 1","RUE"
"Street Address 2","Numéro"
"Street Address 3","Boîte"
"Street Address 4","Addition"

You'd update your code to this then:
<?php echo $this->__('Street Address ' . $_i); ?>


text:
Q: How to deal with serialization and deserialization of objects with dependencies Suppose I have two objects that depend on each other or other objects(so use references to these objects) and I need to save/restore their "state" from/to disk. Since storing pointers to disk does not produce correct results on restore, how do we keep the dependencies correct on restore?
e.g.,
class A {
   B b;
}

class B {
{
   A a;
}

(or more complex chains that may have n-cycles of dependencies)
A a = deserialize(Adata)
B b = deserialize(Bdata)
(and suppose we need a.b = b and b.a = a)
I'm thinking that having unique hashes for objects with lazy evaluation would solve the problem but maybe there are better ways? (if I have a unique hash then it is easy to find the object to use and also to save and restore the object(basically the hash acts as a pointer but is always valid(since it is unique and never changes))


text:
Q: How to capture network traffic application wise using winpcap? I have to make a windows based application for which captures network traffic per application where some of running application uses same port number for sending and receiving the packets.
     I have used winpcap and successfully captured and filtered them port wise and destination wise but I dont know how to capture them application wise that means how to know application information from ip packets.
     Is only winpcap can solve the problem or some other api's or library shoud be used.
     Can we get the application information from which packet is generated from packet header?
 **

Can anyone give me example that uses iphlpapi and winpcap in vc++ for capturing network traffic per application.
**

A: I don't think this is possible with winpcap.
Take a look at Windows Filtering Platform. It's not advanced at all.If you look in the samples you can find one which does exactly what you want.

A: winpcap doesn't have a good way to tell what process is sending what data.
But windows does.
try using
netstat -a -o

netstat is a program that tells you what ports are being used on your terminal.
-a switch says, "show me all the ports"
-o switch says, "show me the pid of the processes using this port"
you can't see what port your processes are sending on, but you can see what ports are receving on for udp packets.
for tcp packets you'll see all the info you could want, includeing the remote connections ip address.


text:
Q: Wordpress Functions Switching From DAP to WooCommerce I have come across an issue past my level of expertise and am hoping for some help.  I am switching my subscription portal on Wordpress from DAP to WooCommerce and have an issue with a section of php in the template.  I have included the part in question.  Basically I need to change the DAP user and session calls to call up the WooCommerce user and session.
Any help would be appreciated. Below is part of the code in question. Thanks in advance.
        <?php $session = Dap_Session::getSession();
            $user = $session->getUser();
            $userProducts = Dap_UsersProducts::loadProducts($user->getId()); ?>

Training Programs

                <?php if ( Dap_Session::isLoggedIn() ) {
                        //get userid
                        $session = Dap_Session::getSession();
                        $user = $session->getUser();
                        $user = Dap_User::loadUserById($user->getId());


text:
Q: Проблема с рекурсивным методом Суть задачи состоит в том чтобы убрать из массива строк соседние элементы указывающие в противоположных направлениях (South-North, East-West), и это исключение должно повторяться пока не останется таких пар.
 Проблема в том что программа при вводных данных ["NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"], должна вывести ["WEST"], но в последнем шаге после проверки if что-то происходит и к уже готовому массиву добавляется 2 пустых значения в начале и вывод становится ["","","WEST"]. Хотя в отладчике до последнего момента все как надо. Почему так происходит?
public class Test{
public static void main(String[] args) {
    Task task = new Task();
    System.out.println(Arrays.toString(task.dirReduc(new String[]{"NORTH", "SOUTH", "SOUTH", "EAST", "WEST", "NORTH", "WEST"})));
   }
}

class Task {
public static String[] dirReduc(String[] arr) {
    char c,b;
    int count = 0;
   /*Цикл проверяет на наличие двух "противоположных" соседей и
   меняет строки на пустые в случае такого совпадения.*/
    for(int i = 0; i<arr.length-1;i++){
        c = arr[i].charAt(0);
        b = arr[i+1].charAt(0);
        if((c=='S'&&b=='N')||(c=='N'&&b=='S')) {arr[i] = ""; arr[i+1] = ""; i = i+2; count++;}
        else if((c=='W'&&b=='E')||(c=='E'&&b=='W')) {arr[i] = ""; arr[i+1] = ""; i = i+2; count++;}
    }

   /*Создается List в который происходит копирование всех не пустых строк и из него
копируется в новый массив который либо возвращается как ответ либо происходит рекурсивный вызов самого метода.*/
    List<String> list = new ArrayList<>();
    for(String y: arr) {if(y.length()>1) list.add(y);}
    String[] arr2 = list.toArray(new String[0]);

   //Если произошло изменение и длина больше 1 то повторить.
    if(count>0&&arr2.length>1){dirReduc(arr2);}

    return arr2;
}

A: if(count>0&&arr2.length>1){dirReduc(arr2);}

Не мешало бы использовать значение, возвращаемое dirReduc:
if (count > 0 && arr2.length > 1)
{
  arr2 = dirReduc(arr2);
}

A:  if (count > 0 && arr2.length > 1) {return dirReduc(arr2);}

Нужно добавить return
И  i = i+2;, for тоже инкрементирует, в итоге +3 получается


text:
Q: How can an array of 1+ elements be at the same time not true and not false? In Javascript, how can an element of 1+ elements return false if compared to a boolean?
> [1, 2] == true
< false

> [1, 2] == false
< false

I know that if the array contains only a 0 or a 1 a casting will be done and the comparison will return true if 0 is compared to false or if 1 is compared to true.


text:
Q: Are an Animagus' markings always the same? When Prof. McGonagall turns into her cat form, she has markings on her face in the shape of her glasses. But what if she wasn't wearing them at the time? Would they still show up after she transformed? If she hung them from her gown, would the mark move from her face to her chest? Or what about when she gets a new pair of glasses that don't resemble her old ones? Would the shape/color of the mark change?
Are an Animagus' markings always the same?
If any of these are true, does that mean she would have to register each possibility/new prescription?

A: Yes, they probably are - or the Ministry of Magic has made a serious oversight..
An Animagus is required to register with the Ministry, and their registration also includes notifying the Ministry of any identifiable markings their Animagus form has. There's no mention of them having to update the register if they change their markings, which a law-abiding and registered Animagus like McGonagall would do if it was required. Since registering these distinguishing markings is considered enough to keep track of the Animagus, this supports the theory, though is not conclusive proof, that these markings will not change.

"Because … because people would know if Peter Pettigrew had been an Animagus. We did Animagi in class with Professor McGonagall. And I looked them up when I did my homework – the Ministry keeps tabs on witches and wizards who can become animals; there's a register showing what animal they become, and their markings and things …" - Harry Potter and the Prisoner of Azkaban, Chapter 18 (Padfoot and Prongs)


text:
Q: How to inherit another class in the navigation drawer Fragment? I have a new android project with a navigation drawer. Now i want to add a new base class and inherit it in the navigation drawer fragment class. But it already extends Fragment. So how do I inherit the base class in the navigation drawer fragment?

A: Multiple inheritance does not exit in Java. Essentially what you have to do is make the base class inherit from Fragment and then you can extend your navigation drawer Fragment from the base class.
public class BaseFragment extends Fragment {
    ...
}

public class NavigationDrawerFragment extends BaseFragment {
    ...
}


text:
Q: google calendar api (ruby) event insert error: Missing end time I'm using a service account and attempting to insert an event into a calendar. I'm using the ruby bindings. I constantly get an error

Missing end time

even though i am sending an end time!
my insert code looks like this
event = {start: DateTime.now, end: (DateTime.now + 0.5)}
result = client.execute( api_method: calendar.events.insert,
   parameters:{calendarId: 'MYCALENDARID@group.calendar.google.com'},
   authorization: client.authorization,
   headers: { "Content-Type" => "application/json" },
   body: JSON.dump(event))

as you can tell, the event has a start and end date! based on some old SO answers i also tried:

*

*sticking the body in an array (like body: [JSON.dump(event)]) which resulted in an exception (undefined methodbytesize' for #`)

*using a body_object property instead (like body_object: event), same issue

and for reference, the setup looks like:
require 'google/api_client'
require 'google/api_client/client_secrets'
require 'google/api_client/auth/installed_app'

client = Google::APIClient.new(:application_name => 'Example Ruby application',:application_version => '1.0.0')
key = Google::APIClient::KeyUtils.load_from_pkcs12('MYKEY.p12', 'notasecret')
client.authorization = Signet::OAuth2::Client.new(
:token_credential_uri => 'https://accounts.google.com/o/oauth2/token',:audience => 'https://accounts.google.com/o/oauth2/token',:scope => 'https://www.googleapis.com/auth/calendar',
issuer: 'MYSERVICEACCOUNT@developer.gserviceaccount.com', signing_key: key)
client.authorization.fetch_access_token!
calendar = client.discovered_api('calendar', 'v3')

A: The docs (https://developers.google.com/google-apps/calendar/v3/reference/events/insert) give the following Ruby example:
event = {
  'summary' => 'Appointment',
  'location' => 'Somewhere',
  'start' => {
    'dateTime' => '2011-06-03T10:00:00.000-07:00'
  },
  'end' => {
    'dateTime' => '2011-06-03T10:25:00.000-07:00'
  },
  'attendees' => [
    {
      'email' => 'attendeeEmail'
    },
    #...
  ]
}
result = client.execute(:api_method => service.events.insert,
                        :parameters => {'calendarId' => 'primary'},
                        :body => JSON.dump(event),
                        :headers => {'Content-Type' => 'application/json'})
print result.data.id

Suggest you confirm that your code that outputs the start/end date times {start: DateTime.now, ...} is actually creating the nested {'start' => {'dateTime' => '2011-....'}, ...} that you need.
I don't know Ruby, but my guess is that {'start' => {'dateTime' => DateTime.now}, ...} will do what you need (for both start and end datetimes) .


text:
Q: How to let Handbrake recognize a VIDEO_TS folder? My Kung Fu Panda DVD movie has become scratched. It contains the following files:
BUP files:

 - VIDEO_TS.BUP *
 - VTS_01_0.BUP *
 - VTS_02_0.BUP
 - VTS_03_0.BUP

IFO files:

 - VIDEO_TS.IFO *
 - VTS_01_0.IFO *
 - VTS_02_0.IFO
 - VTS_03_0.IFO

VOB files:

 - VTS_01_0.VOB *
 - VTS_01_1.VOB *
 - VTS_01_2.VOB *
 - VTS_01_3.VOB *
 - VTS_01_4.VOB *
 - VTS_01_5.VOB *
 - VTS_02_1.VOB
 - VTS_03_1.VOB

Filenames with an asterisk can be copied without any problems; most of the other files cannot be copied. I tried CDCheck and DVDDecrypter. Since title 1 is the main movie and related files can be copied, I copied them to a folder and can run the movie from the folder using VLC Media Player.
However, I'd like to convert the DVD movie using Handbrake 0.9.4. When I choose the folder that contains the asterisk-marked files in Handbrake interface (Source > DVD/VIDEO_TS Folder), Handbrake scans the folder and shows the following error message:
---------------------------
Error
---------------------------
No Title(s) found.

Your Source may be copy protected, badly mastered
or in a format which HandBrake does not support.
Please refer to the Documentation and FAQ (see Help Menu).
---------------------------
OK
---------------------------

Clearly there is a title which Handbrake cannot find. If I could copy all files in a folder, Handbrake would not give this message. But all files cannot be copied even using CDCheck or DVDDecrypter. Are there any hacks to fool Handbrake into recognize the files?

A: according to this link handbrake is libdvdcss free in specific versions and therefore can't process protected dvds. since most dvds you can buy are protected i'm pretty sure that's your problem.
the linked text furthermore claims that handbrake automatically utilizes vlc for this job if installed.

A: Don't rename the VIDEO_TS folder, otherwise Handbrake would not recognize files in it.


text:
Q: How to implement q-learning in R? I am learning about q-learning and found a Wikipedia post and this website.
According to the tutorials and pseudo code I wrote this much in R
#q-learning example
#http://mnemstudio.org/path-finding-q-learning-tutorial.htm
#https://en.wikipedia.org/wiki/Q-learning

set.seed(2016)
iter=100
dimension=5;
alpha=0.1 #learning rate
gamma=0.8 #exploration/ discount factor

# n x n matrix
Q=matrix( rep( 0, len=dimension*dimension), nrow = dimension)
Q

# R -1 is fire pit,0 safe path and 100 Goal state########
R=matrix( sample( -1:0, dimension*dimension,replace=T,prob=c(1,2)), nrow = dimension)
R[dimension,dimension]=100
R #reward matrix
################

for(i in 1:iter){
  row=sample(1:dimension,1)
  col=sample(1:dimension,1)
  I=Q[row,col] #randomly choosing initial state

  Q[row,col]=Q[row,col]+alpha*(R[row,col]+gamma*max(Qdash-Q[row,col])
  #equation from wikipedia

}

But I have problem in max(Qdash-Q[row,col] which according to the website is Max[Q(next state, all actions)]  How to I programmatically search all actions for next state?
The second problem is this pseudo code
Do While the goal state hasn't been reached.

Select one among all possible actions for the current state.
Using this possible action, consider going to the next state.
Get maximum Q value for this next state based on all possible actions.
Compute: Q(state, action) = R(state, action) + Gamma * Max[Q(next state, all actions)]
Set the next state as the current state.
End Do

Is it this
while(Q<100){
Q[row,col]=Q[row,col]+alpha*(R[row,col]+gamma*max(Qdash-Q[row,col])
}

A: This post is by no means a complete implementation of Q-learning in R. It is an attempt to answer the OP with regards to the description of the algorithm in the website linked in the post and in Wikipedia.
The assumption here is that the reward matrix R is as described in the website. Namely that it encodes reward values for possible actions as non-negative numbers, and -1's in the matrix represent null values (i.e., where there is no possible action to transition to that state).
With this setup, an R implementation of the Q update is:
Q[cs,ns] <- Q[cs,ns] + alpha*(R[cs,ns] + gamma*max(Q[ns, which(R[ns,] > -1)]) - Q[cs,ns])

where

*

*cs is the current state at the current point in the path.

*ns is the new state based on a (randomly) chosen action at the current state. This action is chosen from the collection of possible actions at the current state (i.e., for which R[cs,] > -1). Since the state transition itself is deterministic here, the action is the transition to the new state.

*For this action resulting in ns, we want to add its maximum (future) value over all possible actions that can be taken at ns. This is the so-called Max[Q(next state, all actions)] term in the linked website and the "estimate of optimal future value" in Wikipedia. To compute this, we want to maximize over the ns-th row of Q but consider only columns of Q for which columns of R at the corresponding ns-th row are valid actions (i.e., for which R[ns,] > -1). Therefore, this is:
max(Q[ns, which(R[ns,] > -1)])

An interpretation of this value is a one-step look ahead value or an estimate of the cost-to-go in dynamic programming.

*The equation in the linked website is the special case in which alpha, the learning rate, is 1. We can view the equation in Wikipedia as:
Q[cs,ns] <- (1-alpha)*Q[cs,ns] + alpha*(R[cs,ns] + gamma*max(Q[ns, which(R[ns,] > -1)]))

where alpha "interpolates" between the old value Q[cs,ns] and the learned value R[cs,ns] + gamma*max(Q[ns, which(R[ns,] > -1)]). As noted in Wikipedia,

In fully deterministic environments, a learning rate of alpha=1 is optimal

Putting it all together into a function:
q.learn <- function(R, N, alpha, gamma, tgt.state) {
  ## initialize Q to be zero matrix, same size as R
  Q <- matrix(rep(0,length(R)), nrow=nrow(R))
  ## loop over episodes
  for (i in 1:N) {
    ## for each episode, choose an initial state at random
    cs <- sample(1:nrow(R), 1)
    ## iterate until we get to the tgt.state
    while (1) {
      ## choose next state from possible actions at current state
      ## Note: if only one possible action, then choose it;
      ## otherwise, choose one at random
      next.states <- which(R[cs,] > -1)
      if (length(next.states)==1)
        ns <- next.states
      else
        ns <- sample(next.states,1)
      ## this is the update
      Q[cs,ns] <- Q[cs,ns] + alpha*(R[cs,ns] + gamma*max(Q[ns, which(R[ns,] > -1)]) - Q[cs,ns])
      ## break out of while loop if target state is reached
      ## otherwise, set next.state as current.state and repeat
      if (ns == tgt.state) break
      cs <- ns
    }
  }
  ## return resulting Q normalized by max value
  return(100*Q/max(Q))
}

where the input parameters are:

*

*R is the rewards matrix as defined in the blog

*N is the number of episodes to iterate

*alpha is the learning rate

*gamma is the discount factor

*tgt.state is the target state of the problem.

Using the example in the linked website as a test:
N <- 1000
alpha <- 1
gamma <- 0.8
tgt.state <- 6
R <- matrix(c(-1,-1,-1,-1,0,-1,-1,-1,-1,0,-1,0,-1,-1,-1,0,-1,-1,-1,0,0,-1,0,-1,0,-1,-1,0,-1,0,-1,100,-1,-1,100,100),nrow=6)
print(R)
##     [,1] [,2] [,3] [,4] [,5] [,6]
##[1,]   -1   -1   -1   -1    0   -1
##[2,]   -1   -1   -1    0   -1  100
##[3,]   -1   -1   -1    0   -1   -1
##[4,]   -1    0    0   -1    0   -1
##[5,]    0   -1   -1    0   -1  100
##[6,]   -1    0   -1   -1    0  100

Q <- q.learn(R,iter,alpha,gamma,tgt.state)
print(Q)
##     [,1] [,2] [,3] [,4] [,5]      [,6]
##[1,]    0    0  0.0    0   80   0.00000
##[2,]    0    0  0.0   64    0 100.00000
##[3,]    0    0  0.0   64    0   0.00000
##[4,]    0   80 51.2    0   80   0.00000
##[5,]   64    0  0.0   64    0 100.00000
##[6,]    0   80  0.0    0   80  99.99994


text:
Q: CSS | Navigationlinks Padding problems I'm trying to build a new Homepage... but i got Problems with the Padding of the Navigationbar. Here is my Navigationbar:
CodePen

body {
 background: black;
 font-family: Oswald;
 font-size: 20px;
 font-weight: normal;
 line-height: 1;
 margin: 0;
 min-width: 960px;
 padding: 0;
}
a {
 text-decoration: none;
 outline: none;
}
a:active {
 background: none;
}
img {
 border: none;
}
/*-------------------------------------------Header-------------------------------------------*/
p {
 color: #252525;
 line-height: 20px;
 margin: 0;
 padding: 0;
}
p a {
 color: #252525;
 text-decoration: underline;
}
.border-right {
    border-right: 5px solid #A40900;

}
.border-left {
    border-left: 5px solid #A40900;
}
#header {
 margin: 0 auto;
 padding: 4px 0 0px;
 text-align: center;
 width: 960px;
}
#header a.logo {
 display: block;
 margin: 0 auto;
 padding: 0;
 width: 540px;
}
#header a.logo img {
 border: 0;
 display: block;
 margin: 0;
 padding: 0;
    width: 100%;
}
#header ul {
 margin: 0;
 padding: 0;
    background-color: white;
    height: 35px;
    padding-top: 2%;
    border-top: 5px solid #A40900;
    border-bottom: 5px solid #A40900;
}
#header ul li {
 display: inline-block;
 list-style: none;
 margin: 0px;
 padding: 0;
    text-align: center;
}
#header ul li a {
 color: #000;
 font-family: Oswald ExtraLight;
 font-size: 20px;
 font-weight: normal;
 margin: 0;
 padding: 0;
 text-decoration: none;
 text-transform: uppercase;
}
#header ul li a:hover, #header ul li.selected a {
 color: #0ba39c;
}
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Willkommen beim Phönix-Brandschutz</title>
    <link rel="stylesheet" href="css/style.css" type="text/css">
    <link rel="stylesheet" type="text/css" href="css/mobile.css">

    Startseite

    Über uns

    Anfahrt

                Leistungen

                Kontaktanfrage

                Allgemeine Informationen

                Impressum

But it should look like :

Could you help me with my padding issue ?

A: Find the following block in your CSS:
#header ul li {
    display: inline-block;
    list-style: none;
    margin: 0px;
    padding: 0;
    text-align: center;
}

And change the padding: 0; to padding: 0 5px;
Adjust the 5px to whatever value you want, bigger or smaller. Bigger values will mean bigger gaps, and smaller values smaller gaps.
So you end up with:
#header ul li {
        display: inline-block;
        list-style: none;
        margin: 0px;
        padding: 0 5px;
        text-align: center;
    }

And it will look like your screenshot
Below is the code from your codepen, with the CSS edit. Next time remember to include the code in you question

body {
  background: black;
  font-family: Oswald;
  font-size: 20px;
  font-weight: normal;
  line-height: 1;
  margin: 0;
  min-width: 960px;
  padding: 0;
}
a {
  text-decoration: none;
  outline: none;
}
a:active {
  background: none;
}
img {
  border: none;
}
/*-------------------------------------------Header-------------------------------------------*/

p {
  color: #252525;
  line-height: 20px;
  margin: 0;
  padding: 0;
}
p a {
  color: #252525;
  text-decoration: underline;
}
.border-right {
  border-right: 5px solid #A40900;
}
.border-left {
  border-left: 5px solid #A40900;
}
#header {
  margin: 0 auto;
  padding: 4px 0 0px;
  text-align: center;
  width: 960px;
}
#header a.logo {
  display: block;
  margin: 0 auto;
  padding: 0;
  width: 540px;
}
#header a.logo img {
  border: 0;
  display: block;
  margin: 0;
  padding: 0;
  width: 100%;
}
#header ul {
  margin: 0;
  padding: 0;
  background-color: white;
  height: 35px;
  padding-top: 2%;
  border-top: 5px solid #A40900;
  border-bottom: 5px solid #A40900;
}
#header ul li {
  display: inline-block;
  list-style: none;
  margin: 0px;
  padding: 0 5px;
  text-align: center;
}
#header ul li a {
  color: #000;
  font-family: Oswald ExtraLight;
  font-size: 20px;
  font-weight: normal;
  margin: 0;
  padding: 0;
  text-decoration: none;
  text-transform: uppercase;
}
#header ul li a:hover,
#header ul li.selected a {
  color: #0ba39c;
}

      Startseite

      Über uns

      Anfahrt

      Leistungen

      Kontaktanfrage

      Allgemeine Informationen

      Impressum

A: When you use percentage values for vertical padding or margin, it uses the width to calculate it.

https://www.w3.org/TR/CSS2/box.html#padding-properties

You may here,  instead,  use line-height to use some percentage value in regards to the height you want to give to your element.
Example: line-height:35px; will give for one line an height of 35px to the container.
Your screen shows an height at average 60px. You may use (without height) :
line-height:60px;

or (DEMO)
font-size:20px;
line-height:300%;

line-height:200%; is equal to line-height:2em; twice the font-size .

Why line-height would be a good idea ?

because static height is not needed, if the menu breaks into many lines (font-family not loaded,visitor zooming, ...) , it will not be messy and will expand without overflowing on next content, ...

body {
  background: black;
  font-family: Oswald;
  font-size: 20px;
  font-weight: normal;
  line-height: 1;
  margin: 0;
  min-width: 960px;
  padding: 0;
}

a {
  text-decoration: none;
  outline: none;
}

a:active {
  background: none;
}

img {
  border: none;
}

/*-------------------------------------------Header-------------------------------------------*/

p {
  color: #252525;
  line-height: 20px;
  margin: 0;
  padding: 0;
}

p a {
  color: #252525;
  text-decoration: underline;
}

.border-right {
  border-right: 5px solid #A40900;
}

.border-left {
  border-left: 5px solid #A40900;
}

#header {
  margin: 0 auto;
  padding: 4px 0 0px;
  text-align: center;
  width: 960px;
}

#header a.logo {
  display: block;
  margin: 0 auto;
  padding: 0;
  width: 540px;
}

#header a.logo img {
  border: 0;
  display: block;
  margin: 0;
  padding: 0;
  width: 100%;
}

#header ul {
  font-family: 'Open Sans Condensed', sans-serif;
  margin: 0;
  padding: 0;
  background-color: white;
  line-height: 60px;/* will size height and also center text/inline boxes on this value */
  border-top: 5px solid #A40900;
  border-bottom: 5px solid #A40900;
}

#header ul li {
  display: inline-block;
  list-style: none;
  margin: 0px;
  padding: 0;
  line-height: 100%;/*reset to normal*/
  text-align: center;
}

#header ul li a {
  color: #000;
font-family: 'Yanone Kaffeesatz', sans-serif;
  font-size: 20px;
  font-weight: normal;
  margin: 0;
  padding: 0 1em;
  text-decoration: none;
  text-transform: uppercase;
}

#header ul li a:hover,
#header ul li.selected a {
  color: #0ba39c;
}
<link href='https://fonts.googleapis.com/css?family=Yanone+Kaffeesatz' rel='stylesheet' type='text/css'>

      Startseite

      Über uns

      Anfahrt

      Leistungen

      Kontaktanfrage

      Allgemeine Informationen

      Impressum

A:

body {
    background: black;
    font-family: Oswald;
    font-size: 20px;
    font-weight: normal;
    line-height: 1;
    margin: 0;
    min-width: 960px;
    padding: 0;
}
ul{
  margin:0;
  padding:0;
}
a {
    text-decoration: none;
    outline: none;
}
a:active {
    background: none;
}
img {
    border: none;
}
/*-------------------------------------------Header-------------------------------------------*/
p {
    color: #252525;
    line-height: 20px;
    margin: 0;
    padding: 0;
}
p a {
    color: #252525;
    text-decoration: underline;
}
.border-right {
    border-right: 5px solid #A40900;

}
.border-left {
    border-left: 5px solid #A40900;
}
#header {
    margin: 0 auto;
    padding: 4px 0 0px;
    text-align: center;
}
#header a.logo {
    display: block;
    margin: 0 auto;
    padding: 0;
    width: 540px;
}
#header a.logo img {
    border: 0;
    display: block;
    margin: 0;
    padding: 0;
    width: 100%;
}
#header ul {
    margin: 0;
    padding: 0;
    background-color: white;
    border-top: 5px solid #A40900;
    border-bottom: 5px solid #A40900;
    padding: 10px 0;
}
#header ul li {
    display: inline-block;
    list-style: none;
    margin: 0px;
    padding: 0 15px;
    float: left;
    text-align: center;
}
#header ul li a {
    color: #000;
    font-family: Oswald ExtraLight;
    font-size: 20px;
    font-weight: normal;
    margin: 0;
    padding: 0;
    text-decoration: none;
    text-transform: uppercase;
}
#header ul li a:hover, #header ul li.selected a {
    color: #0ba39c;
}
<!DOCTYPE HTML>

    <title>XOXO</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="so/sample.css" />

        Startseite

        Über uns

        Anfahrt

                Leistungen

                Kontaktanfrage

                Allgemeine Informationen

                Impressum

Please find code here. Check result in full page


text:
Q: I need some help in solving this recurrence equation/relation I was given a whole bunch of recurrence equations to solve but there's one in  particular that i can't seem to solve...
T(n) = T(9n/10) + n
Assume that..
T(1) = 0
n = $a^k$ (for some appropriate value of a)
Down below is my attempt at solving this...
1) T(n) = T(9n/10) + n
2) T(9n/10) = T(81n/100) + 9n/10
3) T(n) = T(81n/100) + 9n/10 + n
4) T(81n/100) = T(729n/1000) + 81n/100
5) T(n) = T(729n/1000) + 81n/100 + 9n/10 + n
.
.
.
k) T(n) = T($9^k$n/$10^k$) + n($(9/10)^0$ + $(9/10)^1$ + $(9/10)^2$ + ... + $(9/10)^{k-1}$)
T(n) = T($9^k$n/$10^k$) + n$\sum_{i=0}^{k-1} (9/10)^i$
Ok this is where im stuck, i know how to solve the summation above, but the T($9^k$n/$10^k$) is throwing me off a little. In the other recurrence equations that i have solved, the extra T(n) in the equation usually ends up being zero, but even if i applied the rule $n = a^k$ i will get the following...
T(n) = T(n) + n$\sum_{i=0}^{k-1} (9/10)^i$
what am i supposed to do with the extra T(n)?
Any help will be appreciated

A: Why not try $a=\frac{10}{9}$? Then your recurrence relation $$T(n)=T\left(\frac{9}{10}n\right)+n$$
with the substitution $n=a^k$ becomes
$$T(a^k)=T(a^{k-1})+a^k$$
Now, make the substitution $t_k=T(a^k)$ and our recurrence relation becomes
$$t_k=t_{k-1}+a^k$$
Do you know how to solve this last recurrence relation? Then you can trace back the substitutions to get a form for $T(n)$.


text:
Q: Retrieve item's price history on Steam market Regarding items from Steam market I was wondering if there is a way to retrieve the price history of an item over a period of time.
I know that Steam provides a special api for developers who want to integrate market specific data into their own sites but I haven't been able to find anything about retrieving price history for an item in the form of a json.
Have any of you already done this ?

A: If calling from code
url ="http://steamcommunity.com/market/pricehistory/"

and the query string payload is:
{
    "country" = "US",      # two letter ISO country code
    "currency"= 1,       # 1 is USD, 3 is EUR, not sure what others are
    "appid"   = 753,     # this is the application id.  753 is for steam cards
    "market_hash_name"  ="322330-Shadows and Hexes" # this is the name of the item in the steam market.
}

country code is the ISO Country Code.
you can find the app id for a game from the URL of its store page.  Example: The game "CS:GO" app id is 730.  Store page
You can find the market hash name from the URL of its market page.  Example: This CS:GO item hash name is "Glove Case Key".
Price history for the Glove Case Key is here.

A: I've done some more research and found the way you can retrieve the price history for an item.
As an example for those who are curious, the price history for this random item "Specialized Killstreak Brass Beast" can be retrieved in this way:
http://steamcommunity.com/market/pricehistory/?country=DE&currency=3&appid=440&market_hash_name=Specialized%20Killstreak%20Brass%20Beast


text:
Q: One to many to many relationship, with composite keys In my game, an archetype is a collection of associated traits, an attack type, a damage type, and a resource type. Each piece of data is unique to each
archetype. For example, the Mage archetype might look like the following:
archetype:     Mage
attack:        Targeted Area Effect
damage:        Shock
resource:      Mana
trait_defense: Willpower
trait_offense: Intelligence
This is the archetype table in SQLite syntax:
create table archetype
(
archetype_id varchar(16) not null,
attack_id varchar(16) not null,
damage_id varchar(16) not null,
resource_type_id varchar(16) not null,
trait_defense_id varchar(16) not null,
trait_offense_id varchar(16) not null,
archetype_description varchar(128),
constraint pk_archetype primary key (archetype_id),
constraint uk_archetype unique (attack_id, damage_id,
                                resource_type_id,
                                trait_defense_id,
                                trait_offense_id)
);

The primary key should be the complete composite, but I do not want to pass
all the data around to other tables unless necessary. For example, there are
crafting skills associated with each archetype which do not need to know any
other archetype data.
An effect is a combat outcome that can be applied to a friend or foe. An effect has an application type (instant, overtime), a type (buff, debuff, harm, heal, etc.) and a detail describing to which stat the effect applies. It also has most of the archetype data to make each effect unique. Also included is the associated trait used for progress and skill checks. For example, an effect might look like:
apply:     Instant
type:      Harm
detail:    Health
archetype: Mage
attack_id: Targeted Area Effect
damage_id: Shock
resource:  Mana
trait_id:  Intelligence
This is the effect table in SQLite syntax:
create table effect
(
effect_apply_id varchar(16) not null,
effect_type_id varchar(16) not null,
effect_detail_id varchar(16) not null,
archetype_id varchar(16) not null,
attack_id varchar(16) not null,
damage_id varchar(16) not null,
resource_type_id varchar(16) not null,
trait_id varchar(16),
constraint pk_effect primary key(archetype_id, effect_type_id,
                                 effect_detail_id, effect_apply_id,
                                 attack_id, damage_id, resource_type_id),

constraint fk_effect_archetype_id foreign key(archetype_id, attack_id,
                                              damage_id, resource_type_id)
                        references archetype (archetype_id, attack_id,
                                              damage_id, resource_type_id)
);

An ability is a container that can hold multiple effects. There is no limit to
the kinds of effects it can hold, e.g. having both Mage and Warrior effects in
the same ability, or even having two of the same effects, is fine. Each effect
in the ability is going to have the archetype data, and the effect data.
Again.
Ability tables in SQLite syntax:
create table ability
(
ability_id varchar(64),
ability_description varchar(128),
constraint pk_ability primary key (ability_id)
);

create table ability_effect
(
ability_effect_id integer primary key autoincrement,
ability_id varchar(64) not null,
archetype_id varchar(16) not null,
effect_type_id varchar(16) not null,
effect_detail_id varchar(16) not null,
effect_apply_id varchar(16) not null,
attack_id varchar(16) not null,
damage_id varchar(16) not null,
resource_type_id varchar(16) not null,
trait_id varchar(16),
constraint fk_ability_effect_ability_id foreign key (ability_id)
                                 references ability (ability_id),
constraint fk_ability_effect_effect_id foreign key  (archetype_id,
                                                     effect_type_id,
                                                     effect_detail_id,
                                                     effect_apply_id)
                                 references effect  (archetype_id,
                                                     effect_type_id,
                                                     effect_detail_id,
                                                     effect_apply_id)
);

This is basically a one to many to many relationship, so I needed a technical
key to have duplicate effects in the ability_effect table.
Questions:
1) Is there a better way to design these tables to avoid the duplication of
data over these three tables?
2) Should these tables be broken down further?
3) Is it better to perform multiple table lookups to collect all the data? For example, just passing around the archetype_id and doing lookups for the data when necessary (which will be often).
UPDATE:
I actually do have parent tables for attacks, damage, etc. I removed those
tables and their related indexes from the sample to make the question clean,
concise, and focused on my duplicate data issue.
I was trying to avoid each table having both an id and a name, as both would be candidate keys and so having both would be wasted space. I was trying to keep the SQLite database as small as possible. (Hence, the many "varchar(16)"
declarations, which I now know SQLite ignores.) It seems in SQLite having both
values is unavoidable, unless being twice as slow is somehow ok when using the
WITHOUT ROWID option during table creation. So, I will rewrite my database to
use ids and names via the rowid implementation.
Thanks for your input guys!

A: I would probably avoid those composite primary keys.
And use the more commonly used integer with an autoincrement.
Then add the unique or non-unique composite indexes where needed.
Although i.m.h.o it's not always a bad idea to use a short CHAR or VARCHAR as the primary key in some cases. Mostly when easy to understand abbreviations can be used.
An example. Suppose you have a reference table for Countries. With a primary key on the 2 character CountryCode. Then when querying a table with a foreign key on that  CountryCode, then for the human mind it's way easier to understand 'US' than some integer. Even without joining to Countries you'll probably know what Country is referenced.
So here are your tables with a slightly different layout.
create table archetype
(
archetype_id integer primary key autoincrement,
attack_id varchar(16) not null,
damage_id varchar(16) not null,
resource_type_id varchar(16) not null,
trait_defense_id varchar(16) not null,
trait_offense_id varchar(16) not null,
archetype_description varchar(128),
constraint uk_archetype unique (attack_id, damage_id,
                                resource_type_id,
                                trait_defense_id,
                                trait_offense_id)
);

create table effect
(
effect_id integer primary key autoincrement,
archetype_id integer not null, -- FK archetype
effect_apply_id varchar(16) not null,
effect_type_id varchar(16) not null,
effect_detail_id varchar(16) not null,
attack_id varchar(16) not null,
damage_id varchar(16) not null,
resource_type_id varchar(16) not null,
trait_id varchar(16),
constraint pk_effect unique(archetype_id, effect_type_id,
                            effect_detail_id, effect_apply_id,
                            attack_id, damage_id, resource_type_id),

constraint fk_effect_archetype_id foreign key(archetype_id)
                        references archetype (archetype_id)
);

create table ability
(
ability_id integer primary key autoincrement,
ability_description varchar(128)
);

create table ability_effect
(
ability_effect_id integer primary key autoincrement,
ability_id integer not null, -- FK ability
effect_id integer not null, -- FK effect
attack_id varchar(16) not null,
damage_id varchar(16) not null,
resource_type_id varchar(16) not null,
trait_id varchar(16),
constraint fk_ability_effect_ability_id foreign key (ability_id)
                                 references ability (ability_id),
constraint fk_ability_effect_effect_id foreign key  (effect_id)
                                 references effect  (effect_id)
);

A:
1) Is there a better way to design these tables to avoid the
  duplication of data over these three tables?

and also

2) Should these tables be broken down further?

It would appear so.
It would appear Mage is a unique archtype, as is Warrior. (based upon For example, the Mage archetype might look like the following:).
As such why not make the archtype_id a primary key and then reference the attack type, damage etc from tables for these. i.e. have an attack table and a damage table.
So you could, for example, have something like (simplified for demonstration) :-
DROP TABLE IF EXISTS archtype;
DROP TABLE IF EXISTS attack;
DROP TABLE IF EXISTS damage;
CREATE TABLE IF NOT EXISTS attack (attack_id INTEGER PRIMARY KEY, attack_name TEXT, a_more_columns TEXT);
INSERT INTO attack (attack_name, a_more_columns) VALUES
    ('Targetted Affect','ta blah'), -- id 1
    ('AOE','aoe blah'), -- id 2
    ('Bounce Effect','bounce blah') -- id 3
    ;

CREATE TABLE IF NOT EXISTS damage (damage_id INTEGER PRIMARY KEY, damage_name TEXT, d_more_columns TEXT);
INSERT INTO damage (damage_name,d_more_columns) VALUES
  ('Shock','shock blah'), -- id 1
    ('Freeze','freeze blah'), -- id 2
    ('Fire','fire blah'), -- id 3
    ('Hit','hit blah')
    ;
CREATE TABLE IF NOT EXISTS archtype (id INTEGER PRIMARY KEY, archtype_name TEXT, attack_id_ref INTEGER, damage_id_ref INTEGER, at_more_columns TEXT);
INSERT INTO archtype (archtype_name,attack_id_ref,damage_id_ref,at_more_columns) VALUES
    ('Mage',1,1,'Mage blah'),
    ('Warrior',3,4,'Warrior Blah'),
    ('Dragon',2,3,'Dragon blah'),
    ('Iceman',2,2,'Iceman blah')
    ;
    SELECT archtype_name, damage_name, attack_name FROM archtype JOIN damage ON damage_id_ref = damage_id JOIN attack ON attack_id_ref = attack_id;

*

*Note that the aliases of rowid have been used for id's rather than the name as these are generally the most efficient.

*

*The data for rowid tables is stored as a B-Tree structure containing one entry for each table row, using the rowid value as the key. This means that retrieving or sorting records by rowid is fast. Searching for a record with a specific rowid, or for all records with rowids within a specified range is around twice as fast as a similar search made by specifying any other PRIMARY KEY or indexed value. SQL As Understood By SQLite - CREATE TABLE- ROWIDs and the INTEGER PRIMARY KEY

*A rowid is generated for all rows (unless WITHOUT ROWID is specified), by specifying ?? INTEGER PRIMARY KEY column ?? is an alias of the rowid.

*Beware using AUTOINCREMENT, unlike other RDMS's that use this for automatically generating unique id's for rows. SQLite by default creates a unique id (the rowid). The AUTOINCREMENT keyword adds a constraint that ensures that the generated id is larger than the highest existing. To do this requires an additional table sqlite_sequence that has to be maintained and interrogated and as such has overheads. The AUTOINCREMENT keyword imposes extra CPU, memory, disk space, and disk I/O overhead and should be avoided if not strictly needed. It is usually not needed. SQLite Autoincrement
The query at the end will result in :-

Now say you wanted types to have multiple attacks and damages per type then the above could easily be adapted by using many-many relationships by introducing reference/mapping/link tables (all just different names for the same). Such a table will have two columns (sometime other columns for data specific to the distinct reference/map/link) one for the parent (archtype) reference/map/link and the other for the child (attack/damage) referenced/mapped/linked.
e.g. the following could be added :-
DROP TABLE IF EXISTS archtype_attack_reference;
CREATE TABLE IF NOT EXISTS archtype_attack_reference
    (aar_archtype_id INTEGER NOT NULL, aar_attack_id INTEGER NOT NULL,
    PRIMARY KEY(aar_archtype_id,aar_attack_id))
    WITHOUT ROWID;

DROP TABLE IF EXISTS archtype_damage_reference;
CREATE TABLE IF NOT EXISTS archtype_damage_reference
    (adr_archtype_id INTEGER NOT NULL, adr_damage_id INTEGER NOT NULL,
    PRIMARY KEY(adr_archtype_id,adr_damage_id))
    WITHOUT ROWID
    ;

INSERT INTO archtype_attack_reference VALUES
    (1,1), -- Mage has attack Targetted
    (1,3), -- Mage has attack Bounce
    (3,2), -- Dragon has attack AOE
    (2,1), -- Warrior has attack targetted
    (2,2), -- Warrior has attack AOE
    (4,2), -- Iceman has attack AOE
    (4,3) -- Icemane has attack Bounce
;

INSERT INTO archtype_damage_reference VALUES
  (1,1),(1,3), -- Mage can damage with Shock and Freeze
    (2,4), -- Warrior can damage with Hit
    (3,3),(3,4), -- Dragon can damage with Fire and Hit
  (4,2),(4,4) -- Iceman can damage with Freeze and Hit
;

SELECT archtype_name, attack_name,damage_name FROM archtype
    JOIN archtype_attack_reference ON archtype_id = aar_archtype_id
    JOIN archtype_damage_reference ON archtype_id = adr_archtype_id
    JOIN attack ON aar_attack_id = attack_id
    JOIN damage ON adr_damage_id = damage_id
;

The query results in :-

With a slight change the above query could even be used to perform a random attack e.g. :-
SELECT archtype_name, attack_name,damage_name FROM archtype
    JOIN archtype_attack_reference ON archtype_id = aar_archtype_id
    JOIN archtype_damage_reference ON archtype_id = adr_archtype_id
    JOIN attack ON aar_attack_id = attack_id
    JOIN damage ON adr_damage_id = damage_id
    ORDER BY random() LIMIT 1 -- ADDED THIS LINE
;

You could get :-

Another time you might get :-

3) Is it better to perform multiple table lookups to collect all the
  data? For example, just passing around the archetype_id and doing
  lookups for the data when necessary (which will be often).

That's pretty hard to say. You may initially think gather all the data once and keep it in memory say as an object. However, at times the underlying data may well already be in memory due to it being cached. Perhaps it could be better to utilise part of each. So I believe the answer is, you will need to test various scenarios.


text:
Q: Get array key value with Alamofire I am making a simple request to get specific data from a JSON file, but I am having issues getting the exact data.
The JSON file:
{
    "Something1": {
        "Added": "09-10-2016",
        "Expires": "09-12-2016",
        "Reliability": "78%",
        "Views": "2",
        "Priority": "High"
    },
    "Something2": {
        "Added": "09-11-2016",
        "Expires": "09-13-2016",
        "Reliability": "98%",
        "Views": "5",
        "Priority": "Low"
    }
}

The swift code:
Alamofire.request("https://example.com/args.json").responseJSON { response in
            if let JSON = response.result.value as? [String:AnyObject] {
                print(JSON["Something1"])
            }
        }

With print(JSON["Something1"]), it prints everything for Something1 just like it's supposed to but an error is thrown when I try to do print(JSON["Something1"]["Views"]) for example. How would I go about fixing this?

A: Your problem isn't related to Alamofire I'm afraid, it's more of deal with JSON using Swift. In your case when you make your first optional binding you're converting to a [String: AnyObject] and it's correct and this implies that you can subscript JSON["Something1"].
But after that when you try to subscript again over the JSON["Something1"]["Views"] the compiler doesn't know what have the JSON["Something1"] so you can't using as a dictionary instead you need to cast it again to a dictionary because is nested using optional binding like this:
if let nestedDictionary1 = JSON["Something1"] as? [String: AnyObject] {
    // access individual value in dictionary

    if let views = nestedDictionary1["Views"] as? Int {
         print(views)
    }
}

You can read more about the work with JSON in this article of Apple.
I hope this help you.


text:
Q: In PHP cc email, how to use group email address instead of too many comma separate emails of outlook I have created a group in Outlook it's group id name is 'php@domain.com', which have 5 member in that group.
So i want to send mail to this group in CC.I am using 'php@domain.com' group id name in CC but no any member is receiving any mail.
$emp_email = $row["email"];
$msg = "test";
$subject = 'Happy Birthday!!';
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'Cc: php@******.com' . "\r\n";
$headers .= "From: From Name <info@******.com>";
$sentmail = mail($emp_email, $subject, $msg, $headers);

here $emp_email is receiving mail but there is no any action in CC.

A: Groupid is a one unique from multiple cc. So PHP can not understand the group id.
you must have to use array in cc.

A: This group id you can use only for outlook. PHP can't understand this. You should send array in CC.


text:
Q: I have created a parametric Optic Plan over a view using JavaScript in MarkLogic. How can I pass a parameter to the plan while invoking it? Here is the plan I have created which can accept a parameter emplId to filter the results of the view:
declareUpdate();
const op = require('/MarkLogic/optic');

const EmployeePlanSQL = op.fromView('employees', 'EmployeeRecordsView',"")
     .select(['employeeId', 'employeeName', 'pnone'])
     .where(op.eq(op.col('employeeId'), op.param('emplId')))
     .orderBy('employeeId');;
const planObj = EmployeePlanSQL.export();

xdmp.documentInsert("emplRatePlanSQL.json", planObj);

Here is how I invoke it using JavaScript :
op.import(cts.doc('emplRatePlanSQL.json').toObject())
  .result();

How to pass the parameter emplId while invoking this plan?

A: The optional second argument of the result() method specifies parameter bindings as in:
.result('object', {emplId: 1});

For more information, see:
http://docs.marklogic.com/guide/app-dev/OpticAPI#id_35758
and
http://docs.marklogic.com/AccessPlan.prototype.result
Hoping that helps,

A: When parameterizing query plans, specify the parameter values in the second argument to .result():
.result(null, { emplId: 1234 });

There is an example in the Optic API guide.


text:
Q: IIS W3C Log (Abnormally?) Three of our intranet IIS servers are behind F5 Load Balancer. I grabbed the W3c log from one of the servers for a typical day, and there turned out to be about 100k entries.
What I feel uneasy is the number of occurrences of half-complete entries.
Our servers use Windows Authentication, but out of 100k entries, nearly 70k of them are missing cs-username (the cs-uri-stem of which are just 1 single slash '/').
The servers mainly attends to requests to a Content Management System hooked up to IIS by ISAPI. Does this have anything to do with the large amount of "weird" log entries? And is this something I should be concerned about?

A: Sounds like you're using NTLM Authentication .
NTLM uses 2 round trips to authenticate a request or a connection. 401, 401, 200 (with username) - only the 200 gets the username.
You may want to look into the AuthPersist family of settings: AuthPersistNTLM, AuthPersistNonNTLM, and related items. With a proxy in the mix, sometimes per-connection authentication is disabled, and you need to authenticate every request instead.
Another alternative is to get Kerberos working, so that you only use a single round-trip (albeit with a large payload) to authenticate a client (i.e. 401, 200 (with username).


text:
Q: What captures our intuitive notion of faces, edges, and vertices? This answer suggests that laypeople's intuitive notion of the meaning of these words is consistent with the following claims:

*

*A cube has 6 faces, 12 edges, 8 vertices.

*A cylinder has 3 faces, 2 edges, 0 vertices.

*A cone has 2 faces, 1 edge, 1 vertex.

*A sphere has 1 face, 0 edges, 0 vertices.

What formal, mathematical definition best captures this intuition and is consistent with the above claims? For example, the following was suggested in the comments:

I think the definition of the tangent space at a point via equivalence
  classes of smooth curves works in this situation, and then I believe
  it's true that the naive count of faces, edges, etc. counts connected
  components of the subspaces of points whose tangent spaces have the
  relevant dimensions.

Is this a good approach? If so, does it have an existing name and literature? Are there any other approaches?

A: Partial answer: From generalizations of manifolds:

Orbifolds: An orbifold is a generalization of manifold allowing for certain kinds of "singularities" in the topology. Roughly
speaking, it is a space which locally looks like the quotients of some
simple space (e.g. Euclidean space) by the actions of various finite
groups. The singularities correspond to fixed points of the group
actions, and the actions must be compatible in a certain sense.
Stratified space: A "stratified space" is a space that can be divided into pieces ("strata"), with each stratum a manifold, with the
strata fitting together in prescribed ways (formally, a filtration by
closed subsets). There are various technical definitions, notably a
Whitney stratified space (see Whitney conditions) for smooth manifolds
and a topologically stratified space for topological manifolds.
CW-complexes: A CW complex
is a topological space formed by gluing disks of different
dimensionality together. In general the resulting space is singular,
and hence not a manifold. However, they are of central interest in
algebraic topology, especially in homotopy theory, as they are easy to
compute with and singularities are not a concern.

From topologically stratified space:

In topology, a branch of mathematics, a topologically stratified space
is a space X that has been decomposed into pieces called strata; these
strata are manifolds and are required to fit together in a certain
way. Topologically stratified spaces provide a purely topological
setting for the study of singularities analogous to the more
differential-geometric theory of Whitney.
Basic examples of stratified spaces include manifolds with boundary
(top dimension and codimension 1 boundary) and manifolds with corners
(top dimension, codimension 1 boundary, codimension 2 corners).


text:
Q: Summing results from a monte carlo I am trying to sum the values in the 'Callpayoff' list however am unable to do so, print(Callpayoff) returns a vertical list:
0
4.081687878300656
1.6000410648454846
0.5024316862043037
0

so I wonder if it's a special sublist ? sum(Callpayoff) does not work unfortunately. Any help would be greatly appreciated.
def Generate_asset_price(S,v,r,dt):
    return (1 + r * dt + v * sqrt(dt) * np.random.normal(0,1))

def Call_Poff(S,T):
    return max(stream[-1] - S,0)

# initial values
S = 100
v = 0.2
r = 0.05
T = 1
N = 2 # number of steps
dt = 0.00396825
simulations = 5

for x in range(simulations):
    stream = [100]
    Callpayoffs = []
    t = 0
    for n in range(N):
        s = stream[t] * Generate_asset_price(S,v,r,dt)
        stream.append(s)
        t += 1
        Callpayoff = Call_Poff(S,T)
    print(Callpayoff)
    plt.plot(stream)

A: Right now you're not appending values to a list, you're just replacing the value of Callpayoff at each iteration and printing it. At each iteration, it's printed on a new line so it looks like a "vertical list".
What you need to do is use Callpayoffs.append(Call_Poff(S,T)) instead of Callpayoff = Call_Poff(S,T).
Now a new element will be added to Callpayoffs at every iteration of the for loop.
Then you can print the list with print(Callpayoffs) or the sum with print(sum(Callpayoffs))
All in all the for loop should look like this:
for x in range(simulations):
    stream = [100]
    Callpayoffs = []
    t = 0
    for n in range(N):
        s = stream[t] * Generate_asset_price(S,v,r,dt)
        stream.append(s)
        t += 1
        Callpayoffs.append(Call_Poff(S,T))
    print(Callpayoffs,"sum:",sum(Callpayoffs))

Output:
[2.125034975231003, 0] sum: 2.125034975231003
[0, 0] sum: 0
[0, 0] sum: 0
[0, 0] sum: 0
[3.2142923036024342, 4.1390018820809615] sum: 7.353294185683396


text:
Q: in background image url I have got [site_url] instead of real url in wordpress I used add_theme_option('custom-background') in my wordpress functions.php file. And it is working but when i set background image i have not got the image. In the page style it is showing [site_url] in the url. But i need to show localhost/wordpress instead of [site_url].The style line is given below:
background-image: url("http://[site_url]/wp-content/uploads/2019/02/pexels-photo-958168.jpeg");

A: I got an alternative solutions. The problem is with the theme. Other theme is working correctly. For this theme i did this:
<body <?php body_class();?> style="background-image: url('<?php echo substr(get_background_image(),11);?>')">

Now it is returning- "wp-content/uploads/2019/02/bg.jpeg". And i will get background image dynamically.

A: You probably mean add_theme_support(), not add_theme_option().
Don't know why it's happening, but a workaround would be to tweak @Emma's suggestion a bit. Something like
<?php $url = parse_url(get_background_image(), PHP_URL_PATH); ?>
<div
    class="myClass"
    style="background-image: url(<?php echo $url?>)">
</div>

(Probably also need to test if the initial image URL is empty or not.)
(And of course this assumes the WordPress install is at the site root. Some further changes might be needed otherwise, and it might end being more like Emma's. I might also add that you could instead use jquery on the client side the fix the problematic URL.)


text:
Q: Обработка списка Есть реальный список  row:
row=['1101516021', '0', '1', '', 'TTT', 'ppp', '997476042736', '', '20150320092249', '20150320092249', '1', '1', '110', '', '', '00', '22', '', '999470000032', '40711569', '', '1', '0']

Его необходимо инсертить в БД. Но перед инсертом обработать так:
row[8]="to_date('"+row[8]+"','yyyymmddhh24miss')"
row[9]="to_date('"+row[9]+"','yyyymmddhh24miss')"
row[3]="'"+row[3]+"'"
row[4]="'"+row[4]+"'"
row[5]="'"+row[5]+"'"
row[6]="'"+row[6]+"'"
row[7]="'"+row[7]+"'"
row[11]="'"+row[11]+"'"
row[12]="'"+row[12]+"'"
row[13]="'"+row[13]+"'"
row[14]="'"+row[14]+"'"
row[15]="'"+row[15]+"'"
row[16]="'"+row[16]+"'"
row[17]="'"+row[17]+"'"
row[18]="'"+row[18]+"'"
row[19]="'"+row[19]+"'"
row[0]="0"+row[0]
row[1]="0"+row[1]
row[2]="0"+row[2]
row[10]="0"+row[10]
row[20]="0"+row[20]
row[21]="0"+row[21]
row[22]="0"+row[22]

Получилось очень громоздко и некрасиво.
А хотелось что-то типа
row[3,4,5,6,7,11,12,13,14,15,16,17,18,19]= ["'"+x+"'" for x in row[3,4,5,6,7,11,12,13,14,15,16,17,18,19]]

Но, к сожалению, в питоне так писать нельзя.
A: В питоне можно писать проще и красивее. Ваш код будет выглядеть где-то так (две строки, потому что есть разрыв):
row[3:7] = ["'"+x+"'" for x in row[3:7]]
row[11:19] = ["'"+x+"'" for x in row[11:19]]

A: Как я понял, вам нужно, в частности, заключать в кавычки те записи, которые не состоят полностью из цифр, в том числе и пустые строки. По этому условию можно все и обработать:
row=['1101516021', '0', '1', '', 'TTT', 'ppp', '997476042736', '', '20150320092249', '20150320092249', '1', '1', '110', '', '', '00', '22', '', '999470000032', '40711569', '', '1', '0']
for i, item in enumerate(row):
    if not item or not all(x.isnumeric() for x in item):
        row[i] = "'" + row[i] + "'"
print(row)

Результат:
['1101516021', '0', '1', "''", "'TTT'", "'ppp'", '997476042736', "''", '20150320092249', '20150320092249', '1', '1', '110', "''", "''", '00', '22', "''", '999470000032', '40711569', "''", '1', '0']


text:
Q: Asymptotic form for a generalized hypergeometric function ${}_3{F_2}\left( {m+m_s,{m_s},{m_s};1 + {m_s},1 + {m_s}; - \frac{{{m_s}\overline \gamma  }}{{m{\gamma _0}}}} \right)$, where $m$, $m_s$, $\gamma_0$, and $\overline \gamma$ are positive real numbers. When $\overline \gamma$ goes to infinity, can we derive asymptotic form for that generalized hypergeometric function?

A: The structure of the asymptotic expansion can be seen from the representation of ${_3F_2}$ in terms of the Meijer G-function:
$$F(x) = {_3F_2}(m + m_s, m_s, m_s; 1 + m_s, 1 + m_s; -x) = \\
\frac {m_s^2} {\Gamma(m + m_s)}
 G_{3, 3}^{1, 3} \left( x \middle|
  {1 - m_s, 1 - m_s, 1 - m - m_s \atop 0, -m_s, -m_s} \right) = \\
\frac {m_s^2} {2 \pi i \Gamma(m + m_s)} \int_\mathcal L
 \frac {\Gamma(-y) \Gamma(m + m_s + y) \Gamma^2(m_s + y) x^y}
  {\Gamma^2(1 + m_s + y)} dy.$$
For $x > 1$, the integral is $2 \pi i$ times the sum of the residues at the points $y = -m_s$ and $y = -m -m_s - k$. The leading term in the expansion will be determined by the residue at the double pole $y = -m_s$, giving
$$\operatorname{Res}_{y = -m_s}
 \frac {\Gamma(-y) \Gamma(m + m_s + y) \Gamma^2(m_s + y) x^y}
  {\Gamma^2(1 + m_s + y)} = \\
\Gamma(m) \Gamma(m_s) x^{-m_s} (\ln x + \psi(m) -\psi(m_s)), \\
F(x) =
\frac {m_s} {\binom {m + m_s - 1} {m_s}} x^{-m_s} \ln x + O(x^{-m_s}),
\quad x \to \infty.$$


text:
Q: Form's client area not rendering size set in Form.ClientSize I've got a System.Windows.Forms.Form where I need to set the size of the client area at runtime. Strangely, though, even when I set the ClientSize property to 800x600, the area is smaller by 4 pixels on the right and bottom sides, which causes my content to be clipped by 4 pixels in both directions.
This behavior is observed with both the Windows XP and Windows Classic themes.
From my understanding of the MSDN documentation this should be doing what I want -- but it's not.

The size of the client area of the
  form is the size of the form excluding
  the borders and the title bar.

Sample code here:
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        this.ClientSize = new Size(800, 600);
    }
}

What gives? I noticed in the comments of an answer to another question that this is happening to someone else. Is there any way I can set the size of the client area reliably?

A: As it turns out, my problem was not with the Form at all. The form has a System.Windows.Forms.WebBrowser control in it -- and that has a border. Since the WebBrowser control doesn't have any border property I didn't suspect it.