text:
Q: Estou problemas para ler uma string dentro de uma função Boa noite, gostaria de saber métodos para ler uma string em C(Versão C99), já tentei bastante coisa, e não funciona, abaixo, o código defeituoso.
Obs: O erro que relato é que, logo após apertar "ENTER" no primeiro 'gets' da função cadastro, o programa buga, e exibe a mensagem "o programa.exe parou de funcionar".
Obs.1: Retirei os < > dos includes pois o navegador identifica isso como uma tag html e não exibe o conteúdo dos includes.
#include stdio.h
#include stdlib.h

int menu()
{
    int opc;
    printf("\n Opcoes: \n1. Cadastrar livros\n2. Consultar livros\n3. Alterar informacoes de livros\n4. Remover um livro da lista");
    scanf("%d", &opc);
    return(opc);
}
struct informacoes
{
    char nome[100];
    char autor[100];
    long long int isbn;
    char volume[10];
    int data;
    char editora[100];
    int paginas;
};
int cadastro(struct informacoes *livros, int i){
    printf("\nNome do livro: ");
    gets(livros[i].nome);
    printf("\nAutor: ");
    gets(livros[i].autor);
    printf("\n ISBN : ");
    scanf("%lli", livros[i].isbn);
    printf("\n Volume em romanos: ");
    gets(livros[i].volume);
    printf("\n Ano de lancamento: ");
    scanf("%d", livros[i].data);
    printf("\nEditora do livro: ");
    gets(livros[i].editora);
    printf("\nQuantidade de paginas no livro: ");
    scanf("%d", livros[i].paginas);
}
int main()
{
    int opc = menu();
    struct informacoes livros[10];
    int i=0;
    switch(opc)
    {
        case 1:
            cadastro(livros, &i);
    }
    return (EXIT_SUCCESS);
}

A: Seu código na verdade tem vários erros, os 2 mais claros são:

*

*Você não pode enviar um ponteiro para um método que você pede um valor inteiro como parâmetro:

Onde você colocou:
cadastro(livros, &i);

Troque por:
cadastro(livros, i); //Note que não possui o &

*O método cadastro é do tipo int mais não retorna nenhum valor, coloque-o do tipo void, ou seja, não retorna nada:

