text:
Q: How do I create a WebAssembly.Memory in JS and then access it in C? I have a demo fiddle online at https://webassembly.studio/?f=0r9gxzb9rdq where I'm using an array buffer that gets shared between JS and WebAssembly.
As suggested in this answer How to access WebAssembly linear memory from C/C++, I'm declaring it as a global array that I'm reading and writing to, along with a helper function to return the starting address:
const SIZE = 6 * 1000 * 1000;
int array[SIZE]

WASM_EXPORT
int* getStartByteOffset() {
  return &array[0];
}

Then, in JS-land, once I load the wasm file and get the module instance:
const SIZE = 6 * canvas.width * canvas.height;
const heap = instance.exports.memory.buffer;
const offset = instance.exports.getStartByteOffset()
const arrayView = new Int32Array(heap, offset, SIZE)

This works, and now JS and WebAssembly can access this array. But it's not the way I want to do it. I don't know the required array size beforehand (the canvas could turn out to be any size), so I'm idiotically preallocating one large enough to accommodate 1000x1000 pixels (where each pixel needs six 32-bit wide ints).
What I want to do is calculate in JS the memory required, and pass it in as a WebAssembly.Memory once I know how many 64k pages I need:
  fetch('../out/main.wasm').then(response => response.arrayBuffer())
    .then((bytes) => {
      WebAssembly.instantiate(bytes, {
        env: {
          memoryBase: 0,
          memory: new WebAssembly.Memory({
            initial: 1 + ((6 * 4 * canvas.width * canvas.height) >> 16)
          })
        }
      }).then((wasm) => {...});
    });

What I can't figure out is the precise way to access the WebAssembly.Memory buffer using C. The Internet is crammed full of code samples on how the JS side of the API works, but all the code samples I can ever find on the WebAssembly side are written in WAT.


text:
Q: How can I detect closing window angular5 I want to delete some data when the user closes the page
I already used  beforeunload event but it work only when I refresh the page but when I close it nothing executes.
@HostListener('window:beforeunload', ['$event'])
  beforeUnloadHander($event) {
    console.log('fdfsdfsd')
    if(!this.accepted && this.details.length != 0){
      this.bookingService.deleteRequest(this.details[3]);
    }
  }

if there's any other method can I use it
I'm using Angular 5

redpajama_set_name: RedPajamaStackExchange


text:
Q: Changing the background color of xml shape in android I have a shape I've created in an xml file as follows
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/shape">
<padding
    android:left="2dp"
    android:top="2dp"
    android:right="2dp"
    android:bottom="2dp" />
<corners android:radius="10dp" />
<solid android:color="@color/red" />
</shape>

In my app I have 10-14 views with the above shape as the background however for each view I need to have a seperate shape file just to change the colors of each. Is there some way that I can use just one file and change the background color when I create a new shape? and is it possible to do it directly in the xml file when I create the shape views?


text:
Q: JQuery Submit not called with remote verification I am trying to get my form to submit with jquery, and having a bit of trouble.
Why is my submit handler not being called?
I am trying to verify if a user name is already taken in the db using remote validation in the jquery rules section.  The php code to look up in the db works fine.  Very simplified code below.
If I remove the "remote" entry, the submit handler is called.  If the code has the remote entry in the rules, then the submit handler is not called.  From tracing through the JQuery code, it looks like there is some "pending request" preventing the submit from being called.
HTML:
<script src="/js/jquery.1.11.2.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>

<script src="/js/jquery.validate.js"></script>

<input type ='text' placeholder='Username' name="username" maxlength="25" size="20"  id="username" >

<input type="submit" value="submit" title="submit" >

Javascript:
$(document).ready(function(){
     // ----------- Form Validation -----------------
 $("#test").validate({
      rules: {
         username: {
            required: true,
            minlength:5,
            maxlength:25,

            remote: {
        //      async: false,
        //     data: {
        //            'username': $('#username').val()
      //          },
    //           dataType: 'json',
                //dataType: "Text",
                url: "/account/account-search/checkusername.php",
                type: "POST"
            }
        }

        },
        messages: {
        username: {
           required: "Please Enter A Username",
           remote: 'Username Not Available, Please Choose Another!'
        }
    },

    submitHandler: function(form)
    {
        var username = $("#username").val();

        // Returns successful data submission message when the entered information is stored in database.
        var dataString = 'username='+ username ;
        // AJAX Code To Submit Form.

            $.ajax({
                type: "POST",
                url: "/account/artistRegistration.php",
                data: dataString,
                cache: false
            });

        return false;
    }

});

 });

PHP:
<?php
//      $retval =  'true';
//      echo 1;
//      return true;
//  header('Content-Type: application/json');
//  echo json_encode($retval);
echo 'true';
//  return;
}


text:
Q: Issues running github package specifically with Tensorflow on python 3.6 I am running python 3.6 (32-bit) on my Windows 10 pro (64-bit). I have been using Command prompt to try and install the packages to get this up and running but am not having much luck. Just began coding yesterday, would really appreciate some help. Thanks in advance.
This is the error message coming up in command prompt when i try and run the git hub file:
C:\Users\sek53\Desktop\BatchEffectRemoval-master\BatchEffectRemoval-master\src>python train_MMD_ResNet.py
Using TensorFlow backend.
Traceback (most recent call last):
  File "C:\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 18, in swig_import_helper
fp, pathname, description = imp.find_module('_pywrap_tensorflow', [dirname(__file__)])
File "C:\Python36-32\lib\imp.py", line 297, in find_module
  raise ImportError(_ERR_MSG.format(name), name=name)
ImportError: No module named '_pywrap_tensorflow'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Python36-32\lib\site-packages\tensorflow\python\__init__.py", line
66, in <module>
from tensorflow.python import pywrap_tensorflow
  File "C:\Python36-32\lib\site-
 packages\tensorflow\python\pywrap_tensorflow.py", line 28, in <module>
 _pywrap_tensorflow = swig_import_helper()
  File "C:\Python36-32\lib\site-
packages\tensorflow\python\pywrap_tensorflow.py", line 20, in
swig_import_helper
    import _pywrap_tensorflow
ModuleNotFoundError: No module named '_pywrap_tensorflow'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "train_MMD_ResNet.py", line 8, in <module>
    import keras.optimizers
  File "C:\Python36-32\lib\site-packages\keras\__init__.py", line 3, in
<module>
    from . import utils
  File "C:\Python36-32\lib\site-packages\keras\utils\__init__.py", line 6,
in <module>
    from . import conv_utils
  File "C:\Python36-32\lib\site-packages\keras\utils\conv_utils.py", line 3, in <module>
    from .. import backend as K
  File "C:\Python36-32\lib\site-packages\keras\backend\__init__.py", line 83, in <module>
    from .tensorflow_backend import *
  File "C:\Python36-32\lib\site-packages\keras\backend\tensorflow_backend.py", line 1, in <module>
    import tensorflow as tf
  File "C:\Python36-32\lib\site-packages\tensorflow\__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "C:\Python36-32\lib\site-packages\tensorflow\python\__init__.py", line 72, in <module>
    raise ImportError(msg)
 ImportError: Traceback (most recent call last):
  File "C:\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 18, in swig_import_helper
    fp, pathname, description = imp.find_module('_pywrap_tensorflow' [dirname(__file__)])
  File "C:\Python36-32\lib\imp.py", line 297, in find_module
    raise ImportError(_ERR_MSG.format(name), name=name)
ImportError: No module named '_pywrap_tensorflow'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Python36-32\lib\site-packages\tensorflow\python\__init__.py", line 66, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "C:\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 28, in <module>
    _pywrap_tensorflow = swig_import_helper()
  File "C:\Python36-32\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 20, in swig_import_helper
    import _pywrap_tensorflow
ModuleNotFoundError: No module named '_pywrap_tensorflow'

Failed to load the native TensorFlow runtime.

See https://github.com/tensorflow/tensorflow/blob/master/tensorflow/g3doc/get_started/os_setup.md#import_error

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.


text:
Q: Using <= in Subquery to output results I've got a query that first declares and inserts data into a temporary table. This table is being used to filter out the main table in sql server that contains customer data.
Query with dummy data filled into temp table is as follows:
Declare @myInputTable TABLE (Customer_input INT, Date_of_interest bigint)
insert into @myInputTable values(12345, '20140924'),(22234,'20210508')

select top 1
MainTable.CustomerID,
MainTable.PurchaseDate
From MainTable
Where (customerID in (select Customer_input from @myInputTable) and PurchaseDate <= (select Date_of_interest from @myInputTable))

When I comment out the 2nd customer+date of interest the query runs normally and gives me the result, but moment it deals with multiple customer and date of interest combinations it spits out the following error:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

I understand that the problem lies in "PurchaseDate <=...", but I am not sure how else I can filter out results to match customerIDs and only output the closest purchase date records to the date of interest of each customer. Any pointers would be appreciated!
Test data from MainTable:

CustomerID
PurchaseDate

12345
20150120

12345
20140213

12345
20120811

22234
20210419

22234
20220322

Expected result from the query overall:

CustomerID
PurchaseDate

12345
20140213

22234
20210419

The query should rule out all PurchaseDate that are >Date_of_interest and only display the closest past PurchaseDate to Date_of_interest of a given CustomerID (matched to Customer_input). Customer 12345 has 2 dates that qualify (20140213 and 20120811), but only 20140213 is outputted as it's the closest to the date of interest listed in myInputTable (12345, '20140924')

A: I would suggest all you need is an inner join and then simple aggregation for your desired results:
select m.customerId, Max(PurchaseDate) PurchaseDate
From @myInputTable t
join MainTable m on m.CustomerID = t.Customer_input and m.PurchaseDate <= t.Date_of_interest
group by m.customerId;

A: As you need to map each source row to a row from your variable table, you have to do a join and not simply check that a value exists somewhere in it. And as you need just one value per customer, you will need to use ROW_NUMBER. Maybe something like this (not tested):
SELECT *
FROM (
    SELECT
      MT.CustomerID,
      MT.PurchaseDate,
      Number = ROW_NUMBER() OVER (PARTITION BY MT.CustomerID ORDER BY MT.PurchaseDate DESC)
    FROM MainTable MT
    INNER JOIN @myInputTable IT
      ON MT.CustomerID = IT.Customer_input AND MT.PurchaseDate <= IT.Date_of_interest
) Subquery
WHERE Number = 1
ORDER BY CustomerID, PurchaseDate

A: This can also be achieved by inner joining with the table variable and aggregating it.

DECLARE @myInputTable TABLE (
 Customer_input INT,
 Date_of_interest INT
);
insert into @myInputTable values
  (12345, '20140924')
, (22234, '20210508')
;

SELECT
  t.CustomerID
, MAX(PurchaseDate) AS PurchaseDate
FROM MainTable t
JOIN @myInputTable i
  ON i.Customer_input = t.CustomerID
 AND i.Date_of_interest >= t.PurchaseDate
GROUP BY t.CustomerID, i.Date_of_interest

CustomerID
PurchaseDate

12345
20140213

