text:
Q: How to list sum of values in the specific period Sorry for very newbie questions. I have a table, shown below with values about duration of events. Sometimes I have several events in one hour/day. Instead of showing each particular event, I would like ot have sum of duration of all events on hourly/daily basis. How to achieve that?
SELECT *
FROM [dbo].[switches]
WHERE previousevent='on'
AND friendlyname='BathroomLight'
ORDER BY timestamp DESC;

A: It's a good idea to provide example DDL and DML when asking these sorts of questions. This let's folks reproduce your data set quickly and easily.
Here's a method that does that, and generates some random data to put in to it. Feel free to use it in your next question, or to add some data to this one.
DECLARE @switches TABLE (DeviceID NVARCHAR(10), FriendlyName NVARCHAR(50), Core NVARCHAR(10), Location NVARCHAR(20), Room NVARCHAR(20), Event NVARCHAR(3),
                         PreviousEvent NVARCHAR(3), PreviousEventTime DATETIME, Timestamp DATETIME, ID INT IDENTITY, Duration INT)

INSERT INTO @switches (DeviceID, FriendlyName, Core, Location, Room, Event, PreviousEvent, PreviousEventTime, Timestamp,  Duration)
SELECT TOP 200 '10008c937d', 'BathroomLight', 'main', 'Poppeska', 'Bathroom', 'off', 'on',
        DATEADD(SECOND,ROUND((20000 - 2000) * RAND(CAST(CAST(NEWID() AS VARBINARY) AS INT) + 0),0),GETUTCDATE()),
        DATEADD(SECOND,ROUND((20000 - 2000) * RAND(CAST(CAST(NEWID() AS VARBINARY) AS INT) + 0),0),GETUTCDATE()),
        ROUND((2000 - 0) * RAND(CAST(CAST(NEWID() AS VARBINARY) AS INT) + 0),0)
  FROM sys.sysobjects

You may need to adjust this to match your specific data set.
Now on to your question. You could just run a aggregate query over the table:
SELECT s.DeviceID, s.FriendlyName, s.Core, s.Location, s.Event, DATEPART(HOUR,s.Timestamp) AS hour, CAST(s.Timestamp AS DATE) AS Date, COUNT(*) AS EventCount, AVG(s.Duration) AS AverageDuration
  FROM @switches s
 GROUP BY s.DeviceID, s.FriendlyName, s.Core, s.Location, s.Event, DATEPART(HOUR,s.Timestamp), CAST(s.Timestamp AS DATE)
 ORDER BY Date DESC, Hour DESC

DeviceID    FriendlyName    Core    Location    Event   hour    Date        EventCount  AverageDuration
-------------------------------------------------------------------------------------------------------
10008c937d  BathroomLight   main    Poppeska    off     2       2023-01-05  5           948
10008c937d  BathroomLight   main    Poppeska    off     1       2023-01-05  31          1206
10008c937d  BathroomLight   main    Poppeska    off     0       2023-01-05  47          927
10008c937d  BathroomLight   main    Poppeska    off     23      2023-01-04  47          950
10008c937d  BathroomLight   main    Poppeska    off     22      2023-01-04  36          1037
10008c937d  BathroomLight   main    Poppeska    off     21      2023-01-04  34          910

But, if there are no rows for a particular hour you won't get that row back at all. Let's say there were no events between 22:00:00 and 22:59:59 on 2023-01-04, there would be no row at all for that date and hour.
To get around that you can setup a range CTE using the min and max dates from your table:
;WITH Hours AS (
SELECT DATEADD(MILLISECOND,-DATEPART(MILLISECOND,@start),DATEADD(SECOND,-DATEPART(SECOND,@start),DATEADD(MINUTE,-DATEPART(MINUTE,@start),@start))) AS hour
UNION ALL
SELECT DATEADD(HOUR,1,hour)
  FROM Hours
 WHERE HOUR < @end
)

SELECT s.DeviceID, s.FriendlyName, s.Core, s.Location, s.Event, h.hour, COUNT(*) AS EventCount, AVG(s.Duration) AS AverageDuration
  FROM Hours h
    INNER JOIN @switches s
      ON s.Timestamp BETWEEN h.hour AND DATEADD(HOUR,1,h.hour)
 WHERE PreviousEvent = 'On'
   AND FriendlyName = 'BathroomLight'
 GROUP BY s.DeviceID, s.FriendlyName, s.Core, s.Location, s.Event, h.hour
 ORDER BY h.hour DESC
OPTION (MAXRECURSION 0)

DeviceID    FriendlyName    Core    Location    Event   hour                    EventCount  AverageDuration
-----------------------------------------------------------------------------------------------------------
10008c937d  BathroomLight   main    Poppeska    off     2023-01-05 02:00:00.000 5           948
10008c937d  BathroomLight   main    Poppeska    off     2023-01-05 01:00:00.000 31          1206
10008c937d  BathroomLight   main    Poppeska    off     2023-01-05 00:00:00.000 47          927
10008c937d  BathroomLight   main    Poppeska    off     2023-01-04 23:00:00.000 47          950
10008c937d  BathroomLight   main    Poppeska    off     2023-01-04 22:00:00.000 36          1037
10008c937d  BathroomLight   main    Poppeska    off     2023-01-04 21:00:00.000 34          910

This generates a row for each hour in the table, and then aggregates by those. If there are no rows in the table you will still get a row back, with appropriate aggregates.


text:
Q: rvest trouble: POST submission I'm trying download data from a USGS post form using rvest. What am I doing wrong?
make_url = function(base_url, parameter_list)
  parameter_list %>%
  names %>%
  paste(parameter_list, sep = "=", collapse = "&") %>%
  paste(base_url, ., sep = "")

session =
  list(sn = "01170000") %>%
  make_url("http://ida.water.usgs.gov/ida/available_records.cfm?", .) %>%
  html_session

test =
  session %>%
  html_form %>%
  .[[1]] %>%
  set_values(fromdate = "1990-10-01") %>%
  set_values(todate = "2007-09-30") %>%
  set_values(rtype = "3") %>%
  submit_form(session, .)

A: No need for either rvest or a session. The following function will take in station and dates and returns a data frame with the data file comment that the USGS spits out with each download.
It uses the "download compressed file" option to save bandwidth and speed up the download. It makes temporary files to read the data but cleans up after itself. Columns are converted to proper type (you can omit that part of the code if you want to, though). You can omit the comment attaching as well if you don't need it (it seemed to have useful information to me).
readr::read_lines() is used for speed and you can use readLines() instead if you don't want to rely on the readr package.
The conversion to a tibble version of a data.frame is mainly for better printing but it has other potential advantages, so you can omit that as well if you don't want to rely on the tibble package.
There's a hard-coded  99 second timeout but you can parameterize it if desired.
library(httr)
library(readr)
library(tibble)

#' Retrieve IDA Station Data
#'
#' @param site_no site id
#' @param date_from records from date YYYY-mm-dd
#' @param date_to records to date YYYY-mm-dd
#' @return a parsed, type-converted data frame with a comments attribute.
#' @example
#' deerfield <- get_ida("01170000", "1990-10-01", "2007-09-30")
#'
#' head(deerfield)
#'
#' cat(comment(deerfield))

get_ida <- function(site_no, date_from, date_to) {

  date_from_time <- sprintf("%s 00:15:00.0", date_from)
  date_to_time <- sprintf("%s 23:45:00.0", date_to)

  ida_referer <- sprintf("http://ida.water.usgs.gov/ida/available_records.cfm?sn=%s", site_no)

  tf <- tempfile(".zip")

  res <- POST(url = "http://ida.water.usgs.gov/ida/available_records_process.cfm",
              body = list(fromdate = date_from,
                          todate = date_to,
                          mindatetime = date_from_time,
                          maxdatetime = date_to_time,
                          site_no = site_no,
                          rtype = "2",
                          submit1 = "Retrieve+Data"),
              add_headers(Origin="http://ida.water.usgs.gov",
                          Referer=ida_referer),
              write_disk(tf),
              timeout(99),
              encode = "form")

  fils <- unzip(tf, exdir=tempdir())
  tmp <- read_lines(fils)

  unlink(tf)
  unlink(fils)

  comments <- grep("^#", tmp, value=TRUE)
  records <- grep("^#", tmp, value=TRUE, invert=TRUE)
  header <- records[1:2]
  records <- records[-(1:2)]
  cols <- strsplit(header[1], "[[:space:]]+")[[1]]

  comments <- paste0(comments, collapse="\n")
  records <- paste0(records, collapse="\n")

  df <- read_tsv(records, col_names=cols, "cccnnnnc")
  df$date_time <- as.POSIXct(df$date_time, format="%Y%m%d%H%M%S")
  df <- as_tibble(df)

  comment(df) <- comments

  df

}

Proof it works:
deerfield <- get_ida("01170000", "1990-10-01", "2007-09-30")

dplyr::glimpse(deerfield)
## Observations: 550,917
## Variables: 8
## $ site_no     <chr> "01170000", "01170000", "01170000", "01170000", "0117000...
## $ date_time   <time> 1990-10-01 00:15:00, 1990-10-01 00:30:00, 1990-10-01 00...
## $ tz_cd       <chr> "EDT", "EDT", "EDT", "EDT", "EDT", "EDT", "EDT", "EDT", ...
## $ dd          <dbl> 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,...
## $ accuracy_cd <dbl> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,...
## $ value       <dbl> 146, 139, 135, 143, 154, 166, 171, 175, 171, 166, 162, 1...
## $ prec        <dbl> 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,...
## $ remark      <chr> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, ...

head(deerfield)
## # A tibble: 6 x 8
##    site_no           date_time tz_cd    dd accuracy_cd value  prec remark
##      <chr>              <time> <chr> <dbl>       <dbl> <dbl> <dbl>  <chr>
## 1 01170000 1990-10-01 00:15:00   EDT     7           1   146     3   <NA>
## 2 01170000 1990-10-01 00:30:00   EDT     7           1   139     3   <NA>
## 3 01170000 1990-10-01 00:45:00   EDT     7           1   135     3   <NA>
## 4 01170000 1990-10-01 01:00:00   EDT     7           1   143     3   <NA>
## 5 01170000 1990-10-01 01:15:00   EDT     7           1   154     3   <NA>
## 6 01170000 1990-10-01 01:30:00   EDT     7           1   166     3   <NA>