Onde você colocou:
int cadastro(struct informacoes *livros, int i){

Troque por:
void cadastro(struct informacoes *livros, int i){

A: faça dessa forma:
scanf("%[^\n]s",nome_variavel);


text:
Q: Navigation changed in react native I have changed from the this navigation
"react-navigation": "^4.4.3",

to
"@react-navigation/stack": "^6.0.11",

But the problem is now app is crashing due to
props.navigation?.state?.params?.data

Above route params are working in the whole app so anyone can let me know how can i resolve it. So i got all the params with less changes. As these are changed in both versions.
Thanks

A: Follow the below code,
function DetailsScreen({ route, navigation }) {
    const {itemId} = route.params;
}

--------------OR----------------
using hooks
import {useRoute} from '@react-navigation/core';
function DetailsScreen({ route, navigation }) {
    const route = useRoute();
    const {itemId} = route.params;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: GSON throwing error when trying to pares a simple rest api response: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $ I'm trying to parse a JSON like this
{
    "meta": {
        "limit": 20,
        "next": null,
        "offset": 0,
        "previous": null,
        "total_count": 1
    },
    "objects": [
        {
            "customer_id": "some-customer-id",
            "id": 5,
            "is_active": true,
            "product_code": "some-product-code",
            "resource_uri": "/api/v1/aws-marketplace/5/",
            "support_subscription_id": "22"
        }
    ]
}

generated for http://www.jsonschema2pojo.org I got his Java clases
package com.greenqloud.netappstats.collector.metrics.gqconsole.api;

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class AwsMarketplace {

@SerializedName("meta")
@Expose
private Meta meta;
@SerializedName("objects")
@Expose
private List<Object> objects = null;

public Meta getMeta() {
return meta;
}

public void setMeta(Meta meta) {
this.meta = meta;
}

public List<Object> getObjects() {
return objects;
}

public void setObjects(List<Object> objects) {
this.objects = objects;
}

}

Meta class
package com.greenqloud.netappstats.collector.metrics.gqconsole.api;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Meta {

@SerializedName("limit")
@Expose
private int limit;
@SerializedName("next")
@Expose
private String next;
@SerializedName("offset")
@Expose
private int offset;
@SerializedName("previous")
@Expose
private String previous;
@SerializedName("total_count")
@Expose
private int totalCount;

public int getLimit() {
return limit;
}

public void setLimit(int limit) {
this.limit = limit;
}

public String getNext() {
return next;
}

public void setNext(String next) {
this.next = next;
}

public int getOffset() {
return offset;
}

public void setOffset(int offset) {
this.offset = offset;
}

public String getPrevious() {
return previous;
}

public void setPrevious(String previous) {
this.previous = previous;
}

public int getTotalCount() {
return totalCount;
}

public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}

}

Object class
package com.greenqloud.netappstats.collector.metrics.gqconsole.api;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Object {

@SerializedName("customer_id")
@Expose
private String customerId;
@SerializedName("id")
@Expose
private int id;
@SerializedName("is_active")
@Expose
private boolean isActive;
@SerializedName("product_code")
@Expose
private String productCode;
@SerializedName("resource_uri")
@Expose
private String resourceUri;
@SerializedName("support_subscription_id")
@Expose
private String supportSubscriptionId;

public String getCustomerId() {
return customerId;
}

public void setCustomerId(String customerId) {
this.customerId = customerId;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public boolean isIsActive() {
return isActive;
}

public void setIsActive(boolean isActive) {
this.isActive = isActive;
}

public String getProductCode() {
return productCode;
}

public void setProductCode(String productCode) {
this.productCode = productCode;
}

public String getResourceUri() {
return resourceUri;
}

public void setResourceUri(String resourceUri) {
this.resourceUri = resourceUri;
}

public String getSupportSubscriptionId() {
return supportSubscriptionId;
}

public void setSupportSubscriptionId(String supportSubscriptionId) {
this.supportSubscriptionId = supportSubscriptionId;
}

}

But when trying to deserialise with this func
Type localVarReturnType = new TypeToken<List<InstanceCreatorForAwsMarketplace>>(){}.getType();
ApiResponse<List<InstanceCreatorForAwsMarketplace>> responseFromApiCleint = apiClient.execute(newCall, localVarReturnType);

I get the following error:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

Any idea what might be the issue? This looks like a fairly simple json that the rest service returns, but I have not been able to get it work, any help would be greatly appreciated.

A: Right after I had written the question, I found out the answer, of course the top level class should not be a list, just the class it self. But I have a secondary question, can the three mapper classes be mounted into one class, just a cosmetic issue?


text:
Q: Prove that $f$ is Riemann-integrable on $[a,b]$ Assume that $\{r_n\}$ is an index of rational numbers in the interval $[a,b]$ and $\{v_n\}$ is a sequence of non-zero real numbers which converges to $0$.
Define $f:[a,b] \to \mathbb R$ this way :
If $x=r_n$ ,  $f(x)=v_n$
If $x \notin \mathbb Q \cap [a,b]$ , $f(x)=0$

Prove that $f$ is Riemann-integrable on $[a,b]$.

My try :
I observed that $f$ is discontinuous on each interval and is not monotonic on any interval. That makes it hard to prove the statement above. I don't know what to do next...

A: Lemma (not hard to prove): If $f_1,f_2,\dots$ are Riemann integrable (RI) on $[a,b],$ and $f_n\to f$ uniformly on $[a,b],$ then $f$ is RI on $[a,b].$
In our problem, we have
$$f(x) = \sum_{k=1}^{\infty}v_k\chi_{\{r_k\}}(x).$$
Now each summand above is RI, hence so is $S_n(x) =\sum_{k=1}^{n}v_k\chi_{\{r_k\}}(x)$ for any finite $n.$ For any $x\in [a,b],$ we have
$$|f(x) - S_n(x)| =  \sum_{k=n+1}^{\infty}v_k\chi_{\{r_k\}}(x) \le \sup \{v_{n+1}, v_{n+2}, \dots \}.$$
The supremum on the right $\to 0$ by hypothesis. Hence $S_n \to f$ uniformly on $[a,b],$ and we're done by the lemma.

A: Let $x$ not in $Q\cap [0,1]$, suppose that $f$ is not continuous at $x$, there exists $c>0$ and a sequence $x_m$ such that $lim_nx_m=x$ and$|f(x_m)|>c$.
We have $x_n\in Q\cap [a,b]$, and $f(x_m)=v_{g(m)}$ where $x_m=r_{g(m)}$. The sequence of $x_m$ contains infinite distinct terms. This implies that for every $M>0$ there exists  $L$ such that $m>L$ implies that $g(m)>M$. Since $lim_nv_n=0$, there exists $M_c$ such that $n>M_c, |v_n|<c$, we can choose $L_c$ such that $m>L_c$ implies that $g(m)>M_c$.  We deduce that $m>L_c$ implies that $|f(x_m)|=|v_{g(m)}|<c$. Contradiction.
The Lebesgue integrability condition implies that $f$ is Riemann integrable.

A: I think in this way it should work:
Consider for the sake of simplicity $v_n >0$ for each $n \in \mathbb{N}$. Let $ 1 > \epsilon >0$ By definition there exists $n_m \in \mathbb{N}$ such that $v_n < \epsilon$ for each $n \ge n_m$.
Now observe that one can assume that $ a = r_1 < r_2 < . . . < r_{n_m} = b$. Take $\delta$ to be $\epsilon\min\{ | r_i - r_j |\}/2$ Consider the partition $P =r_1< r_1 + \delta/2 < r_2 . . . r_{n_m - 1} + \frac{\delta}{2^{n_m - 1}} < r_{n_m} $ which now i rename $ x_{1}^0 < x_{1}^1 < . . . < x_{n_m}^0$. We have that $U(P) = \sum_{i=1}^{n_m-1} v_i ( x_{i}^1 - x_{i}^0) + \sum_{i=2}^{n_m} \sup_{[ x_{i-1}^1, x_{i}^0]}(f(x)) (x_{i}^0 - x_{i-1}^1)$ Now you can extimate this upper riemann sum observing:

*

*our choose of $n_m$ gives $\sup_{[ x_{i-1}^1, x_{i}^0]}(f(x)) < \epsilon$

*our choose of the partition gives $\sum_{i=1}^{n_m-1} v_i ( x_{i}^1 - x_{i}^0) \le \max\{v_1, . . .,v_{n_m}\}\ \epsilon$

Thus you get $U(P) \le \max\{v_1, . . .,v_{n_m}\}\ \epsilon + \epsilon (b - a)$ and you can conclude, because a convergent sequence of real numbers is bounded, that $U(P) \rightarrow 0$, thus the claim since it's obvious that $L(P) \ge 0$ (I supposed $v_n \ge 0$, otherwise you have to do the same thing for lower sums).


text:
Q: Android SwitchCompat: OnClick check programatically if switch should be triggered I already searched a long time, but couldn't find a proper solution.
I have a SwitchCompat and if the user clicks on it, and REST call is fired.
I only want to switch the SwitchCompat when the REST-call is successful. I implemented the onCheckedChanged() method, but since the call is asynchronous the SwitchCompat get switched before I receive the response.
-> I want to check on buttonclick if the switch gets switched or not.

A: You have several options:

*

*You can add your network call to onCheckedChanged() method, and show progress bar while making api call. After that, set state according to response.

*You can override touch callbacks so that checkedChanged does not get called from user actions and only trigger it yourself from code.


text:
Q: Image printing, file in use by another process When I click on the print button, the program saves an image to a certain file name. The program then gets the file and print it. But when I do it a second time, the file is in use by another process, even though the printing is done. Is there any way that I can close the file before the print button is pressed again?
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
    string pathImage = Environment.CurrentDirectory + "\\chart1.png";
    chart1.SaveImage(pathImage, System.Windows.Forms.DataVisualization.Charting.ChartImageFormat.Png);
    Image newImage = Image.FromFile(pathImage);
    Point ulCorner = new Point(50, 425);
    e.Graphics.DrawImage(newImage, ulCorner);
}

private void button4_Click(object sender, EventArgs e)
{
    if (printPreviewDialog1.ShowDialog() == DialogResult.OK)
    {
        printDocument1.Print();
    }
}

A: Probably because you're not releasing the image:
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
    string pathImage = Environment.CurrentDirectory + "\\chart1.png";
    chart1.SaveImage(pathImage, System.Windows.Forms.DataVisualization.Charting.ChartImageFormat.Png);
    using (var newImage = Image.FromFile(pathImage))
    {
        Point ulCorner = new Point(50, 425);
        e.Graphics.DrawImage(newImage, ulCorner);
    }
}

Remember that Image is IDisposable.


text:
Q: Applet to find least-crossings drawing for an input graph Is there a convenient online applet that allows me to draw a graph, after which it outputs a plane drawing of an isomorphic graph that has (approximately) the least number of crossings among all drawings of the graph?
I have this small graph whose drawing I would like to simplify, and it would be great if I could label the vertices with names.


text:
Q: Self study, non-linear optimization I want to self study a small (5 ECTS) introductory course on nonlinear optimization.
The course content on the university website is not very detailed, but I'll report it anyways:

Modelling of practical problems as optimization problems, unconstrained optimization (optimality conditions, globally convergent descent methods, Newton method and Newton-type methods, globalization of locally convergent methods), elements of constrained optimization.

Lastly, the lectures are based on the book https://www.springer.com/de/book/9783034601429, which unfortunately is in German, so I can't really study on it.
Do you have any reference material/book I could learn to this purpose?

A: Begin with Boyd's Convex Analysis: https://web.stanford.edu/~boyd/cvxbook/ (free).
And continue with Bertsekas' Nonlinear Programming: http://web.mit.edu/6.252/www/.


text:
Q: problem with creating docker image for spring boot application i'm trying to create docker image for spring boot application and i'm getting this error

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.18.1:test (default-test) on project onlineStorePlatform: Execution default-test of goal org.apache.maven.plugins:maven-surefire-plugin:2.18.1:test failed: Plugin org.apache.maven.plugins:maven-surefire-plugin:2.18.1 or one of its dependencies could not be resolved: The following artifacts could not be resolved: org.apache.maven.surefire:maven-surefire-common:jar:2.18.1, org.apache.maven.surefire:surefire-api:jar:2.18.1, org.apache.maven:maven-core:jar:2.2.1, org.apache.maven:maven-settings:jar:2.2.1, org.codehaus.plexus:plexus-interpolation:jar:1.11, org.apache.maven:maven-plugin-parameter-documenter:jar:2.2.1, org.slf4j:slf4j-jdk14:jar:1.5.6, org.slf4j:slf4j-api:jar:1.5.6, org.slf4j:jcl-over-slf4j:jar:1.5.6, org.apache.maven.reporting:maven-reporting-api:jar:3.0, org.apache.maven:maven-profile:jar:2.2.1, org.apache.maven:maven-model:jar:2.2.1, org.apache.maven:maven-repository-metadata:jar:2.2.1, org.apache.maven:maven-error-diagnostics:jar:2.2.1, org.apache.maven:maven-project:jar:2.2.1, org.apache.maven:maven-plugin-registry:jar:2.2.1, org.apache.maven:maven-plugin-descriptor:jar:2.2.1, org.apache.maven:maven-artifact-manager:jar:2.2.1, backport-util-concurrent:backport-util-concurrent:jar:3.1, org.apache.maven:maven-monitor:jar:2.2.1, org.codehaus.plexus:plexus-utils:jar:1.5.15, org.apache.maven:maven-artifact:jar:2.2.1, org.apache.maven.plugin-tools:maven-plugin-annotations:jar:3.3: Cannot access central (https://repo.maven.apache.org/maven2) in offline mode and the artifact org.apache.maven.surefire:maven-surefire-common:jar:2.18.1 has not been downloaded from it before. -> [Help 1]

POM.xml file
<project
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>io.javabrains.spring</groupId>
  <artifactId>onlineStorePlatform</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>onlineStorePlatform</name>

    <!-- step #1: add the parent -->
  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.10.RELEASE</version>
  </parent>
  <!-- End of step #1 -->

  <!-- step #2: create dependencies -->

  <dependencies>

         <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.19</version>
        </dependency>

        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <version>7.0.0.jre8</version>
        </dependency>

  </dependencies>

  <!-- step #3: change java version -->
 <properties>
         <java.versions>13.0.1</java.versions>
 </properties>

 <build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.5.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    </plugins>
    <finalName>onlineStoreplatform</finalName>
 </build>

 </project>

and finally the content of Dockerfile
FROM openjdk:8
EXPOSE 8080
ADD target/onlineStoreplatform.jar onlineStoreplatform.jar
ENTRYPOINT ["java","-jar","/onlineStoreplatform.jar"]

any help would be appreciated.

A: Did you read the stacktrace?
Cannot access central (https://repo.maven.apache.org/maven2) in offline mode and the artifact org.apache.maven.surefire:maven-surefire-common:jar:2.18.1 has not been downloaded from it before
It looks like your build engine is not connected to the internet.


text:
Q: Download file from network using PyQGIS 2.x I have a python plugin targeting QGIS 1.8 that uses QgsNetworkAccessManager and QNetworkRequest to issue a GetCapabilities request to WMS servers.
With 1.8 everything was working fine.  Now we are porting this plugin to QGIS 2.x (tested on 2.6 and 2.7 of 16/02/2015) and have found that some errors are being displayed.
As far as our python code can tell everything is working as expected, however 20 seconds after a network request is initiated a "Network request ... timed out" message is displayed in the messages log and in a banner at the top of the map pane.

I have created a minimal example that can be copy/pasted into the python console:
from datetime import datetime
from PyQt4.QtCore import SIGNAL, QUrl
from PyQt4.QtNetwork import QNetworkAccessManager, QNetworkRequest

def request_download():
    global reply
    manager = QgsNetworkAccessManager.instance()
    url = QUrl("http://www.example.net")
    request = QNetworkRequest(url)
    print "Download start time: {}".format(datetime.now())
    reply = manager.createRequest(QNetworkAccessManager.GetOperation, request)
    reply.connect(reply, SIGNAL("finished()"), handle_download)

def handle_download():
    global reply
    print "Download finish time: {}".format(datetime.now())
    print "Finished: {}".format(reply.isFinished())
    print "Bytes received: {}".format(len(reply.readAll()))

request_download()

# python console:
#   Download start time: 2015-02-23 15:24:39.887000
#   Download finish time: 2015-02-23 15:24:41.077000
#   Finished: True
#   Bytes received: 1270
#
# message log:
#   2015-02-23T15:25:01    1    Network request http://www.example.com timed out

As this example shows the download appears to succeed:

*

*The finish() signal is emitted.

*The reply.isFinished() method returns True.

*The reply.readAll() method returns the correct data.

However the time out error message is displayed :

*

*Prominently on a yellow banner at the top of the map pane.

*Under the Network tab on the Log Messages panel.

How do I perform a download without triggering this error?

A: If you are fine with a solution that uses QNetworkAccessManager from Qt (instead of the manager from QGIS libs), you can do it this way:
from datetime import datetime
from PyQt4.QtCore import QUrl
from PyQt4.QtNetwork import QNetworkAccessManager, QNetworkRequest

def request_download(manager):
    url = QUrl("http://www.geotux.tuxfamily.org")
    request = QNetworkRequest(url)
    print "Download start time: {}".format(datetime.now())
    manager.get( request )

def handle_download(reply):
    print "Download finish time: {}".format(datetime.now())
    print "Finished: {}".format(reply.isFinished())
    print "Bytes received: {}".format(len(reply.readAll()))

manager = QNetworkAccessManager()
manager.finished.connect( handle_download )
request_download(manager)

As you can see, you don't need to use global variables.

BTW, I couldn't use your code from a QGIS Python console, it threw this error: RuntimeError: no access to protected functions or signals for objects not created from Python


text:
Q: Is to possible to use Ansible synchronize on two directories on target node? Can I use the synchronize module to synchronize two directories on the target node?
Default synchronize is used to transfer files from the control machine to the target machine. Can it be configured to sync two directories on the target machine as well? How?

A: Yes.  Something like this will do it:
  - name: Syncs sources to target
    synchronize:
      src: '/my/origin/'
      dest: '/my/destination'
    delegate_to: "{{ inventory_hostname}}"

Key is the delegation to the target host itself.  You may need to play with the become option and, of course, see the other options from the module.


text:
Q: Can't install charlock holmes gem, libicu-devel installed I am trying to install charlock holmes, nevertheless, I keep getting an error:
[root@hugovm gitlab]# gem install charlock_holmes --version '0.6.9.4'
Building native extensions.  This could take a while...
ERROR:  Error installing charlock_holmes:
    ERROR: Failed to build gem native extension.

    /usr/bin/ruby extconf.rb
checking for main() in -licui18n... yes
checking for main() in -licui18n... yes
checking for unicode/ucnv.h... yes
  -- tar zxvf file-5.08.tar.gz
  -- ./configure --prefix=/usr/local/share/gems/gems/charlock_holmes-0.6.9.4/ext/charlock_holmes/dst/ --disable-shared --enable-static --with-pic
  -- patch -p0 < ../file-soft-check.patch
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
    --with-opt-dir
    --without-opt-dir
    --with-opt-include
    --without-opt-include=${opt-dir}/include
    --with-opt-lib
    --without-opt-lib=${opt-dir}/lib64
    --with-make-prog
    --without-make-prog
    --srcdir=.
    --curdir
    --ruby=/usr/bin/ruby
    --with-icu-dir
    --without-icu-dir
    --with-icu-include
    --without-icu-include=${icu-dir}/include
    --with-icu-lib
    --without-icu-lib=${icu-dir}/
    --with-icui18nlib
    --without-icui18nlib
    --with-icui18nlib
    --without-icui18nlib
extconf.rb:7:in `sys': patch -p0 < ../file-soft-check.patch failed, please report issue on http://github.com/brianmario/charlock_holmes (RuntimeError)
    from extconf.rb:61:in `block (2 levels) in <main>'
    from extconf.rb:59:in `chdir'
    from extconf.rb:59:in `block in <main>'
    from extconf.rb:55:in `chdir'
    from extconf.rb:55:in `<main>'

Gem files will remain installed in /usr/local/share/gems/gems/charlock_holmes-0.6.9.4 for inspection.
Results logged to /usr/local/share/gems/gems/charlock_holmes-0.6.9.4/ext/charlock_holmes/gem_make.out

I already installed libicu-devel.
Thanks

A: I had the exact same issue today. Tried to install gitlab on a clean fedora machine.
For me, a line in /usr/local/share/gems/gems/charlock_holmes-0.6.9.4/ext/charlock_holmes/gem_make.out pointed to mkmf.log, which is in the same directory as above log file.
There it said "patch: command not found"

sudo yum install patch

A: In you output I can read:

extconf.rb:7:in `sys': patch -p0 < ../file-soft-check.patch failed, please report issue on http://github.com/brianmario/charlock_holmes (RuntimeError)

So it all points to a bug. I suppose it is a good idea follow the output and created an issue there, explaining what you are trying to do and giving details of your environment.

A: ruby-devel is missing
yum install ruby-devel

and you'll be set :)


text:
Q: How to wait for a http request to finish in Angular? I've been building a SPA with Angular 4 on the front end and ASP.NET Core 2 on the Backend. Basically, I'm trying to automatically renew an user login, given a valid token. When I reload a page, for example, I would like that Angular stayed logged in. I'm storing the token on local storage, as well as an user object so I can check some user properties (if he/she is logged in for example).
How should I force angular to wait for the http request to finish?
Here's the .net get Service:
get<T>(url: string): Observable<T> {
    let options = this.doHeaders();
    return this.doSub(this.http.get(this.doUrl(url), options));
}

private doSub<T>(obs: Observable<Response>) {
    var ob1: Observable<T> = obs.map(this.extractData)
        .catch(this.handleError);

    return ob1;
}

Here's the HTTP Request code:
   getUser() {

    if (this.storage.token == null || this.storage.token == '') {
        return;
    }

    this.net.get<LoginModel>(`Authentication/GetUser`).subscribe(t => {
        this.storage.token = t.token;
        this.storage.user = t.user;
        console.log(this.storage.user);
    });
}

Here's how I'm checking for the user:
export class StorageService {

    constructor(
        private storage: LocalStorageService
    ) {
    }

    public user: User = null;

    public get isLoggedIn(): boolean {
        return this.user != null;
    }

}
export class IsLoggedIn implements CanActivate {

constructor(
    private storage: StorageService,
    private router: Router
) { }

canActivate(
    childRoute: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
) {
    if (this.storage.isLoggedIn) {
        return true;
    }

    this.router.navigate(['account/login'], {
        queryParams: {
            return: state.url,
            message: 'You must be logged in'
        }
    });
    return false;
}}

The real issue is: Whenever I try to reload the page on a protected page, Angular does not wait for the http to complete, and redirects me to the login page. After about a few seconds, it logs in, but i've been redirected already.
The above code is being executed on AppComponent (NgOnInit). Thanks in advance.

A: Use .toPromise on your observable followed by async/await.
await this.net.get<LoginModel>(`Authentication/GetUser`).toPromise();

A: You can use promises with async/await
async getUser() {
    if (this.storage.token == null || this.storage.token == '') {
        return;
    }

    const t = await this.net.get<LoginModel>(`Authentication/GetUser`).toPromise();

    this.storage.token = t.token;
    this.storage.user = t.user;

    console.log(this.storage.user);
}

See more:

*

*Promises

*async

*await

*ES8 async/await

*async/await tutorial

*async/await explained

A: Since .toPromise has been deprecated deprecations,  you should use one of the two built in static conversion functions firstValueFrom or lastValueFrom.
It should be something like that
await firstValueFrom(this.net.get<LoginModel>(`Authentication/GetUser`));

A: You can not use the async/await syntax with Observables returned by Angular HttpClient so you first need to convert the observable to a promise first.
Luckily the Observable interface exports a toPromise() method which returns a promise from the observable:
await this.net.get<LoginModel>('Authentication/GetUser').toPromise();

See this example of how to use Async/Await with Angular HttpClient


text:
Q: python split function not creating a list? x = input('Hey, wanna know the area of a triangle? Enter the height and base  \\n')

for x_element in x.split(" "):
    print(x_element)

So the goal is to create a function that calculates the area of a triangle. However when I use the code above and enter two values for the input statement, I'm thinking the split function will separate them into a list but instead, if I enter 5 6 it will create the following output
5
6

Both numbers are on new lines as opposed to making a list. I'm pretty new to python so I'm not sure why this is happening. Any help would be greatly appreciated.
Thanks,

A: Yes, when x is the string '5 6', then x.split(' ') returns the list [5,6]. Your "for" loop is iterating over that list and printing each item in the list.  By default, the print() function adds a newline after the arguments.

A: You are printing each value in the list individually. By default, print inserts a trailing newline, so they appear on separate lines.
If you want to print the list, just do so.
x = input('Hey, wanna know the area of a triangle? Enter the height and base  \\n')

print(x.split(' '))


text:
Q: Gradient Descent on Function that is non-differentiable at finitely many points Suppose that I have a (possibly non-convex) function that maps $R^N$ to $R$, and is differentiable at all points except finitely many points. I want to use gradient descent algorithm to show convergence to a local optima,
$$
x(k+1) = x(k) + \alpha(k) \nabla f |_{x=x(k)},
$$
where $\nabla f |_{x=x(k)}$ is derivative computed at point $x(k)$, $\alpha(k)$ is step-size at iteration $k$. When derivative is not defined, a random step is taken (say Gaussian) with variance $\alpha(k)$.
Assume that (wherever derivative is defined) the norm of derivative is uniformly bounded by $B$, i.e. $\sup_{x} \|\nabla f \| \le B$.
Is it true that the iterates converge to a local optima?

A: Edit : This answers the original question. The question has been edited after this answer was made.
No, this does not work :
Consider $f : x \mapsto \frac{1}{x}$, which isn't differentiable at $0$. For any positive value of $\alpha(k)$, if you take $x(k)$ whose absolute value is small enough (eg. smaller than $\alpha(k)$ and close to $0$), $x(k+1)$ will be a number with HUGE absolute value. I suspect that the sequences formed as described in original post will exhibit a chaotic behavior.

A: The result does hold for such a general case, even if the function has only one global maximizer. For example, there is no way to guarantee that the function does not oscillate too much, like the function $g$ such that $g(0)=0$ and $$g(x)=-(\sin(1/x)+1.5)\dfrac{x^{2}}{1+x^2},$$ for all $x\not=0$, does. This function is differentiable everywhere and have bounded derivative. In this setting,  the sequence generated by the function $g$ that starts at any of its infinite minimizer around $0$ would stay still at this critical point forever, i.e., $x^{k}=x^{k+1},$ for all $k\in\mathbb{N}$, whenever $x^{0}$ is a minimizer point.

If local optima means maximum or minimum, the function $g:\mathbb{R}\rightarrow\mathbb{R}$ such that
$$h(x) = x^3/(1+x^2)$$ for all $x \in \mathbb{R}$ works if you start at the point $x_0=0.$ The sequence generated is the constant one.

If you want a example that the function is bounded and local optima means maximum or minimum, the function $i:\mathbb{R}\rightarrow\mathbb{R}$ such that
$$i(x) = x^3/(1+x^4)$$ for all $x \in \mathbb{R}$ works if you start at the point $x_0=0.$ The sequence generated is the constant one.

The fourth and the brighter example, if local optima means maximum or minimum, the function $j:\mathbb{R}\rightarrow\mathbb{R}$ such that
$$j(x)=\dfrac{x}{1+(-x+|x|)^2}+\sin\left(\dfrac{x}{1+(-x+|x|)^2}\right),$$ for all $x \in \mathbb{R},$ is an example of differentiable function that it will be quite rare for a starting point $x_0<0$ to be such that the GD method to converge to a local maximum. This function has only one local maximum (it's global maximum as well) and yet have such behavior because of the huge amount of critical points in the negivive axis.

I think it's clear that there is no possible assumption that makes your result holds in such generality.


text:
Q: Jquery Control image move up and down inside div Jquery Control image move up and down inside div
Hi, i need your help by make image move up and down inside some div ,
for example ( i saw the example in stackoverflow)
http://jsfiddle.net/PKBXL/29/

A: $(document).ready(function() {
    var intId = setInterval(animateImage,1000);
    var intId=   setInterval(animateupImage,1000);
});

function animateImage() {
    $('#bee').animate({bottom: '-50%'}, 3000, 'linear', 1000);
      }
function animateupImage() {
   $('#bee').animate({bottom: '0%'}, 3000, 'linear',1000 );
  }

DEMO


text:
Q: Did Arthur Dayne give Dawn to the Smiling Knight? Discussing a recent question on M&TV, It occurred to me that the duel between Ser Arthur Dayne and the Smiling Knight isn't all that clear.
The passage says:

And he'd held his own against the Smiling Knight, though it was Ser
  Arthur who slew him. What a fight that was, and what a foe. The
  Smiling Knight was a madman, cruelty and chivalry all jumbled up
  together, but he did not know the meaning of fear. And Dayne, with
  Dawn in hand . . .
The outlaw's longsword had so many notches by the end that Ser Arthur had stopped to let him fetch a new one. "It's that white sword
  of yours I want," the robber knight told him as they resumed, though
  he was bleeding from a dozen wounds by then. "Then you shall have it,
  ser," the Sword of the Morning replied, and made an end of it.
The world was simpler in those days, Jaime thought, and men as well as
  swords were made of finer steel.ASOS - Jaime VIII

When reading this, I always thought it meant that Arthur handed over his sword to his foe but still won. But there are those who read it as Arthur Dayne killing the Smiling Knight right there, denying his request for Dawn. My understanding is based on the following reasons:

*

*Arthur Dayne had the reputation of being the finest and most chivalrous Knight who ever lived.

*Jaime remembers both men and their fight with admiration. It would have been very dishonourable and unchivalrous of him to mislead his opponent that he was considering his request. Jaime would have made some cynical comment about it then. Like he made about Ser Gerold Hightower on his response to Jaime on Aerys burning Rickard Stark to death and Ser Oswell Whent on his refusal to do something about protecting the Queen from savagery of the King. As he notes right after his recollection of the duel, men were made of finer steel back in those days, there is nothing fine about relying on superior quality of your sword rather than your skill. That too in face of an enemy bleeding from a dozen wounds taken from that very sword, who also happens to be more or less equally chivalrous.

*It makes no sense for Arthur Dayne to stop the fight to allow his opponent to rearm himself if he was just going to kill him anyways.

So is there any official, explicit indicator as to what really happened there? Did Arthur Dayne really give his sword to the Smiling Knight and finish the job with a new sword? Or did he just kill the robber Knight with Dawn?

A: There are three interpretations from the quote "Then you shall have it, ser" and they are:

*

*Here, take it, I don't like it anymore

*You will have to pry it from my dead body!

*You will get it but it will be buried in your skull!

Now from the initial quote alone they all appear to be equally likely. However, you need to take into the surrounding words of the quote to work out what happened.

Ser Arthur had stopped to let him fetch a new one

If he was going to give him Dawn for the rest of the duel, even as a slither of a thought, I doubt he would have told the other knight to fetch a new sword.

"It's that white sword of yours I want," the robber knight told him as they resumed

When Arthur told the knight he "can have it" they'd already resumed their fighting, I doubt they'd pause again to trade swords. This is also similar to the Tower of Joy with Ned saying "Noh nowy tends" (No, now it ends).

and made an end of it.

With the fact that Dayne killed the knight after he said he can have it I find it highly likely he was meaning it by interpretation number 3.
It's also worth noting if Dayne had given the knight Dawn for the rest of the fight it would highly likely have been retold in the stories. Such a big event missing from the story seems very unlikely to me. It's also worth noting that Dawn is a very superior sword to normal ones and so Dayne putting himself at a disadvantage is also unlikely.


text:
Q: boost::asio::deadline_timer doesn't call handler I have a tcp client that polls a server for an answer with a deadline so that if the server cannot be reached the client is not blocked. The problem I have encountered is that the async_wait never seems to call its handler, effectively blocking the client when it fails to connect. Every call to tcpPoll will have its own thread (which is why I create a new io_service) but it doesn't seem to work even without multithreading. Also, the NetworkEntity object can call tcpPoll more than once during its lifetime.
My question would be : What is blocking the deadline_timer from calling its handler? (and how to fix it)
Here is some relevant code, which is working as long as nothing fails (connect, write, read) (sorry if it's a bit long) :
void NetworkEntity::stop()
{
    stopped_ = true;
    //close socket
    //cancel timeout
}

void NetworkEntity::check_timeout(const boost::system::error_code& error)
{
    if (stopped_)
        return;
    if (timeout_.expires_at() <= boost::asio::deadline_timer::traits_type::now())
    {
        stop();
        timeout_.expires_at(boost::posix_time::pos_infin);
        std::cout << address_ << " timed out\n";
    }
    timeout_.async_wait(boost::bind(&NetworkEntity::check_timeout, this, boost::asio::placeholders::error));
}

std::vector<std::string> NetworkEntity::tcpPoll(const char* message, const char endOfMessage)
{
    boost::asio::io_service io_service;
    stopped_ = false;
    timeout_.expires_from_now(boost::posix_time::seconds(TIMEOUT_));
    timeout_.async_wait(boost::bind(&NetworkEntity::check_timeout, this, boost::asio::placeholders::error));
    tcp::resolver resolver(io_service);
    start_connect(&io_service, resolver.resolve(tcp::resolver::query(address_, port_)), message, endOfMessage);
    io_service.run();
    //retrieve answer from class
    //return answer
}

void NetworkEntity::start_connect(boost::asio::io_service* io_service, tcp::resolver::iterator endpoint_iterator, const std::string message, const char endOfMessage)
{
    socket_.reset(new tcp::socket(*io_service));
    socket_->async_connect(endpoint_iterator->endpoint(),
        boost::bind(&NetworkEntity::handle_connect, this, io_service, boost::asio::placeholders::error, endpoint_iterator, message, endOfMessage));
}

void NetworkEntity::handle_connect(boost::asio::io_service* io_service, const boost::system::error_code& err, tcp::resolver::iterator endpoint_iterator, const std::string message, const char endOfMessage)
{
    if(stopped_)
        return;
    if (err)
    {
        std::cout << "Connect error: " << err.message() << "\n";
        stop();
    }
    else
    {
        start_write(message, endOfMessage);
    }
}

void NetworkEntity::start_write(const std::string message, const char endOfMessage)
{
    std::ostream request_stream(&request_);
    request_stream << message;
    boost::asio::async_write(*socket_, request_,
        boost::bind(&NetworkEntity::handle_write, this, boost::asio::placeholders::error, endOfMessage));
}

void NetworkEntity::handle_write(const boost::system::error_code& error, const char endOfMessage)
{
    if (stopped_)
        return;
    if (!error)
    {
        //sleep for 500ms to let time for the reciever to process info (had a bug on this one)
        start_read(endOfMessage);
    }
    else
    {
        std::cout << "write error : " << error.message() << "\n";
        stop();
    }
}

void NetworkEntity::start_read(const char endOfMessage)
{
    boost::asio::async_read_until(*socket_, answer_, endOfMessage,
        boost::bind(&NetworkEntity::handle_read, this, boost::asio::placeholders::error));
}

void NetworkEntity::handle_read(const boost::system::error_code& error)
{
    if (stopped_)
        return;
    if (error)
    {
        std::cout << "read error : " << error.message() << "\n";
        stop();
    }
    else
    {
        stop();
    }
}

A: I think you must be confused with multiple instances of io_service.
The reason I think this is because in your code you never show how you initialize timeout_. And the io_service instance you are using for the connection is only instantiated inside your tcpPoll function... This leads me to believe that you are accidentally registering the deadline timer on a separate io_service that you don't even run?
Here's a version that actually works, notes:

*

*it has done away with the stopped_ boolean, as it's unnecessary and bound to confuse

*see new implementation of check_timeout and stop on how to detect the various program flows

*the full code, self-contained, is exactly only few more lines of code than what you posted in the question

#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>

using tcp = boost::asio::ip::tcp;

struct NetworkEntity {

    boost::asio::io_service io_service;
    boost::asio::deadline_timer timeout_{io_service};
    std::string address_ = "localhost";
    std::string port_    = "6767";
    int TIMEOUT_         = 3;
    boost::shared_ptr<tcp::socket> socket_;
    boost::asio::streambuf request_, answer_;

    void stop()
    {
        if (socket_)
        {
            socket_->cancel();
            socket_->close();
        }
        timeout_.cancel();
        io_service.stop();
    }

    void check_timeout(const boost::system::error_code& error)
    {
        if (error != boost::asio::error::operation_aborted)
        {
            stop();
            std::cout << address_ << " timed out\n";
        }
        timeout_.async_wait(boost::bind(&NetworkEntity::check_timeout, this, boost::asio::placeholders::error));
    }

    std::vector<std::string> tcpPoll(const char* message, const char endOfMessage)
    {
        timeout_.expires_from_now(boost::posix_time::seconds(TIMEOUT_));
        timeout_.async_wait(boost::bind(&NetworkEntity::check_timeout, this, boost::asio::placeholders::error));

        tcp::resolver resolver(io_service);
        start_connect(&io_service, resolver.resolve(tcp::resolver::query(address_, port_)), message, endOfMessage);

        io_service.run();
        //retrieve answer from class
        //return answer
        std::ostringstream oss;
        oss << &answer_;
        return { oss.str() };
    }

    void start_connect(boost::asio::io_service* io_service, tcp::resolver::iterator endpoint_iterator, const std::string message, const char endOfMessage)
    {
        socket_.reset(new tcp::socket(*io_service));
        socket_->async_connect(endpoint_iterator->endpoint(),
                boost::bind(&NetworkEntity::handle_connect, this, io_service, boost::asio::placeholders::error, endpoint_iterator, message, endOfMessage));
    }

    void handle_connect(boost::asio::io_service* io_service,
            const boost::system::error_code& err,
            tcp::resolver::iterator endpoint_iterator,
            const std::string message,
            const char endOfMessage)
    {
        if (err)
        {
            std::cout << "Connect error: " << err.message() << "\n";
            stop();
        }
        else
        {
            start_write(message, endOfMessage);
        }
    }

    void start_write(const std::string message, const char endOfMessage)
    {
        std::ostream request_stream(&request_);
        request_stream << message;
        boost::asio::async_write(*socket_, request_,
                boost::bind(&NetworkEntity::handle_write, this, boost::asio::placeholders::error, endOfMessage));
    }

    void handle_write(const boost::system::error_code& error, const char endOfMessage)
    {
        if (!error)
        {
            //sleep for 500ms to let time for the reciever to process info (had a bug on this one)
            start_read(endOfMessage);
        }
        else
        {
            std::cout << "write error : " << error.message() << "\n";
            stop();
        }
    }

    void start_read(const char endOfMessage)
    {
        boost::asio::async_read_until(*socket_, answer_, endOfMessage,
                boost::bind(&NetworkEntity::handle_read, this, boost::asio::placeholders::error));
    }

    void handle_read(const boost::system::error_code& error)
    {
        if (error)
        {
            std::cout << "read error : " << error.message() << "\n";
        }
        stop();
    }
};

int main()
{
    NetworkEntity ne;
    for (auto& s : ne.tcpPoll("this is my request", '\n'))
    {
        std::cout << "Line: '" << s << "'\n";
    }
}


text:
Q: AutoHotkey unreliable behaviour in Windows 10 Simple AutoHotkey script that should open Firefox is unreliable in Windows 10.
#f::Run firefox.exe

Sometimes it opens Firefox, but other times it opens 'Feedback Hub' window.
It looks like sometimes AutoHotkey scripts are ignored or maybe Windows 10 native shortcuts take precedence.
AutoHotkey version: v1.1.25.02, loaded as regular user (not run as administrator)
Any ideas?

A: You could try $#f::Run firefox.exe - you can read about the various modifiers including $ here https://autohotkey.com/docs/Hotkeys.htm#Symbols


text:
Q: The Peano form of the remainder of $\frac1{1+x^2}$'s Maclaurin formula? I need to get the Maclaurin formula with the Peano form of the remainder of $\displaystyle \frac{1}{1+x^2}$. Here is what I do:
Since we have $$\displaystyle \frac{1}{1+x}=1-x+x^2+...+(-1)^nx^n+o(x^n)$$
then $$\displaystyle \frac{1}{1+x^2}=1-x^2+x^4+...+(-1)^nx^{2n}+o(x^{2n})$$
But in my textbook the remainder is different:
$$\displaystyle \frac{1}{1+x^2}=1-x^2+x^4+...+(-1)^nx^{2n}+o(x^{2n+1})$$
I can't figure out why the remainder can be $o(x^{2n+1})$, which is stronger than $o(x^{2n})$. Could anyone help me out here?

A: The function $$x \mapsto\frac1{1+x^2},\qquad x \in (-1,1),$$is even, then there is no term in $x^{2n+1}$ and you are allowed to write $o(x^{2n})=o(x^{2n+1})$.


text:
Q: Sublime text 4 curly bracket indentation problem Sublime text 4 is giving weird indentation when pressing enter between curly braces
    for(int i=0;i<10;++i){
                          }

In some already opened file it is working fine by indenting like this :
   for(int i=0;i<10;++i){
   }

I tried disabling packages and re enabling them but no success, can someone please help.
Thanks!


text:
Q: How to use same config file for serving modules with requirejs and using r.js on the server side to concatenate and minify? I am working on a project that uses requirejs to dynamically load modules from a web browser. Some of the modules are vendor files, e.g. jQuery, which are all installed into a folder /project/root/lib/ via bower. This project's modules are located in a folder /project/root/components/. So I have a requirejs config, components/main.js, that looks something like this:
  requirejs.config({
    baseUrl: '/components',
    paths: {
      jquery: '/lib/jquery/jquery',
    }
  });

This way, when a vendor module is requested, require finds it by using the mappings defined in paths, while all other modules are located relative to components.
I also want to use r.js to perform concatenation and minification and reduce all javascript files to simply app.js for use in production. I was able to successfully perform this task with r.js -o build.js. Here is what build.js looks like:
({
    baseUrl:'components',
    out:    'js/app.js',
    name:   'app',
    paths: {
      jquery: '../lib/jquery/jquery'
    }
})

However, because there are dozens of vendor file paths defined in my require.js config (main.js), I don't want to have to replicate the configuration across two different files. I would rather use a single config file. The problem is that the paths defined in main.js are absolute (/lib/..., /components), because they're URL paths, but the paths in build.js need to be relative (../lib/..., ./components), because they're filesystem paths. Is there a way to reconcile these differences and define the paths only in main.js, which I then I load in using mainConfigFile in build.js? I tried using the require config called map in build.js, but this method required that I defined a new mapping for each module, which is just as bad as re-defining all of the paths. I want a blanket mapping, essentially.
Is there a method to consolidate my config files to avoid duplicate path definitions?

A: There is nothing that requires using absolute paths in the configuration passed to RequireJS. RequireJS interprets paths that are relative using baseUrl as the starting point so this should work:
requirejs.config({
    baseUrl: '/components',
    paths: {
      jquery: '../lib/jquery/jquery',
    }
});

RequireJS will perform the final path computation for jquery by merging /components with ../lib/jquery/jquery, which resolves to /lib/jquery/jquery, which is exactly the same as the absolute path that was there originally.


text:
Q: Swift swipe through photos randomly Originally I had a different post, just wanted to redo it to clean it up.

This is more or less the layout I wanted to go with. Imagine the first imageview had dog pictures, the second one had cat pictures and the third one had rabbit pictures. three folders contain a group of three separate sets of pictures.
What is the best way to set it up so I can randomly swipe, lets say the first image view where it would only show pictures of dogs.
What I am asking is, is there a certain way to create the file structures or link the pictures to each image view?
I have the basics of the random (something with a 4 in it don't remember the method exactly) and the basics of swipe, just was looking for help with linking the photos and file structure.
Please let me know if this still doesn't make sense.
Thank you
EDIT
after messing with this this is where I am at:
with a very simple array basically
catsArray: [String] = ["catpic1","catpic2"......]

then I have it set up as
        let randomIndex = Int(arc4random_uniform(UInt32(catArray.count)))

    if (sender.direction == .Right)
    {
        self.catImageView.image = UIImage(named: catArray[randomIndex])
    }

just me hacking things off the internet. now I am running into an issue. after a few swipes I get a null images or its just blank. Why is that?
now that I have some of this set up I am debating if I should just use parse for a server or if there is a better way.
thanks

A: Your question is far too vague. Are you worried about memory? If so, you should not load the images into an array. Instead load the image names, and load each image as it is swiped on-screen. You might want to load the current image and the next image so it's already in memory and can be displayed without lag.
Are you talking about using a UIPageViewController? That's a good class for managing a set of pages that you can scroll through. There is a sample app from Apple called PhotoScroller that illustrates that technique, along with tiling the images so you can display large images and handle zooming and panning. (The app is written in Objective-C however.)
EDIT:
Your updates make your question a little clearer.
There are lots of ways to handle this. Here's 1.
Create 3 separate folders, one for cats, one for dogs, and one for rabbits. (in your app's documents directory, or in the bundle, if the images will be shipped with the app.)
Use NSFileManager to create 3 separate arrays of filenames. Take a look at the methods contentsOfDirectoryAtURL:includingPropertiesForKeys:options:error: and contentsOfDirectoryAtPath:error:. You should be able to make either of those work.
Then you'll need to scramble your arrays of filenames to create a randomized order. You can use one of the block-based sort methods where your block uses a random number to determine the sort order of each pair of objects.
Finally you'll need to implement the swipe to switch.
It sounds like you are beginner so this is a lot to work through. You should break the problem into pieces and tackle them one at a time.

A: Either approach will work. It's probably a good exercise to write both versions. You'd learn from it.


text:
Q: Grails - not-null property references a null or transient value error only with concurrent users a web application that we have been developing in Grails has recently moved into the stress testing phase, and now we are encountering this issue that seems to only be happening when multiple users (different user accounts) perform the same actions at the same time.  These actions are transactional but none of them are executed on the same object (new objects are being created). The exception that we have been getting is:

Class: org.hibernate.PropertyValueException
  Message: not-null property references a null or transient value: xxx.xxx.xxx.domains.PathSections._PathViews_sectionsBackref

This is generally what the exception looks like, with some variations to the involved domain classes. To make it even worse, when this error occurs, every other transactional action that involves a list will result in the same error (different domain classes), whether concurrently done or not.  The server then needs to be restarted in order to temporarily fix it.  Here are some snippets of the relevant domain classes:
class PathViews extends View{

static constraints = {
    molreports(nullable:true)
    molorders(nullable:true)
    otherreports(nullable: true)
    sections(nullable:true)
    addendum(nullable:true)
    images(nullable:true)
    edits(nullable:true)
}

List sections
List otherreports
List molreports
List molorders
List images
PathEdits edits
PathSections addendum
int headings
String accid

static auditable = true

static hasMany = [sections: PathSections, otherreports: PathSections, molorders:MolecularOrder, molreports: MolecularReport, images: PathLocalImage]

static mappedBy = [sections: 'pathviews', otherreports: 'reports']

class PathSections extends Sections {

static constraints = {
    pathviews(nullable:true)
    reports(nullable:true)
}

static auditable = true

static belongsTo =  [pathviews: PathViews, reports: PathViews]

}
A temporary fix that I thought was working at first was to make most of the transactional service methods synchronized.  This seems to have just made the error more random and less reproducible. I have also double checked other things such as making sure the child objects of a hasMany relationship are not explicitly saved before being added to a parent and using domainClass.lock(id) instead of domainClass.get(id).  This issue does not occur at all when it's just one user using the application.
Versions used:

Grails: 2.3.7
  Hibernate: 3.6.10.10

Any help would be greatly appreciated as I'm close to pulling out whatever's left of my hair right now, and please let me know if anymore information is needed.
Thanks!
Shawn.

A: The first thing you should do is upgrade to the latest version within the same minor version - 2.3.11. It's unlikely to help, but you might get lucky.
Collections are tricky, since they're considered a property of the owning domain class, but are represented as multiple database records. So you have interesting effects like not being able to properly lock an updating instance; given "Author has many Books", if you explicitly lock an author instance the resulting SQL is something like select ... from author for update where id=?. But you can't lock the books, and if you could and the collection were much larger, would you want to lock a million collection instances? So you inevitably get concurrency problems with many-to-many where child items are shared between top-level instances, and even with yourself when doing Ajax requests that overlap with synchronous requests.
And that's just data correctness - the potential performance costs of using collections for persistence in GORM are pretty high. This talk that I did 4 years ago is as relevent now as it was then, and it demonstrates the performance issues with 1-many and many-many, and shows code that doesn't use collections and isn't affected by any of these issues. You do have to do a little more work, but I think it's a small price to pay.


text:
Q: Deleting a mailchimp campaign - Resource not found I am trying to delete a mailchimp campaign, but getting an error. What am I doing wrong?
Here is my curl command:
public function executeCurlDelete($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_USERPWD, 'apikey:'.$this->apikey);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//returns output as variable

    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
    $result = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    $output = CJSON::decode(curl_exec($ch));
    curl_close($ch);
    if ($output !== true){
        throw new CException($output['title']);
    }

    return $output === true;
}

public function deleteCampaign($campaignId){
    ///campaigns/{campaign_id}
    $url = "$this->apiEndpoint/campaigns/$campaignId";
    return $this->executeCurlDelete($url);
}

Here is the error:
The requested resource could not be found.


text:
Q: Display cart Grand Total instead of Sub Total On my magento theme I have a cart total in the header.
At the moment it displays the sub total, I was just wondering how I could change this value to display the grand total instead.
This is the code in the template already
<?php echo Mage::helper('checkout')->formatPrice($this->getSubtotal()) ?>

I have tried changing getSubtotal() to getGrandtotal() but it just returns 0.
Anyone got any ideas?
Thank you

A: you can get with total object
used my working code to get grand total any where in magento
<?php
 $totals = Mage::getSingleton('checkout/session')->getQuote()->getTotals(); //Total object
 $grandtotal = round($totals["grand_total"]->getValue()); //Grandtotal value
 echo $formattedPrice = Mage::helper('core')->currency($grandtotal , true, false);
?>

hope this will sure help you.

A: Not enough Reputation to Comment so I'm writing this here.
liyakat's answer worked for me on community 1.7 but I don't understand why he wants to round up the numbers.
I wanted to display the exact total (€21.50 not rounded up to €22.00) so I removed "round(" and the last ")" which gives me:
        <?php
         $totals = Mage::getSingleton('checkout/session')->getQuote()->getTotals(); //Total object
         $grandtotal = $totals["grand_total"]->getValue(); //Grandtotal value
         echo $formattedPrice = Mage::helper('core')->currency($grandtotal , true, false);
        ?>

Which works PERFECT!
Thanks a lot, I gave it +1


text:
Q: Lazy loading of partitioned parquet in Apache Spark As I understand it, Apache Spark uses lazy evaluation. So for example code like the following that consists only of transformations will do no actual processing:
val transformed_df = df.filter("some_field = 10").select("some_other_field", "yet_another_field")

Only when we do an "action" will any processing actually occur:
transformed_df.show()

I had been under the impression that load operations are also lazy in spark. (See How spark loads the data into memory.)
However, my experiences with spark have not borne this out. When I do something like the following,
val df = spark.read.parquet("/path/to/parquet/")

execution seems to depend greatly on the size of the data in the path. In other words, it's not strictly lazy. This is inconvenient if the data is partitioned and I only need to look at a fraction of the partitions.
For example:
df.filter("partitioned_field = 10").show()

If the data is partitioned in storage on "partitioned_field", I would have expected spark to wait until show() is called, and then read only data under "/path/to/parquet/partitioned_field=10/". But again, this doesn't seem to be the case. Spark appears to perform at least some operations on all of the data as soon as read or load is called.
I could get around this by only loading /path/to/parquet/partitioned_field=10/ in the first place, but this is much less elegant than just calling "read" and filtering on the partitioned field, and it's harder to generalize.
Is there a more elegant preferred way to lazily load partitions of parquet data?
(To clarify, I am using Spark 2.4.3)

A: I think I've stumbled on an answer to my question while learning about a key distinction that is often overlooked when talking about lazy evaluation in spark.
Data is lazily evaluated, but schemas are not. So if we are reading parquet, which is a structured data type, spark does have to at least determine the schema of any files it's reading as soon as read() or load() is called. So calling read() on a large number of files will take longer than on a small number of files.
Given that partitions are part of the schema, it's less surprising to me now that spark has to look at all of the files in the path to determine the schema before filtering on a partition field.
It would be convenient for my purposes if spark were to wait until schema evaluation was strictly necessary and was able to filter on partition fields prior to determining the rest of the schema, but it sounds like this is not the case. I believe Dataset objects always must have a schema, so I'm not sure there's a way around this problem without significant changes to Spark.
In conclusion, it seems like my only option currently is to pass in a list of paths for the partitions that I need rather than the base path if I want to avoid evaluating the schema over the entire data repository.


text:
Q: Append role to a playbook in Ansible 2.0 Python API Building on this question How to use Ansible 2.0 Python API to run a Playbook?
How can I create an instance of PlaybookExecutor class and append an Ansible role that will be executed when pbex.run() is called?
This is an example Playbook ls.yml - Note roles is an empty list.
---

- hosts: 127.0.0.1
  connection: local
  gather_facts: yes

  roles: []

This is the code to run the playbook using the API:
#!/usr/bin/env python

import os
import sys
from collections import namedtuple

from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory
from ansible.executor.playbook_executor import PlaybookExecutor

variable_manager = VariableManager()
loader = DataLoader()

inventory = Inventory(loader=loader, variable_manager=variable_manager,  host_list='/home/slotlocker/hosts2')
playbook_path = '/home/slotlocker/ls.yml'

if not os.path.exists(playbook_path):
    print '[INFO] The playbook does not exist'
    sys.exit()

Options = namedtuple('Options', ['listtags', 'listtasks', 'listhosts', 'syntax', 'connection','module_path', 'forks', 'remote_user', 'private_key_file', 'ssh_common_args', 'ssh_extra_args', 'sftp_extra_args', 'scp_extra_args', 'become', 'become_method', 'become_user', 'verbosity', 'check'])
options = Options(listtags=False, listtasks=False, listhosts=False, syntax=False, connection='ssh', module_path=None, forks=100, remote_user='slotlocker', private_key_file=None, ssh_common_args=None, ssh_extra_args=None, sftp_extra_args=None, scp_extra_args=None, become=True, become_method=None, become_user='root', verbosity=None, check=False)

variable_manager.extra_vars = {'hosts': 'mywebserver'} # This can accomodate various other command line arguments.`

passwords = {}

pbex = PlaybookExecutor(playbooks=[playbook_path], inventory=inventory, variable_manager=variable_manager, loader=loader, options=options, passwords=passwords)

results = pbex.run()

In pre Ansible 2.0 - specifically in 1.7 I was able to simply append the name of the role as follows (skipping imports) and call the run method:
pb = ansible.playbook.PlayBook(
        playbook='ls.yml',
        callbacks=playbook_cb,
        runner_callbacks=runner_cb,
        stats=stats,
        host_list=host_list,
        private_key_file=p_key_file,
        check=True,
        forks=1,
        extra_vars={'remote_user': remote_user}
    )

**pb.playbook[0]['roles'].append(role_name)**

pb.run()

I want to replicate this in Ansible 2.0.
thanks


text:
Q: Intellij IDEA Ruby Language Level I got a Rails Project in intellij idea but somehow the language level seems to be set on 1.8. I got the following configuration:

But it still shows the following error:

Am I missing something? When I had problems with the colon syntax before, it was always the language level.
Thanks,
Robin

A: I still don't know what the problem exactly was but I guess it had something todo with binstubs. What I did:

*

*I opened the project in RubyMine, where I got the warning: "no ruby interpreter configured for the project", though the correct rvm ruby was selected

*I deleted the .idea folder and the bin folder

*I opened the project in RubyMine again, this time it correctly recognised the rvm ruby

*I opened the project in Intellij IDEA, everything works fine here too.

A: The answer is given by rweng:

*

*Remove .idea folder

*File/New/ProjectFromExistingSources

Maybe deleting the module and recreating the same might also help


text:
Q: Java Swing- adding a label below a single line bottom border in GridBagLayout I want the label Hotel Management System copyright 2016 to appear below the MatteBorder at the bottom and also centered. I have tried copyrightL.setVerticalAlignment(JLabel.BOTTOM);but it doesn't seem to work.
Here is my code:
 public class Admin_hs extends JFrame {

JButton bking_btn= new JButton("Bookings");
JButton fd_btn= new JButton("Financial Data");
JButton ctm_btn= new JButton("Customers");
JButton room_btn= new JButton("Rooms");
JButton adc_btn= new JButton("Additional Costs");
JButton endb_btn= new JButton("Ending Bookings");

//Images
JLabel bking_img= new JLabel();
JLabel fd_img= new JLabel();
JLabel ctm_img= new JLabel();
JLabel room_img= new JLabel();
JLabel adc_img= new JLabel();
JLabel endb_img= new JLabel();
JLabel copyrightL = new JLabel("Hotel Management System \u00a9 2016");

///Panels

JPanel pnl1= new JPanel();
JPanel pnl= new JPanel((new FlowLayout(FlowLayout.LEFT)));

///Constructors

public Admin_hs(){
    this.setTitle("Welcome Admin!");
    this.setLayout(new GridBagLayout());

    ///Setting a layout

    pnl1.setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridwidth= GridBagConstraints.REMAINDER;
    gbc.fill= gbc.HORIZONTAL;

     gbc.weightx = 1;                       // ADD THIS LINE so it uses all the existing window size in x direction
     pnl1.add(pnl);                         // ADD THIS LINE

    pnl.setLayout(new GridBagLayout());

    GridBagConstraints gc= new GridBagConstraints();

    ///First Column of Grid

    gc.insets = new Insets(6, 6, 6, 6);
    gc.anchor = GridBagConstraints.WEST;
    gc.weightx = 0.5;
    gc.weighty = 0.5;

    gc.gridx = 0;
    gc.gridy = 0;

    pnl.add(bking_btn, gc);

    gc.gridx = 0;
    gc.gridy = 1;
    pnl.add(fd_btn, gc);

    gc.gridx = 0;
    gc.gridy = 2;
    pnl.add(ctm_btn, gc);

    gc.gridx = 0;
    gc.gridy = 3;
    pnl.add(room_btn, gc);

    gc.gridx = 0;
    gc.gridy = 4;
    pnl.add(adc_btn, gc);

    gc.gridx = 0;
    gc.gridy = 5;
    pnl.add(endb_btn, gc);

    gc.gridx = 0;
    gc.gridy = 8;
    pnl.add(copyrightL, gc);

    /////second column of grid

    gc.anchor = GridBagConstraints.WEST;
    gc.gridx = 1;
    gc.gridy = 0;
    bking_img.setIcon(new ImageIcon("C:/Users/Diksha/Desktop/OOSD Assignment/icons/60-60/booking.jpg"));
    pnl.add(bking_img, gc);

    gc.gridx = 1;
    gc.gridy = 1;
    fd_img.setIcon(new ImageIcon("C:/Users/Diksha/Desktop/OOSD Assignment/icons/60-60/fd.jpg"));
    pnl.add(fd_img, gc);

    gc.gridx = 1;
    gc.gridy = 2;
    ctm_img.setIcon(new ImageIcon("C:/Users/Diksha/Desktop/OOSD Assignment/icons/60-60/guest.jpg"));
    pnl.add(ctm_img, gc);

    gc.gridx = 1;
    gc.gridy = 3;
    room_img.setIcon(new ImageIcon("C:/Users/Diksha/Desktop/OOSD Assignment/icons/60-60/room.jpg"));
    pnl.add(room_img, gc);

    gc.gridx = 1;
    gc.gridy = 4;
    adc_img.setIcon(new ImageIcon("C:/Users/Diksha/Desktop/OOSD Assignment/icons/60-60/adc.jpg"));
    pnl.add(adc_img, gc);

    gc.gridx = 1;
    gc.gridy = 5;
    endb_img.setIcon(new ImageIcon("C:/Users/Diksha/Desktop/OOSD Assignment/icons/60-60/endb.png"));
    pnl.add(endb_img, gc);

    //copyrightL.setHorizontalAlignment(JLabel.CENTER);
    //copyrightL.setVerticalAlignment(JLabel.BOTTOM);
    //pnl.add(copyrightL);

    pnl1.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK));

     this.add(pnl1,gbc);

     }

}

Main class
public class Admin_main {

public static void main(String[] args) {

    Admin_hs adm= new Admin_hs();

    adm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    adm.pack();
    adm.setVisible(true);
    adm.setSize(780,520);

    }

}

Here is how it currently looks:

EDIT:
It worked for me in this way:
public class Admin_hs extends JFrame {

JButton bking_btn= new JButton("Bookings");
JButton fd_btn= new JButton("Financial Data");
JButton ctm_btn= new JButton("Customers");
JButton room_btn= new JButton("Rooms");
JButton adc_btn= new JButton("Additional Costs");
JButton endb_btn= new JButton("Ending Bookings");

//Images
JLabel bking_img= new JLabel();
JLabel fd_img= new JLabel();
JLabel ctm_img= new JLabel();
JLabel room_img= new JLabel();
JLabel adc_img= new JLabel();
JLabel endb_img= new JLabel();
JLabel copyrightL = new JLabel("Hotel Management System \u00a9 2016");

///Panels

JPanel pnl1= new JPanel();
JPanel pnl2= new JPanel(new GridBagLayout());

///Constructors

public Admin_hs(){
    this.setTitle("Welcome Admin!");
    this.setLayout(new GridBagLayout());

    ///Setting a layout

    pnl1.setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.fill= gbc.HORIZONTAL;

    GridBagConstraints gc= new GridBagConstraints();

    ///First Column of Grid

    gc.insets = new Insets(6, 6, 6, 6);
    gc.anchor = GridBagConstraints.WEST;
    gc.weightx = 0.5;
    gc.weighty = 0.5;

    gc.gridx = 0;
    gc.gridy = 0;

    pnl1.add(bking_btn, gc);

    gc.gridx = 0;
    gc.gridy = 1;
    pnl1.add(fd_btn, gc);

    gc.gridx = 0;
    gc.gridy = 2;
    pnl1.add(ctm_btn, gc);

    gc.gridx = 0;
    gc.gridy = 3;
    pnl1.add(room_btn, gc);

    gc.gridx = 0;
    gc.gridy = 4;
    pnl1.add(adc_btn, gc);

    gc.gridx = 0;
    gc.gridy = 5;
    pnl1.add(endb_btn, gc);

    gc.gridx = 0;
    gc.gridy = 8;
    pnl1.add(copyrightL, gc);

    /////second column of grid

    gc.anchor = GridBagConstraints.WEST;
    gc.gridx = 1;
    gc.gridy = 0;
    bking_img.setIcon(new ImageIcon("C:/Users/Diksha/Desktop/OOSD Assignment/icons/60-60/booking.jpg"));
    pnl1.add(bking_img, gc);

    gc.gridx = 1;
    gc.gridy = 1;
    fd_img.setIcon(new ImageIcon("C:/Users/Diksha/Desktop/OOSD Assignment/icons/60-60/fd.jpg"));
    pnl1.add(fd_img, gc);

    gc.gridx = 1;
    gc.gridy = 2;
    ctm_img.setIcon(new ImageIcon("C:/Users/Diksha/Desktop/OOSD Assignment/icons/60-60/guest.jpg"));
    pnl1.add(ctm_img, gc);

    gc.gridx = 1;
    gc.gridy = 3;
    room_img.setIcon(new ImageIcon("C:/Users/Diksha/Desktop/OOSD Assignment/icons/60-60/room.jpg"));
    pnl1.add(room_img, gc);

    gc.gridx = 1;
    gc.gridy = 4;
    adc_img.setIcon(new ImageIcon("C:/Users/Diksha/Desktop/OOSD Assignment/icons/60-60/adc.jpg"));
    pnl1.add(adc_img, gc);

    gc.gridx = 1;
    gc.gridy = 5;
    endb_img.setIcon(new ImageIcon("C:/Users/Diksha/Desktop/OOSD Assignment/icons/60-60/endb.png"));
    pnl1.add(endb_img, gc);

    pnl1.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK));

     gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 2;
        pnl2.add(copyrightL, gbc);

        gbc.gridwidth = 1;
        gbc.weightx = 1.0;
        gbc.gridx = 0;
        gbc.gridy = 0;
        add(pnl1, gbc);

        gbc.gridx = 0;
        gbc.gridy = 1;
        add(pnl2, gbc);

    }

}
Here is how it looks now:

The buttons have somehow shifted to the left. That's fine for me as I had to move them to the left for some reason. How can I get their corresponding images to the left though? I mean, how can I get the the images closer to the buttons to the left?

A: I believe the easiest way to do this would be to use code similar to this
import javax.swing.*;
import java.awt.*;

public class Test extends JFrame {
    private JPanel testPanel = new JPanel(new GridBagLayout()), testPanel2 = new JPanel(new GridBagLayout());
    private GridBagConstraints c = new GridBagConstraints();
    private JLabel label1 = new JLabel("Something"), label2 = new JLabel("Something Else");

    Test() {
        super("Example Frame");
        setLayout(new GridBagLayout());
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        buildGUI();

        c.weightx = 1.0;
        c.gridx = 0;
        c.gridy = 0;
        add(testPanel, c);

        c.gridx = 0;
        c.gridy = 1;
        add(testPanel2, c);

        pack();
        setVisible(true);
    }

    private void buildGUI() {
        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = 0;
        testPanel.add(label1, c);

        testPanel.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK));

        c.gridx = 0;
        c.gridy = 0;
        testPanel2.add(label2, c);
    }

    public static void main(String[] args) {
        new Test();
    }
}

In this code, there are two JPanels, each with a JLabel on it. The first panel has a border on the bottom and the second panel is placed underneath. You can do this by setting a layout on your JFrame You could adopt this idea to work with your code.
With your code, it would look like this.
Admin_main
import javax.swing.*;