22234
20210419

Test on db<>fiddle here
Side-note : Columns that contain dates should have the DATE datatype.
You can insert dates in the same "yyyyMMdd" format.


text:
Q: React unwanted refreshing after my post call to api I am confused as to why my react app is auto refreshing after I send a post call? On my server side I am using express and everything is saving to the database alright.  It should be retuning a res.status of 200 but before the code hits the .then() it auto refreshes.
here is my submit code:
onSubmit = (event) => {

  let body = {
    name: this.state.name,
    email: this.state.email,
    body : this.state.body,
    subject : this.state.subject,
  }

  fetch('/api/inbox', {
    method: 'POST',
    body: JSON.stringify(body),
    headers: {
      'Content-Type': 'application/json'
    }
  })
  .then(res => {
      debugger
    if (res.status === 200) {
        console.log("WORKED!!")
    //    this.setState({messageSent: true})

    } else {
      const error = new Error(res.error);
      throw error;
    }
  })
  .catch(err => {
    console.error(err);
    alert('Error logging in please try again');
  });
}

I put a debugger in but its never triggered. I don't want the screen to refresh since I want to show a success message after the result is returned.


text:
Q: Android date query not working properly I am creating an app in which I have to store date and time on certain time when gps location changes but. I am having trouble in retrieving data from SQLITE. I am using these two functions to get current date and time and store them in DataBase.
public static String getCurentDate() {
    Calendar calender = Calendar.getInstance();
    return String.valueOf(calender.get(Calendar.MONTH) + 1) + "/"
            + String.valueOf(calender.get(Calendar.DAY_OF_MONTH)) + "/"
            + String.valueOf(calender.get(Calendar.YEAR));
}

public static String getCurentTime() {
    Calendar calender = Calendar.getInstance();
    String strHour = String.valueOf(calender.get(Calendar.HOUR_OF_DAY));
    String strMinute = String.valueOf(calender.get(Calendar.MINUTE));
    if (strMinute.length() == 1)
        strMinute = "0" + strMinute;
    return strHour + ":" + strMinute;
}

I am using these 3 functions to get data retrieved from DB.
public ArrayList<LocationItem> getLocationItemsByDateTime(String timeFrom,
            String timeTo, String dateFrom, String dateTo) throws Exception {
        Cursor cur;
        ArrayList<LocationItem> locationItems = new ArrayList<LocationItem>();
        try {
            openDB(true);
            cur = dBase.rawQuery("select * from "
                    + LocationItemTable.TABLE_NAME + " where "
                    + LocationItemTable.COL_TIME + " between '" + timeFrom
                    + "' and '" + timeTo + "' and "
                    + LocationItemTable.COL_DATE + " between '" + dateFrom
                    + "' and '" + dateTo + "'", null);
            if (cur.moveToFirst()) {
                do {
                    locationItems
                            .add(new LocationItem(cur.getInt(0), new Gson()
                                    .fromJson(cur.getString(1), LatLng.class),
                                    cur.getString(2), cur.getString(3)));
                } while (cur.moveToNext());
            }
            cur.close();
            return locationItems;
        } catch (Exception ex) {
            throw ex;
        } finally {
            closeDB();
        }
    }

public ArrayList<LocationItem> getLocationItemsByTime(String timeFrom,
        String timeTo) throws Exception {
    Cursor cur;
    ArrayList<LocationItem> locationItems = new ArrayList<LocationItem>();
    try {
        openDB(true);
        cur = dBase.rawQuery("select * from "
                + LocationItemTable.TABLE_NAME + " where "
                + LocationItemTable.COL_TIME + " between '" + timeFrom
                + "' and '" + timeTo + "'", null);
        if (cur.moveToFirst()) {
            do {
                locationItems
                        .add(new LocationItem(cur.getInt(0), new Gson()
                                .fromJson(cur.getString(1), LatLng.class),
                                cur.getString(2), cur.getString(3)));
            } while (cur.moveToNext());
        }
        cur.close();
        return locationItems;
    } catch (Exception ex) {
        throw ex;
    } finally {
        closeDB();
    }
}

public ArrayList<LocationItem> getLocationItemsByDate(String dateFrom,
        String dateTo) throws Exception {
    Cursor cur;
    ArrayList<LocationItem> locationItems = new ArrayList<LocationItem>();
    try {
        openDB(true);
        cur = dBase.rawQuery("select * from "
                + LocationItemTable.TABLE_NAME + " where "
                + LocationItemTable.COL_DATE + " between '" + dateFrom
                + "' and '" + dateTo + "'", null);
        if (cur.moveToFirst()) {
            do {
                locationItems
                        .add(new LocationItem(cur.getInt(0), new Gson()
                                .fromJson(cur.getString(1), LatLng.class),
                                cur.getString(2), cur.getString(3)));
            } while (cur.moveToNext());
        }
        cur.close();
        return locationItems;
    } catch (Exception ex) {
        throw ex;
    } finally {
        closeDB();
    }
}

But on these queries are not working for all possibilities. Like if I enter time 10:00 to 20:00 it give results but if I enter 11:00 to 20:00 query returns null. Same case is for date

A: Strings are compared as strings, so 2/1/2000 is larger than 11/30/2014.
To get correct comparisons, use formats like yyyy-mm-dd and hh:mm:ss.
(These also happen to be the formats supported by the built-in date functions.)


text:
Q: FPDF prints one extra blank page I am using FPDF to view/print data in PHP.
There is only one page I can see on my browser. But, When I try to print that page. I get one extra blank page from printer. Why FPDF submits one extra page every time? Is there any setting that I need to do?
Thanks.


text:
Q: Non-reducedness of schemes and projective morphisms(revisited) This is a continuation of a question asked by me previously with some added hypothesis. Let $X, Y$ be irreducible projective schemes over $\mathbb{C}$, $W \subset X \times Y$ a closed irreducible subscheme. Suppose that the natural projection map $pr_2:W \to Y$ is surjective on the underlying topological spaces, and every fiber is reduced. Note that for all $x \in W$, there is a natural map of tangent spaces $\phi_x:T_{W,x} \to T_{Y,pr_2(x)}$. If there is a point $y \in Y$ such that the $\mathbb{C}$-vector space generated by the union $\cup_{x \in pr_2^{-1}(y)} \phi_x(T_{W,x})$ does not coincide with $T_{Y,y}$, does this mean that $Y$ is nonreduced at the point $y$?

A: This is not true.  Let $X$ be $\mathbb{A}^1$ with coordinate $s$.  Let $\mathbb{A}^2$ have coordinates $t$ and $u$.  Let $Y\subset \mathbb{A}^2$ be the irreducible, reduced closed subset with defining equation $u^2 - t^2(t+1) = 0$, i.e., $Y$ is a nodal cubic curve.  Let $W\subset X\times Y$ be the closed subset with defining equations, $$s(u+t) - t = 0, \ \ s^2(1+t)-(s-1)^2 = 0.$$  On the open subset where $t$ is nonzero, then $W$ has defining equation $s=(1+(u/t))^{-1}$, so that $W$ is smooth and irreducible.  On the open set where $t+1$ is nonzero, then the second defining equation gives that $W$ is smooth over the $t$-line.
So, altogether, $W$ is smooth.  Except over the point $y$ with $(t,u)=(0,0)$, the projection from $W$ to $Y$ is an isomorphism.  The fiber of $W$ over $y$ is one reduced point $x$, namely $(s,t,u) = (1/2,0,0)$.  The Zariski tangent space $T_yY$ is two-dimensional generated by $\partial/\partial t$ and $\partial/\partial u$.  However, $T_xW$ is one-dimensional, since $W$ is a smooth curve near $x$.  Thus, the image of $T_xW$ does not generate $T_yY$.  However, $Y$ is reduced.


text:
Q: how can i tap on wheel picker to enter time in swiftui I am using wheel picker style for time in Swift UI
    HStack {
        Text(title)
        Spacer()
        Text("\(formatter.string(from: date))")
            .onTapGesture {
                showPicker.toggle()
            }
            .padding(8)
            .background(bg1Color)
            .foregroundColor(showPicker ? fgColor : Color.black)
            .cornerRadius(8)
    }
    if showPicker {
         DatePicker("", selection: $date, displayedComponents: displayedComponents)
            .datePickerStyle(.wheel)
            .accentColor(fgColor)
    }

But with this I can't tap and enter time using keyboard  like below screen shot in calender..
please let me know if there a way to achieve this behavior..Thanks in advance .


text:
Q: Convergence of random variables, almost sure and L1 Let $Y_1, Y_2, ...$ be a sequence of random variables such that $Y_n \rightarrow 1 \ \text{a.s.}$ and $\mathbb{E}[Y_n] \rightarrow 1 \ \text{as} \ n \rightarrow \infty.$ I want to prove or disprove the following statement: $\mathbb{E}[|Y_n - 1|] \rightarrow 0 \ \text{as} \ n \rightarrow \infty.$
I think this statement is true. I know that since $\mathbb{E}[Y_n] \rightarrow 1$, there exists some $C \in \mathbb{R}$ such that $\mathbb{E}[Y_n] < C$ and thus $\mathbb{E}[|Y_n|]$ is bounded, which means that $\mathbb{E}[|Y_n - 1|]$ is bounded. Assume that $\mathbb{E}[|Y_n - 1|]$ is bounded by some constant $D \in \mathbb{R}.$ Let $\epsilon > 0.$ Then,
$$\mathbb{E}[|Y_n - 1|] = \mathbb{E}[|Y_n - 1| \mathbf{1}_{|Y_n - 1| \geq \epsilon}] + \mathbb{E}[|Y_n - 1| \mathbf{1}_{|Y_n - 1| < \epsilon}].$$
Thus,
$$\mathbb{E}[|Y_n - 1|] \leq D P(|Y_n - 1| > \epsilon) + \epsilon.$$
The right hand side goes to $0.$
However, I am not sure that this works. I feel like the bounded thing I did in the beginning isn't totally valid. Can someone help me? Thanks.

A: If $\mathbb E[Y_n]<C$ then you cannot deduce that $\mathbb E[\vert Y_n\vert]$ is bounded so your proof is invalid.
In fact you can find a counterexample: $Y_n=1$ with probabiliy $1-\frac{2}{n^2}$, $Y_n=1+n^2$ with probability $\frac{1}{n^2}$ and $Y_n=1-n^2$ with probability $\frac{1}{n^2}$. For all $\varepsilon>0$, Borel-Cantelli's lemma yields that for $n$ large enough, $\vert Y_n-1\vert<\varepsilon$, hence $Y_n\to1$ almost surely. Moreover $\mathbb E[Y_n]=1\to1$. But $\mathbb E[\vert Y_n-1\vert]=2\not\to0$.
Note that if in your initial statement you had assumed that $\mathbb E[\vert Y_n\vert]\to1$ then you would have been able to conclude positively. That is a direct application of Scheffe's lemma https://en.wikipedia.org/wiki/Scheff%C3%A9%27s_lemma.