cat(comment(deerfield))
# retrieved: 2016-09-12 05:32:34 CST
#
# Data for the following station is contained in this file
# ---------------------------------------------------------
#  USGS 01170000 DEERFIELD RIVER NEAR WEST DEERFIELD, MA
#
# This data file was retrieved from the USGS
# instantaneous data archive at
# http://ida.water.usgs.gov
#
# ---------------------WARNING---------------------
# The instantaneous data you have obtained from
# this automated U.S. Geological Survey database
# may or may not have been the basis for the published
# daily mean discharges for this station. Although
# automated filtering has been used to compare these
# data to the published daily mean values and to remove
# obviously bad data, there may still be significant
# error in individual values. Users are strongly
# encouraged to review all data carefully prior to use.
# These data are released on the condition that neither
# the USGS nor the United States Government may be held
# liable for any damages resulting from its use.
#
# This file consists of tab-separated columns of the
# following fields.
#
# column       column definition
# -----------  -----------------------------------------
# site_no      USGS site identification number
# date_time     date and time in format (YYYYMMDDhhmmss)
# tz_cd        time zone
# dd           internal USGS sensor designation (''data descriptor'')
# accuracy_cd  accuracy code
#                   0 - A daily mean discharge calculated from the instantaneous
#                       data on this day is 0.01 cubic feet per second
#                       or less and the published daily mean is zero.
#                   1 - A daily mean discharge calculated from the instantaneous
#                       data on this day matches the published daily mean
#                       within 1 percent.
#                   2 - A daily mean discharge calculated from the instantaneous
#                       data on this day matches the published daily mean
#                       from greater than 1 to 5 percent.
#                   3 - A daily mean discharge calculated from the instantaneous
#                       values on this day matches the published daily mean
#                       from greater than 5 to 10 percent.
#                   9 - The instantaneous value is considered correct by the
#                       collecting USGS Water Science Center. A published daily
#                       mean value does not exist and/or no comparison was made.
# value        discharge in cubic feet per second
# precision    digits of precision in the discharge
# remark       optional remark code
#                 Remark  Explanation
#                   <     Actual value is known to be less than reported value.
#                   >     Actual value is known to be greater than reported value.
#                   &     Value is affected by unspecified reasons.
#                   A     Value is affected by ice at the measurement site.
#                   B     Value is affected by backwater at the measurement site.
#                   e     Value has been estimated by USGS personnel.
#                   E     Value was computed from an estimated value.
#                   F     Value was modified due to automated filtering.
#                   K     Value is affected by instrument calibration drift.
#                   R     Rating is undefined for this value.
#
#

A: Ok, here's a way to get rvest to work:
library(magrittr)

make_url = function(base_url, parameter_list = list(), ...) {
  together_list =
    parameter_list %>%
    c(list(...) )

  together_list %>%
    names %>%
    paste(together_list, sep = "=", collapse = "&") %>%
    paste(base_url, ., sep = "?")
}

download_ida = function(site_no,
                        fromdate = "1990-10-01",
                        todate = "2007-09-30",
                        dir = ".",
                        filename = paste(site_no, "txt", sep = ".") ) {

  session =
    "http://ida.water.usgs.gov/ida/available_records.cfm" %>%
    make_url(sn = "01170000") %>%
    html_session

  form =
    session %>%
    html_form %>%
    .[[1]] %>%
    set_values(fromdate = fromdate,
               todate = todate,
               rtype = "2")

  tempfile = tempfile(".zip")

  submit_form(session, form, submit = NULL,
              httr::write_disk(tempfile,
                               overwrite = TRUE),
              httr::add_headers(Referer = session$url) )

  filename = file.path(dir, filename)

  tempfile %>%
    unzip(exdir = dir) %>%
    file.rename(filename)

  filename
}

read_ida = function(filename) {

  col_names =
    filename %>%
    readr::read_tsv(comment = "#", n_max = 1, col_names = FALSE)

  filename %>%
    readr::read_tsv(comment = "#", skip= 2, col_names = FALSE, na = "Ice",
                    col_types = cols(X2 = col_datetime(format = "%Y%m%d%H%M%S"))) %>%
    stats::setNames(col_names)
}

deerfield =
  "01170000" %>%
  download_ida %>%
  read_ida

But there's a caveat: rvest currently has an open pull request, https://github.com/hadley/rvest/pull/161 , which is needed to get this to work. To that end, it is necessary to redefine both submit_request and submit_form integrating the new pull request:
submit_request = function(form, submit = NULL) {
  is_submit <- function(x)
    if ( is.null(x$type) ) FALSE else
      tolower(x$type) %in% c("submit", "image", "button")

  submits <- Filter(is_submit, form$fields)

  if (length(submits) == 0) {
    stop("Could not find possible submission target.", call. = FALSE)
  }
  if (is.null(submit)) {
    submit <- names(submits)[[1]]
    message("Submitting with '", submit, "'")
  }
  if (!(submit %in% names(submits))) {
    stop("Unknown submission name '", submit, "'.\n", "Possible values: ",
         paste0(names(submits), collapse = ", "), call. = FALSE)
  }
  other_submits <- setdiff(names(submits), submit)
  method <- form$method
  if (!(method %in% c("POST", "GET"))) {
    warning("Invalid method (", method, "), defaulting to GET",
            call. = FALSE)
    method <- "GET"
  }
  url <- form$url
  fields <- form$fields
  fields <- Filter(function(x) length(x$value) > 0, fields)
  fields <- fields[setdiff(names(fields), other_submits)]
  values <- pluck(fields, "value")
  names(values) <- names(fields)
  list(method = method, encode = form$enctype, url = url, values = values)
}

submit_form = function(session, form, submit = NULL, ...) {
  request <- submit_request(form, submit)
  url <- xml2::url_absolute(form$url, session$url)
  if (request$method == "GET") {
    rvest:::request_GET(session, url = url, query = request$values, ...)
  } else if (request$method == "POST") {
    rvest:::request_POST(session, url = url, body = request$values,
                         encode = request$encode, ...)
  } else {
    stop("Unknown method: ", request$method, call. = FALSE)
  }
}

Hopefully the pull request will get merged soon.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is this a convolution of two PDFs? This is my first question on the site!
I want to get the sum of two (or more) random variables, so I did this
from scipy.stats import exponweib
import numpy as np
import matplotlib.pyplot as plt

# Parameters
shape, scale, delta = 1.3, 12, 1e-2

dist = exponweib(a=1, loc=0, c=shape, scale=scale)
grid = np.arange(0, 100, delta)
pmfs = dist.pdf(grid)*delta

# Do convolution (?)
def conv(a,b):
    x = np.array([sum(a[:i+1]*b[i::-1]) for i in range(len(a))])
    return x

# Loop to convolve over multiple RVs
c = {1: pmfs}
for i in range(2, 4):
    c[i] = conv(c[i-1], pmfs)

plt.plot(grid, c[1])
plt.plot(grid, c[2])
plt.plot(grid, c[3]);

So, this gets me
this, which looks like what I want, but it is super slow to run.

I want to implement this equation to sum two independent random variables and get their discretized PDF.

Other questions suggested to use scipy.signal.fftconvolve
x = fftconvolve(pmfs, pmfs, 'same')
plt.plot(grid, x);

But it got me this. Why is it different?

A: You have to have zeroes on the left side (and right side) when computing PDF grid, otherwise F-image won't be computed properly
After running the code below
import numpy as np
from scipy import signal
from scipy.stats import exponweib
import matplotlib.pyplot as plt

shape, scale, delta = 1.3, 12.0, 1.0e-1
dist = exponweib(a=1, loc=0, c=shape, scale=scale)

grid = np.arange(-50, 100, delta)
ewei = dist.pdf(grid)*delta

plt.plot(grid, ewei)
plt.show()

# %%
t = signal.fftconvolve(ewei, ewei, 'same')
plt.plot(grid, t)
plt.show()

I got nice picture for convolved distribution


text:
Q: 'stack build' fails on windows with missing regex-pcre dependency $ stack build
Error is below. I have
$ stack --version
Version 2.7.3, Git revision 7927a3aec32e2b2e5e4fb5be76d0d50eddcc197f x86_64 hpack-0.34.4
How would I know if it were installed non-standard? Where do I find and how to install the dev system package on windows?
Thanks
regex-pcre   > Configuring regex-pcre-0.94.4...
tf-random    > Registering tf-random-0.5...
regex-pcre   > Cabal-simple_Z6RU0evB_1.22.5.0_ghc-7.10.3.exe: Missing dependency on a foreign
regex-pcre   > library:
regex-pcre   > * Missing C library: pcre
regex-pcre   > This problem can usually be solved by installing the system package that
regex-pcre   > provides this library (you may need the "-dev" version). If the library is
regex-pcre   > already installed but in a non-standard location then you can use the flags
regex-pcre   > --extra-include-dirs= and --extra-lib-dirs= to specify where it is.


text:
Q: What to insert in onInit function I have a very big cache problem in my app. See this SPA (Single-page app) load always from cache
In summary I have a view with an iconTabBar https://openui5.hana.ondemand.com/explored.html#/sample/sap.m.sample.IconTabBar/code.
For each tab I have an IconTabFilter fragment in two version: display and change.
In onInit function I load all display IconTabFilter fragments and when the user want switch to change mode, he press the button, call removeAllItems; function and load the new set of new tabs (change fragments).
The problem is that the fragments loaded in onInit function have Cache-Control: max-age=0 in the HTTP call, instead the call for fragments called after (outside onInit) not have Cache-Control: max-age=0 .
In this mode all change fragment that I retrieve after the first page loading are loaded
from cache...
I solve the problem loading all fragmens (display and change) in onInit, but I don't know if this is the right way because I might not want to open the change tabs, and in this case I have loaded them uselessly.
I think that I must load a fragment only when I need it!

A: Your last sentence is the answer. If your app has two dedicated states it makes sense to load the change related fragments if the user switches to change state.
There might be other optimizations like lazy loading of the content of IcontTabFilters or setting the visibility of IconTabFilters depending on the change state. But for this an example would required.


text:
Q: Problema com RecyclerView Estou com o seguinte problema, tenho uma tela onde exibo uma lista utilizando um RecyclerView, ate então funciona de boas, ai quando eu utilizo o Scroll da view ele cria "espaços" em branco na lista ...
private RecyclerView recyclerView;
private TreinoAdapter mAdapter;
private List<Treino> treinos;
private Long idCliente;
private String escolhaSelect;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_principal);

    recyclerView = (RecyclerView) findViewById(R.id.recycle);

}

/***
 * Adiciona o menu setting
 * @param menu
 * @return
 */
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item){

    String tipoEscolhido = (String) item.getTitle();

    if( tipoEscolhido.equalsIgnoreCase("Realizar") )
        this.escolhaSelect = "AR";
    else if( tipoEscolhido.equalsIgnoreCase("Realizado") )
        this.escolhaSelect = "S";
    else
        this.escolhaSelect = "N";

    this.idCliente = ((long) 1);

    retornaTreinos();

    return true;
}

/**
 * Método que abastece o RecycleView após a escolha do Item
 * */