public class Admin_main {
    public static void main(String[] args) {

        Admin_hs adm= new Admin_hs();

        adm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        adm.pack();
        adm.setVisible(true);
    }
}

Admin_hs
import javax.swing.*;
import java.awt.*;

public class Admin_hs extends JFrame {
    JButton bking_btn= new JButton("Bookings");
    JButton fd_btn= new JButton("Financial Data");
    JButton ctm_btn= new JButton("Customers");
    JButton room_btn= new JButton("Rooms");
    JButton adc_btn= new JButton("Additional Costs");
    JButton endb_btn= new JButton("Ending Bookings");

    //Images
    JLabel bking_img= new JLabel();
    JLabel fd_img= new JLabel();
    JLabel ctm_img= new JLabel();
    JLabel room_img= new JLabel();
    JLabel adc_img= new JLabel();
    JLabel endb_img= new JLabel();
    JLabel copyrightL = new JLabel("Hotel Management System \u00a9 2016");

    ///Panels

    JPanel pnl1 = new JPanel(new GridBagLayout()), pnl2 = new JPanel(new GridBagLayout());

    ///Constructors

    public Admin_hs(){
        setTitle("Welcome Admin!");
        setLayout(new GridBagLayout());

        ///Setting a layout

        pnl1.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill= GridBagConstraints.HORIZONTAL;

        gbc.insets = new Insets(6, 6, 6, 6);
        gbc.weightx = 1;
        gbc.weighty = 1;
        gbc.gridx = 0;
        gbc.gridy = 0;

        pnl1.add(bking_btn, gbc);

        gbc.gridx = 0;
        gbc.gridy = 1;
        pnl1.add(fd_btn, gbc);

        gbc.gridx = 0;
        gbc.gridy = 2;
        pnl1.add(ctm_btn, gbc);

        gbc.gridx = 0;
        gbc.gridy = 3;
        pnl1.add(room_btn, gbc);

        gbc.gridx = 0;
        gbc.gridy = 4;
        pnl1.add(adc_btn, gbc);

        gbc.gridx = 0;
        gbc.gridy = 5;
        pnl1.add(endb_btn, gbc);

        /////second column of grid
        gbc.weightx = 0;
        gbc.fill= GridBagConstraints.BOTH;

        ImageIcon icon = new ImageIcon("Smiley.gif");
        Image image2 = icon.getImage().getScaledInstance(50, 50, 0);
        ImageIcon icon2 = new ImageIcon(image2);

        gbc.gridx = 1;
        gbc.gridy = 0;
        bking_img.setIcon(icon2);
        pnl1.add(bking_img, gbc);

        gbc.gridx = 1;
        gbc.gridy = 1;
        fd_img.setIcon(icon2);
        pnl1.add(fd_img, gbc);

        gbc.gridx = 1;
        gbc.gridy = 2;
        ctm_img.setIcon(icon2);
        pnl1.add(ctm_img, gbc);

        gbc.gridx = 1;
        gbc.gridy = 3;
        room_img.setIcon(icon2);
        pnl1.add(room_img, gbc);

        gbc.gridx = 1;
        gbc.gridy = 4;
        adc_img.setIcon(icon2);
        pnl1.add(adc_img, gbc);

        gbc.gridx = 1;
        gbc.gridy = 5;
        endb_img.setIcon(icon2);
        pnl1.add(endb_img, gbc);

        pnl1.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK));

        gbc.insets = new Insets(0, 0, 0, 0);

        gbc.gridwidth = 1;
        gbc.weightx = 1.0;
        gbc.gridx = 0;
        gbc.gridy = 0;
        add(pnl1, gbc);

        gbc.fill= GridBagConstraints.HORIZONTAL;

        gbc.weightx = 0;
        gbc.weighty = 0;
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 2;
        pnl2.add(copyrightL, gbc);

        gbc.weightx = 0;
        gbc.gridx = 0;
        gbc.gridy = 1;
        add(pnl2, gbc);
    }
}