text:
Q: Como montar um XSD apartir da consulta wsdl? Objetivo: montar o XSD em blocos no eclipse da consulta ao webservice abaixo:
https://valadares.sigiss.com.br/valadares/ws/sigiss_ws.php?wsdl
é gerado o XML:
<definitions xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="urn:sigiss_ws" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="urn:sigiss_ws">
<script id="tinyhippos-injected"/>
<types>
<xsd:schema targetNamespace="urn:sigiss_ws">
<xsd:import namespace="http://schemas.xmlsoap.org/soap/encoding/"/>
<xsd:import namespace="http://schemas.xmlsoap.org/wsdl/"/>
<xsd:complexType name="tcDescricaoRps">
<xsd:all>
<xsd:element name="ccm" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="cnpj" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="senha" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="crc" type="xsd:int" minOccurs="1" maxOccurs="1"/>
<xsd:element name="crc_estado" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="aliquota_simples" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="id_sis_legado" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="servico" type="xsd:int" minOccurs="1" maxOccurs="1"/>
<xsd:element name="situacao" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="valor" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="base" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="descricaoNF" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="tomador_tipo" type="xsd:int" minOccurs="1" maxOccurs="1"/>
<xsd:element name="tomador_cnpj" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="tomador_email" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="tomador_ie" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="tomador_im" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="tomador_razao" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="tomador_fantasia" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="tomador_endereco" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="tomador_numero" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="tomador_complemento" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="tomador_bairro" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="tomador_CEP" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="tomador_cod_cidade" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="tomador_fone" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="tomador_ramal" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="tomador_fax" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="rps_num" type="xsd:int" minOccurs="1" maxOccurs="1"/>
<xsd:element name="rps_serie" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="rps_dia" type="xsd:int" minOccurs="1" maxOccurs="1"/>
<xsd:element name="rps_mes" type="xsd:int" minOccurs="1" maxOccurs="1"/>
<xsd:element name="rps_ano" type="xsd:int" minOccurs="1" maxOccurs="1"/>
<xsd:element name="outro_municipio" type="xsd:int" minOccurs="1" maxOccurs="1"/>
<xsd:element name="cod_outro_municipio" type="xsd:int" minOccurs="1" maxOccurs="1"/>
<xsd:element name="retencao_iss" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="pis" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="cofins" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="inss" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="irrf" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="csll" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="tipo_obra" type="xsd:int" minOccurs="0" maxOccurs="1"/>
<xsd:element name="dia_emissao" type="xsd:int" minOccurs="0" maxOccurs="1"/>
<xsd:element name="mes_emissao" type="xsd:int" minOccurs="0" maxOccurs="1"/>
<xsd:element name="ano_emissao" type="xsd:int" minOccurs="0" maxOccurs="1"/>
</xsd:all>
</xsd:complexType>
<xsd:complexType name="tcLoteRps">
<xsd:complexContent>
<xsd:restriction base="SOAP-ENC:Array">
<xsd:attribute ref="SOAP-ENC:arrayType" wsdl:arrayType="tns:tcDescricaoRps[]"/>
</xsd:restriction>
</xsd:complexContent>
</xsd:complexType>
<xsd:complexType name="tcRetornoNota">
<xsd:all>
<xsd:element name="Resultado" type="xsd:int" minOccurs="1" maxOccurs="1"/>
<xsd:element name="Nota" type="xsd:int" minOccurs="1" maxOccurs="1"/>
<xsd:element name="LinkImpressao" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="autenticidade" type="xsd:string" minOccurs="1" maxOccurs="1"/>
</xsd:all>
</xsd:complexType>
<xsd:complexType name="tcEstruturaDescricaoErros">
<xsd:all>
<xsd:element name="id" type="xsd:int" minOccurs="1" maxOccurs="1"/>
<xsd:element name="DescricaoProcesso" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="DescricaoErro" type="xsd:string" minOccurs="1" maxOccurs="1"/>
</xsd:all>
</xsd:complexType>
<xsd:complexType name="tcDescricaoErros">
<xsd:complexContent>
<xsd:restriction base="SOAP-ENC:Array">
<xsd:attribute ref="SOAP-ENC:arrayType" wsdl:arrayType="tns:tcEstruturaDescricaoErros[]"/>
</xsd:restriction>
</xsd:complexContent>
</xsd:complexType>
<xsd:complexType name="tcDadosPrestador">
<xsd:all>
<xsd:element name="ccm" type="xsd:int" minOccurs="1" maxOccurs="1"/>
<xsd:element name="cnpj" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="senha" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="crc" type="xsd:int" minOccurs="1" maxOccurs="1"/>
<xsd:element name="crc_estado" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="aliquota_simples" type="xsd:string" minOccurs="1" maxOccurs="1"/>
</xsd:all>
</xsd:complexType>
<xsd:complexType name="tcDadosCancelaNota">
<xsd:all>
<xsd:element name="ccm" type="xsd:int" minOccurs="1" maxOccurs="1"/>
<xsd:element name="cnpj" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="senha" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="nota" type="xsd:int" minOccurs="1" maxOccurs="1"/>
<xsd:element name="motivo" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="email" type="xsd:string" minOccurs="1" maxOccurs="1"/>
</xsd:all>
</xsd:complexType>
<xsd:complexType name="tcNotas">
<xsd:complexContent>
<xsd:restriction base="SOAP-ENC:Array">
<xsd:attribute ref="SOAP-ENC:arrayType" wsdl:arrayType="xsd:int[]"/>
</xsd:restriction>
</xsd:complexContent>
</xsd:complexType>
<xsd:complexType name="tcDadosNota">
<xsd:all>
<xsd:element name="nota" type="xsd:int" minOccurs="1" maxOccurs="1"/>
<xsd:element name="id_sis_legado" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="autenticidade" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="dt_conversao" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="num_rps" type="xsd:int" minOccurs="1" maxOccurs="1"/>
<xsd:element name="serie_rps" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="emissao_rps" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="prestador_razao" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="prestador_endereco" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="prestador_numero" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="prestador_complemento" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="prestador_bairro" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="prestador_cidade" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="prestador_estado" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="prestador_cep" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="prestador_email" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="valor" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="base" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="servico" type="xsd:int" minOccurs="1" maxOccurs="1"/>
<xsd:element name="aliquota_atividade" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="iss" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="cnpj_tomador" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="razao_tomador" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="endereco_tomador" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="numero_tomador" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="complemento_tomador" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="bairro_tomador" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="cidade_tomador" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="estado_tomador" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="cep_tomador" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="email_tomador" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="descricao" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="ISSRetido" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="StatusNFe" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="situacao" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="OpcaoSimples" type="xsd:int" minOccurs="1" maxOccurs="1"/>
<xsd:element name="LinkImpressao" type="xsd:string" minOccurs="1" maxOccurs="1"/>
</xsd:all>
</xsd:complexType>
<xsd:complexType name="tcConsultaFaixaNota">
<xsd:all>
<xsd:element name="mesI" type="xsd:int" minOccurs="1" maxOccurs="1"/>
<xsd:element name="mesF" type="xsd:int" minOccurs="1" maxOccurs="1"/>
<xsd:element name="anoI" type="xsd:int" minOccurs="1" maxOccurs="1"/>
<xsd:element name="anoF" type="xsd:int" minOccurs="1" maxOccurs="1"/>
</xsd:all>
</xsd:complexType>
<xsd:complexType name="tcDadosConsultaNota">
<xsd:all>
<xsd:element name="nota" type="xsd:int" minOccurs="1" maxOccurs="1"/>
<xsd:element name="serie" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="valor" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="prestador_ccm" type="xsd:int" minOccurs="1" maxOccurs="1"/>
<xsd:element name="prestador_cnpj" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="autenticidade" type="xsd:string" minOccurs="1" maxOccurs="1"/>
</xsd:all>
</xsd:complexType>
<xsd:complexType name="tcListaDadosNota">
<xsd:complexContent>
<xsd:restriction base="SOAP-ENC:Array">
<xsd:attribute ref="SOAP-ENC:arrayType" wsdl:arrayType="tns:tcDadosNota[]"/>
</xsd:restriction>
</xsd:complexContent>
</xsd:complexType>
</xsd:schema>
</types>
<message name="GerarNotaRequest">
<part name="DescricaoRps" type="tns:tcDescricaoRps"/>
</message>
<message name="GerarNotaResponse">
<part name="RetornoNota" type="tns:tcRetornoNota"/>
<part name="DescricaoErros" type="tns:tcDescricaoErros"/>
</message>
<message name="CancelarNotaRequest">
<part name="DadosCancelaNota" type="tns:tcDadosCancelaNota"/>
</message>
<message name="CancelarNotaResponse">
<part name="RetornoNota" type="tns:tcRetornoNota"/>
<part name="DescricaoErros" type="tns:tcDescricaoErros"/>
</message>
<message name="ConsultarNotaValidaRequest">
<part name="DadosConsultaNota" type="tns:tcDadosConsultaNota"/>
</message>
<message name="ConsultarNotaValidaResponse">
<part name="RetornoNota" type="tns:tcRetornoNota"/>
<part name="DescricaoErros" type="tns:tcDescricaoErros"/>
</message>
<message name="ConsultarNotaPrestadorRequest">
<part name="DadosPrestador" type="tns:tcDadosPrestador"/>
<part name="Nota" type="xsd:int"/>
</message>
<message name="ConsultarNotaPrestadorResponse">
<part name="DadosNota" type="tns:tcDadosNota"/>
<part name="DescricaoErros" type="tns:tcDescricaoErros"/>
</message>
<message name="geratesteRequest">
<part name="dado" type="xsd:int"/>
</message>
<message name="geratesteResponse">
<part name="retorno" type="xsd:string"/>
</message>
<portType name="WebService SigISSPortType">
<operation name="GerarNota">
<documentation>Gera a nota fiscal eletrônica</documentation>
<input message="tns:GerarNotaRequest"/>
<output message="tns:GerarNotaResponse"/>
</operation>
<operation name="CancelarNota">
<documentation>Faz o cancelamento da nota fiscal eletrônica</documentation>
<input message="tns:CancelarNotaRequest"/>
<output message="tns:CancelarNotaResponse"/>
</operation>
<operation name="ConsultarNotaValida">
<documentation>
Faz a consulta de uma nota fiscal eletrônica para saber se esta válida
</documentation>
<input message="tns:ConsultarNotaValidaRequest"/>
<output message="tns:ConsultarNotaValidaResponse"/>
</operation>
<operation name="ConsultarNotaPrestador">
<documentation>Faz a consulta de uma nota fiscal eletrônica</documentation>
<input message="tns:ConsultarNotaPrestadorRequest"/>
<output message="tns:ConsultarNotaPrestadorResponse"/>
</operation>
<operation name="gerateste">
<documentation>1 - retorna Hello World</documentation>
<input message="tns:geratesteRequest"/>
<output message="tns:geratesteResponse"/>
</operation>
</portType>
<binding name="WebService SigISSBinding" type="tns:WebService SigISSPortType">
<soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="GerarNota">
<soap:operation soapAction="urn:sigiss_ws#GerarNota" style="rpc"/>
<input>
<soap:body use="encoded" namespace="urn:sigiss_ws" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
</input>
<output>
<soap:body use="encoded" namespace="urn:sigiss_ws" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
</output>
</operation>
<operation name="CancelarNota">
<soap:operation soapAction="urn:sigiss_ws#CancelarNota" style="rpc"/>
<input>
<soap:body use="encoded" namespace="urn:sigiss_ws" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
</input>
<output>
<soap:body use="encoded" namespace="urn:sigiss_ws" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
</output>
</operation>
<operation name="ConsultarNotaValida">
<soap:operation soapAction="urn:sigiss_ws#ConsultarNotaValida" style="rpc"/>
<input>
<soap:body use="encoded" namespace="urn:sigiss_ws" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
</input>
<output>
<soap:body use="encoded" namespace="urn:sigiss_ws" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
</output>
</operation>
<operation name="ConsultarNotaPrestador">
<soap:operation soapAction="urn:sigiss_ws#ConsultarNotaPrestador" style="rpc"/>
<input>
<soap:body use="encoded" namespace="urn:sigiss_ws" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
</input>
<output>
<soap:body use="encoded" namespace="urn:sigiss_ws" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
</output>
</operation>
<operation name="gerateste">
<soap:operation soapAction="urn:sigiss_ws#gerateste" style="rpc"/>
<input>
<soap:body use="encoded" namespace="urn:sigiss_ws" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
</input>
<output>
<soap:body use="encoded" namespace="urn:sigiss_ws" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/>
</output>
</operation>
</binding>
<service name="WebService SigISS">
<port name="WebService SigISSPort" binding="tns:WebService SigISSBinding">
<soap:address location="https://valadares.sigiss.com.br:443/valadares/ws/sigiss_ws.php"/>
</port>
</service>
</definitions>