public void abasteceRecyclerView(){

    mAdapter = new TreinoAdapter(treinos, this);

    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
    recyclerView.setLayoutManager(mLayoutManager);
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setAdapter(mAdapter);

    recyclerView.addOnItemTouchListener(new RecycleTouchListener(
            getApplicationContext(),
            recyclerView,
            new RecycleTouchListener.ClickListener() {

                @Override
                public void onClick(View view, int position) {

                    Treino treino = treinos.get(position);

                    Intent intent = new Intent(PrincipalActivity.this, DetalheActivity.class);

                    Bundle bundle = new Bundle();

                    String tipoTreino = "";
                    String terreno = "";

                    if(treino.getTipo().equalsIgnoreCase("T")){

                        tipoTreino = "Bike";

                        if(treino.getTerreno().equalsIgnoreCase("T"))
                            bundle.putString("terreno", "Terra");
                        else
                            bundle.putString("terreno", "Alsfalto");

                    }
                    else if(treino.getTipo().equalsIgnoreCase("M"))
                        tipoTreino = "Musculação";
                    else
                        tipoTreino = "Descanso";

                    bundle.putString("data", treino.getDataTreino());
                    bundle.putString("tipoTreino", tipoTreino);
                    bundle.putString("descricao", treino.getDescricao());

                    intent.putExtras(bundle);
                    startActivity(intent);

                    /*Toast.makeText(getApplicationContext(), "Exibindo Detalhe",//treino.getDescricao()
                            Toast.LENGTH_LONG).show();*/

public class TreinoAdapter extends RecyclerView.Adapter {

    private List<Treino> treinos;
    private Context context;

    public TreinoAdapter(List<Treino> treinos, Context context){

        this.treinos = treinos;
        this.context = context;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);

        TreinoViewHolder treinoViewHolder = new TreinoViewHolder(view);
        return treinoViewHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        TreinoViewHolder treinoViewHolder = (TreinoViewHolder) holder;

        treinoViewHolder.dataTreino.setText(treinos.get(position).getDataTreino());
        treinoViewHolder.descricao.setText(treinos.get(position).getDescricao());

    }

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

    public class MyViewHolder extends RecyclerView.ViewHolder{

        TextView dataTreino;
        TextView descricao;

        public MyViewHolder(View itemView) {
            super(itemView);
            dataTreino = (TextView) itemView.findViewById(R.id.diaTreino);
            descricao = (TextView) itemView.findViewById(R.id.descricao);
        }
    }
}

A Activity que recebe o Recycler
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_principal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="PrincipalActivity">

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/recycle"
        android:scrollbars="vertical"/>

</RelativeLayout>


text:
Q: wp_link_pages and the_posts_pagination → whats the difference

*

*REQUIRED: The theme doesn't have post pagination code in it. Use
posts_nav_link() or paginate_links() or the_posts_pagination() or
the_posts_navigation() or next_posts_link() and
previous_posts_link() to add post pagination.

*REQUIRED: Could not find wp_link_pages. See: wp_link_pages

above are theme-check plugin warning.
On the basis of Implementation, what is the difference between the two.
Please validate my understanding →
1 is for front/homepage in WordPress
2 is for single posts
Right?

A: Yes,
1/ It is for all the pages wich contain multiple post preview (like a /blog/ page),
2/ wp_link_pages is for display page-links for paginated within posts


text:
Q: Cassandra incorrect TTL value for select ttl() I have a 3 node cluster with replication factor : 2.
The column family in consideration has default_time_to_live = 3600
Which is set using alter table :
cqlsh:summary> alter table match with default_time_to_live=3600;
After inserting data into columnfamily and immediately, querying, select ttl(column_name), i get incorrect results.
cqlsh:summary> select ttl(end_time) from match limit 5;

 ttl(end_time)
      3132
      5342
      5342
      1802
      1802

(5 rows)
Keyspace definition:
CREATE KEYSPACE summary WITH replication = {'class': 'NetworkTopologyStrategy', 'DC1': '2'}  AND durable_writes = true;

Column family definition:
CREATE TABLE summary.match (
match_name text,
start_time bigint,
end_time bigint,
PRIMARY KEY (match_name, start_time)) WITH CLUSTERING ORDER BY (start_time ASC)
AND bloom_filter_fp_chance = 0.01
AND caching = '{"keys":"ALL", "rows_per_partition":"NONE"}'
AND comment = ''
AND compaction = {'min_threshold': '4', 'class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy', 'max_threshold': '32'}
AND compression = {'sstable_compression':'org.apache.cassandra.io.compress.LZ4Compressor'}
AND dclocal_read_repair_chance = 0.1
AND default_time_to_live = 3600
AND gc_grace_seconds = 864000
AND max_index_interval = 2048
AND memtable_flush_period_in_ms = 0
AND min_index_interval = 128
AND read_repair_chance = 0.0
AND speculative_retry = '99.0PERCENTILE';

Using :
Cassandra 2.1.0 | CQL spec 3.2.0
Should it not be something less than 3600?
Where is the TTL value of 5342 coming in account?
Question: How does the default_time_to_live value come into effect?

A: This is a non-issue.
The timestamps of node in the cluster was out of sync.
Running ntpdate -bu <ntp server> to sync clocks in each node.
Then TTL is coming as expected.
Some reading onto why syncing time is important for cassandra.
https://blog.logentries.com/2014/03/synchronizing-clocks-in-a-cassandra-cluster-pt-1-the-problem/
https://ria101.wordpress.com/2011/02/08/cassandra-the-importance-of-system-clocks-avoiding-oom-and-how-to-escape-oom-meltdown/


text:
Q: Why does this for loop over an ArrayList generate a warning that "the for statement does not loop" in IntelliJ I have an ArrayList that contains instances of the Staff class. When I write the following code I am told by IntelliJ that the 'for statement does not loop':
public String getTypist() {
    String tempTy = "";
    for (Staff g : staffList) {
        if (g.getStaffID().contains("TY") && g.isAvailable()){
            tempTy = g.getStaffID();
        }
        staffList.remove(g);
        staffWorking.add(g);
        break;
    }

    return tempTy;
}

I'm really confused as I thought that this was the way to properly use a for loop on an ArrayList. What am I doing incorrectly with my for loop?

A: Your for loop contains a break statement which always executes no matter what happens before in the loop, so after the very first looping occurs, the break happens, and nothing else is looped afterwards. This basically makes it as though there was no for loop at all, as executing code one time is the default way a series of statements are executed. Correcting this involves making sure the break executes only some of the loops (specifically, making sure it only executes on the loop you want to be the last loop). Making that correction with the addition of some other fixes you would get code similar to this:
public String getTypist() {
    for (Staff s : staffList) {
        if (s.getStaffID().contains("TY") && s.isAvailable()){
            staffList.remove(s);
            staffWorking.add(s);
            return s.getStaffID();
        }
    }

    return "";
}

However, there is an alternative solution that would allow you to avoid iterating over the ArrayList at all. You can replace that code with this code and it will work without any for loop because it uses the methods of the ArrayList itself to accomplish the task:
public String getTypist() {
    ArrayList<Staff> staffWorking = new ArrayList<>(staffList);
    staffWorking.removeIf(staff -> !(staff.isAvailable() && staff.getStaffID().contains("TY")));

    staffList.removeAll(staffWorking);

    Optional<Staff> typist = staffWorking.stream().findFirst();
    if(typist.isPresent()){
        return typist.getStaffID();
    }else{
        return "";
    }
}

Though even that could be simplified and improved to this (this code supports concurrent filtering so on multi-processor systems it will be much faster):
private static final Predicate<Staff> isATypistWorker =
    staff -> staff.isAvailable() && staff.getStaffID().contains("TY");

public String getTypist() {
    ArrayList<Staff> typistWorkers = staffList.stream()
         .parallel()
         .filter(isATypistWorker)
         .distinct()
         .collect(Collectors.toCollection(ArrayList::new));

    staffList.removeAll(typistWorkers);
    staffWorkers.addAll(typistWorkers);

    Optional<Staff> typist = typistWorkers.stream().findFirst();

    return typist.isPresent() ? typist.getStaffID() : "";
}

A: You aren't looping because you always break after the first iteration of the loop. I think you need braces around your if statement.
public String getTypist() {
    String tempTy = "";

    for (Staff g : staffList) {
        if (g.getStaffID().contains("TY") && g.isAvailable()) {
            tempTy = g.getStaffID();
            staffList.remove(g);
            staffWorking.add(g);
            break;
        }
    }

    return tempTy;
}

Also the code I posted won't work because you can't remove from an ArrayList while looping through it. But that is a different issue.


text:
Q: Why class attribute not work in WebAPI? I used default ASP.NET MVC4 Web Application Template and Visual Studio Create InitializeSimpleMembershipAttribute in Filters Directory and create account Controller like this:
[Authorize]
[InitializeSimpleMembership]
public class AccountController : Controller
{
/* Some Default Actions like Login, LogOff, Register, ...*/
}

and i try to make AccountController WebAPI, my code is:
[Authorize]
[InitializeSimpleMembership]
public class APIAccountController : ApiController
{
    [System.Web.Http.AcceptVerbs("GET", "POST")]
    [System.Web.Http.HttpGet]
    [System.Web.Http.HttpPost]
    [System.Web.Http.AllowAnonymous]
    [System.Web.Mvc.ValidateAntiForgeryToken]
    public string Login(string UserName, string Password, bool RememberMe)
    {
        if (WebSecurity.Login(UserName, Password, persistCookie: RememberMe))
        {
            return "OK";
        }

        return "Failed";
    }
}

now, when i call api, its break in this line:
if (WebSecurity.Login(UserName, Password, persistCookie: RememberMe))
and said: You must call the "WebSecurity.InitializeDatabaseConnection" method before you call any other method of the "WebSecurity" class.
i ran it in InitializeSimpleMembershipAttribute and webapi controller is same with controller.
why attribute not run in WebAPI?

A: The [InitializeSimpleMembership]-attribute inherits from System.Web.Mvc.ActionFilterAttribute
Action filters for Web API need to inherit from System.Web.Http.Filters.ActionFilterAttribute, so the filter is not actually getting executed on your Web API controller.
There's two things you can do:

*

*Either implement your own filter, inheriting from System.Web.Http.Filters.ActionFilterAttribute

*Add the following code to your global.asax
private static SimpleMembershipInitializer _initializer;
private static object _initializerLock = new object();
private static bool _isInitialized;

protected void Application_Start()
{
    // Ensure ASP.NET Simple Membership is initialized only once per app start
LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
}

For this to work you need to move the logic from InitializeMembership into a separate class and make sure you can access it from the global.asax.


text:
Q: BottomAppBar and handle OnClickNavigation I'm attempting to implement a BottomAppBar within my Android App.
The MainActivity XML looks like:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <fragment
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:layout_weight="1"
        app:defaultNavHost="true"
        app:navGraph="@navigation/mobile_navigation" />
<androidx.coordinatorlayout.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:id="@+id/coordinator"
    android:layout_height="match_parent">
    <com.google.android.material.bottomappbar.BottomAppBar
        android:id="@+id/bottomAppBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:background="@drawable/rpurple"
        android:backgroundTint="@color/reallyDarkPurple"
        style="@style/Widget.MaterialComponents.BottomAppBar.PrimarySurface"
        app:menu="@menu/bottom_nav_menu"
        app:tint = "@color/white"
        >
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <ImageButton
                android:id="@+id/navigation_profile"
                android:layout_width="60dp"
                android:layout_height="60dp"
                android:src="@drawable/user"
                android:padding="5dp"
                app:tint  = "@color/lightPurple"
                android:scaleType="centerCrop"
                android:background="@android:color/transparent"
                android:adjustViewBounds="true"/>
            <ImageButton
                android:id="@+id/historyBtn"
                android:layout_width="60dp"
                android:padding="5dp"
                android:layout_marginEnd="10dp"
                android:layout_height="60dp"
                android:src="@drawable/clock"
                android:layout_alignParentEnd="true"
                app:tint  = "@color/lightPurple"
                android:scaleType="centerCrop"
                android:background="@android:color/transparent"
                android:adjustViewBounds="true"/>
        </RelativeLayout>

    </com.google.android.material.bottomappbar.BottomAppBar>
    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:layout_width="56dp"
        android:layout_height="56dp"
        android:backgroundTint="@color/lightPurple"
        app:srcCompat="@drawable/addwhite"
        app:tint = "@color/white"
        app:borderWidth="0dp"
        android:adjustViewBounds="true"
        app:fabCustomSize="56dp"
        app:layout_anchor="@id/bottomAppBar"
        />

</androidx.coordinatorlayout.widget.CoordinatorLayout>
</RelativeLayout>

And i've implemented the code like so within my MainActivity:
BottomAppBar bottomAppBar = findViewById(R.id.bottomAppBar);
bottomAppBar.replaceMenu(R.menu.bottom_nav_menu);
setSupportActionBar(bottomAppBar);

Ideally what I'd like to do is navigate between 4 seperate fragments, A,B,C,D using the BottomAppBar's ImageButtons R.id.navigation_profile & R.id.historyBtn  A key part of the requirement is that the buttons are on opposite sides of the screen.
How could I handle the OnClick for each imageButton and then the subsequent fragment transition?

A: What I understand that you want to add a navigation that have 4 fragment to the bottomAppBar. You can do it by remove the relative layout that in the BottomAppBar
and include it as an item in a menu like this
first add that to the dependencies
  implementation 'androidx.coordinatorlayout:coordinatorlayout:1.1.0'
  implementation 'com.google.android.material:material:1.2.1'

your main Activity
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
>
<FrameLayout
    android:id="@+id/hostFragment"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:backgroundTint="#009FFF"

    app:layout_anchor="@id/bottomAppBar"
    app:maxImageSize="35dp"/>

<com.google.android.material.bottomappbar.BottomAppBar
    android:id="@+id/bottomAppBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    app:fabAlignmentMode="center"
    android:backgroundTint="#3498DB"
    app:fabCradleVerticalOffset="10dp"
    app:fabCradleMargin="8dp"
    app:hideOnScroll="true"
    app:fabCradleRoundedCornerRadius="20dp"
    app:menu="@menu/menu"
    style="@style/Widget.MaterialComponents.BottomAppBar"
    android:theme="@style/AppThemeMaterial"
    >

</com.google.android.material.bottomappbar.BottomAppBar>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

and the menu file should look something like this
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<item
    android:id="@+id/menu_home"
    android:title="Home"
    app:showAsAction="always" />
<item
    android:id="@+id/menu_message"
    android:title="Message"
    app:showAsAction="always" />

 </menu>

add this to the style file
  <style name="AppThemeMaterial"
     parent="Theme.MaterialComponents.Light.DarkActionBar">
     <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

you can handle the item on the bottom like that
 BottomAppBar bottomAppBar=findViewById(R.id.bottomAppBar) ;
 bottomAppBar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            Fragment itemSelected = null ;
            switch (item.getItemId()){
                case R.id.menu_home:
                    itemSelected=new Home();
                    break;
                case R.id.menu_message:
                    itemSelected=new Message();
                    break;

            }   getSupportFragmentManager().beginTransaction().replace(R.id.hostFragment,itemSelected).commit();
            return true;
        }

and you can use this to decide what fragment show when you open the activity
put in onCreate
getSupportFragmentManager().beginTransaction().replace(R.id.hostFragment,
            new Home()).commit();

A: In Kotlin we can do this, also
     private lateinit var bottomNavigationView: BottomNavigationView

     bottomNavigationView = binding.bottomNavView!!

     bottomNavigationView.setOnItemReselectedListener {
        when (it.itemId) {
            R.id.navigation_play-> startGame()
        }
    }

this will give you the result, but with two clicks...
A little bit different is (with one click)
        bottomNavigationView.setOnItemSelectedListener { item ->
           when (item.itemId) {
            R.id.navigation_play-> startGame()
        }
        true
    }


text:
Q: Kernel option in /sys change If /proc/sys and /sys are the same, can I change the kernel options in /sys not in /proc/sys?

If not, why?

A: They are not the same: /proc/sys gives access to sysctl files, which provide various configuration options for kernel features; sys is sysfs, which gives access to kernel data structures.
Some of these might overlap, so a setting in /proc/sys could show up in the corresponding data structure in /sys. In such cases you can't change one without changing the other.


text:
Q: Can a High Enough Temperature Create a Black Hole? My very basic understanding of GR leads me to think that if a substance has a high enough temperature, it can transform into a black hole without a mass required to create a black hole.
The equation that I figure can express this is:
$$\frac{2G(m+(stm)/c^2)}{c^2}=\text{Schwarzschild radius}$$
Where $G$ is the gravitational constant, $m$ is mass, $s$ is specific heat, $t$ is temperature, and $c$ is the speed of light. "$stm$" is equal to heat in joules and when it is divided by $c^2$ it is equal to mass. The masses are then added together, and the equation becomes identical to the Schwarzschild radius equation.
I'm sure there are much more advanced principles than what I am familiar with at such high heats, but is the premise of my logic sound? I doubt that energy from heat can translate so easily into mass, but I don't see the error in writing it so. Also, would this mean that there is a "maximum temperature" since anything that surpasses it would create a singularity?

A: You are asking about micro black holes.

Some hypotheses involving additional space dimensions predict that micro black holes could be formed at energies as low as the TeV range, which are available in particle accelerators such as the LHC (Large Hadron Collider). Popular concerns have then been raised over end-of-the-world scenarios (see Safety of particle collisions at the Large Hadron Collider). However, such quantum black holes would instantly evaporate, either totally or leaving only a very weakly interacting residue. Beside the theoretical arguments, the cosmic rays bombarding the Earth do not produce any damage, although they reach center of mass energies in the range of hundreds of TeV.

So it is a hypothesis at the frontier of research, theoretical and experimental.

I give a summary of BSM searches performed by the ATLAS and CMS experiments with an focus on heavy gauge bosons, extra dimensions and quantum black holes. The presented results use data collected during 2012 when the LHC operated at an center of mass energy of √s=8 TeV.


text:
Q: Не работает overflow:scroll в Android 2.2 и 2.3 Есть блок c фиксированной высотой, с контентом внутри. Внизу кнопка, которая подгружает еще контент. При этом должен появиться скроллбар и контент должен прокручиваться (overflow:scroll). На мобильных устройствах скроллбар не появляется, но это понятно почему(это было бы некрасиво с точки зрения UI). Прокрутка все равно работает везде, за исключением Андроида 2 и скорее всего 3.
Судя по всему это баг самой системы. Вопрос в том, как заставить контент прокручиваться. Прокрутка работает в iOS прекрасно, и на Android 4 все ок.
Пробовал использовать iscroll.js
Но что-то не работает. Есть ли у кого опыт в этом вопросе?
A: CSS свойства overflow:scroll, overflow:auto не поддерживаются стоковым браузером Webkit. Описание бага висит на сайте Google - фтыкать сюда. Согласно отчетам наблюдается с 1.5 до 2.3
P.S. На iPhone говорят то же самое, что неудивительно поскольку обе оси юзают один и тот же браузер Webkit


text:
Q: List comprehension for np matrixes I have two np.matrixes, one of which I'm trying to normalize. I know, in general, list comprehensions are faster than for loops, so I'm trying to convert my double for loop into a list expression.
# normalize the rows and columns of A by B
 for i in range(1,q+1):
     for j in range(1,q+1):
         A[i-1,j-1] = A[i-1,j-1] / (B[i-1] / B[j-1])

This is what I have gotten so far:
A = np.asarray([A/(B[i-1]/B[j-1]) for i, j in zip(range(1,q+1), range(1,q+1))])

but I think I'm taking the wrong approach because I'm not seeing any significant time difference.
Any help would be appreciated.

A: First, if you really do mean np.matrix, stop using np.matrix. It has all sorts of nasty incompatibilities, and its role is obsolete now that @ for matrix multiplication exists. Even if you're stuck on a Python version without @, using the dot method with normal ndarrays is still better than dealing with np.matrix.
You shouldn't use any sort of Python-level iteration construct with NumPy arrays, whether for loops or list comprehensions, unless you're sure you have no better options. Assuming A is 2D and B is 1D with shapes (q, q) and (q,) respectively, what you should instead do for this case is
A *= B
A /= B[:, np.newaxis]

broadcasting the operation over A. This will allow NumPy to perform the iteration at C level directly over the arrays' underlying data buffers, without having to create wrapper objects and perform dynamic dispatch on every operation.


text:
Q: Godel's proof of Completeness Where could I find a detailed exposition in English of Godel's proof (not Henkin's) of Completeness Theorem for first order logic? The wikipedia article omits certain details that I am not clear about, and Godel's original dissertation is not in English.

A: In addition to an English translation of the original version contained in the Collected Works referred to by Andrés, there is an English translation of a rewritten version of the paper contained in From Frege to Gödel edited by Jean van Heijenoort. The latter is also contained in the Collected Works.


text:
Q: How do I solve this rational function in terms of $x$? How would I solve for $x$ where $y=(1-x)/(1+x)$?.  I have tried multiplying both sides by $(1+x)$, but I couldn't get far with that, as I had a pesky $xy$ on one side, which I couldn't figure out how to take out. How would I solve this?

A: This is a useful trick to learn; it comes up frequently.
$$y=\frac{1-x}{1+x} \implies y(1+x)=1-x  \implies y+xy=1-x$$
Now remember we want to solve for $x$, so collect all terms involving $x$:
$$xy+x=1-y \implies x(1+y)=1-y \implies x=\frac{1-y}{1+y}$$
The reason these expressions for $x$ in terms of $y$ and $y$ in terms of $x$ are the same is that the function $f(x)=\frac{1-x}{1+x}$ is its own inverse - if you put in one number and get out a second, putting that back in will return you to your first number. You may be interested to know that your expression is a special case of the Möbius transformation, and these in general have very interesting properties.

A: Your approach is just fine. Multiplying by $1+x$ on both sides gets us $$(1+x)y=1-x,$$ and distributing on the left gets us $$y+xy=1-x.$$ Now, gather the terms with $x$ factors on the left side and terms without $x$ factors on the other, getting us $$x+xy=1-y,$$ whence factoring out the $x$ on the left gets us $$(1+y)x=1-y.$$ Finally, divide by $1+y$ to get $$x=\frac{1-y}{1+y}.$$

A: A mechanical way of doing it is to first multiply both sides by $1+x$. We get
$$y(1+x)=1-x.$$
Rewrite this as
$$y+xy=1-x.$$
Now bring all the $x$ stuff to one side, and the rest to the other side. We get
$$x+xy=1-y.$$
Thus
$$x(1+y)=1-y,$$
and therefore
$$x=\frac{1-y}{1+y}.$$

A: Since $$y=\frac{1-x}{1+x}=\frac{2-(1+x)}{1+x}=\frac{2}{1+x}-1$$ we have $$x=\frac{2}{1+y}-1.$$


text:
Q: vbs runs by double clicking, freezes when run from task scheduler I have a .vbs script that copies files from multiple remote computers. Each server has a shared folder that I map as a network drive (W:). When I run it by double-clicking, it runs fine, but if I run it from Task Scheduler (Win Server 2003) it hangs on this line:
NetworkObject.MapNetworkDrive "W:", "\xxx.xxx.xxx.xxx\sharename", false, [username], [password]
I've tried everything but I can't figure out why it won't run in task scheduler. Please help!

A: Did you try to run it like:
C:\Windows\system32\cscript.exe yourscript.vbs


text:
Q: How to update USING sum and subquery I have a SQL Server table similar to this:

InkitemNo
CapacityUnit
NewInk
OldInk
ReturnInk
ProdQty
Description
UsedInk

204
Machine1
5
2
0
4000
Next
?

223
machine2
4
3
1
8000
NULL
?

204
Machine2
0
0
0
5000
Next
?

224
Machine2
4
0
2
3000
Next
?

I'm trying to write a query with this formula:
Example to get 1 row used ink
(5 + 2 -2 )* 4000/ 12000 = 1,67

to get 2 row used ink
(4 + 3 - 1) = 6

to get 3 row usedink
(5 + 2 - 2) * 5000 / 12000 = 2,08

to get 4 row usedink
(5 + 2 - 2) * 3000 / 12000 = 1,25

(NewInk + OldInk - ReturnInk) * ProdQty / Sum(ProdQty)

This formula used when the criteria is

*

*CapacityUnit & InkItemNo is same

*Description is not NULL

To get the result of used ink, I used this query
update InkEstimationSave =

(NewInk + OldInk - ReturnInk) * ProdQty / Sum(ProdQty]
but it does not work.

A: Based on your logic query you are looking for is
fiddle link
    ;with cte as
(
select *, SUM(ProdQty) OVER (partition by InkItemNo, Capacityunit) as denom
from yourtable
)

update  cte
set UsedInk =
           (newInk+OldInk - ReturnInk) * ProdQty
          /denom
         *1.00
where Description is NOT NULL

select * from Yourtable


text:
Q: FastAPI Models in multiple files relationship I'm new to fastapi and I'm setting up some models to use with sqlalchemy in separate files but for some reason the one to many relationship between the two tables isn't working and the client_id column in the tasks table isn't being created at all. Below is the code for the models and also the main.py file, any help would be appreciated so I'm struggling to figure out why it's not working as most examples online have their models just in one file.
task model:
from sqlalchemy import Column, Integer, String, ForeignKey, DateTime
from sqlalchemy.orm import relationship

from database import Base

class TaskModel(Base):
    __tablename__ = "tasks"

    id = Column(Integer, primary_key=True, index=True)
    script_log = Column(String, index=True)
    start_timestamp = Column(DateTime, index=True)
    finish_timestamp = Column(DateTime, index=True)

    client_id = Column(Integer, ForeignKey("clients.id"))
    client = relationship(
        "ClientModel", foreign_keys=[client_id],
         back_populates="tasks"
    )

client model:
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import relationship

from database import Base

class ClientModel(Base):
    __tablename__ = "clients"

    id = Column(Integer, primary_key=True, index=True)
    client_name = Column(String, index=True)

    tasks = relationship(
        "TaskModel", foreign_keys="[TaskModel.client_id]", back_populates="client"
    )

main.py
from pydoc import cli
from fastapi import FastAPI

from routers import clients, processes, statuses

from database import SessionLocal, engine

from models import task, client

client.Base.metadata.create_all(bind=engine)
task.Base.metadata.create_all(bind=engine)

app = FastAPI()

app.include_router(clients.router)
app.include_router(processes.router)
app.include_router(statuses.router)

I dont get any errors when starting uvicorn and all of the other columns are showing in postgres fine except the client_id column

A: After changing the models you'll have to remove the existing tables, otherwise the create_all statement won't do anything (i.e. if the table exists, it'll just leave it - it won't update it).
To get migration support (which is what will change an existing structure into the new format), use Alembic - a project to generate migration scripts from different SQLAlchemy model versions. Add these files to your version control as any other files, and you'll be able to handle multiple versions of the same database in multiple locations as well. Run the migrations to make sure the database is up to date with your code.


text:
Q: Remove from array PHP I use preg_match_all($pattern, $string, $matches) regularly on data, and basically, I always need to remove either £0.00 or $0.00 or €0.00 from the array should it be in there.
I never know the position within the array that it will be in, if at all.
I've tried unset($matches['£0.00']) and unset($matches[0]['£0.00']) but didn't work
Also, can it be done without using the actual currency symbol and maybe regex \p{Sc}
So, summary, I have an array of numbers with currency symbols, and need to remove any zero entries.
sample array:
Array ( [0] => Array ( [0] => £18.99 [1] => £0.00 [2] => £0.00 [3] => £0.00 ) )

Is this possible?

A: The usage of preg_match() and preg_match_all() sometimes can be weird
$matches will be array of the matches to the pattern - in this instance if you
preg_match("/\p{Sc}0\.00/","£0.00",$matches);
//$matches[0] => £0.00

or if you add parenthesis () to the pattern you can extract a part
preg_match("/\p{Sc}(0\.00)/","£0.00",$matches);
//$matches[0] => £0.00
//$matches[1] => 0.00

so to solve this problem try this
foreach($sample_array as $key => $value)
{
     if(preg_match("/(\$|\p{Sc})0\.00/",$value))
     {
          unset($sample_array[$key]);
     }
}

Notice the pipe | that denotes $ or £ - if you add another pipe for the euro symbol it will capture that as well - also notice that we are unset()-ing a key in the original array instead of unset()-ing the $matches array

A: function remove_element($arr, $val)

        {

            foreach ($arr as $key => $value)

            {

                if ($arr[$key] == $val)

                {

                unset($arr[$key]);

                }

            }

            return $arr = array_values($arr);

        }

You can use this function these function returns the array elements after delete the specified value.


text:
Q: Ebean with unidirectional OneToMany relationship causing duplicate column exception during insert I have a table ENTRY with unique id UID. A second table PROGRAM with ID column as the key and PROGRAM_LIST_UID foreign key that refers to UID in ENTRY. I did not create the names, this is legacy code I am trying to maintain.
@Entity(name="entry")
public class Entry {
    @Id
    public int uid;

    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name="program_list_uid", referencedColumnName="uid")
    public List<Program> programList;

    ...
}

@Entity(name="program")
public class Program {
    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    public int id;

    @Column(length=150,name="program_name")
    public String programName;

    @Column(name="program_list_uid")
    public Integer entryId = 0;
}

When trying to save entry Ebean.save(entry), I get an exception

ERROR executing DML bindLog[] error[[SQL0121] Duplicate name PROGRAM_LIST_UID not allowed...

Trace shows that the insert statement indeed has the program_list_uid specified twice:
insert into program (program_list_uid, program_name, program_list_uid)
values (?,?,?)

The only way I have found to make this work is to remove the entryId from Program. However this property is used elsewhere in the code.

A: The solution turns out to be adding insertable = false, updatable = false to @Column annotation on entryId. How can I retrieve the foreign key from a JPA ManyToOne mapping without hitting the target table?
@Entity(name="program")
public class Program {
    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    public int id;

    @Column(length=150,name="program_name")
    public String programName;

    @Column(name="program_list_uid", insertable = false, updatable = false)
    public Integer entryId = 0;
}


text:
Q: Filter values before aggregating to a number on DataDog "query_value" visualization I have a counting metric in DataDog, that has positive and negative counts.  When using a "timeseries" visualization to show only the positive counts, I simply just apply a clamp_min(query1, 0), and it works.
Essentially, the JSON looks like below for the "timeseries"
{
    "viz": "timeseries",
    "requests": [
        {
            "style": {
                "palette": "dog_classic",
                "type": "solid",
                "width": "normal"
            },
            "type": "line",
            "formulas": [
                {
                    "formula": "clamp_min(query1, 0)"
                }
            ],
            "response_format": "timeseries",
            "queries": [
                {
                    "query": "sum:my_counting_metric.as_count()",
                    "data_source": "metrics",
                    "name": "query1"
                }
            ]
        }
    ]
}

When I try to do this same thing, and aggregate all these positive numbers that I've filtered for on a "query_value" viz, I can't find a single way to do anything similar because it sums all the counts to a number before making it possible to apply filters like clamp_min above.  Ideally, I would like to do something like below if possible.
{
    "viz": "query_value",
    "requests": [
        {
            "response_format": "scalar",
            "formulas": [
                {
                    "formula": "query1"
                }
            ],
            "queries": [
                {
                    "query": "sum:clamp_min(my_counting_metric.as_count(), 0)",
                    "data_source": "metrics",
                    "name": "query1",
                    "aggregator": "avg"
                }
            ]
        }
    ],
    "precision": 2,
    "autoscale": true
}

Is there any way to do this?  I'm feeling pretty stuck and would greatly appreciate any help!

A: I was able to get in contact with DataDog on this question.
They basically told me this behavior mentioned in my post is expected because the "query_value" viz runs a procedure called point reduction.  This is why the clamp_min function had no effect.  To put it short, there's not a way to filter/map before the execution of the initial aggregating function on a "query_value" viz.


text:
Q: Remove elements from array A if those elements are contained in arrays B0 ... Bn - using Linq? I have a character array char[] a_chA that contains elements i don't want.
The elements i don't want are in some more character arrays in a list List<char[]> l_a_chB.
I would like to remove all the unwanted elements using linq, but i can't seem to get the syntax right!
Something like ...
char[] a_chResult = l_a_chB.All(chRemove => a_chA.Union(ch => ch != chRemove))

Any help is much appreciated.

A: var charsInAExceptInAllBs = a_chA.Where(a => !l_a_chB.SelectMany(x => x).Contains(a)).ToArray();

This takes the elements in the B lists, flattens them (that's the SelectMany call) and then filters the elements of A by those characters that apper in the newly flattened B lists (that's the Where call.)
Note that if you don't have any duplicates in A (or don't care about losing duplicates) then you can use this:
var charsInAExceptInAllBs = a_chA.Except(l_a_chB.SelectMany(x => x)).ToArray();

Because Except takes the set difference, it will eliminate duplicates in the final result.

A: var chars = from c in l_a_chB
            from x in c
            select x;
var result = a_chA.Except(chars);

is what you are looking for.

A: var result = a_chA.Except(l_a_chB.SelectMany(a=>a));


text:
Q: Navigation drop downs sitting behind the video created with mediaelement.js - how to fix? The page in question is sitting at:
newnetpartners.inspirationincbeta.co.uk/voice.php

The issue we are having is with the drop down on the navigation falling behind the video (created with mediaelements.js).
So far the z-index on both the site's css and the video's css have been set as they should be but still the problem is occuring.
Has anyone had the same issues as this and found a fix for it, or does anyone have any ideas on what could be causing it.
Thank you all in advance.


text:
Q: Color qubit lines using QCircuit I'd like to color some qubit lines in quantum circuit diagrams drawn using QCircuit as exemplified in the following image:

Can this be done with Qcircuit? As a follow-up, is it possible to do some other modifications like making lines dashed, bold, etc?
The code producing the uncolored image is:
\Qcircuit @C=1em @R=1em {
   \lstick{|\psi\rangle} & \qw & \gate{R_x(\theta)} & \ctrl{1} & \meter \\
   \lstick{|0\rangle} & \qw {/} & \qw & \gate{U} & \qw & \rstick{|\phi\rangle}
}

A: Reading different comments on web I have finded a specific similar question in this link
https://github.com/CQuIC/qcircuit/wiki/FAQ.
At the end of the clarifications there is a specific question with an answer:
How do I color parts of my circuit?
[...] LaTeX views the wires and gate outlines as a single object, so you cannot color them separately. The entire circuit or any text argument can be colored in the normal manner.
Looking also this link that it is related with Qcircuit https://www.researchgate.net/publication/327592129_Tutorial_on_the_Quantikz_Package, you can see that all the wires are colored only with the black color.
This suggests that you can't color the wires with the colors of your choice. It will be interesting, lastly, to understand the source (with the full LaTeX MWE) of your first image where a thread is colored red.

A: I can, perhaps, partly answer this question. If, in your document's preamble, you add the line \xyoption{color}, then you can create customisations of the Qcircuit elements.
A simple example which will take you a step towards a solution is to add
\newcommand{\qwred}[1][-1]{\ar @[red]@{-} [0,#1]}
to your preamble. Then in a circuit you use \qwred instead of \qw and it will come out coloured red. The key part, which you can use to alter many of the Qcircuit elements (looking at the qcircuit.sty for what the commands should look like) is the addition of @[red] in the above \newcommand. I simple took the command from qcircuit.sty and added that, creating a new red line.
The complication, however, comes with the addition of gates. The command, as written in qcircuit.sty is:
\newcommand{\gate}[1]{*+<.6em>{#1} \POS ="i","i"+UR;"i"+UL **\dir{-};"i"+DL **\dir{-};"i"+DR **\dir{-};"i"+UR **\dir{-},"i" \qw}
If you include this in your preamble with the \qw command changed to \qwred (after you've created the \qwred command) like
\newcommand{\gatered}[1]{*+<.6em>{#1} \POS ="i","i"+UR;"i"+UL **\dir{-};"i"+DL **\dir{-};"i"+DR **\dir{-};"i"+UR **\dir{-},"i" \qwred},
then this allows for something like what you've shown in your question.
This isn't elegant, and requires you to fiddle with each element of the circuit you want to create, but it's the only way I know.


text:
Q: xkbmap remap PrtScr and Insert Keys to Home and Escape I've been fumbling with xkbmap for a while, and I can't figure out how to remap the Print Screen button to Home. It's as if the us keymap just doesn't mention the PRSC key code at all. I can't use xmodmap because switching keyboards destroys my configuration.
How can I remap the PrtScr key to Home and the Insert key to End using xkbmap?

A: I managed to do this by editing my keymap in xkb.
In /usr/share/X11/xkb/symbols/, add this to the file corresponding to the layout you're using (I use an US layout, so I edit the us file):
partial alphanumeric_keys modifier_keys
xkb_symbols "remap_prtsc_home_insert_end" {
    replace key <PRSC> { [ Home ] };
    replace key <INS> { [ End ] };
};

// Then include the previous block in the layout variant you're using
// For instance I'm using an international US layout so I edit the "intl" block:

partial alphanumeric_keys
xkb_symbols "intl" {
   include "us(remap_prtsc_home_insert_end)"
   // ...
   // Here the rest of your configuration, left unchanged
}

Then you need to reboot for these changes to be taken into account.
Warning: double check for typos in these files, as if they are invalid you could have trouble logging in after reboot, and you will need to boot in recovery mode and manually edit the file mentionned above to correct them.

Note on where to find the name of the keys:
On the left hand you need to use the key event names (like <PRSC>), which can be found in /usr/share/X11/xkb/keycodes/evdev.
On the right hand you need to use a valid X11 name for characters (like Home). It seems they can be found in /usr/include/X11/keysymdef.h if you ignore the leading XK_ (not a 100% sure about that, but they seem to match for what I've seen so far).


text:
Q: Roboto is invisible in Firefox This problem is annoy me for a long time, but now i want to fix that finally. The problem is some Roboto fonts is not visible on pages.
I tried reinstall system (all except /home is new) several times (changing distros), but problem still exists.
In Chrome this issue is missing, he's rendering all as it must be.
I also tried to remove Roboto font from system completely, I tried to reinstall it. It's fixed just part of the problem.

This is how Amazon S3 control panels looks like to me.

Inspecting says the interface uses Roboto-Bold font from sytem, but i haven't Roboto-Bold font in the system. Why did he try to load it from system, not from web? This is the problem i see.

If i remove Roboto font from system, the most of the sites, which uses 'Roboto' is also come blank. F.e. YouTube will be completely white with pictures. For now on YouTube only tooltips has the problem.

How can i remove Roboto from system correctly or fix missing font. I tried to remove $HOME/.mozilla folder, but no results. As I say, this problem is only in FireFox, all Roboto fonts from system works perfectly in Chrome, LibreOffice, Inkscape and other programs.
My distribution KDE Neon, but this problem present in Ubuntu, Kubuntu and other distros i tried.

A: I had the same problem. While searching for a fix I came across the issue on gitlab https://gitlab.com/gitlab-org/gitlab-ce/issues/31389 and there someone suggested installing the roboto font on the system.

apt install fonts-roboto*

fixed it for me.
Why does gnome and firefox think that font is installed is another bug I guess. Hope this helps.

A: I was able to fix a similar issue by installing
fonts-ubuntu-font-family-console
It seems my system was missing some core fonts that would render if original font wasn't found.


text:
Q: Two iPhone Simulators at the same time? Is it possible to run the iphone app in two iphone simulator at the same time?
If Yes Let me know?Please.

A: Yes there is. Download the script here
and then run it before you open xcode in each users account. It will open the simulator in such a way that for every user you can run a simulator. Also, running multiple instances of xcode and debugging on multiple devices under the same user seems to work fine for me at the moment (XCode 4, ios 4.3.3) however I still havent managed to find a way to open more than one simulator for the same user though.


text:
Q: Issue with package installation - Not in package.xml I am installing my managed package into a testing org and getting this error:

All these labels are included in the package:

Does anybody know why this happens and how to fix it?

A: I got an answer from support regarding this problem. It appeared that another component Custom Object Criteria Based Sharing Rule was the real cause, not custom labels. I just removed it from the package and installed it successfully.
I wish Salesforce had more informative and what is more precise descriptions for error messages.
It's also worth checking out this page Components Available in Managed Packages and Metadata Coverage Report if package installation fails due to the not in package.xml error.


text:
Q: Loading UTF-8 file in Python 3 using numpy.genfromtxt I have a CSV file that I downloaded from WHO site (http://apps.who.int/gho/data/view.main.52160 , Downloads, "multipurpose table in CSV format"). I try to load the file into a numpy array. Here's my code:
import numpy
#U75 - unicode string of max. length 75
world_alcohol = numpy.genfromtxt("xmart.csv", dtype="U75", skip_header=2, delimiter=",")
print(world_alcohol)

And I get

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position
  2: ordinal not in range(128).

I guess that numpy has a problem reading the string "Côte d'Ivoire". The file is properly encoded UTF-8 (according to my text editor). I am using Python 3.4.3 and numpy 1.9.2.
What am I doing wrong? How can I read the file into numpy?

A: Note the original 2015 date.  Since then genfromtxt has gotten an encoding parameter.

In Python3 I can do:
In [224]: txt = "Côte d'Ivoire"
In [225]: x = np.zeros((2,),dtype='U20')
In [226]: x[0] = txt
In [227]: x
Out[227]:
array(["Côte d'Ivoire", ''],   dtype='<U20')

Which means I probably could open a 'UTF-8' file (regular, not byte mode), and readlines, and assign them to elements of an array like x.
But genfromtxt insists on operating with byte strings (ascii) which can't handle the larger UTF-8 set (7 bytes v 8).  So I need to apply decode at some point to get an U array.
I can load it into a 'S' array with genfromtxt:
In [258]: txt="Côte d'Ivoire"
In [259]: a=np.genfromtxt([txt.encode()],delimiter=',',dtype='S20')
In [260]: a
Out[260]:
array(b"C\xc3\xb4te d'Ivoire",  dtype='|S20')

and apply decode to individual elements:
In [261]: print(a.item().decode())
Côte d'Ivoire

In [325]: print _
Côte d'Ivoire

Or use np.char.decode to apply it to each element of an array:
In [263]: np.char.decode(a)
Out[263]:
array("Côte d'Ivoire", dtype='<U13')
In [264]: print(_)
Côte d'Ivoire

genfromtxt lets me specify converters:
In [297]: np.genfromtxt([txt.encode()],delimiter=',',dtype='U20',
    converters={0:lambda x: x.decode()})
Out[297]:
array("Côte d'Ivoire", dtype='<U20')

If the csv has a mix of strings and numbers, this converters approach will be easier to use than the np.char.decode.  Just specify the converter for each string column.
(See my earlier edits for Python2 tries).


text:
Q: Lambda Expression for joining three tables Employee Table
EmpID
Emp_First_Name
Manager_ID
Department_ID
RoleID

Department Table
Department_ID
Department_N

ame
Role Table
RoleID
RoleName

Joining Three Tables
var join = from u in db.TBL_Employees
                       join v in db.TBL_Departments
                       on u.Department_ID equals v.Department_ID
                       join x in db.TBL_Employees
                       on u.Manager_ID equals x.Emp_ID
                       join z in db.TBL_Roles
                       on u.RoleID equals z.RoleID
                       select new
                       {
                           Name = u.Emp_First_Name,
                           Department = v.Department_Name,
                           Manager = x.Emp_First_Name,
                           Role = z.RoleName
                       };

This Query is working fine.
But I want to write the same query in Lambda Expression.
How to display the same output using Lambda Expression?

A: You could do this as a succession of Joins, each continuing the preceding projection with the new join, but as mentioned in the comments, this soon becomes messy and difficult to follow: (especially if you are accustomed to using the Sql join syntax)
var result = db.TBL_Employees
   .Join(db.TBL_Departments, u => u.Department_ID, v => v.Department_ID,
         (u, v) => new {Employee = u, Department = v})
   .Join(db.TBL_Employees, ed => ed.Employee.Manager_ID, x => x.Emp_ID,
         (ed, x) => new {EmployeeDepartment = ed, Manager = x})
   .Join(db.TBL_Roles, edm => edm.EmployeeDepartment.Employee.RoleID, z => z.RoleID,
         (edm, z) => new {EmployeeDepartmentManager = edm, Role = z})
.Select(edmr => new
{
  Name = edmr.EmployeeDepartmentManager.EmployeeDepartment.Employee.Emp_First_Name,
  Department = edmr.EmployeeDepartmentManager.EmployeeDepartment.Department.Department_Name,
  Manager = edmr.EmployeeDepartmentManager.Manager.Emp_First_Name,
  Role = edmr.Role.RoleName
});

(I've retained your original aliases for tracebility, and added new aliases for the intermediate anonymous projections using your pattern, e.g. edmr is EmployeeDepartmentManagerRole)
However, I would instead recommend that you ensure that the foreign key relationships which seem to be present on the tables are enforced, and then pull these through as navigable relationships in your Linq2Sql DBML model. With either lazy loading enabled, or with appropriate eager loading LoadsWith DataContext options set, you will be able to reduce the query and projection into simply:
var result = db.TBL_Employees
   .Select(e => new
{
    Name = e.Emp_First_Name,
    Department = e.Department.Department_Name,
    Manager = e.Manager.Emp_First_Name,
    Role = e.Role.RoleName
});


text:
Q: Prove that if two rational numbers are equal, then they are proportional. If $(m_1, n_1)$ and $(m_2, n_2)$ are two equal rational numbers, i.e. $m_1*n_1^{-1} = m_2 * n_2^{-1}$, so $m_1*n_2 = m_2*n_1$.
And if $m_1$ and $n_1$ are coprime, prove that $n_2 * n_1^{-1} = m_2 * m_1^{-1} = k \in \mathbb Z$.
The main problem is to show that k is an integer.

A: We consider the equation $m_1*n_2=m_2*n_1$
Since $m_1$ and $n_1$ are coprime, and $$m_2*n_1 \text{ mod } m_1 \equiv m_1*n_2 \text{ mod } m_1\equiv 0$$ Then, $$m_2 \equiv 0 \text{ mod } m_1$$
This implies $m_2 = m_1*a$ for some  $a \in Z$. Thus,
$m_2 * m_1^{-1} = m_1*a * m_1^{-1}=a=k\in Z$, completing the proof.


text:
Q: How do I use Azure Resouce Provider to receive payments for my service? This is Windows Azure Resource Provider SDK. I've tried to read about concepts and can't definitely understand whether it allows me to do what I want.
I have a web service that is hosted in Windows Azure. Users get a userid-password pair, pay for the service via PayPal and then they can make web requests to a designated URL providing their userid-password pairs and the service will deduct funds based on number of their requests. When they pay via PayPal they buy "right to make N requests" - their balance inside the service is increased by the "number of requests" they paid for. So it's a pay-per-usage-volume service.
Now I want to expose my service to the Azure Store using the Resource Provider SDK charging people for the number of requests they make to my service.
The concepts document says

The user then creates a Subscription. A Subscription is a named entity e.g. 3-month Free Trial or MyApp Production. You can view your own Subscriptions on the Account Portal.
Next, the user creates one or more Resources such as a Website or Virtual Machine. Website and Virtual Machine are two different ResourceTypes. Each Resource is deployed under exactly one Subscription.

The subscription part is more or less clear. What about Resource objects? I mean the description continues "such as a Web Site or Virtual Machine" but what I want to offer is not a site and not a VM, it's a right to queue a certain number of requests to my service URL.
Either I don't get something simple or the Azure Resource Provider SDK is just not what I can use.
How do I expose my pay-per-usage-volume service to Azure Store using Azure Resource Provider SDK?

A: All the confusion is because how the documentation is worded. It says

The user then creates a Subscription. A Subscription is a named entity e.g. 3-month Free Trial or MyApp Production.

This is partially true. The user indeed creates a subscription but that typically happens long before he makes his first purchase from Azure Store. Subscriptions are Azure thing, they are not specific to Azure Store. What the RP sees is the subscription id (currently in form of GUID string representation) and by the subscription id the RP can distinguish between purchases made by different users.
Then goes this

Next, the user creates one or more Resources such as a Website or Virtual Machine. Website and Virtual Machine are two different ResourceTypes. Each Resource is deployed under exactly one Subscription.

This is just very far from true.
The user chooses an "offering" from Azure Store showcase (basically a list of available services), then he selects a "plan" (which is a "you pay X money and get Y of the service" type of offer, X is zero for free plans) and he chooses a "resource name". The "resource name" is up to the user - he chooses it.
The "resource type" is a unique symbolic identifier for the "offering" which must be unique across the entire Azure Store and is chosen by the RP designer. So examples like "Websites" or "Virtual machines" are both very bad and useless - in fact you'll want to have a "resource type" like CompanyXMalingService so that when someone else wants to offer a "mailing service" he could offer CompanyYMailingService and when you yourself want to offer a "telephony service" you can use CompanyXTelephonyService and not collide with others.
Now if you offer something with "N requests per period" billing model you only can have "one month" as a period, so it can only be "N requests per month", nothing else. Suppose your offering "resource type" is CompanyXCoolRequests.
The model is then as follows: user clicks on your offering, selects a plan (for example, 1000 requests per month) and clicks through until he is billed. Meanwhile the store will send a request to your RP saying that there was a purchase for subscription with a certain id of resource of type CompanyXCoolRequests and with some resource name, the plan identifier will be inside the request. Your RP creates an account inside your service and debits the number of requests there, it has to provide the user id and password (or whatever stuff is needed to use your service) - either as "output items" which are displayed when the user clicks "Connection info" button or via the service page where the user is redirected when he clicks the "Manage" button.
Now there're the following options. Either just nothing happens for years and then it means the user purchase is active and he is billed every month, the month starts att he date he made a purchase and lasts till the same date of the next month. You have to provide him with 1000 requests every month. You have to decide what to do with the leftover balance (like the month is ending and he only used 800 requests) and what to do when he uses everything up before the new month starts. The user can also "delete" your offering from his subscription - he will no longer be billed ad the store will send a request to your RP and you have to delete or block the account you created earlier in you service. Also it's possible that there's a subscription-level event like suspension of the subscription - then you have to temporarily block all the resources of that subscription and be able to restore them all one the subscription is "resumed. And finally the user can "upgrade" his purchase by switching to a more expensive plan - you'll have to debit extra units to his "account" inside your service.

A: The Subscription can be thought of an identifier for the Users commerce relation ship [think an identifier for which Credit Card to charge]
The Resource or The addon on the other had is what identifies the instance of the service that the user is buying.
In your case lets call your Service "SharpToothService" and the user can go to the service and buy the ability to send "n SharpTooths/month" for 9.99.
Sharp tooth would be the resource.
& The user name and password would be the Output Items [Result of Provisioning and Purchasing the resource]
[As you get along you might have question on plans]-
Plan is what identifies the sold packagae for eg. You might have Silver plan for "100 Sharptooths for 9.99/month: a gold one for "500 SHarptooths for 19.99/month" etc


text:
Q: Length Cannot be zero vb.net Hi is there away to detect the length of a byte before I get the error message:
Length cannot be less than zero. Parameter name: length
I get the error on this line:
new_username = new_username.Substring(0, new_username.IndexOf(" Joined "))
I am removing the "joined" from the string I get....how can I ignore it is "joined" isnt the the data?
Thanks

A: I would test to see what IndexOf returned before using it in this context:
if(new_username.IndexOf(" Joined") > 0)
{
      new_username = new_username.Substring(0, new_username.IndexOf(" Joined "))
}

A: Try this:
new_username = new_Username.Replace(" Joined ", "")

Be warned that this will remove all occurrences of the "Joined" substring rather than just the first.

A: It looks like new_username.IndexOf(" Joined ") is returning -1 meaning the string " Joined" was not found by Substring.  I would break this out into two statements:
The error you are seeing is that you are effectively making this call:
new_username = new_username.Substring(0, -1)


text:
Q: In android, Add 3 different fragments on single screen in landscape view I have to add three fragments in single screen in landscape mode. Please help me out how it can be achieved using fragment manager. attached is the dummy screen for the same.

A: Your going to want to define a layout that includes 3 FrameLayouts that are all next to each other. Perhaps something like the following:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <FrameLayout
        android:id="@+id/fragment_1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"/>

    <FrameLayout
        android:id="@+id/fragment_2"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"/>

    <FrameLayout
        android:id="@+id/fragment_3"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"/>

</LinearLayout>

Then, from your parent Fragment's onCreateView method, inflate the layout resource that contains the above. At that point, use the FragmentManager to add each Fragment to the appropriate FrameLayout like so:
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.my_layout_file, parent, false);

    FragmentManager fm = getChildFragmentManager();

    fm.beginTransaction()
            .add(R.id.fragment_1, fragment1, "fragment_1")
            .commit();

    fm.beginTransaction()
            .add(R.id.fragment_2, fragment2, "fragment_2")
            .commit();

    fm.beginTransaction()
            .add(R.id.fragment_3, fragment3, "fragment_3")
            .commit();

    return v;
}

That, in a nutshell, should get your Fragment's displaying as you'd like. If you're using an Activity as the parent of this 3-Fragment layout, you can do pretty much the same thing from onCreate, just call getFragmentManager() rather than getChildFragmentManager().


text:
Q: Chrome extension jquery post wierd charset I'm trying to create an chrome extension for a chat on a webpage. I've created a method to post messages into the chat:
function postMsg(msg) {
    var data = {chat_message:msg.trim(), "chat_submit": "Send"}
    console.log(msg);
    $.post("http://example.com/", data);
}

It does not support æåø characters that uft-8 supports. It appear like this: MÃ¥ gÃ¥ and it should look like Må gå.
I've tried to output the var into the console. And it output it how it should be outputted. The chat also support UFT-8.
How should I solve this task?
EDIT: my problem was exacly like descibed here: How do I transcode a Javascript string to ISO-8859-1?
It also solved my problem.


text:
Q: setImageResource Not working for some icons in android I am trying to use setImageResource in one of my custom adapter.
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    NavDrawerItem current = data.get(position);
    holder.title.setText(current.getTitle() + current.getIcon());
    holder.imgIcon.setImageResource(R.drawable.account_circle);
}

both account_circle and account_home icons are available in drawable folder.
Everything works fine with
holder.imgIcon.setImageResource(R.drawable.account_home);

But when i try to draw account_circle
holder.imgIcon.setImageResource(R.drawable.account_circle);

It does not show any icon for that?
What is wrong here? How to fix this?

A: You can try this as well holder.imgIcon.setBackgroundDrawable(getResources().getDrawable(R.drawable.account_circle));
Hope this helps.


text:
Q: How to populate and access any element of 3 Dimensional Array List I have a requirement to create a 3-Dimensional ArrayList.
  ArrayList<ArrayList< ArrayList<Object>>> data_Header_Mapper;

How can i populate the 3 D arraylist and how i acccess the leaf child ( Object) of 3 Dimensional ArrayList. Lots of thanks in advance for any help.
I am familiar working with Vectors , But due to some problems i want to convert the below code of Vectors to ArrayList.
Code For Populating 3 D Vectors is as follows.
  for (int r=0;r<totalRows;r++) // r - Rows
   {

     for (int c=0;c<totalViewedCols;c++) //c- Columns
     {

       cAct=0;
       while (cAct < totalActualCols)
      // for (int cAct=0;cAct<totalActualCols;cAct++) //c- Columns
       {
         if (Cols.get(cAct).toLowerCase().equals(columnName.toLowerCase())  )
         {
          ColValindex =  colHeader_ForSave.indexOf(columnName)  ;//Temp Comment
          colValue= (String)data_ForSave.elementAt(r).get(ColValindex);
         //  ColValindex =  header.indexOf(columnName)  ;
         //  colValue= (String)data.elementAt(r).get(ColValindex);

           data_Header_Mapper_Element.add(columnName);
           data_Header_Mapper_Element.add(colValue);
          }
         cAct++;
       }
       if (data_Header_Mapper_Element.size() !=0)
       {
        data_Header_Mapper_Row.add(data_Header_Mapper_Element);
       // data_Header_Mapper_Element.removeAllElements();
      data_Header_Mapper_Element =null;
      data_Header_Mapper_Element=new Vector<String>();
       }
     }
      if (data_Header_Mapper_Row.size() !=0)
     {
       data_Header_Mapper.add(data_Header_Mapper_Row);

       data_Header_Mapper_Row =null;
       data_Header_Mapper_Row=new Vector<Vector<String>>();
      }

   }

Code For Access 3 D Vectors is below
  for(int r=0;r<rowSize;r++)
      {

      for (int c=0;c<colSize;c++)
      {

      // To Build Insert And Update Query
           columnDataType=  dbe.GetDataTypeOfTableColumn(rsMetaData,data_Header_Mapper.elementAt(r).get(c).get(0).toString());
           dataSize=dbe.GetDataSizeOfTableColumn(rsMetaData,data_Header_Mapper.elementAt(r).get(c).get(0).toString());
           Validation.ValidateData(columnDataType, data_Header_Mapper.elementAt(r).get(c).get(1), dataSize);

         }

        }

A: public class My3DArray {

    private List<List<List<Object>>> list;

    public My3DArray() {
        this.list = generate3DArray(5, 5, 5);
    }

    public List<List<List<Object>>> generate3DArray(int dim1, int dim2, int dim3) {
        List<List<List<Object>>> list = new ArrayList<List<List<Object>>>();
        for(int i = 0; i < dim1; i++) {
            List<List<Object>> list2 = new ArrayList<List<Object>>();
            for(int j = 0; j < dim2; j++) {
                List<Object> list3 = new ArrayList<Object>(dim3);
                list2.add(list3);
            }
            list.add(list2);
        }
        return list;
    }

    public Object getElementIn3DArray(int i, int j, int k)
        throws NullPointerException, ArrayIndexOutOfBoundsException {
        return list.get(i).get(j).get(k);
    }

    public void setElementIn3DArray(Object o, int i, int j, int k)
        throws NullPointerException, ArrayIndexOutOfBoundsException {
        list.get(i).get(j).add(o);
    }
}

public class Main {
    public static void main(String[] args) {
        My3DArray x = new My3DArray();
        x.setElementIn3DArray("Hello World", 0, 0, 0);
        System.out.println(x.getElementIn3DArray(0, 0, 0));
        System.exit(0);
    }
}

I omit some variables in the class like the dimensions but this is an idea. Its up to you how to use this example.


text:
Q: Can I change an iFrame's source from within? This is a question that I'm having trouble wording clearly; read carefully. I want to know whether or not it's possible for the source of an iFrame (the page displayed via the iFrame) to change it's inner source without changing the source of the iFrame's parent page.
For example:
If I create an iFrame in my web page, and click a traditional link within the iFrame, the source (location) of the master page (the page where I've created the iF) will be changed rather than the iFrame's content.

I want, instead, to change the source of the iFrame via the framed content (this could be cross-domain content) to a new location within the frame itself.

I've noticed different behaviors in JS methods of changing a page's
  location. This SO question has a few of them detailed. Some methods of
  changing the page behave differently, I noticed, such as not allowing
  the user to use the back button to get to the page that the user
  navigated from.

Using one of these different JS location changing methods, I thought this could be possible, but I'm not sure how it would be done.
The question:
Provided that the iFrame's requested web page is cooperating with it, is it possible to achieve the result of an iFrame resource changing its own location? If so, how is it done?

A: Do like this:
window['iframe_name'].src = 'http://yourdomain.com';

Or do like this:
document.getElementById('iframe_id').src = 'http://yourdomain.com';

As per the comment you need to define the taget of a link to _self:
Link

A: For any anchor tags within the iframe, try setting the target to _self. Like this:
Test

I'll play around with it, but I know this was the standard for old school frames.
EDIT
Based on some tests I did, the default action for anchor links within an iframe is to load the new content within the iframe. target="_self" is redundant unless there is something else overriding it. Maybe you should supply more info about the source code if this isn't resolving it for you.
I could also make an assumption that you are running into the problem using javascript. If you are using window.location.href, you'll want to change that as follows:
Instead Of:
window.location.href = 'newpage.html';

Try:
window.open('/newpage.html', '_self');

A: I belive that postmessage() would help you
https://developer.mozilla.org/en-US/docs/Web/API/window.postMessage

A: Thank you Lawrence Johnson for reminding me.  And you don't even need any Javascript for this.  The "target" of a link is a window name so as long as that matches the name attribute on the window or iframe the link will open in the iframe.  The link can be inside or outside the iframe.  I just made myself an astonishingly simple panorama viewer at http://ab1jx.1apps.com/pix/panoramas/index.html using this principle.  Each image has its own html wrapper.  When you click the links below the iframe they load the wrapper into their target of picframe, changing the images in the process.  Look at the source.


text:
Q: Should i choose GData for youtube or Youtube api I want to integrate youtube in my app for uploading and watching videos so i search on this topic and i found there are two ways to do that.

*

*youtube api

*GData for youtube

Now question is which one i should use to develop my application and which is more efficient way.

A: Both ways are good, but to increase your efficience, i would suggest to use Gdata, because it makes certain tasks easier... you should take a look in this link, for the Objective-C Gdata.r


text:
Q: display post from html in following php script I have a html page that posts to mysql database through a php script. How do I get the information that was entered in the html page to display after 1 record created?
<?php
$link = mysqli_connect('****', '****', '****', 'orders');

$sequence = $_POST['sequence'];
$items_count = $_POST['items_count'];
$total = $_POST['total'];
$payment_type = $_POST['payment_type'];

$sql="INSERT INTO orders (sequence,items_count,total,payment_type)
VALUES
('$sequence','$items_count','$total','$payment_type')";

if (!mysqli_query($link,$sql)) {
die('Error: ' . mysqli_error($link));
}
echo '1 record created';

mysqli_close($link);

?>

A: In the page that is supposed to display the posts, have another query
$sql = "SELECT sequence,items_count,total,payment_type FROM orders";

and I'm not sure if it's the right mysqli function, but after you retrieve the data from mysql as an array (mysqli_fetch_array ?) - you have to iterate through the returned results.
foreach($fetched_row as $row){
echo "<pre>"; print_r($row); echo "</pre>"
}

Which, you'll obviously want to use your own HTML - and the $row will be an associative array with the column names as the keys --

A: You need to add this code on the page where your fields will be displayed.
<?php
$last_record_id = mysql_insert_id();
$query = "SELECT * FROM <tablename> WHERE <$table_primary_key_id> = '$last_record_id'";
$result = mysqli_query($dbcon, $query);
$row = mysqli_fetch_array($result)
?>

Then fetch each field in separate variable like $price = $row['price'] and display them. You don't need looping because there is only one record to fetch and display.


text:
Q: Using bytes.Buffer with csv.writer I'm currently trying to serialize some string slice in a CSV without saving output to a file. I saw some examples using bytes.Buffer but even my the smallest test doesn't work. I don't know how to debug this, the code compiles without warning and doesn't throw error after writer.Flush(). It also works correctly with saving result to a file or piping it directly to standard output
Any help would be appreciated :)
Thx.
PS: the final print is just a test. I know i can use csv.NewWriter(os.stdout) to do so (and it works) but it doesn't fit my needs. I really would like to get the result in a byte array.
package main

import (
    "bytes"
    "encoding/csv"
    "fmt"
)

func main() {
    var buffer bytes.Buffer
    writer := csv.NewWriter(&buffer)
    writer.Write([]string{"1", "2", "3", "4"})
    writer.Write([]string{"5", "6", "7", "8"})

    defer writer.Flush()
    if err := writer.Error(); err != nil {
        panic(err)
    }
    fmt.Println(buffer.Bytes())
}

A: You are deferring the Flush call, making it execute after the fmt.Println call. Call Flush immediately:
package main

import (
    "bytes"
    "encoding/csv"
    "fmt"
)

func main() {
    var buffer bytes.Buffer
    writer := csv.NewWriter(&buffer)
    writer.Write([]string{"1", "2", "3", "4"})
    writer.Write([]string{"5", "6", "7", "8"})

    writer.Flush()
    if err := writer.Error(); err != nil {
        panic(err)
    }
    fmt.Println(buffer.String())
}

https://play.golang.org/p/BHTyfsuf0tY