This produces this


text:
Q: Where does this probability problem come from? A long time ago, a friend gave me a probability problem. Here is rough reconstruction.

A spaceship is lost in deep ($3$-d) space. Its home planet is $X$
  meters away. Every second, the spaceship teleports $Y$ meters in a
  random direction. If it gets within $Z$ meters of its home planet, the
  spaceship stops teleporting and is rescued. Otherwise, it continues
  teleporting. The spaceship can only move through teleportation -- it
  begins stationary, and is stationary at each point it teleports to.
  What is the probability the spaceship makes it home safely?

I believe my friend told me this a classic problem from a well-known book. What is the exact citation?

A: My friend clearly had in mind problems E10.10 and problem E10.11 in Williams's Probability With Martingales.


text:
Q: UIContainer viewcontroller segue within bounds of container I am using a container to present a tableView. The container only covers 1/5 of the screen. When user selected a row I want to push a viewController within the container , but so far the first viewController is presenting fullscreen.
This is what I currently have on my storyboard

A: @poolHallJunkie Your question is not clear. What I can tell you with your query is you have some problem with your element width setting. Please clarify the question

A: Use UINavigationController and hide NavigationBar for it.
To do so - select your tableViewController in storyboard and choose Editor -> Embedded in -> Navigation Controller from Xcode menu. Configure navController to hide navBar. In your back button action use
navigationController.popViewController(animated: true)