Objetivo

De que forma posso montar o XSD para ser visualizado no eclipse ?


text:
Q: в Recyclerview событие onClick public class ModelClass {
private int imageResourse1;
private int imageResourse2;
private int getImageResourse3;
private String title;

public ModelClass(int imageResourse1, int imageResourse2, int getImageResourse3, String title) {
    this.imageResourse1 = imageResourse1;
    this.imageResourse2 = imageResourse2;
    this.getImageResourse3 = getImageResourse3;
    this.title = title;
}

public int getImageResourse1() {
    return imageResourse1;
}

public int getImageResourse2() {
    return imageResourse2;
}

public int getGetImageResourse3() {
    return getImageResourse3;
}

public String getTitle() {
    return title;
}

}
public class Adapter_class extends RecyclerView.Adapter<Adapter_class.ViewHolder> {
private List<ModelClass> modelClassList;
public Adapter_class(List<ModelClass> modelClassList) {
    this.modelClassList = modelClassList;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View view= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_layout,viewGroup,false);return new ViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {
    int resourse1 = modelClassList.get(i).getImageResourse1();
    int resourse2=modelClassList.get(i).getImageResourse2();
    int resourse3=modelClassList.get(i).getGetImageResourse3();
    String title=modelClassList.get(i).getTitle();

    viewHolder.setData(resourse1,resourse2,resourse3,title);

}

@Override
public int getItemCount() {
    return modelClassList.size() ;
}

class ViewHolder extends RecyclerView.ViewHolder
{
    private Button button1;
    private Button button2;
    private Button button3;
    private TextView title;

    public ViewHolder(@NonNull View itemView) {
        super(itemView);

        title =itemView.findViewById(R.id.textView);
        button1=itemView.findViewById(R.id.button4);
        button2=itemView.findViewById(R.id.button7);
        button3 =itemView.findViewById(R.id.button8);

    }

    private  void setData( int resourse1,int resourse2,int resourse3, String titleText ){
        button1.setBackgroundResource(resourse1);
        button2.setBackgroundResource(resourse2);
        button3.setBackgroundResource(resourse3);
        title.setText(titleText);
    }
}

}
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    recyclerView=findViewById(R.id.recyclerView);
    LinearLayoutManager layoutManager=new LinearLayoutManager(this);
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    recyclerView.setLayoutManager(layoutManager);
    List<ModelClass>modelClassList=new ArrayList<>();
    modelClassList.add(new ModelClass(R.drawable.ic_launcher_background, R.drawable.ic_launcher_background,R.drawable.ic_launcher_background,"hello this is user 1"   ));//картинка кнопки 1 к,картинка кнопки 2 ,картинка кнопки 3 ,текст.
    modelClassList.add(new ModelClass(R.drawable.ic_launcher_background, R.drawable.ic_launcher_background,R.drawable.ic_launcher_background,"hello this is user 2"   ));
    modelClassList.add(new ModelClass(R.drawable.ic_launcher_background,0,0,"hello this is user 3"   ));

    Adapter_class adapter =new Adapter_class(modelClassList);
    recyclerView.setAdapter(adapter);
    adapter.notifyDataSetChanged();
}

}
Здравствуйте подскажите можно ли сделать так чтобы в Recyclerview можно было для каждой кнопки назначить разное onClick(); и разные действия соответственно

A: В простом варианте вы можете реализовать OnClick во ViewHolder:
public ViewHolder(@NonNull View itemView) {
    super(itemView);

    title =itemView.findViewById(R.id.textView);
    button1=itemView.findViewById(R.id.button4);
    button2=itemView.findViewById(R.id.button7);
    button3 =itemView.findViewById(R.id.button8);

    button1.setOnClickListener(this);
    button2.setOnClickListener(this);
    button3.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    switch(v.getId) {
      case R.id.button4:
      // Действие при нажатии на кнопку
      break;
      case R.id.button7:
      // Действие при нажатии на кнопку
      break;
      case R.id.button8:
      // Действие при нажатии на кнопку
      break;
    }
}
};


text:
Q: Cannot print help topic on exported rcp product When I try to print an help topic using the embedded help system my eclipse app, nothing happens and the help freezes until I close the app manually.
Strange thing is printing works perfectly when I run my application directly in Eclipse but not working when I launch the exported product.
It's like the Windows standard printing modal is launched but no shown..
Does someone know how to fix that ?
Note : I'm using Eclipse RCP 3.X with E4 compatibility layer


text:
Q: OnCreateOptionsMenu is called for the wrong Fragment I have SherlockFragmentActivity with 3 fragments and ViewPager to swipe between them (in addition to ActionBar).
Every SherlockFragment has its own menu and looks like this:
public class MyFragment1 extends SherlockFragment {
    private Menu menu;
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setHasOptionsMenu(true);
    }
//...
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.fr1, menu);
        super.onCreateOptionsMenu(menu, inflater);
        this.menu = menu;
    }
//...
}

Other fragment classes look similar.
You know, ViewPager instantiates two fragments at first activity launch. So, first executes OnCreateView() of the first fragment, then OnCreateOptionsMenu() of the first fragment, then OnCreateView() of the second fragment, and then OnCreateOptionsMenu() of the FIRST fragment AGAIN!
Please help, I need to understand what I do wrong.

A: Checking if the viewpager is hosted by SherlockFragmentActivity to make sure i can make that cast and the followed call :)
public void onPageSelected(int position) {
    ...
    if (context instanceof SherlockFragmentActivity)
        ((SherlockFragmentActivity)context).supportInvalidateOptionsMenu();
}

and you need to start the inflation in the contexts onCreateOptionsMenu like this:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    Fragment f = get your current Fragment
    if (f != null && f instanceof SherlockFragment)
            ((SherlockFragment)f).onCreateOptionsMenu(menu, getSupportMenuInflater());
    return super.onCreateOptionsMenu(menu);
}


text:
Q: What is the difference between std::unique_ptr and type&&? I can't get difference between two variants:
class test {
    std::unique_ptr<std::vector<float>> m_field;
    test(const std::vector<float>&& values) : m_field{std::make_unique<vector<float>>(std::move(values))} {}
};

And
class test {
    const std::vector<float>&& m_field;
    test(const std::vector<float>&& values) : m_field{std::move(values)} {}
};

In the first variant the default destructor will remove unique_ptr and inner vector automatically but what will happen in the second variant how will the default destructor work?
What variant is better?
P.S. Maybe it's easy but I am looking for and can't find. My English isn't good, please, don't send me to hard docs.

A: First test class is useful when we remove const in constructor, it should be
class test {
public:
std::unique_ptr<std::vector<float>> m_field;
test(std::vector<float>&& values) : m_field{std::make_unique<vector<float>>(std::move(values))} {}
};

because move operation can be done on non-const object.
For example
vector<float> v(20, 3.0);
test t(move(v));
cout << v.size() << endl; // print 20 if `const` will be in constructor definition
                     // print 0 if `const` specifier is missed in constructor, object was moved

Second test class is nonsense. Destructor of this class does nothing. In constructor m_field member is initialized and points at passed vector, and it is all, nothing more is done in ctor/dtor of this class.


text:
Q: What does the open circle in the circuit depict? The open circle at pin 4 in 555 and pin 13 in 4017 has got me confused. I'm new to electronics and any help will be appreciated.
Also does the pin 5 in 555 need to be connected to pin 12 in 4017?
Thanks.

A: A circle on a logic input means that the 'logic' is inverted. In this case pin 13 is the clock enable and it needs to be pulled low to enable the clock input (pin 14).

Also does the pin 5 in 555 need to be connected to pin 12 in 4017?

CTRL    Provides "control" access to the internal voltage divider (by default, 2/3 VCC). See Wikipedia, 555 timer.
No, it doesn't get connected to pin 12 on the 4017. That's used if you want more than ten stages on the counter and pin 12 passes the data to the next 4017 chip.

A: The "bubble" on a pin signifies an inverted input.  The pin is active-low.


text:
Q: What are these index parameters in Robotium? Many of the methods in the Solo class of Robotium take an index parameter, for example Solo.clickOnButton(int). What is this index for? What is it indexing into? More importantly, how do I determine the index for a button or other view that I want to interact with?

A: Many views cannot be reached in another way than by index. For instance dynamically loaded imageViews or imageButtons without R.id That's why there are indexes in robotium. Indexes are set from top left corner to bottom right corner - it means that for instance for layout with four buttons in square grid (2x2) indexes will be 0, 1 for first row and 2, 3 for second row.


text:
Q: How to read file names and word count in respective files in Hadoop? I am trying to fetch file names from sequence file from hadoop with the help of dumbo package of python.
But it provides me some kind of identifier. How can i map this to file name?
Below is my steps on hadoop system for getting filenames :
Steps 1) Generating Sequence file
Command :
hadoop jar /mnt/Clustering/Checking/AllJars/binarypig-1.0-SNAPSHOT-jar-with-dependencies.jar com.endgame.binarypig.util.BuildSequenceFileFromDir /mnt/Clustering/Checking/text_files text_files_seq

Step 2) Running python script on sequence file through hadoop
Command:
dumbo start dumbo_map_red.py -input text_files_seq -output out_res -hadoop /usr/local/hadoop

Step 3) Getting output in local directory
Command:
dumbo cat out_res/part-* -hadoop /usr/local/hadoop > out_res.txt

where dumbo_map_red.py is
#!/usr/bin/env python

def mapper(key, value):
    yield key, 1

def reducer(key, values):
    yield key, sum(values)

if __name__ == "__main__":
    import dumbo
    dumbo.run(mapper, reducer)

Please help me know how to fetch filenames.
If their is other package in python which will allow me to work that way, please let me know..

A: Finally got the hint of mapping identifier in sequence file to actual file.
The identifier is MD5 of file in the directory.


text:
Q: Storing value of a text input in AngularJS I have an input:

In the controller I want to obtain the value of the text input by setting available. For example:
vm.inputValue = document.getElementById('link').value;
It breaks my code as I get a console error of:
TypeError: Cannot read property 'value' of null
What am I doing wrong?

A: Probably you forget to set the id (id = "link")of the input field in HTML:
<input id = "link" type = "text">

Also, you can do the same thing using ng-model
<input ng-model = "vm.inputValue" type = "text">

And from controller, you can get the correct value if you define a scope variable:
$scope.vm = {};
$scope.vm.inputValue = "";

A: AngularJS have a directive that does it to you, the ng-model. It binds in a variable the input you enter in the HTML and it reflect the changes you make in the variable inside your controller in JavaScript.
In your HTML
<input type="text" ng-model="vm.myText">
{{ vm.myText }} <!-- This is output the value of vm.myText in the HTML -->
<button ng-click="vm.logData()"></button>

In your JavaScript
function MyController(){
  var vm = this;

  vm.myText = '';

  vm.logData = logData;

  function logData(){
    console.log('Your data is ', vm.myText);
    // This easy, you can access your value in the JavaScript
  }
}


text:
Q: AWK in the middle of a pipe returns no output I want to process all changed logfiles from apache and made a simple oneliner:
inotifywait --format="%w%f" -rm /var/log/apache2/ | gawk '{ print }'

This is exactly my start. But if I pipe that output further, I get no output:
inotifywait --format="%w%f" -rm /var/log/apache2/ | gawk '{ print }' | wc -l

Anyway, if I use 'ls', 'tail' (what I really want), there is never output
(in another console, running the first statement, I know, there are changes).
I tried with adding stdbuf, fflush(), nothing works. I dont understand the problem!
I want to keep this onliner into a script, which I can use as a string point. Otherwise, I could (but dont wish to) use xargs.
Any help or tips would be fine!

A: The reason you do not get output is because wc -l is consuming all of the output. You can use tee in combination with process substitution to get awk to output to the console as well as read by wc:
inotifywait --format="%w%f" -rm /var/log/apache2/ | gawk '{ print }' | tee >(wc -l)

This is still slightly problematic as inotifywait is a command that never exits, but wc -l does not print output until it has read all the data, in this case when the pipe closes. You can do your counting directly in awk:
inotifywait --format="%w%f" -rm /var/log/apache2/ | gawk 'BEGIN { total=0 } { print; total++; print total } END { print "final total: " total }'


text:
Q: How to do an UPSERT in Python for MSSQL I have the following problem. I am getting some data from an api in form of a json.
I want to load this json data into an existing table.
I get the data in following format:
{
  "abcd": "blablabla",
  "value": [
    {
        "a": "1",
        "b": "2",
        "c": "3"
    },
    {
        "a": "4",
        "b": "5",
        "c": "6"
    }
  ]
}

I am only interested in the data in "value" with "a", "b" and "c" being my columns in the table.
I get only the interesting values by creating a pandas Dataframe:
contents = pandas.json_normalize(response.json(), record_path=['value'])

I can insert this data into mssql with the to_sql method from pandas, however, I would like to do an insert if it doesn't exist or update if a certain key already exists. (e.g. in this example column "a" could be the key column).
I have read about certain sqlalchemy methods with merge and so on, however I was no able to reproduce it in my case.
Here is how I loaded the data into my database:
with open('db_con.json') as db:
            con = json.load(db)

            con_url = URL.create(
                "mssql+pyodbc",
                username = con['username'],
                password = con['password'],
                host = con['host'],
                port = con['port'],
                database = con['database'],
                query = con['query'],
                )
            engine = sqlalchemy.create_engine(con_url, fast_executemany = False, echo = True)

            contents.to_sql(
                test_db,
                engine,
                if_exists='append',
                index = False,
                chunksize = 2500,
                schema = 'test'
            )

What would I need to do, to implement such an upsert method?
I guess I cannot use to_sql anymore.


text:
Q: Deployment to Ethereum Ropsten test net fails I am trying the freecodecamp project here:
https://www.freecodecamp.org/news/how-to-make-an-nft/
I am stuck with the step
node ./scripts/deploy.js

But it fails to deploy to the Ropsten test network.
I am a beginner with NFT and Ethereum and I am not sure how to debug that.
The error message is now that the funds are insufficient.
but I got now more than 10 Ethereum in the Metamask wallet.
Error: insufficient funds for intrinsic transaction cost (error={"name":"ProviderError","code":-32000,"_isProviderError":true}, method="sendTransaction", transaction=undefined, code=INSUFFICIENT_FUNDS, version=providers/5.5.0)

How can I find out how much Ethereum I would need ?
I expect it to be sufficient but not sure of course.
And what can be the real reason for the failure ?
Here the deploy script:
// ethereum/scripts/deploy.js

async function main() {
  const EmotionalShapes = await ethers.getContractFactory("EmotionalShapes");
  const emotionalShapes = await EmotionalShapes.deploy();

  console.log("EmotionalShapes deployed:", emotionalShapes.address);
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });


text:
Q: Why does this Rust import need `self`? I have the following set of imports at the top of my program:
extern crate serde_bencode;
extern crate serde;
extern crate serde_bytes;
extern crate url;
extern crate url_serde;

use serde_bytes::ByteBuf;
use serde_bencode::de;
use serde_bencode::error::Result;
use serde_bencode::Error::{Custom, InvalidLength};
use self::url::{Url};

This program currently does compile. However, I don't understand why I need to write self on the use self::url::{Url}; line. None of the other use statements need self - why does url?
For context, the snippet above is from a file called file_reader.rs, in a directory with the following structure:
roar/
    file_reader.rs
    main.rs
    lib.rs

Edit: I just noticed that if I add the line extern crate url; to lib.rs, then I don't need the self; however, I don't know why this step is necessary.


text:
Q: MySQL dump ignores full DB views create statement --> I've MySQL DB running v5.7.40
mysql> SHOW VARIABLES LIKE 'version';
+---------------+-----------------------------+
| Variable_name | Value                       |
+---------------+-----------------------------+
| version       | 5.7.40-0ubuntu0.18.04.1-log |
+---------------+-----------------------------+
1 row in set (0.00 sec)
mysql>

--> Currently doing backup of one of the DBs using mysqldump
root@reporting:~# cat /var/scripts/backup.sh
#!/bin/bash
.
.
.
backup(){
    DBASE="jiradbrepl"
    mysqldump -u root $DBASE  >/storage/backup/$DBASE-$MONTH_DAY.sql
}
root@reporting:~#

--> The backup completes without any errors or warnings but it doesn't include full create statement of DB views
root@reporting:~# bash  /var/scripts/backup.sh
++ hostname -s
+ MY_HOSTNAME=reporting
++ date +%b-%d
+ MONTH_DAY=Jan-15
+ backup
+ DBASE=jiradbrepl
+ mysqldump -u root jiradbrepl
+ cleanup
+ find /storage/backup/ -type f -name '*.sql' -mtime +5 -exec rm '{}' ';'
root@reporting:~#

root@reporting:~# ls -lh /storage/backup/jiradbrepl-Jan-15.sql
-rw-r--r-- 1 root root 748M Jan 15 14:37 /storage/backup/jiradbrepl-Jan-15.sql
root@reporting:~#

--> For example this view stops at the middle of the creation statement
root@reporting-db:~# less /storage/backup/jiradbrepl-Jan-15.sql
.
.
.
DROP TABLE IF EXISTS `V_R_PROJECTS_BIRDEYE`;
/*!50001 DROP VIEW IF EXISTS `V_R_PROJECTS_BIRDEYE`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `V_R_PROJECTS_BIRDEYE` AS SELECT
 1 AS `projectName`,
 1 AS `CPID`,
 1 AS `GEO`,
 1 AS `region`,
 1 AS `subRegion`,
 1 AS `startDate`,
 1 AS `endDate`,
 1 AS `status`,
 1 AS `LOE`,
 1 AS `discountedLOE`,
 1 AS `status_history`,
 1 AS `prjPoCName`,
 1 AS `ML_CQ`,
 1 AS `BC_CQ`,
 1 AS `commitedBudget`,
 1 AS `URL`,
 1 AS `prjActualDays`,
 1 AS `prjPendingDays`,
 1 AS `prjPlannedDays`,
 1 AS `currentQuarterActualDays`,
 1 AS `currentQuarterPendingDays`,
 1 AS `remainingQuarterPlannedDays`,
 1 AS `currentQuarterPlannedDays`,
 1 AS `nextQuarterPlannedDays`,
 1 AS `PSO_PM`,
 1 AS `COE_PM`,
 1 AS `techList`,
 1 AS `budgetActuals`,
 1 AS `budgetForecast`,
 1 AS `budgetPlanned`*/;
SET character_set_client = @saved_cs_client;
root@reporting-db:~#

--> The backup runs with root user which has all privileges
mysql> show grants for root;
+-------------------------------------------------------------+
| Grants for root@%                                           |
+-------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION |
+-------------------------------------------------------------+
1 row in set (0.00 sec)

mysql>

root@reporting-db:~# mysql -ANe"SELECT USER(),CURRENT_USER()"
+----------------+----------------+
| root@localhost | root@localhost |
+----------------+----------------+
root@reporting-db:~#

--> I've tried running the backup using the command in Views not being dumped by mysqldump
--> Also using this command but that didn't help
mysqldump -u root --lock-tables --comments --dump-date --force --events --routines --add-drop-table --add-locks --log-error=/tmp/jiradbreplbackup.log jiradbrepl  > /storage/backup/jiradbrepl-Jan-15_2.sql

root@reporting-db:~# cat /tmp/jiradbreplbackup.log
root@reporting-db:~#

Please let me know if you have any suggestion for this issue.