You should get something like this:


text:
Q: Date function is not working with Mysql 5.1 In command prompt of mysql 5.1 I am not able to use Date function.It tells syntax error. Can any buddy help me to solve this issue. In my local system where mysql version is 5.0 same command is working fine...!
I am confused what could be wrong with mysql 5.1.39 Is there any setting in my.cnf for date support.
SELECT date('2012-03-01 03:15:00')

Above command is giving error:
MySQL said:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near '('2012-03-01 03:15:00')' at line 1

Above command is not working in mysql 5.1.39 . Can you please help me regarding this?

A: Check ANSI_QUOTES sql mode if it is set -
SHOW VARIABLES LIKE 'sql_mode';

From the reference: ANSI_QUOTES - Treat '"' as an identifier quote character (like the '' quote character) and not as a string quote character. You can still use '' to quote identifiers with this mode enabled. With ANSI_QUOTES enabled, you cannot use double quotes to quote literal strings, because it is interpreted as an identifier.
Change " quote with ', and execute -
SELECT DATE('2012-03-01 03:15:00');

A: You need to use single quotes instead of double quotes.
You can find the MySQL date functions at http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html


text:
Q: Resolved: Two more generators needed for a Z/6 elliptic curve We are searching for the rank 8 elliptic curves with the torsion subgroup Z/6 using newly discovered families similar to Kihara's (Kihara's family is described in https://arxiv.org/pdf/1503.03667.pdf).
Today we came across a curve
$[0,8169768624655967629114128598,0,-451787550647310420612086468536366715869054405951830599,0]$
Both Magma Calculator (http://magma.maths.usyd.edu.au/calc/) and mwrank with $-b12$ return 6 generators for this curve.
Magma V2.20-10 (STUDENT) runs out of memory running the following code:
SetClassGroupBounds("GRH");
E := EllipticCurve([0,8169768624655967629114128598,0,-451787550647310420612086468536366715869054405951830599,0]);
MordellWeilShaInformation(E);

Sagemath returns $8$ for the upper bound of analytic rank, even for max_Delta=$3.3$ (we are still testing for higher max_Delta):
E = EllipticCurve([0,8169768624655967629114128598,0,-451787550647310420612086468536366715869054405951830599,0])
E.analytic_rank_upper_bound(max_Delta=3.3,root_number="compute")

Is there a way to find two more generators?
A similar question for the $6$ <= Rank(E) <= $7$ situation was successfully resolved by Jeremy Rouse (One more generator needed for a Z/6 elliptic curve) but our software chokes when we are trying to follow his instructions.
Max

A: Just to give a more complete answer:
SetVerbose("cbrank",1);
E := EllipticCurve([0,8169768624655967629114128598,0,\
    -451787550647310420612086468536366715869054405951830599,0]);
TwoPowerIsogenyDescentRankBound(E);

  /---------------------------------------------------\
  |   SUMMARY TABLE      Step No :  6  5  4  3  2  1  |
  |---------------------------------------------------|
  |  dim_2 ( E'(Q)/phi E(Q) )   <=     4  5  5  5  5  |
  |  dim_2 ( E(Q)/phi'E'(Q) )   <=     4  5  5  5  5  |
  |     Therefore rank E(Q) <= 6                      |
  \---------------------------------------------------/

Total time: 22.980 seconds, Total memory usage: 96.16MB


text:
Q: What is wrong with my PHP? I am new to PHP, I watched a tutorial about SQL and PHP, and I made those files:
insert_news.php:

    require_once __DIR__ .'/db_connect.php';

    $sql = "INSERT INTO news ( descriere, data, autor) VALUES (?, ?, ?)" ;
    $params = array("The description", "12/11/2011", "COsmin");

    $serverName = "my server";
    $connectionInfo = array( "Database"=>"myusername", "UID"=>"myusername", "PWD"=>"mypassword");

    $conn = sqlsrv_connect($serverName, $connectionInfo );
    $stmt = sqlsrv_query( $conn , $sql, $params );

    if( $stmt == false ) {
        echo("NOT");
        die( print_r( sqlsrv_errors(), true));
    }

?>

This code seems to be working well.
Now my problem is that I wanted to make a class which will make the connections to the database more easier.
That's the code:
db_connect.php
<?php
class DB_CONNECT {
    function __construct(){
        $this->connect();
    }

    function __Destruct(){
        $this->close();
    }

    function connect() {
        $serverName = "my server";
        $connectionInfo = array( "Database"=>"my db", "UID"=>"my user", "PWD"=>"my pass" );

        $con = sqlsrv_connect($serverName, $connectionInfo );
                return $con;
    }
    function close(){
        sqlsrv_close();
    }
}
?>

And if I want to call this class from my insert_new.php file like that:
    <?php

    require_once __DIR__ .'/db_connect.php';

    $sql = "INSERT INTO Stiri ( descriere, data, autor) VALUES (?, ?, ?)" ;
    $params = array("ASta e o stvnmbvire aduagata printr-un web service php", "12/11/2011", "COsn");

    $conn = new DB_CONNECT() ;
    $stmt = sqlsrv_query( $conn , $sql, $params );

    if( $stmt == false ) {
        echo("NU");
        die( print_r( sqlsrv_errors(), true));
    }
?>

When I try this, my server returns me that:
Warning: sqlsrv_query() expects parameter 1 to be resource, object given in C:\xampp\htdocs\android_connect\insert_news.php on line 9
NUArray ( [0] => Array ( [0] => IMSSP [SQLSTATE] => IMSSP [1] => -14 [code] => -14 [2] => An invalid parameter was passed to sqlsrv_query. [message] => An invalid parameter was passed to sqlsrv_query. ) )
I mention that I use XAMPP to compile the php files and the database is a SQL Server 2005...
Sorry If I wasted your time with my silly stuff...

A: You are giving your custom object to the function sqlsrv_query instead of the DB Instance. In Your class, you should make the $con variable a public attribute like this:
class DB_CONNECT {
    public $con = false;
    function __construct(){
        $this->connect();
    }

    function __Destruct(){
        $this->close();
    }

    function connect() {
        $serverName = "my server";
        $connectionInfo = array( "Database"=>"my db", "UID"=>"my user", "PWD"=>"my pass" );

        $this->con = sqlsrv_connect($serverName, $connectionInfo );
                return $con;
    }
    function close(){
        sqlsrv_close();
    }
}

and give this attribute to your query function like this:
if($conn->con) {
   $stmt = sqlsrv_query( $conn->con , $sql, $params );
} else {
   // error
}

A: It seems as if you are not actaully connecting to the DB.
This is your problem
$conn = new DB_CONNECT();
$stmt = sqlsrv_query( $conn , $sql, $params );

$conn is not a connection here it is just a DB_CONNECT object. You need to call connect() method to get a connection. So try this:
$conn = new DB_CONNECT();
$stmt = sqlsrv_query( $conn->connect() , $sql, $params );


text:
Q: EF Core: The multi-part identifier \"m.Added\" could not be bound I'm trying to migrate from EF 6 to EF Core.
I have this Linq to SQL query which returns daily top photo:
var model = db.Photos
    .Where(m => m.Added <= startDate && m.Active == true)
    .GroupBy(m => new { Year = m.Added.Year, Month = m.Added.Month, Day = m.Added.Day })
    .Select(m => m.FirstOrDefault())
    .OrderByDescending(m => m.Added)
    .ThenBy(m => m.Rates.Sum(r => r.Points))
    .Take(10)
    .ToList();

but same code on EF Core returns error:

Core .Net SqlClient Data Provider: No column name was specified for column 1 of 'm2'. No column name was specified for column 2 of 'm2'. No column name was specified for column 3 of 'm2'. The multi-part identifier "m.Added" could not be bound. The multi-part identifier "m.Added" could not be bound. The multi-part identifier "m.Added" could not be bound.

how can i translate this to EF Core?

A: I had this same issue with a very simple expression:
var dates = items.Select(item => item.DateTime).Distinct();
// the multi-part identifier item.DateTime could not be bound

I got around this by creating and passing the equivalent function rather than an expression:
function DateTime GetItemDate(Item item)
{
    return item.DateTime;
}

var dates = items.Select(GetItemDate).Distinct();

As it's a workaround I would have preferred to post this to the comment discussion but I don't have the rep :/


text:
Q: Materialize: How to add icons to input-field submit buttons? I am trying to build a todo app based on Materialize-css. I want the input-field to be on the same line, as the submit button which should include a materialize icon. That's what I have currently:

        Hinzufügen

            <input id="todo" type="email" class="validate">
            todo
               <input type ="submit" class ="btn waves-effect waves-light inline" value = "Submit"/>

Here's a picture about how it looks currently. I just don't know how to add the icon to the submit button, because there is no opening and closing tag, it's just an input tag. I need that input-tag to be able to use php code after the submition.
Todo-App

A: You just have to replace the input tag with a button tag like in the example, hope it will help

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <title>Home</title>

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

     <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
     <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

                Charts

        Hinzufügen

            <input id="todo" type="email" class="validate">
            todo
            <button class="btn waves-effect waves-light" type="submit" name="action">Submit
              send
            </button>


text:
Q: Не отображаются картинки в файле html Не отображается локальная картинка в файле html.
<img src="projectSphynx\dev\images\orange-square.jpg" alt="orange-square">

Вместо картинки отображается маленький значок и текст из alt. Браузеры: Chrome и Firefox. Редактор - Visual Studio Code. Адреса верные - я использую "копировать относительный адрес" к изображению. Также при попытке открыть ссылку через Ctrl+ЛКМ внутри Visual Code пишет ошибку: "При загрузке изображения произошла ошибка."
Что пишет консоль в Хроме, когда картинка внутри div:

Failed to load resource: the server responded with a status of 404 (Not Found)

В пустом body где только картинка:

GET http://127.0.0.1:5500/projectSphynx/dev/projectSphynx/dev/images/orange-square.jpg 404 (Not Found)

Открываю и через Live Server, и просто через браузер из папки.


text:
Q: sqlite4java no such table error by attaching another database I'm using sqlite4java to handle with sqlite db. I want now to copy a table from database to dbtest. So I found the code here on stackoverflow. But I get always an error. First of all I open a connection to my new created database and afterwards I attach the other database with the following command:

ATTACH DATABASE database AS database;

This works fine. dbtest has been opended earliere as new database.
Then I want to copy the tables: Hence, the table is already created and it is the same as in the other database.

INSERT INTO dbtest.Routing (id, source, destination, metadata, zone_src, zone_dst,cost) SELECT * FROM database.Routing;

But after executing this I get the error:

com.almworks.sqlite4java.SQLiteException: [1] DB[1] exec() no such table: dbtest.Routing

I tried it also with sqlite Studio and there it is working without any problems, but I cannot attach a database there (this is done automatically). Do I have to use another notation to use two databases?
EDIT:
I use now the answer from CL. But this leads to the new issue:

com.almworks.sqlite4java.SQLiteException: [1] DB[1] exec() no such table: second.Routing

What did I change?

ATTACH DATABASE database AS second; //new name for the database file and it will be attached as second, because if I use the debug function it says: Database second already in use.

If I use this command I get the error mentioned above.

INSERT INTO Routing (id, source, destination, metadata, zone_src, zone_dst,cost) SELECT * FROM second.Routing;

Problem solved by using the absolute path for the database file.

A: The name of attached databases is not its file name but whatever you've specified as name in the AS clause of the ATTACH statement.
Neither is the name of the main database (the database to which the other database was attached) its file name. Its name always is main.
To specify the name of a table in your main database, use main.Routing, or just Routing.

Please note that SQLite is perfectly happy with creating a new database if the file does not yet exist, so you have to ensure to give the correct file name to the ATTACH statement.
If your database file is not named database or if it is not in the current directory, the second database will be empty.
It is strongly recommended to always give the complete file path, like this:
ATTACH DATABASE '/some/where/whatever.db' AS second;


text:
Q: Could not resolve all files for configuration :compileClasspath I have a problem with building a gradle java project when I run the command./gradlew build I get the error in the screenshot below. I have spent several hours trying all the ways I could find here on SO but none of them worked (so don't mark this as duplicate) all the answers seem to be about proxies but I'm not using any proxies in the gradle.properties file and I could also access the urls from the logs in my browser and they work just fine.
Thank you in advance
https://i.stack.imgur.com/IAFEE.png
Here's my build.gradle
https://i.stack.imgur.com/HaoLG.png
NOTE: As you can see I'm running gradle on my phone yes I know that's not the best idea but I know for sure this problem is not related to this.


text:
Q: How can I solve java lang unsatisfiedlink error when runing jdeveloper?
I cannot run Jdeveloper. My java is in /usr/java
How can I fix this? I run rpm --query --whatprovides 'libX....' but it says no package provides this

A: Take a look here - the answer appears to correspond to your needs. It appears to be more of a progamming question than a DBA one, but we're here to help! :-).
Furthermore, a quick Google of sudo yum install libXext got me to this link. Please take the statckexchange site tour and in particular, check out the "help us to help you" blog - both available at the bottom of the page on the left.


text:
Q: java - can I skip static analysis in SonarQube? Our project is currently using SonarQube for code coverage analysis only. Is it possible to skip/disable the static analysis part?

A: No. Static analysis is the point of SonarQube.


text:
Q: Quick sort Hoare array partitioning Trying to figure out why Hoare partition algorithm always splits an array into two right parts. In code below, I extend Hoare algorithm to make it more clear to me (see comments for details)
int partition(int[] arr, int leftIndex, int rightIndex) {
  int pivot = arr[(leftIndex + rightIndex) / 2];

  while (leftIndex <= rightIndex) {
    while (arr[leftIndex] < pivot) leftIndex++;
    while (arr[rightIndex] > pivot) rightIndex--;

    // If all numbers at right places, than leftIndex and rightIndex
    // could point at same array element index
    // So it's means partion done.
    // We should return leftIndex + 1 cause
    // rightIndex points at the last element of the left sub array

    if (leftIndex == rightIndex) return leftIndex + 1;

    if (leftIndex < rightIndex) {
      swap(arr, leftIndex, rightIndex);
      leftIndex++;
      rightIndex--;
    }
  }

  //But here the tricky thing: Why does this "if case" never execute?
  if (leftIndex - 1 > rightIndex)
    System.out.println("leftIndex - 1 > rightIndex");

  return leftIndex;
}

So the question is: Is it possible to pass an array to partition function, so the line below will be executed?
if (leftIndex - 1 > rightIndex)
  System.out.println("leftIndex - 1 > rightIndex");?

A: For that to execute, leftIndex would have to be at least rightIndex + 2, and that just can't happen, assuming we start the function with leftIndex <= rightIndex:
With these two loops:
while (arr[leftIndex] < pivot) leftIndex++;
while (arr[rightIndex] > pivot) rightIndex--;

The indices can never cross each other - if not sooner, they'll stop at either side of the pivot.
Then we leave the function if this is the case:
if (leftIndex == rightIndex) return leftIndex + 1;

So, the only thing that remains is:
if (leftIndex < rightIndex) {
  swap(arr, leftIndex, rightIndex);
  leftIndex++;
  rightIndex--;
}

Even if they're as close as can be (leftIndex == rightIndex - 1), after that executes they'll be at leftIndex == rightIndex + 1. And we still didn't get a difference of 2.