A: If you look further down in your dump file, you'll see the view is created a second time in a format that will look more complete. The name of the view is first created as a temporary table (that create statement is what you've shown above) in case other views depend on it (ref https://github.com/twitter-forks/mysql/blob/master/client/mysqldump.c#L2557). Then it is created as a view with the full create statement you expect. Here is an example.
Given this table:
create table mytable (id int, firstname varchar(50), lastname varchar(50));

And this view on that table:
create view myview as select id, firstname from mytable;

Do a dump of the database:
mysqldump -u user -ppassword mydatabase  >/tmp/dump.sql

Resulting dump file:
cat /tmp/dump.sql
-- MySQL dump 10.13  Distrib 8.0.31, for macos13.0 (x86_64)
...

--
-- Table structure for table `mytable`
--

DROP TABLE IF EXISTS `mytable`;
...
CREATE TABLE `mytable` (
  `id` int DEFAULT NULL,
  `firstname` varchar(50) DEFAULT NULL,
  `lastname` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
...

--
-- Dumping data for table `mytable`
--

...

--
-- Temporary view structure for view `myview`
--

DROP TABLE IF EXISTS `myview`;
/*!50001 DROP VIEW IF EXISTS `myview`*/;
...
/*!50001 CREATE VIEW `myview` AS SELECT
 1 AS `id`,
 1 AS `firstname`*/;

...

--
-- Final view structure for view `myview`
--

/*!50001 DROP VIEW IF EXISTS `myview`*/;
...
/*!50001 CREATE ALGORITHM=UNDEFINED */
/*!50013 DEFINER=`user`@`localhost` SQL SECURITY DEFINER */
/*!50001 VIEW `myview` AS select `mytable`.`id` AS `id`,`mytable`.`firstname` AS `firstname` from `mytable` */;
...

-- Dump completed on 2023-01-17  7:40:31


text:
Q: Is it bad to use wrong measurement system with a particular English style We have two major English styles: American English (AmE) and British English (BrE).
If I use AmE in a question, should I also stick to the system of measurement that most Americans use (Fahrenheit scale, pounds, feet etc.)? Or can I use the SI system (kilogram, Celsius scale1 etc.)?

1 No, Celsius isn't in the SI system, but AFAIK no one uses kelvin in everyday life.

A: The purpose of language is to communicate, so use whichever measurements your audience is most likely to understand. Even though you are writing in American English, your audience may expect metric measurements based on the subject matter.
I could write an article about the London Stock Exchange for an American audience and favor putting prices in US dollars instead of pounds or euros because that is what my audience understands best.


text:
Q: Mysql returns duplicate results with numbered key I did a SELECT query on MySQL and get this as result.

The problem is how can I remove the 2nd duplicated results at for instance we use the 1st item in the list. "0":"1" is a duplicate for "id":"1" I would rather use "id" instead of "0" as the key later on the the app. How could I remove this to simplify the results. I do notice that the "0" means the 1st column as the successive columns does add up by 1.
Here's the $query I run.
SELECT id FROM clubsinformation WHERE :comparisonTime < updateTime

A: This is caused by most likely the fetching mode, you need to fetch it by associative indices only because right now you're including both associative and numeric index fetching:
No matter what DB API you got, MySQLi or PDO, just set it to associative.
So that it turn it doesn't include the numeric indices, only the column names as keys:
So this would roughly look like in code (from looking at your query placeholders, it seems PDO, so I'll draft a PDO example):
$data = array(); // container
$query = 'SELECT * FROM clubsinformation WHERE :comparisonTime < updateTime';
$select = $db->prepare($query);
$select->bindValue(':comparisonTime', $comparisonTime);
$select->execute();

while($row = $select->fetch(PDO::FETCH_ASSOC)) { // associative
    $data[] = $row; // only includes column names
}

// then finally, encode
echo json_encode($data);

// OR SIMPLY
// $data = $select->fetchAll(PDO::FETCH_ASSOC); // associative
// echo json_encode($data);

That fetching is by way of PDO API. If you're using MySQLi you can still use the basic idea.


text:
Q: Exception in thread "main" java.util.NoSuchElementException Tenho o seguinte método de java que lê um arquivo de texto e cria novos pontos(coordenadas num gráfico), porém estou me deparando com o do titulo erro na leitura do arquivo. Ao seguir meu stackTrace ele aponta que o erro está quando tento ler o primeiro nextDouble().
Outra coisa curiosa é que as vezes ele funciona normalmente, daí tento aumentar o número de pontos no meu arquivo de texto e ele começa a surtar.
public void readDatabase(String s) throws FileNotFoundException{
    try {
        BufferedReader br = new BufferedReader(new FileReader(s));
        String line = br.readLine();
        Scanner trainFile = null;
        while (line != null) {
            line.trim();
            trainFile = new Scanner(line);
            double x = trainFile.nextDouble();
            double y = trainFile.nextDouble();
            int type = trainFile.nextInt();
            this.database.add(new Ponto(x,y,type));
            line = br.readLine();
        }
        trainFile.close();
        br.close();
    }
    catch (IOException ioe) {
        ioe.printStackTrace();
    }
}

Alguém tem alguma ideia do que seja o problema?

A: Existem linhas vazias no seu arquivo? (a última talvez) A documentação do getDouble diz:

NoSuchElementException - if the input is exhausted

Eu noto que você faz trim na linha e segue para a leitura via Scanner, sem verificar se essa linha está vazia. Sugiro fazer isso e, se estiver, prosseguir com o loop:
  while (line != null) {
      line = line.trim(); // Nota: Strings são imutáveis - é preciso reatribuir o valor após o trim
      if ( line.length() == 0 )
          continue;
      trainFile = new Scanner(line);
      ...

A: Para solucionar o problema eu fiz as seguintes alterei as condições de leitura da próxima linha no meu código, desta forma eu nao me deparei com linhas inválidas.
public void readDatabase(String s) throws FileNotFoundException{
    try {
        final BufferedReader br = new BufferedReader(new FileReader(s));
        final Scanner trainFile = new Scanner(br);
        while (trainFile.hasNextDouble()) {
            double x = trainFile.nextDouble();
            double y = trainFile.nextDouble();
            int type = trainFile.nextInt();
            this.database.add(new Ponto(x,y,type));
        }
        trainFile.close();
        br.close();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}

A:
Um tipo de entrada era um arquivo de texto simples com dois valores double e um int por linha separados por whitespace. O interessante é que ao utilizar . como separador obtive erro, porém ao usar , meu código funcionou.

Alguns lugares convencionam o ponto (.), enquanto outros lugares utilizam a vírgula (,).
Por exemplo:

*

*Se o idioma estiver em inglês o padrão é o ponto (.);

*Se o idioma estiver em português o padrão é a vírgula (,);

Utilize o método useLocale da classe Scanner para especificar a regra que deseja utilizar:
trainFile.useLocale(Locale.US);

Dessa forma, você conseguirá utilizar a entrada utilizando ponto (.).


text:
Q: Bind event/callback to keyword in Java I am new in Java coming from javascript background.
In javascript , we can save callbacks in objects like this-
//we register some callback on a keyword
    var observerCallbacks = {};
     registerObserverCallback = function(eventname ,callback){
                observerCallbacks[eventname] =  callback;
            };
//For calling events
    notifyObservers = function(eventname){
         observerCallbacks[eventname]();
            };

Usage :
//Register event
      registerObserverCallback('eventA',function(){
          //body of callback
     });

//For calling event
notifyObservers('eventA');

I am looking for equivalent functionality in Java. Is there way of creating this type of custom functionality.

A: Java has a slightly different mechanism for this purpose. A object  registers itself as a listener to specific type of event When this kind of event occurs, all listeners are notified.
Here you can find a tutorial about it. Below code is from there.
public class MultiListener ... implements ActionListener {
    ...
    //where initialization occurs:
        button1.addActionListener(this);
        button2.addActionListener(this);

        button2.addActionListener(new Eavesdropper(bottomTextArea));
    }

    public void actionPerformed(ActionEvent e) {
        topTextArea.append(e.getActionCommand() + newline);
    }
}

class Eavesdropper implements ActionListener {
    ...
    public void actionPerformed(ActionEvent e) {
        myTextArea.append(e.getActionCommand() + newline);
    }
}

More on this topic could be found here

A: JavaScript is an asynchronous language, Java is a synchronous language. What you want to do is the same as asking "How to I turn my hammer into a screwdriver?" While it's still fully possible with creativity to make the hammer screw something in, it's not how the tool is intended to be used and the result may vary.
The callbacks are essential in JavaScript to let your program know that the function has completed, Java knows that the function is completed since it stops to execute it.
Java offers you event listeners for events that may seem similar when you don't know better; they lay idle until whatever they're listening for activates them, then it activates, executes and goes back to listening.
The Java way of doing this is to tell your listener to do whatever you want it to do straight away; you don't stop to wait for a callback because Java will stop, execute what you tell it to, then go back into the place where it came from. How to write the code for a listener can be found in the oracle tutorial but your issue is more of a logic issue rather than the specific code.
If you want the listener to store something for another method, a bean with getters and setters would be one Java way.


text:
Q: How can I animate the addClass() and removeClass jQuery methods? I'm working on a site and want to display and hide sections of it by adding ".hidden" bootstrap class under click events.
  Basically:
  $('selector').click(function(){
     $('*part-to-hide*').addClass("hidden");
     $('*part-to-show*').removeClass("hidden");
   }

It's working properly but needs some smooth animations. What are my options?
Note: while I'v seen similar questions, I'd consider mine different (and thus not a duplicate) as it centers around the use of the bootstrap "hidden" class. On that note, I'd appreciate it if answers tackle the issue while sticking to the main idea of the code, which is adding and removing the "hidden" class to an element.

A: just assign a transition property to your element ;)
Check here for more info: https://www.w3schools.com/css/css3_transitions.asp
Fiddle:
https://www.w3schools.com/css/tryit.asp?filename=trycss3_transition1

A:

$('#selector').on('click',function(){
    if($(this).attr("data-animate")=="0"){
      $('#Div1').removeClass('Div2').addClass('Div1');
      $(this).attr("data-animate","1");
           $(this).val("Change color");
    }
    else{
     $('#Div1').removeClass('Div1').addClass('Div2');
          $(this).attr("data-animate","0");

                 $(this).val("start animate");
    }

});
.Div2{
    width: 100px;
    height: 100px;
    background-color: red;
    position: relative;
    -webkit-animation-name: example2; /* Safari 4.0 - 8.0 */
    -webkit-animation-duration: 4s; /* Safari 4.0 - 8.0 */
    animation-name: example2;
    animation-duration: 4s;
}

.Div1{

    width: 100px;
    height: 100px;
    background-color: red;
    position: relative;
    -webkit-animation-name: example; /* Safari 4.0 - 8.0 */
    -webkit-animation-duration: 4s; /* Safari 4.0 - 8.0 */
    animation-name: example;
    animation-duration: 4s;
}

/* Safari 4.0 - 8.0 */
@-webkit-keyframes example {
    0%   {background-color:red; left:0px; top:0px;}
    25%  {background-color:yellow; left:200px; top:0px;}
    50%  {background-color:blue; left:200px; top:100px;}
    75%  {background-color:green; left:0px; top:100px;}
    100% {background-color:red; left:0px; top:0px;}
}

/* Standard syntax */
@keyframes example {
    0%   {background-color:red; left:0px; top:0px;}
    25%  {background-color:yellow; left:200px; top:0px;}
    50%  {background-color:blue; left:200px; top:100px;}
    75%  {background-color:green; left:0px; top:100px;}
    100% {background-color:red; left:0px; top:0px;}
}

@-webkit-keyframes example2 {
    0%   {background-color:red;}
    25%  {background-color:yellow; }
    50%  {background-color:blue; }
    75%  {background-color:green; }
    100% {background-color:red;}
}
}

<input id="selector" type="button" data-animate="0" value="start animate"/>

A:

$( document ).ready(function() {
    $(".togglediv").on('click',function(){
      $(".showdiv").toggleClass("hidden");
      $(".hidediv").toggleClass("hidden");
    });
});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

             show div

             hide div

        <button class="togglediv">show/hide content</button>


text:
Q: Can my tortoise vs. hare race be improved? Here is my code for detecting cycles in a linked list:
do
{
    hare = hare.next();
    if (hare == back) return;

    hare = hare.next();
    if (hare == back) return;

    tortoise = tortoise.next();
}
while (tortoise != hare);
throw new AssertionError("cyclic linkage");

*

*Is there a way to get rid of the code duplication inside the loop?

*Am I right in assuming that I don't need a check after making the tortoise take a step forward? As I see it, the tortoise can never reach the end of the list before the hare (contrary to the fable).

*Any other ways to simplify/beautify this code?

A:
Is there a way to get rid of the code
  duplication inside the loop?

How about:
for(int i = 0; i < 2; i++)
{
    hare = hare.next();
    if (hare == back) return;
}

 tortoise = tortoise.next();

That isn't a massive improvement by any means.

Am I right in assuming that I don't need a check after making the tortoise take a step forward?

Yes, as you correctly reason, the tortoise is always behind the hare just before it moves; so the tortoise is always covering ground that has been covered before.
If the data-structure were for any reason mutated during the race, this would of course no longer be true (but if so, you would have much bigger problems).

Any other ways to simplify/beautify
  this code?

Not that I can think of.

A: Here is my improved code based on Steve's comment (having the back sentinel node link to itself):
while (hare != back)
{
    tortoise = tortoise.next();
    hare = hare.next().next();
    if (hare == tortoise) throw new AssertionError("cyclic linkage");
}

I don't see any place where this would break client code, and my unit tests confirm that. Great :)

A: You can use a single if-statement and use the fact that || is a short-circuit operator. This is a bit more concise, but may be harder to understand and there is still code duplication.
    do
    {
        if ((hare = hare.next()) == back ||
            (hare = hare.next()) == back)
                return;
        tortoise = tortoise.next();
    }
    while (tortoise != hare);

A: To avoid the duplication, you could use a for (int i = 0; i < 2; i++) loop. Other than that, I think you've pretty much got the simplest code you can have right there.


text:
Q: Подскажите почему не отрабатывает запрос Пытаюсь отладить будущий триггер
Пример надуманый и очень простой
делаю
begin
  IF (1<>0) THEN
    select * from aa.csv;
  ELSE
    select * from aa.csv;
  END IF;
end

Но не отрабатывает возвращает ошибку

Unrecognized statement type. (near "begin" at position 0)
begin IF (1<>0) THEN select * from aa.csv
#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 'IF (1<>0) THEN
select * from aa.csv' at line 2

При этом, у других судя по всему все прекрасно работает (пример взят с форума где у человека все прекрасно работает) - запрос вроде бы простой до тупости...
Подскажите почему не отрабатывает?
MySQL - 5.7


text:
Q: Why is it not possible to group Telerik chart legend items? I would need to group the elements of a Kendochart series, so they are separated as follows:
Group Title 1:
Serie 1.
Serie 2.
Group Title 2:
Serie 3.
Serie 4.
I tried it with a template, but it does not work.
legend: {
    labels: {
        template: kendo.template($("legend-template").html())
    }
},

<script id="legend-template" type="text/x-kendo-template">
    <div id="Leyenda">  #: text # </div>
</script>

Thank you in advance.

A: SOLVED: The solution was to create a new div with a checkbox for each of the series and through jQuery to play with the checked property of these, alternating the visualization of each elements of the series.
For Example:
 $("#SerieName").change(function () {
            if ($("#SerieName").is(":checked")) {
                $("#Chart").data("kendoChart").options.series[0].visible = true;
                $("#Chart").data("kendoChart").redraw();

            } else {

                $("#Chart").data("kendoChart").options.series[0].visible = false;
                $("#Chart").data("kendoChart").redraw();
            }
        });


text:
Q: Error on Rollout : it doesn't allow any existing users to upgrade to the newly added APKs I am getting an error when I try to upload the app on the Play Store.

 minSdkVersion 23
    targetSdkVersion 29
    versionCode 167
    versionName "2.1.55"

A: I have just removed the following line from the Manifest file
<uses-feature android:name="android.hardware.type.watch" />


text:
Q: window.open doesn't work in android emulator I'm trying to have an OAuth2 implemented for Ionic application
This is my login for:
<ion-view view-title="Login" align-title="left">
<ion-nav-bar class="bar-positive">
    <ion-nav-back-button class="button-clear icon ion-ios7-arrow-back">
    </ion-nav-back-button>
</ion-nav-bar>
<ion-content class="padding">

    Sign in with Foo Account

</ion-content>

and this is my login controller:
'use strict';

angular.module('fooapp')
.controller('loginCtrl', function($scope, $state, $http) {

$scope.signIn = function(user) {
 console.log('Sign-In', user);
 $state.go('tab.home');
}

$scope.loginToFoo = function() {

var URL_AUTH = 'https://foo.com/api/oauth2/auth';
var RESPONSE_TYPE_CODE = 'code';
var CLIENT_ID = '{xxxxxx-xxxxx-xxxxx-xxxxx}';
var REDIRECT_URL = 'http://localhost/callback';

var loginUrl = URL_AUTH + '?client_id=' + CLIENT_ID +
              '&redirect_uri=' + REDIRECT_URL +
              '&force_login=1&response_type=' + RESPONSE_TYPE_CODE ;

window.open(loginUrl, "_system", "location=yes");
};
})

I have also added these lines to config.xml:
<feature name="InAppBrowser">
  <param name="android-package" value="org.apache.cordova.InAppBrowser"/>
</feature>
<feature name="InAppBrowser">
  <param name="ios-package" value="CDVInAppBrowser" />
</feature>

Although I have already added cordova-plugin-inappbrowser, as I use 'ionic serve', I can see the correct result in a browser but as I use 'ionic emulate android', in the android emulator, nothing happens as I click on my login button.
what am I missing in here?


text:
Q: MVC pattern in android?
Possible Duplicate:
MVC pattern in Android?

I'm new to Android, I need to know that, how to create MVC pattern in an Android application?
If any one knows please guide me to right direction.....

A: Check below link for MVC:
http://mindtherobot.com/blog/675/android-architecture-message-based-mvc/
http://code.google.com/p/android-mvc/source/checkout


text:
Q: PDFTron draw vertical box if layout is Horizontal I have below code which will draw rectangle when user press "Shift + Left Mouse Click"
 // Draw text box with alt + mouse left click
docViewer.on('click', (evt: any) => {
    if (evt.shiftKey) {
        // Get get window coordinates
        const windowCoords = getMouseLocation(evt);

        // Get current page number
        const displayMode = docViewer.getDisplayModeManager().getDisplayMode();
        const page = displayMode.getSelectedPages(windowCoords, windowCoords);
        const clickedPage = (page.first !== null) ? page.first : docViewer.getCurrentPage();

        // Get page coordinates
        const pageCoordinates = displayMode.windowToPage(windowCoords, clickedPage);

        // create rectangle
        const rectangleAnnot = new instanceAnnotations.RectangleAnnotation();
        rectangleAnnot.PageNumber = clickedPage + 1;
        rectangleAnnot.X = pageCoordinates.x;
        rectangleAnnot.Y = pageCoordinates.y - 14;
        rectangleAnnot.Width = 200;
        rectangleAnnot.Height = 14;
        rectangleAnnot.StrokeColor = new instanceAnnotations.Color(255, 0, 0, 1);
        rectangleAnnot.StrokeThickness = 2;
        rectangleAnnot.Author = annotManager.getCurrentUser();

        annotManager.addAnnotation(rectangleAnnot, false);
        annotManager.redrawAnnotation(rectangleAnnot);
    }
});

Now the issue is above code draw rectangle fine if PDF is vertical but if PDF is Horizontal then it draw Rectangle vertically. Please check below screenshot for reference.

As you can see on Page 1 it draws vertical box but on 2nd page its draws fine.
So how one can resolve it?

A: You need to account for page rotation to ensure your rect is aligned with the page.
Here is a quick example of how you can achieve that using the getCompleteRotation API, by setting width and height depending on the document rotation.
docViewer.on("click", (evt) => {
if (evt.shiftKey) {
  // Get get window coordinates
  const windowCoords = getMouseLocation(evt);

  // Get current page number
  const displayMode = docViewer.getDisplayModeManager().getDisplayMode();
  const page = displayMode.getSelectedPages(windowCoords, windowCoords);
  const clickedPage =
    page.first !== null ? page.first : docViewer.getCurrentPage();

  // Get page coordinates
  const pageCoordinates = displayMode.windowToPage(
    windowCoords,
    clickedPage
  );

  // create rectangle
  const rectangleAnnot = new Annotations.RectangleAnnotation();
  rectangleAnnot.PageNumber = clickedPage + 1;

  // Depending on doc orientation set Width and Height
  const rotation = docViewer.getCompleteRotation(clickedPage);

  const widthAndHeight = getWidthAndHeightBasedOnRotation(rotation);
  // You will have to adjust the X, Y  as well depending on rotation
  rectangleAnnot.X = pageCoordinates.x;
  rectangleAnnot.Y = pageCoordinates.y;

  rectangleAnnot.Width = widthAndHeight.width;
  rectangleAnnot.Height = widthAndHeight.height;
  rectangleAnnot.StrokeColor = new Annotations.Color(255, 0, 0, 1);
  rectangleAnnot.StrokeThickness = 2;
  rectangleAnnot.Author = annotManager.getCurrentUser();

  annotManager.addAnnotation(rectangleAnnot, false);
  annotManager.redrawAnnotation(rectangleAnnot);
}});

  const getWidthAndHeightBasedOnRotation = (rotation) => {
    switch (rotation) {
      case CoreControls.PageRotation["E_0"]:
        return {
          width: 200,
          height: 14,
        };
      case CoreControls.PageRotation["E_90"]:
        return {
          width: 14,
          height: 200,
        };
      case CoreControls.PageRotation["E_180"]:
        return {
          width: 200,
          height: 14,
        };
      case CoreControls.PageRotation["E_270"]:
        return {
          width: 14,
          height: 200,
        };
    }
  };

You can access the CoreControls object from the instance. Please note that you will also need to tweak your X,Y coordinates based on the rotation. This is a good resource on PDF coordinates and viewer coordinates to help you wrap your head around that part.


text:
Q: IntelliJ not using external Jar's if not added via Maven when running JSF application? I have a very simple line of code that is called from an .xhtml file ( in a JSF 2.0 project )  which looks like:
try {
    Class.forName("com.mysql.jdbc.Driver");
}catch(Exception e) {
    e.printStackTrace();
}

So in my C:\ folder I have the file: mysql-connector-java-5.1.24-bin. I have added this jar as an extenral jar in IntelliJ Idea 12.
When I start my application like this, I get the "Class not found exception." However, when I add this dependency to my pom.xml file:
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.6</version>
</dependency>

I get no exception and class is loaded fine.
Here is a screenshot:
The jar file I underlined with green is the Jar added externally from **File -> Project Structure -> Libraries **
The one I underlined with red is the jar file that is downloaded by maven.
My question is: Why do I get the Class not found exception, although I have added the Jar externally?
In case I require a Jar file that I will not be able to download via maven, what am I supposed to do?
One extra information: I created a sample Java project with one class only, and I added this external Jar file with the method I explained above. No maven, no tomcat, nothing. Just a simple main method. I ran this same code, and it worked fine. So it has to have something to do with IntelliJ and one or more of:

*

*Maven

*Tomcat ( Deploying a War file )

*Maven and Tomcat?

Edit: When I add the external Jar only and try importing a class from com.mysql.jdbc... IntelliJ IDEA does not come up with any warnings / errors. It finds the class, however after the deployment, it seems like the Class can not be found anymore.

A: The webapp is deployed and run on tomcat. Tomcat doesn't care about the jars in the IntelliJ source project. What matters to tomcat is the set of jar files under the WEB-INF/lib directory of the deployed webapp. Only those jars are in the classpath of the webapp.
I don't know very well how IntelliJ builds and deploys webapps, especially when Maven is in the picture. But I'd guess that it only deploys the jars that are in the compile and runtime scopes of the Maven project. For an external jar, it's probably possible to configure the IntelliJ project in order to include it in the built and deployed archive.
But anyway, if you use Maven, you must be able to build your war without using IntelliJ. That's the whole point of a build tool: it's used to build a project without an IDE. So all the necessary jars must be known by Maven. So the jar, if not available in the Maven central, should be added to your own local Maven repo (at least), or to your company's private repo.


text:
Q: Store Markdown Text as an Object Is there anyway way to store markdown text as an object? For example, say I have the following markdown text, note that this exists in the text editor part, rather than inside a code chunk:
Total Clients:**Total Number of Clients: **`r cohort %>% distinct(CLIENT_ID) %>% nrow`

Total Female Clients:**Total Number of Clients: **`r cohort %>% filter(GEND == "F") %>% distinct(CLIENT_ID) %>% nrow`

As we go through the document, we use a function to create 'cohort', and drop that variable after each use, thus it is always changing. Is there any way for me to store that total clients/total female clients text as an object, i.e. summary_text so that I don't have to type the full thing out each time, I can just call summary_text and it appears? Something along the lines of
summary_text <- list(clients = "Total Clients:**Total Number of Clients: **`r cohort %>% distinct(CLIENT_ID) %>% nrow`",
                     clients_female = "Total Female Clients:**Total Number of Clients: **`r cohort %>% filter(GEND == 'F') %>% distinct(CLIENT_ID) %>% nrow`")


text:
Q: How to fix the coding My site is https://templatemonstrosity.blogspot.com/ . As you can see, on the very top of this page, there is an irritating text '-->'. I have searched through my entire XML do but I cannot find where it is, can someone please tell me what to do? If someone can please check out my template from https://drive.google.com/open?id=0Bw7OiqWvpt5sdXc3cUV5Y2ZMMVk and tell me which exact ine to fix, then it would be a big help.

A: I inspected your website, and right at the top of the body there is a "-->".  Getting rid of that worked for me.
step 1: look for this line/piece of code (I have not done html in forever).

right below that I see:
"-->
"
delete the "-->
".
You should be good to go.

A: It's here (look in the source-code):
@media screen and (max-width: 767px) {.tg {width: auto !important;}.tg col {width: auto !important;}.tg-wrap {overflow-x: auto;-webkit-overflow-scrolling: touch;margin: auto 0px;}}</style>
--></style>

Basically, you have multiple <style>-tags in the source, and here you have two ending tags, with a comment-bit in between - delete the second one. And...okay, I dunno Blogger, but if that is the standard, DAMN it's ugly code.


text:
Q: Why does VS2010 allow for the concept of "include in project"? I'm still learning the basics of how VS2010 sees the world. Apparently, you can optionally "include" a file in a project. I'm a bit confused by this: If a file is version-controlled, AND the file is within the project directory, shouldn't it implicitly be "included" in the project? If not, what's the use case where a version-controlled file in the project directory should NOT be included in the project?
=== Addition ===
Based on the answers I've gotten so far, maybe I should rephrased my question: What does it mean for a file to be "included" in a project?

A: No, you don't want random files that happen to be in the project directory included in source control.

A: A project needs to know about files in order for compilation and distribution to occur.  Just because you have a file that's under source-control, doesn't mean that it will be compiled if the project is unaware of it.
Also, you may want to include files as part of a distribution package. We do this quite often for our web projects that we distribute using web app gallery.
Conversely, you could have documentation or sql scripts that you version control, but do not want them to be part of the project.
EDIT: In answer to your update, what it means for a file to be included in a project is that the file is actually added to the .csproj or .vbproj file and will be used during compilation and/or distribution. VS does differentiate if the file is Content or if it needs to Compile it. This can be seen by clicking on the file in Solution Explorer and looking at the Build Action property.

A: We do sometimes put documentation (pdfs) or drawings/schematics in the project folder and under version control but you don't need them inside the visual studio project (especially when they are not being distributed because they are for internal use only).

A: Excluding the file from your project can be useful if the file is related to the project but not necessarily needed in the solution.
Example
If I need some test XML for an application that i'm writing; that is designed to normally be pulling this from a WCF service, it can be useful to keep that file in the directory for a development environment where I use IO to get the XML for testing, but I don't necessarily want it in my solution which is source controlled.

A: When you exclude a file from a project is no longer compiled or embedded, then when you want to include it again you can do so without having lost your settings.

A: If you e.g. copy a file (containing a helpful class which want to have in your project) into a folder of your project, then you will see ... nothing. You have to check the option "Show all files" of the solution explorer and the copied file can be seen, but it is still "greyed out". No you can choose the menuitem Include in project and that file will be integrated in your project and a pending change (add) for your source control is added too. Visual Studio doesn't include all files it can find in the project folder automatically to the project - and that is a good feature.

A: One of my colleagues explained to me a scenario in which a version-controlled file should NOT be part of the project. Here's the idea:

*

*A developer writes some new code.

*The code is experimental, and not intended to be part of the normal build.

*The easiest way to exclude the file from the build is to NOT include it in the project, but still version-control it.

*This way, the file can be shared with other developers, but not break the build.


text:
Q: When multitasking a fullscreen app, cant get mouse to lock back in the application: Ex. SPAZ game When I am running a fullscreen application, for example the game SPAZ from the HumbleBundle 6, if some popup comes or if I press the super key to come back to desktop and minimize the game, I am unable to play the game again. The game just wont lock my mouse again, I am sometimes able to get it to become fullscreen again (no idea exactly how!), but the mouse just wont get locked..
Any idea how to continue the game without exit and restart?

A: Try disabling mouse capture on the option menu that comes up when you start the game. Then you can wiggle the mouse when you get kicked out and it will re-focus on the game. Worked twice for me when I was playing last night. This also fixes the double mouse icon I was getting.
Still not sure why it looses focus on the full screen, that seems like a bug but I am not sure if it is with SPAZ or Ubuntu.


text:
Q: How to use postman to upload DBRef data in json? I'm trying to post data to mongodb using postman but I don't know the proper convention for uploading the reference to a image file in the fs.files bucket. Basically, the file is already in the database, I'm just trying to post a new user with the reference to the image.
Here is my model:
class Users(db.Document):
    _id = db.StringField()
    name = db.StringField()
    picture = db.FileField()
    email = db.StringField()
    password = db.StringField()
    meta = {'collection': 'Users'}

In postman, I try to post data like so:
{
"_id" : "1",
"name" : "John Doe",
"picture": [{"$id": "5e6a...f9q102"}], #This is the reference id for the image already in the database, in fs.files
"password" : "<hashed pw>",
"email" : "example@example.com"
}

I'm using flask restful api so in the python script, the post function is defined like so:
def post(self):
    body = request.get_json()
    print (body)
    user = Users()
    user = Users(**body).save()
    return 'Successful Upload', 200

I get the error when I try with the above convention:
mongoengine.errors.ValidationError: ValidationError (Users:None) ('list' object has no attribute
    'grid_id': ['picture'])

How do I post a new user in postman? Your help is appreciated

A: You need to change a bit your code
Add these imports:
from mongoengine.fields import ImageGridFsProxy
from mongoengine import ReferenceField, DynamicDocument
from bson.dbref import DBRef
from bson import ObjectId

Modify your class picture field definition + add extra class fs
class Fs(DynamicDocument):
    #Add 'db_alias':'default' to meta
    meta = {'collection': 'fs.files'}

class Users(Document):
    ...
    picture = ReferenceField('Fs', dbref=True)
    ...

Now, you need to create new instance for DBRef this way:
def post(self):
    body = request.get_json()
    body["picture"] = DBRef('fs.files', ObjectId(body["picture"]))

    #mongoengine assumes `ObjectId('xxx')` already exists in `fs.files`.
    #If you want to check, run below code:
    #if Fs.objects(_id=body["picture"].id).first() is None:
    #    return 'Picture ' + str(body["picture"].id) + ' not found', 400

    user = Users(**body).save()
    return 'Successful Upload', 200

At the end, if you need to read picture content:
image = ImageGridFsProxy(grid_id=ObjectId('xxx'))
f = open("image.png", "wb")
f.write(image.read())
f.close()

A: It was a Validation error. The database was accepting JSON in a particular format than what I was posting. And the way I was processing the post request was also incorrect. This is the format it expected:
{
    ...,
    "picture" = {"$ref": "fs.files",
                 "$id": ObjectId("5e6a...f9q102")},
    ...
}

Postman cannot accept the above format, instead, it accepted this:
{
    "_id" : "1",
    "name" : "John Doe",
    "picture": {"$ref": "fs.files", "$id": {"$oid": "5e6a...f9q102"}},
    "password" : "<hashed pw>",
    "email" : "example@example.com"
}

To make this work I changed the model to look this so in my flask app:
class Users(db.Document):
    _id = db.StringField()
    name = db.StringField()
    picture = db.ReferenceField('fs.files') #I changed this to a reference field because it holds the reference for the file and not the actual file in the database
    upload_picture = db.FileField() #I added this field so I can still upload pics via flask and via this document
    email = db.StringField()
    password = db.StringField()
    meta = {'collection': 'Users'}

Then I had to add this import and change the code so that it would read the input as JSON and transfer the reference value of picture to ObjectId(id) so that it matches the format the database was expecting.
from bson.json_util import loads

def post(self):
        body = str(request.get_json())
        x = body.replace("'", '"') #replace single quotes as double quotes to match JSON format
        data = loads(x)
        officer = Officers(**data).save()
        return 'Successful Upload', 200

Then voila, it works!