text:
Q: Auth0 and Google API, access token expired, howto write files to Google Drive I've written an online converter and integrated Auth0 to my website. What I'm trying to achieve is to auto-upload the converted file to the Google Drive of a logged in user. I set up Google oauth in Auth0 and everything seemed to work fine.
The problem is, Google's access_token expires after 60min and I don't have a refresh_token. Therefore, the user needs to log in via the Google Login-page again. That is not, what I want, because the user is in fact logged in way longer than just 60min on my site, but Google refuses API-calls (because the Google token expired).
I know I can request a refresh_token by setting access_type=offline but this will add the permission Have offline access. I don't want that, I just want to upload data to the user's Drive, if he clicked the convert button on my page. I don't want to ask the users for permissions I don't need. If I (as a user) would link my Google account on a similar page and the tool asks for offline access I wouldn't approve, to be honest - the permission sounds like the tool creator can do whatever he wants with your account whenever he wants... There are many tools out there that have write access to a user's Drive without asking for offline access and with one single login until the user revokes the permission. How is that done?
Is there a way to make Google API calls without asking for offline access and without forcing the user to approve the app (that is already approved by him) again and again every 60min?
Thanks in advance,
phlo

A: By asking for offline access you are requesting a refresh token.   Google is going to tell the user that you are requesting offline access.     You can request something without telling the user what they are authorizing.
No there is no way to request a refresh token without displaying that message.   Nor is there a way for you to change the message it's a standard Google thing.

A: Is there a way to make Google API calls without asking for offline access and without forcing the user to approve the app (that is already approved by him) again and again every 60min?
Yes there are ways, but it depends on the specifics of your use case. For example, is your code in Java/php/etc running on a server, or is it JavaScript running in the browser?
Running your auth in the browser is probably the simplest solution as the Google library (https://developers.google.com/api-client-library/javascript/features/authentication) does all the work for you.

A: I found the solution!
Prerequirements

*

*Enable Use Auth0 instead of the IdP to do Single Sign On in your client's Dashboard

*Create a new Angular-route to handle the silent login callback (e.g. /sso)

*Add
$rootScope.$on("$locationChangeStart", function() {
    if ($location.path().indexOf("sso") == -1) {
        authService.relogin(); //this is your own service
    }
});

to your run-function and set the callbackURL in angularAuth0Provider.init() to your new Angular-route (<YOUR_DOMAIN>/sso). Add this URL to your accepted callbacks in the Auth0 dashboard - this won't end in an infinite loop, because the locationChangeStart-event won't call authService.relogin() for this route

*Add $window.close(); to the controller of the Angular-route (/sso) to auto-close the popup

*Authenticate the user via Auth0 and save the timestamp and the Auth0-access_token somewhere

On reload:
Check, if the Auth0-token is still valid in authService.relogin(). If not, the user has to login again either way. If the token is valid and the Google token is about to expire (check this with the saved timestamp to prevent  unnecessary API calls) check for SSO-data and login silently, if present
    /* ... */
    if (validToken && googleExpired) {
        angularAuth0.getSSOData(function (err, data) {
            var lastUsedConnection = data.lastUsedConnection;
            var connectionName = (_.isUndefined(lastUsedConnection) ? undefined : lastUsedConnection.name);
            var isGoogle = (_.isUndefined(connectionName) ? false : connectionName == "google-oauth2");
            if (!err && data.sso && isGoogle) {
                authManager.authenticate();
                localStorage.setItem("last-relogin", new Date().getTime());
                angularAuth0.signin({
                    popup: true,
                    connection: data.lastUsedConnection.name
                });
            }
        });
    }

Now you will find a fresh Google access_token for this user (without asking for offline access)

Resources:

*

*https://auth0.com/docs/quickstart/spa/angularjs/03-session-handling

*https://auth0.com/docs/quickstart/spa/angularjs/11-sso


text:
Q: parsing timestamp from mysql to csv using java i have a mysql db, and i have one table which has many columns including a timestamp one. i want to read the table and write it to a csv file. then i will read from the csv file the data and insert it in another db and table. all these are done through java.
I can read the table date and the timestamp from the first db, but the timestap is not written correctly into the csv file.. only the last few digits are written. for example if i have a timestamp 2012-11-01 02:18:00.0 only the 18:00.0 will be written to the csv. All the other stuff work fine. For example if i hard write a timestamp i can write it to the second db. there;s the code for reading mysql and writing to csv :
                    con = DriverManager.getConnection("jdbc:mysql://localhost/campdb", "...", "...");

                    stmt = (Statement) con.createStatement();
                    fw = new FileWriter(filename);
                    PrintWriter a = new PrintWriter(fw);
                    ResultSet res = stmt.executeQuery("SELECT * FROM CAMPREQ;");
                    while (res.next())
                    {
                        String ID = res.getString(1);
                        java.sql.Date date = res.getDate(2);
                        //java.util.Date jdate = new java.util.Date(date.getTime());
                        String company = res.getString(3);
                        String time = res.getString(4);
                        String origin = res.getString(5);
                        String dest = res.getString(6);
                        String timestamp = res.getString(7);
                        System.out.println(timestamp);
                        a.print(ID);
                        a.print(',');
                        a.print(date);
                        a.print(',');
                        a.print(company);
                        a.print(',');
                        a.print(time);
                        a.print(',');
                        a.print(origin);
                        a.print(',');
                        a.print(dest);
                        a.print(',');
                        a.print(timestamp);
                        a.print('\n');
                        a.flush();

                    }

The System.out command prints the timestamp as it should be written, however it is not written correctly in the csv :(
thank you

A: Don't do things in Java that MySQL can do by itself.
con = DriverManager.getConnection("jdbc:mysql://localhost/campdb", "...", "...");
stmt = (Statement) con.createStatement();

String q =
  "SELECT * INTO OUTFILE '" + filename + "'"
  + " FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"'"
  + " LINES TERMINATED BY '\n'"
  + " FROM " + tablename;

stmt.execute(q);

A: try using the code below, it works for most databases and properly takes all datatypes correctly with correct formatting. This should solve your problem not just for mysql but for any other database
 public static StringBuffer resultSetToStringCsv(ResultSet resultSet) throws Exception{
StringBuffer stringwriter = new StringBuffer();

ResultSet rs = resultSet;
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();

//Write column names
for(int i=1;i<=numberOfColumns;i++){
 stringwriter.append(rsmd.getColumnName(i));
 stringwriter.append(',');
}
stringwriter.append('\n');
//Write rows
while(rs.next()){
 for(int i=1;i<=numberOfColumns;i++){
  try{
   stringwriter.append(""+rs.getObject(i));
  stringwriter.append(',');
  }catch (Exception e) {
   stringwriter.append("null");
 stringwriter.append(',');
}
}
 stringwriter.append('\n');
}

You can check http://bmukorera.blogspot.com/2012/11/resultset-query-to-string-generating.html for full code

redpajama_set_name: RedPajamaStackExchange


text:
Q: HowTo skip deserialization for a field in json4s Here is my json:
{
  "stringField" : "whatever",
  "nestedObject": { "someProperty": "someValue"}
}

I want to map it to
case class MyClass(stringField: String, nestedObject:String)

nestedObject should not be deserialized, I want json4s to leave it as string.
resulting instance shouldBe:
val instance = MyClass(stringField="whatever", nestedObject= """ { "someProperty": "someValue"} """)

Don't understand how to do it in json4s.

A: You can define a custom serializer:
case object MyClassSerializer extends CustomSerializer[MyClass](f => ( {
  case jsonObj =>
    implicit val format = org.json4s.DefaultFormats
    val stringField = (jsonObj \ "stringField").extract[String]
    val nestedObject = compact(render(jsonObj \ "nestedObject"))

    MyClass(stringField, nestedObject)
}, {
  case myClass: MyClass =>
    ("stringField" -> myClass.stringField) ~
      ("nestedObject" -> myClass.nestedObject)
}
))

Then add it to the default formatter:
implicit val format = org.json4s.DefaultFormats + MyClassSerializer
println(parse(jsonString).extract[MyClass])

will output:
MyClass(whatever,{"someProperty":"someValue"})

Code run at Scastie


text:
Q: Transformar level em Variável Gostaria de criar uma nova coluna, transformando Tab1612SojaRend$Nível.Territorial os levels "Grande Região" e "Unidade da Federação" em colunas. A "Unidade da Federação tem que estar na mesma coluna das cidades de acordo com o Estado. Outro ponto que precisava seria eliminar o estado da variável "Município, Grande Região e Unidade da Federação".
library(sidrar)
Tab1612SojaRend <-get_sidra(1612,variable = 112, period = c("last" = 22),
                        geo = c("Region","State","City"),
                        geo.filter = list("Region" = 3,"Region" = 3,"Region" = 3),
                        classific = 'c81',
                        category = list(2713))

Tab1612SojaRend$Nível.Territorial <-
as.factor(Tab1612SojaRend$Nível.Territorial)

dput(Tab1612SojaRendsudeste[c(1:10, 101:110, 24001:24010), ])
structure(list(`Nível Territorial (Código)` = c("6", "6", "6",
"6", "6", "6", "6", "6", "6", "6", "6", "6", "6", "6", "6", "6",
"6", "6", "6", "6", "6", "6", "6", "6", "6", "6", "6", "6", "6",
"6"), `Nível Territorial` = c("Município", "Município", "Município",
"Município", "Município", "Município", "Município", "Município",
"Município", "Município", "Município", "Município", "Município",
"Município", "Município", "Município", "Município", "Município",
"Município", "Município", "Município", "Município", "Município",
"Município", "Município", "Município", "Município", "Município",
"Município", "Município"), `Município, Grande Região e Unidade da Federação
(Código)` = c("3100104",
"3100104", "3100104", "3100104", "3100104", "3100104", "3100104",
"3100104", "3100104", "3100104", "3100500", "3100500", "3100500",
"3100500", "3100500", "3100500", "3100500", "3100500", "3100500",
"3100500", "3506300", "3506300", "3506359", "3506359", "3506359",
"3506359", "3506359", "3506359", "3506359", "3506359"), `Município, Grande
 Região e Unidade da Federação` = c("Abadia dos Dourados - MG",
"Abadia dos Dourados - MG", "Abadia dos Dourados - MG", "Abadia dos Dourados
 - MG",
"Abadia dos Dourados - MG", "Abadia dos Dourados - MG", "Abadia dos Dourados
 - MG",
"Abadia dos Dourados - MG", "Abadia dos Dourados - MG", "Abadia dos Dourados
 - MG",
"Açucena - MG", "Açucena - MG", "Açucena - MG", "Açucena - MG",
"Açucena - MG", "Açucena - MG", "Açucena - MG", "Açucena - MG",
"Açucena - MG", "Açucena - MG", "Bernardino de Campos - SP",
"Bernardino de Campos - SP", "Bertioga - SP", "Bertioga - SP",
"Bertioga - SP", "Bertioga - SP", "Bertioga - SP", "Bertioga - SP",
"Bertioga - SP", "Bertioga - SP"), `Ano (Código)` = c("1996",
"1997", "1998", "1999", "2000", "2001", "2002", "2003", "2004",
"2005", "2008", "2009", "2010", "2011", "2012", "2013", "2014",
"2015", "2016", "2017", "2016", "2017", "1996", "1997", "1998",
"1999", "2000", "2001", "2002", "2003"), Ano = c("1996", "1997",
"1998", "1999", "2000", "2001", "2002", "2003", "2004", "2005",
"2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015",
"2016", "2017", "2016", "2017", "1996", "1997", "1998", "1999",
"2000", "2001", "2002", "2003"), `Variável (Código)` = c("112",
"112", "112", "112", "112", "112", "112", "112", "112", "112",
"112", "112", "112", "112", "112", "112", "112", "112", "112",
"112", "112", "112", "112", "112", "112", "112", "112", "112",
"112", "112"), Variável = c("Rendimento médio da produção", "Rendimento
 médio da produção",
"Rendimento médio da produção", "Rendimento médio da produção",
"Rendimento médio da produção", "Rendimento médio da produção",
"Rendimento médio da produção", "Rendimento médio da produção",
"Rendimento médio da produção", "Rendimento médio da produção",
"Rendimento médio da produção", "Rendimento médio da produção",
"Rendimento médio da produção", "Rendimento médio da produção",
"Rendimento médio da produção", "Rendimento médio da produção",
"Rendimento médio da produção", "Rendimento médio da produção",
"Rendimento médio da produção", "Rendimento médio da produção",
"Rendimento médio da produção", "Rendimento médio da produção",
"Rendimento médio da produção", "Rendimento médio da produção",
"Rendimento médio da produção", "Rendimento médio da produção",
"Rendimento médio da produção", "Rendimento médio da produção",
"Rendimento médio da produção", "Rendimento médio da produção"
 ), `Produto das lavouras temporárias (Código)` = c("2713", "2713",
"2713", "2713", "2713", "2713", "2713", "2713", "2713", "2713",
"2713", "2713", "2713", "2713", "2713", "2713", "2713", "2713",
"2713", "2713", "2713", "2713", "2713", "2713", "2713", "2713",
"2713", "2713", "2713", "2713"), `Produto das lavouras temporárias` =
c("Soja (em grão)",
"Soja (em grão)", "Soja (em grão)", "Soja (em grão)", "Soja (em grão)",
"Soja (em grão)", "Soja (em grão)", "Soja (em grão)", "Soja (em grão)",
"Soja (em grão)", "Soja (em grão)", "Soja (em grão)", "Soja (em grão)",
"Soja (em grão)", "Soja (em grão)", "Soja (em grão)", "Soja (em grão)",
"Soja (em grão)", "Soja (em grão)", "Soja (em grão)", "Soja (em grão)",
"Soja (em grão)", "Soja (em grão)", "Soja (em grão)", "Soja (em grão)",
"Soja (em grão)", "Soja (em grão)", "Soja (em grão)", "Soja (em grão)",
"Soja (em grão)"), `Unidade de Medida (Código)` = c("33", "33",
"33", "33", "33", "33", "33", "33", "33", "33", "33", "33", "33",
"33", "33", "33", "33", "33", "33", "33", "33", "33", "33", "33",
"33", "33", "33", "33", "33", "33"), `Unidade de Medida` = c("Quilogramas
 por
 Hectare",
"Quilogramas por Hectare", "Quilogramas por Hectare", "Quilogramas por
Hectare",
"Quilogramas por Hectare", "Quilogramas por Hectare", "Quilogramas por
Hectare",
"Quilogramas por Hectare", "Quilogramas por Hectare", "Quilogramas por
Hectare",
"Quilogramas por Hectare", "Quilogramas por Hectare", "Quilogramas por
Hectare",
"Quilogramas por Hectare", "Quilogramas por Hectare", "Quilogramas por
Hectare",
"Quilogramas por Hectare", "Quilogramas por Hectare", "Quilogramas por
Hectare",
"Quilogramas por Hectare", "Quilogramas por Hectare", "Quilogramas por
Hectare",
"Quilogramas por Hectare", "Quilogramas por Hectare", "Quilogramas por
Hectare",
"Quilogramas por Hectare", "Quilogramas por Hectare", "Quilogramas por
Hectare",
"Quilogramas por Hectare", "Quilogramas por Hectare"), Valor = c(1620,
2202, 2200, 2400, 2800, 2880, 2700, 2800, 2429, 2700, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, 2550, 2550, NA, NA, NA, NA, NA,
NA, NA, NA)), row.names = c(2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
11L, 102L, 103L, 104L, 105L, 106L, 107L, 108L, 109L, 110L, 111L,
24002L, 24003L, 24004L, 24005L, 24006L, 24007L, 24008L, 24009L,
24010L, 24011L), class = "data.frame")

A: Como a API da SIDRA estava instável ou muito lenta, fiz essa pequena alteração no código (removi os municípios da consulta) para ter dados similares para trabalhar.
library(sidrar)
Tab1612SojaRend <- get_sidra(1612,variable = 112, period = c("last" = 22),
                             geo = c("Region","State"),
                             geo.filter = list("Region" = 3,"Region" = 3),
                             # geo = "Region", geo.filter = list("Region" = 3),
                             classific = 'c81',
                             category = list(2713))

Para fazer o desejado, é possível usar a função spread() para espalhar os valores Nível Territorial em várias colunas.
library(tidyverse)
resp1 <- Tab1612SojaRend %>%
  spread(`Nível Territorial`, Valor)

Agora, sempre cabe perguntar: é isso mesmo que você deseja fazer?
Vamos dar uma olhada em resp1:
glimpse(resp1)
Observations: 110
Variables: 13
$ `Nível Territorial (Código)`                    <chr> "2", "2", "2", "2", "2", "2",...
$ `Grande Região e Unidade da Federação (Código)` <chr> "3", "3", "3", "3", "3", "3",...
$ `Grande Região e Unidade da Federação`          <chr> "Sudeste", "Sudeste", "Sudest...
$ `Ano (Código)`                                  <chr> "1996", "1997", "1998", "1999...
$ Ano                                             <chr> "1996", "1997", "1998", "1999...
$ `Variável (Código)`                             <chr> "112", "112", "112", "112", "...
$ Variável                                        <chr> "Rendimento médio da produção...
$ `Produto das lavouras temporárias (Código)`     <chr> "2713", "2713", "2713", "2713...
$ `Produto das lavouras temporárias`              <chr> "Soja (em grão)", "Soja (em g...
$ `Unidade de Medida (Código)`                    <chr> "33", "33", "33", "33", "33",...
$ `Unidade de Medida`                             <chr> "Quilogramas por Hectare", "Q...
$ `Grande Região`                                 <dbl> 2072, 2330, 2114, 2518, 2316,...
$ `Unidade da Federação`                          <dbl> NA, NA, NA, NA, NA, NA, NA, N...

Veja que as variáveis criadas se intercalam entre Grande Região ter valor e Unidade da Federação ser NA e o contrário.
any(!is.na(resp1$`Grande Região`) & !is.na(resp1$`Unidade da Federação`))
# [1] FALSE

Ocorre que rompemos o terceiro princípio das tabelas tidy: Cada unidade observacional deve ter sua própria tabela, e aqui estamos misturando Unidades da Federação com Regiões.
Por estes motivos, eu acharia melhor trabalhar da seguinte maneira:
resp2 <- split(Tab1612SojaRend, Tab1612SojaRend$`Nível Territorial`)
regioes <- resp2[[1]]
ufs <- resp2[[2]]

Outra maneira ainda, seria mudar o chamado da API para retornar uma unidade observacional (regiões/UFs/municípios) de cada vez.


text:
Q: Using Gephi, how do I show nodes older than X days? I am using Gephi 0.8.2 Beta and I'm just beginning to use it.
I would like to add a node attribute like 'Pass Change Date' of <datetime> type. Then possibly create a node attribute like 'Pass elapsed time' which compares the 'Pass Change Date' to today' date to give elapsed time.
What I am looking for is a way to determine all nodes that are greater than 90 days.


text:
Q: An error message with uploading image to mySql In the following code, I am trying to upload an image to mySql database:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<?php
        $hostname = '';
        $username = '';
        $password = '';
        try {
            $dbh = new PDO("mysql:host=$hostname;dbname= abc", $username, $password);
            //echo 'Connected to database';
        }
        catch(PDOException $e)
        {
          echo $e->getMessage();
        }
            if (!$_POST['uploaded']){
            ?>
          <form action="<? echo $_SERVER['PHP_SELF']; ?>" method="post">

<select name="category">
                     <option value="non">Select category</option>
                     <option value="cars">Cars</option>
                     <option value="real">Real estate</option>
                     <option value="services">Services</option>
                     <option value="electronics">Electronics</option>
                     <option value="furniture">Furniture</option>
                     <option value="home">Home appliance</option>
                     <option value="outdoor">Outdoor</option>
              </select>

Title
<input class="tb10" type="text" name="title" />

Price
<input class="tb10" type="text" name="price" />

Type
<select name="type">
                     <option value="non">Select type</option>
                     <option value="offer">Offer</option>
                     <option value="want">Want</option>
              </select>

Description

              <textarea name="description" rows="5" cols="60"></textarea>

Upload pictures
<input type="file" name="pictures1"/>
<input type="file" name="pictures2"/>
<input type="file" name="pictures3"/>
<input type="file" name="pictures4"/>

Email
<input class="tb10" type="text" id="email1" name="email1" onkeyup="Twitter.updateUrl(this.value)"/>

Phone
<input class="tb10" type="text" name="phone" />

Address
<input class="tb10" type="text" name="address" />

              <input type="submit" value="Submit" name="uploaded" class="button" />
            </form>
            <?php
            }else{
$ip=$REMOTE_ADDR;
copy($pictures1, "./temporary/".$ip."");
copy($pictures2, "./temporary/".$ip."");
copy($pictures3, "./temporary/".$ip."");
copy($pictures4, "./temporary/".$ip."");
$filename1 = "./temporary/".$REMOTE_ADDR;
$filename2 = "./temporary/".$REMOTE_ADDR;
$filename3 = "./temporary/".$REMOTE_ADDR;
$filename4 = "./temporary/".$REMOTE_ADDR;
$fp1 = fopen($filename1, "r");
$fp2 = fopen($filename2, "r");
$fp3 = fopen($filename3, "r");
$fp4 = fopen($filename4, "r");
$contents1 = fread($fp1, filesize($filename1));
$contents2 = fread($fp2, filesize($filename2));
$contents3 = fread($fp3, filesize($filename3));
$contents4 = fread($fp4, filesize($filename4));
fclose($fp1);
fclose($fp2);
fclose($fp3);
fclose($fp4);
$encoded1 = chunk_split(base64_encode($contents1));
$encoded2 = chunk_split(base64_encode($contents2));
$encoded3 = chunk_split(base64_encode($contents3));
$encoded4 = chunk_split(base64_encode($contents4));
$category = $_POST['category'];
$title = $_POST['title'];
$price = $_POST['price'];
$type = $_POST['type'];
$description = $_POST['description'];
$email1 = $_POST['email1'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$query_insert_user = "INSERT INTO `adtable` ( `Category`, `Title`, `Price`, `Type`, `Description`, `Img1`,`Data1`,`Img2`,`Data2`,`Img3`,`Data3`,`Img4`,`Data4`,`Email`, `Phone`, `Address`) VALUES ( '$category', '$title', '$price', '$type', '$description', 'NULL', '$encoded1', 'NULL', '$encoded2','NULL', '$encoded3','NULL', '$encoded4', '$email1', '$phone', '$address')";
$result_insert_user = mysqli_query($dbh, $query_insert_user);
if (!$result_insert_user) {
echo 'Query Failed ';
}
unlink($filename1);
unlink($filename2);
unlink($filename3);
unlink($filename4);
}
?>

I want a user to upload 4 images. I looked for a solution to this problem but I couldn't find anything.
The error that I got is:
Parse error: syntax error, unexpected T_VARIABLE in /home/a6395791/public_html/friendscave/PostAD.php on line

The line is
$filename2 = "./temporary/".$REMOTE_ADDR;

Thanks


text:
Q: How to return HTML response from aiohttp.web server? How can I return HTML page from an aiohttp.web handler?
Is there something similar to json_response()?

A: If you have the HTML already in a string:
from aiohttp import web

routes = web.RouteTableDef()

@routes.get('/')
async def index_handler(request):
    return web.Response(
        text='
Hello!
',
        content_type='text/html')

app = web.Application()
app.add_routes(routes)
# or instead of using RouteTableDef:
# app.router.add_get('/', index_handler)

web.run_app(app)

There is no html_response() in aiohttp, but of course you can create your own helper:
def html_response(text):
    return web.Response(text=text, content_type='text/html')

@routes.get('/')
async def index_handler(request):
    return html_response('
Hello!
')

Jinja2 templates
Another option is to use Jinja2 template engine with aiohttp_jinja2:
# hello.html

Hello, {{ name }}!

# my_web_app.py

from aiohttp import web
import aiohttp_jinja2
import jinja2
from pathlib import Path

here = Path(__file__).resolve().parent

@aiohttp_jinja2.template('hello.html')
def index_handler(request):
    return {'name': 'Andrew'}

app = web.Application()
aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader(str(here)))
app.router.add_get('/', index_handler)

web.run_app(app)

A: Yes it is super easy you just have to read the file
from aiohttp import web

routes = web.RouteTableDef()
def html_response(document):
    s = open(document, "r")
    return web.Response(text=s.read(), content_type='text/html')

@routes.get('/')
async def index_handler(request):
    return html_response('index.html')

app = web.Application()
app.add_routes(routes)
web.run_app(app)


text:
Q: vector tile layer does not display when switching from VectorTile (3.10) to TileVector (3.11) I have this simple layer working with openlayers 3.10
var roads = new ol.layer.Vector({
  source: new ol.source.TileVector({
    format: new ol.format.TopoJSON(),
    tileGrid: ol.tilegrid.createXYZ({maxZoom: 13}),
    tilePixelRatio: 16,
    url: 'http://MY_SERVER/{z}/{x}/{y}.topojson'
  }),
  style: new ol.style.Style({
    stroke: new ol.style.Stroke({
      width: 8,
      color: [0xff,0xff,0,0.3]
    })
  })
});

And then it is laid out on top of an OSM/mapnik layer:
var map = new ol.Map({
  layers: [
    mapnik,
    roads
  ],
  target: 'map',
  view: new ol.View({
    center: ol.proj.fromLonLat([25, 46]),
    zoom: 7,
    minZoom:7,
    maxZoom:17
  })
});

However the 3.11 version
new ol.layer.VectorTile({
  source: new ol.source.VectorTile({
    // ...
  })
});

fails. The tile server is invoked, putting in a styling function reveals that the features are loaded properly, but no feature is displayed! There is no error on the console. What am I doing wrong?

A: With v3.11.0 release ol.source.TileVector was removed. You may use ol.source.VectorTile from now on. Also change your code from ol.layer.Vector to ol.layer.VectorTile. See changelog and an example.


text:
Q: Как обозначить пробел в поиске элементов, что бы их можно было посчитать? print('Введите строку:')
s=input()
a=0
for i in range(0,len(s)):
    n=s.find ( ' ' ) # возможно ли как-то тут обозначить пробел?
    if n>=0:
        a=a+1
print(a)

A: Чтобы посчитать количество символов, воспользуйтесь строковым методом count
>>> s = "a dog is a cat. Its awful!"
>>> s.count(" ")
6

Метод find находит индекс первого вхождения подстроки. Проще говоря, находит позицию, на которой находится первый пробел. Он не считает символы.


text:
Q: Change the text in a div when hovered over a list element So I have a list set up so that when I hover over the different elements it will change the picture to the right of the elements. I want text to go along with the picture so I would like that in a div below. Is there a way with css to make it so when I hover over an element in the list it will change the text in the div? Normally I try and figure these things out myself but I have been searching for a while and can't seem to find a solution.
HTML:

        Arms

TEXT TEST 1

        Back

TEXT TEST 2

        Head

        Feet

        Legs

        Chair

        Desk

and here is the relative css:
ul {
    background-image: url('../img/bg.jpg');
    background-repeat: no-repeat;
    background-origin: border-box;
    background-position:right top;
    border-top: 1px solid #444;
    border-bottom: 1px solid #444;
    border-right: 1px solid #444;
    display: inline-block;
    height: 700px;
    position: relative;
    width: 800px;
    list-style:none;
    padding-left:0;
}
li {
    font: bold 16px/100px sans-serif;
    height: 100px;
}
a {
    border-right: 1px solid #444;
    border-top: 1px solid #444;
    border-left: 1px solid #444;
    color: black;
    display: block;
    text-align: center;
    text-decoration: none;
    width: 99px;
}
a:hover {
    background: gray;
    color: #fff;
}
div.relative {
    position: relative;
    width: 700;
    height: 900;
}

div.absolute {
    position: absolute;
    top: 700px;
    width: 800px;
    height: 100px;
    border: 1px solid #444;
}
h3{
    margin-left:200px;
    margin-top:500px;
}
img {
    display: none;
    height: 700;
    position: absolute;
    right: 0;
    top: 0;
    width: 600px;
    background-color:red;
}
a:hover + img,
img:hover {
    display: block;
}

A: You can just add a style to show and hide the text div, like you already do for the img:
a + img + div
{
  display: none;
}
a:hover + img + div
{
  display: block;
}

A: Here is a solution. Use the li:hover event to hide and show the corrsponding div.

ul {
  background-image: url('../img/bg.jpg');
  background-repeat: no-repeat;
  background-origin: border-box;
  background-position: right top;
  border-top: 1px solid #444;
  border-bottom: 1px solid #444;
  border-right: 1px solid #444;
  display: inline-block;
  height: 700px;
  position: relative;
  width: 800px;
  list-style: none;
  padding-left: 0;
}
li {
  font: bold 16px/100px sans-serif;
  height: 100px;
}
a {
  border-right: 1px solid #444;
  border-top: 1px solid #444;
  border-left: 1px solid #444;
  color: black;
  display: block;
  text-align: center;
  text-decoration: none;
  width: 99px;
}
a:hover {
  background: gray;
  color: #fff;
}
div.relative {
  position: relative;
  width: 700;
  height: 900;
}
div.absolute {
  position: absolute;
  top: 700px;
  width: 800px;
  height: 100px;
  border: 1px solid #444;
}
h3 {
  margin-left: 200px;
  margin-top: 500px;
}
img {
  display: none;
  height: 700;
  position: absolute;
  right: 0;
  top: 0;
  width: 600px;
  background-color: red;
}
a:hover + img,
img:hover {
  display: block;
}
.absolute {
  display: none;
}
.relative li:hover div.absolute {
  display: initial;
}

      Arms

TEXT TEST 1

      Back

TEXT TEST 2

      Head

      Feet

      Legs

      Chair

      Desk

A: I have used a .wrapper div, but you have more possibilities, when you are using javascript.

ul {
  background-image: url('../img/bg.jpg');
  background-repeat: no-repeat;
  background-origin: border-box;
  background-position:right top;
  border-top: 1px solid #444;
  border-bottom: 1px solid #444;
  border-right: 1px solid #444;
  display: inline-block;
  height: 700px;
  position: relative;
  width: 800px;
  list-style:none;
  padding-left:0;
}
li {
  font: bold 16px/100px sans-serif;
  height: 100px;
}
a {
  border-right: 1px solid #444;
  border-top: 1px solid #444;
  border-left: 1px solid #444;
  color: black;
  display: block;
  text-align: center;
  text-decoration: none;
  width: 99px;
}
a:hover {
  background: gray;
  color: #fff;
}
div.relative {
  position: relative;
  width: 700;
  height: 900;
}

div.absolute {
  position: absolute;
  top: 700px;
  width: 800px;
  height: 100px;
  border: 1px solid #444;
}
h3{
  margin-left:200px;
  margin-top:500px;
}
img {
  height: 700;
  position: absolute;
  right: 0;
  top: 0;
  left: 101px;
  background-color:red;
  width: 600px;
}
.wrapper {
  display: none;
}
a:hover + .wrapper {
  display: block;
}

      Arms

TEXT TEST 1

      Back

TEXT TEST 2

      Head

      Feet

      Legs

      Chair

      Desk

A: I solved it with javascript and jQuery. But I'm not sure if it solves your issue.
Just add an eventlistener to all li that changes the text of the corresponding div.
    $("li").mouseover(function(){
        $("#TEXT1").text($(this).children("a").text());
    })

You can give a tag to all your li if you have some you don't want to act this way.


text:
Q: Latex class from remote source? In order to share a bibtex library across projects, it's possible to link to a remote resource using at < some url > using,
\addbibresource[location=remote]{< some url >}

This is a really nice method when collaborating on multiple projects with a shared reference library.
I'd love to do the same with a custom document class file. The closest answer to this question I could find was discussed here but it seems no solution was found.
Any suggestions would be appreciated!


text:
Q: PHP upload local file without button I am  trying to upload a file but i'm not using a upload button.
I want to upload a local file path for e.g C://file etc I currently  use
$_FILES['file']['name']

I would like to use for e.g http://localhost/uploadfile_frompath?filepath=C://file.txt As I would like to use the PHP call as a API to upload files
Is there a way to set the $_Files to a specif local file?


text:
Q: How do I print the sum of a 2 numbers counting down from the sum to 1 // Example program
#include <iostream>
#include <string>
using namespace std;

int main()
{
  int num;
  int num2;
  int sum;
  int i = 0;

  cout << "enter a number: ";
  cin >> num;
  cout << "enter another number: ";
  cin >> num2;

 sum = num + num2;

 for(i = 0 ; i <= sum ; i++)
  {
      cout << "loop iteration: " << sum << endl;
  }
  return 0;

}

this is the code i have so far. Right now it works fine it computes the sum, however, say the sum is 3, it'll print:
loop iteration: 3
loop iteration: 3
loop iteration: 3

but I am trying to get it to print:
loop iteration: 3
loop iteration: 2
loop iteration: 1

I'm not sure if the issue lies inside my for statement, I think I may have the order wrong.

A: The issue is that you are printing the same sum over and over and not decrementing the sum. either you can decrement the sum within for loop using sum-- operator or you can modify the loop as shown below.
for(i = sum ; i >= 1 ; i--)
{
    cout << "loop iteration: " << i << endl;
}

A: // Example program
#include <iostream>
#include <string>
using namespace std;

int main()
{
int num;
int num2;
int sum;
int i = 0;

cout << "enter a number: ";
cin >> num;
cout << "enter another number: ";
cin >> num2;

sum = num + num2;

while(sum != 0){

  cout << "loop iteration: " << sum << endl;
  sum--;
}
return 0;
}


text:
Q: Display x/197 as text in a TextView with x changing each buttonclick I have a textview where im trying to dispay this "1/197" and with a button click change it to 2/197 an so on..
this is my code..
public class playactivity extends Activity {
        public int counter = 1

 @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_jugar);

    Button nextbutton = (Button) findViewById(R.id.button3);
    TextView numbertextview =(TextView) findViewById(R.id.textView3);

    numbertextview.setText(String.valueOf(counter));

 nextbutton.setOnClickListener(new View.OnClickListener() {

            TextView numbertextview =(TextView) findViewById(R.id.textView3);

                 @Override
                  public void onClick(View v) {
                       // LO QUE HACE EL NEXT BUTTON
                    counter = counter + 1;
                    numbertextview.setText(String.valueOf(counter));

As you can see i already got my TextView to display "1" and with a buttonclick it changes to "2" and so on. Now i want to add this "/197" how do i do that?

A: You can just concatenate the "/197" to the number when you set the text:
numbertextview.setText(String.valueOf(counter) + "/197");

A: Perhaps you can try this
numbertextview.setText(String.valueOf(counter)+"/197");


text:
Q: custom list view click on row item but its not give me right data after scrolling i have click on listview row layout and get text but its provide wrong data after then scrolling list means below code sales convert into service.
        convertView.setTag(viewHolder);

    viewHolder.clickViewLayout.setTag(position);
        viewHolder.clickViewLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TextView tv = (TextView)v.findViewById(R.id.txtServiceAndSalesType);
                String stringServiceAndSalesType = viewHolder.txtServiceAndSalesType.getText().toString();
                if (stringServiceAndSalesType.equalsIgnoreCase("Sales")) {
                    context.startActivity(new Intent(context, SalesWizardActivity.class));
                } else {
                    context.startActivity(new Intent(context, ServiceWizardActivity.class));
                }
            }
        });
        viewHolder.emailBtn.setTag(position);
        viewHolder.emailBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                int po = (Integer) v.getTag();
                String auditId;
                if(AppointmentItemjbjects.get(po).getCoreLeadId()==null&&AppointmentItemjbjects.get(po).getCoreLeadId()==""){
                    auditId = AppointmentItemjbjects.get(po).getCoreLeadId();
                }else {
                    auditId = AppointmentItemjbjects.get(po).getWorkorderId();
               }

            }
        });


text:
Q: How to avoid repetitive code in redux (ducks approach)? I've been working with React and Redux for about 3 years.
Also I use redux-thunk for asynchronous stuff.
And I love them a lot, but recently I noticed that almost all ducks in my project are using the same structure of actions, reducers, selectors, etc.
For example - you have an application and it has some users and transactions (or similar) lists, item details and edit functionality.
All of these lists or items have their own ducks (actions, reducers, selectors, etc).
Code below will show the problem more clearly:
// ACTIONS

const const setUser = user => ({
  type: types.SET_USER,
  payload: user,
});

const cleanUser = () => ({ type: types.CLEAN_USER });

const fetchUser = userId => dispatch =>
  dispatch(fetchApi(userRequests.get(userId)))
    .then(response => dispatch(setUser(response)))
    .catch(error => showNotification(error));

// delete, update, etc... user actions

// REDUCER

const userReducer = (state = null, action) => {
  switch (action.type) {
    case types.SET_GROUP_ITEM:
      return action.payload;
    case types.CLEAN_GROUP_ITEM:
      return null;
    default:
      return state;
  }
};

Code above shows the structure of user from users duck which will be almost the same for other ducks.
Is there any ways to reduce the repetitive code?
Thank you for advance!

A:
I noticed that almost all ducks in my project are using the same
  structure of actions, reducers, selectors, etc.

I never implemented the reducks structure within Redux, but I did at one point find myself generating identical actions, reducers, etc. when managing my domain entities (e.g. Persons, Orders, Products, etc).
For instance, I always seemed to care about:

*

*Are we currently fetching the entity? isFetching

*Were there any errors fetching the entity? error

*What's the entity's actual data? data

*When was the entity last fetched? lastUpdated
Also, domain entities are getting added all the time, so continually copying and pasting the reducer/actions is not ideal. We need a way to dynamically store data in Redux, and we want that data to always be attached to properties like isFetching and lastUpdated.
{
  "entities": {
    <SOME_ENTITY>: {
      "isFetching" : null    // Am I fetching?
      "lastUpdated": null    // When was I last fetched?
      "data"       : null    // Here's my data!
      "error"      : null    // Error during fetching
    }
  }
}

So what if we issued an action with a string literal that will be used as a key within Redux (e.g. products, orders)? That way, we can issue whatever valid action types are available to us (FETCH_REQUEST, etc), and we simply need to update the entity key, which will automatically carve out the space in the Store for us:
dispatch({
    entity     : "products",
    type       : "FETCH_SUCCESS",
    data       : [{id: 1}],
    lastUpdated: Date.now()
});

dispatch({
    entity    : "orders",
    type      : "FETCH_SUCCESS",
    data      : [{id: 2}, {id: 3}],
    lastUpdated: Date.now()
});

Resulting State
{
  "entities": {
    "products": {
      "isFetching" : false,
      "lastUpdated": 1526746314736,
      "data"       : [{id: 1}]
      "error"      : null
    },
    "orders": {
      "isFetching" : false,
      "lastUpdated": 1526746314943,
      "data"       : [{id: 2}, {id: 3}]
      "error"      : null
    }
  }
}

Generic Entities Reducer
function entities (state = {}, action) {
    switch (action.type) {
        case FETCH_SUCCESS: // fall through
        case FETCH_FAILURE: // fall through
        case FETCH_REQUEST: {
            return Object.assign({}, state, {
                [action.entity]: entity(
                    state[action.entity],
                    action
                )
            });
        }
        default: {
            return state;
        }
    }
};

Entity Reducer
const INITIAL_ENTITY_STATE = {
    isFetching : false,
    lastUpdated: null,
    data       : null,
    error      : null
};

function entity (state = INITIAL_ENTITY_STATE, action) {
    switch (action.type) {
        case FETCH_REQUEST: {
            return Object.assign({}, state, {
                isFetching: true,
                error     : null
            });
        }
        case FETCH_SUCCESS: {
            return Object.assign({}, state, {
                isFetching : false,
                lastUpdated: action.lastUpdated,
                data       : action.data,
                error      : null
            });
        }
        case FETCH_FAILURE: {
            return Object.assign({}, state, {
                isFetching : false,
                lastUpdated: action.lastUpdated,
                data       : null,
                error      : action.error
            });
        }
    }
}

Again, by using a generic reducer, we can dynamically store whatever we'd like into Redux, since we're using the entity string below as the key within Redux
dispatch({type: "FETCH_REQUEST", entity: "foo"});
dispatch({type: "FETCH_REQUEST", entity: "bar"});
dispatch({type: "FETCH_REQUEST", entity: "baz"});

Resulting State
{
  "entities": {
    "foo": {
      "isFetching": true,
      "error": null,
      "lastUpdated": null,
      "data": null
    },
    "bar": {
      "isFetching": true,
      "error": null,
      "lastUpdated": null,
      "data": null
    },
    "baz": {
      "isFetching": false,
      "error": null,
      "lastUpdated": null,
      "data": null
    }
  }
}

If this looks interesting, I did write a small lib (plug!) that does exactly what's described above:

*

*https://github.com/mikechabot/redux-entity

*https://www.npmjs.com/package/redux-entity
Live Demo: http://mikechabot.github.io/react-boilerplate/dist/
That said, I'm not pushing that lib whatsoever, I'm just trying to describe the approach I took given the problem I had. Your action set might be totally different, in which case, you can still implement the generic pattern, but obviously have the reducer will behave differently.


text:
Q: How to call a stored procedure (with user parameter) via code? From my C# program, I need to call a stored procedure in an Oracle database, which has the following contract:
PKG_ENTITY.ALTER_ENTITY (VARCHAR2 NAME, VARCHAR2 FULLNAME, ATTRS_TYPE ATTRS, VARCHAR2 STATUS, INTEGER OUT RESULT, VARCHAR2 OUT ERRORMSG).

The RESULT and ERRORMSG parameters are OUT parameters.
I know about the ATTRS_TYPE type that it is specified:
TYPE ATTRS_TYPE IS TABLE OF VARCHAR2(2000) INDEX BY VARCHAR2(30);

I used to call this stored procedure as follows:
 private void ExecuteNonQuery(string query, params OracleParameter[] parameters)
 {
      using (var connection = new OracleConnection(_connectionString))
      {
            var command = new OracleCommand(query, connection) { CommandType = CommandType.Text };
            connection.Open();
            command.Parameters.AddRange(parameters);
            command.ExecuteNonQuery();
      }
 }

where query =
DECLARE
    tNAME varchar2(100);
    tATTRS PKG_ENTITY.ATTRS_TYPE;

    tRESULT INTEGER;
    tERRORMSG varchar2(100);

BEGIN

    tNAME := :pEntityId;

     tATTRS(:pPropId) := :pPropValue;

    PKG_ENTITY.ALTER_ENTITY(tUSERNAME,NULL,tATTRS,NULL,tRESULT,tERRORMSG);
END;

Parameter values: pEntityId, pPropId and pPropValue are defined in the code.
Everything was fine, but then I received the requirement that it is necessary to log out values of the tRESULT and tERRORMSG parameters and with this I had great difficulties. I wanted to modify the query by adding a SELECT after calling the stored procedure. Like that:
DECLARE
    tNAME varchar2(100);
    tATTRS PKG_ENTITY.ATTRS_TYPE;

    tRESULT INTEGER;
    tERRORMSG varchar2(100);

BEGIN

    tNAME := :pEntityId;

     tATTRS(:pPropId) := :pPropValue;

    PKG_USER.ALTER_USER(tUSERNAME,NULL,tATTRS,NULL,tRESULT,tERRORMSG);
    SELECT tRESULT, tERRORMSG FROM DUAL;
END;

But such a query is not correct from the point of view of the pl/sql language. Therefore, I came to the conclusion that I need to use the stored procedure call directly and the code should look something like this:
private ProcedureResult ExecuteStoredProcedure(string procedureName)
{
    using (var connection = new OracleConnection(_connectionString))
    {
        var command = new OracleCommand(procedureName, connection) { CommandType = CommandType.StoredProcedure };
        connection.Open();
        command.Parameters.Add("NAME", OracleDbType.Varchar2, "New name", ParameterDirection.Input);
        command.Parameters.Add("FULLNAME", OracleDbType.Varchar2, "New fullname", ParameterDirection.Input);
        var attr = new EntityAttribute() { attribute1 = "id", attribute2 = "value"};
        command.Parameters.Add("ATTRS", EntityAttribute, "New fullname", ParameterDirection.Input);
        command.Parameters.Add("STATUS", OracleDbType.Varchar2, "Status", ParameterDirection.Input);
        command.Parameters.Add("RESULT", OracleDbType.Int32).Direction = ParameterDirection.Output;
        command.Parameters.Add("ERRORMSG", OracleDbType.Varchar2).Direction = ParameterDirection.Output;

        command.ExecuteNonQuery();

        return new ProcedureResult()
        {
            StatusCode = int.Parse(command.Parameters["RESULT"].Value.ToString()),
            Message = command.Parameters["ERRORMSG"].Value.ToString()
        };
    }
}

And here I had difficulties with the PKG_ENTITY.ATTRS_TYPE type definition.
TYPE ATTRS_TYPE IS TABLE OF VARCHAR2 (2000) INDEX BY VARCHAR2 (30);

I know that there is an IOracleCustomType interface, but I don't understand how to implement it correctly.
For example
[OracleCustomTypeMapping("PKG_ENTITY.ATTRS_TYPE")]
public class EntityAttribute : INullable, IOracleCustomType
{
    [OracleObjectMapping("ATTRIBUTE1")]
    public string attribute1 { get; set; }
    [OracleObjectMapping("ATTRIBUTE2")]
    public string attribute2 { get; set; }

    public bool IsNull => throw new System.NotImplementedException();
    public void FromCustomObject(OracleConnection con, IntPtr pUdt)
    {
        throw new NotImplementedException();
    }

    public void ToCustomObject(OracleConnection con, IntPtr pUdt)
    {
        throw new NotImplementedException();
    }
}

What should be the names of the fields of this class? I understand that 'ATTRIBUTE1' and 'ATTRIBUTE2' are not valid names.

A: This answer states that you cannot pass an INDEX BY VARCHAR2 associative array in C#. Instead, you can build the associative array in an anonymous PL/SQL block and call the procedure from there (as you were doing originally).
So you could use:
DECLARE
  tATTRS PKG_ENTITY.ATTRS_TYPE;
BEGIN
  tATTRS(:pPropId) := :pPropValue;

  PKG_USER.ALTER_USER(
    NAME     => :pEntityId,
    USERNAME => NULL,
    ATTRS    => tATTRS,
    STATUS   => NULL,
    RESULT   => :pResult,
    ERRORMSG => :pErrorMsg
  );
END;

Then pass in the parameters pPropId, pPropValue and pEntityId with the direction of  ParameterDirection.Input as you were doing and pass pResult and pErrorMsg with the direction of ParameterDirection.Output.

A: The signature of the PL stored procedure should be
PKG_ENTITY.ALTER_ENTITY (VARCHAR2 NAME, VARCHAR2 FULLNAME, ATTRS_TYPE ATTRS, VARCHAR2 STATUS, INTEGER OUT RESULT, VARCHAR2 OUT ERRORMSG)

Do note that OUT was added to the parameter declaration.
And in the c#code you would need to make sure the parameters are marked as output
.Parameters.Add("RESULT", OracleDbType.Int32).Direction = ParameterDirection.Output;

Once done, you would just need to assign the desired value to the parameters in your PL/SQL stored procedure.
RESULT:= 0;

A: Calling a PL/SQL procedure is much simpler (not tested, but I assume you will get the idea):
var cmd = new OracleCommand("BEGIN PKG_ENTITY.ALTER_ENTITY(:NAME, :FULLNAME, :ATTRS, :STATUS, :RESULT, :ERRORMSG); END;"), connection);
cmd.CommandType = CommandType.Text;

// should work as well
// var cmd = new SqlCommand("PKG_ENTITY.ALTER_ENTITY(:NAME, :FULLNAME, :ATTRS, :STATUS, :RESULT, :ERRORMSG)"), connection);
// cmd.CommandType = CommandType.StoredProcedure;

cmd.Parameters.Add("NAME", OracleDbType.Varchar2, ParameterDirection.Input).Value = "New name"
cmd.Parameters.Add("FULLNAME", OracleDbType.Varchar2, ParameterDirection.Input).Value = "New fullname"

par = cmd.Parameters.Add("ATTRS", OracleDbType.Varchar2, ParameterDirection.Input);
par.CollectionType = OracleCollectionType.PLSQLAssociativeArray;
var arr string[] = new string[] {"id" , "value"};
par.Value = arr;
par.Size = arr .Count;

cmd.Parameters.Add("STATUS", OracleDbType.Varchar2, ParameterDirection.Input).Value = "Status";
cmd.Parameters.Add("RESULT", OracleDbType.Int32, ParameterDirection.Output);
cmd.Parameters("RESULT").DbType = DbType.Int32;
cmd.Parameters.Add("ERRORMSG", OracleDbType.Varchar2, 100, null, ParameterDirection.Output);
cmd.Parameters("ERRORMSG").DbType = DbType.String;

cmd.ExecuteNonQuery();
var result = System.Convert.ToInt32(cmd.Parameters("RESULT").Value);
var errmsg = cmd.Parameters("ERRORMSG").Value.ToString();

Maybe this one helps: PL/SQL Associative Array Binding
Actually, I don't remember anymore why I do cmd.Parameters("RESULT").DbType = DbType.Int32;. Perhaps it was needed to make my code compatible for ODP.NET Provider 1.x and 2.0, see Mandatory Migration of .NET 1.x Stored Procedures to .NET 2.0 or Later


text:
Q: How to keep first option selected in oi-select angularjs Plunker to try I am using oi-select library to select multiple options, I want the first value from data should be selected by default, as soon as the data is available.
html code
<oi-select multiple ng-init="selectedNewRelease=releaseList[0]"
oi-options="item.releaseId for item in releaseList" ng-model="selectedNewRelease"
placeholder="Select Releases"
oi-select-options="{dropdownFilter: 'myDropdownFilter'}" id="selectedReleases"
ng-change="onReleaseChange();toggleCol();"></oi-select>

I tried with ng-init, by assigning as below :
 $scope.selectedNewRelease=$scope.releaseList[0];

This actually works but as soon as I select one or more option it removes default selected option. Any idea any link please. link for oi-select

A: when setting default value for oi-select(multiple) with a Object not Array, selecting new item will lead to overwriting the original value.
So you should init it with an Array.Something like this:
ng-init="selectedNewRelease=[releaseList[0]]

refer this plunker.

UPDATE:
oi-select used ngModel to achieve two-way-databinding, and since angular won't trigger change if the instance of the array is not changed(means ng-change won't fire without instance changed).
So after push new items, you should do something like this:
$scope.selectedNewRelease = $scope.selectedNewRelease.slice(); // create new instance for the array.

A: try this
ng-init="selectedNewRelease=releaseList[0]"  instead of ng-init="releaseList[0]"
Edit:
Or remove ng-init="selectedNewRelease=releaseList[0]"  on oi-select and assign the value in controller after load the releaseList data
like
function controller($scope)
{
Loaddropdown()
{
$http().success(function(data){
$scope.releaseList = data;
$scope.selectedNewRelease =$scope.releaseList[0]//or $scope.selectedNewRelease=$scope.releaseList[0].Id// which id means what's your value
})
}
}


text:
Q: Perforce: how to view the entire history of a single file The contents of a prior submission are missing from the latest sync. It may have been lost due an intermediate bad submit. I would like to go through the entire history to recover it.
I tried:
p4 filelog <file name>

but it lists only the changelist numbers with some metadata. I looked through the options and -l provides the most info but is still limited to changelist description

A: You probably want:
p4 annotate -a <file name>
Look for the missing contents; you'll see what revision they were added in and the last revision that they were present in (so the revision after that will indicate when they were removed and by whom).
The "Time-Lapse View" tool in P4V is a graphical version of p4 annotate that is easier to use than the CLI version IMO.
If you literally just want to see the full contents of each revision all at once, that's:
p4 print -a <file name>


text:
Q: If a derivative is a linear transformation, and for a linear transformation $f$ at $a$, $f'(a) = f(a)$, why doesn't $f''(a) = f'(a)$? Before this gets downvoted into oblivion, let me explain what I'm asking.
There's a well known theorem that states the following

If $f : \mathbb{R}^n \to \mathbb{R}^m$ is a linear transformation, then $f' = f$, where $f'$ is the $m \times n $ matrix of partial derivatives of $f$ (i.e. $f'$ is the derivative of $f$)

But we know that the derivative itself is a linear transformation $f' : \mathbb{R}^n \to \mathbb{R}^m$, so if we let $g = f'$, then $g' = f'$, and since $g'$ is the second derivative of $f$ (that being $f''$), does that not imply that all second derivatives (or any $n^{th}$ derivative) of any function $f: \mathbb{R}^n \to \mathbb{R}^m$ equals the first derivative $f'$?
This obviously cannot be the case, so there must be some error in my interpretation of this theorem. But I'm not sure what my error is. Also I apologize for asking such a silly question such as this.

A: You need to be careful. As DonAntonio pointed out in his comment, you should not confuse the derivative and the differential. Let $a\in \mathbb{R}^n$ and $f: \mathbb{R}^n \rightarrow \mathbb{R}^m$ be twice differentiable. Then you have
$$ df: \mathbb{R}^n \rightarrow L(\mathbb{R}^n, \mathbb{R}^m), \ a \mapsto (x\mapsto df_a x) $$
where $L(\mathbb{R}^n, \mathbb{R}^m)$ is the space of all linear maps from $\mathbb{R}^n$ to $\mathbb{R}^m$. This map is in general not linear. Take for example $n=m=1$ and $f(x)= x^3$, then you have
$$ df: \mathbb{R} \rightarrow L(\mathbb{R}, \mathbb{R}), \ a \mapsto (x\mapsto 3a^2 x).$$
Thus, $d(df)\neq df$ in general (you differentiate with respect to $a$, whereas $df_a(x)$ is only linear with respect to $x$).
On the other hand, you have that for every $a$ that $df_a$ is indeed linear and therefore $d(df_a)=df_a$.


text:
Q: How to do inline editing of a cell in table in an mvc application I have a table in an MVC application within cshtml where Upon clicking on a link(href) present inside td, i need an inline editing of that cell(cell has to be expanded automatically) with textbox, update and cancel buttons, clicking update button saves the data and clicking cancel should redirect to original view.
Please let me know how to implement this.

A: You probably need to use a WebGrid. Follow this tutorial - https://www.codeproject.com/Articles/996400/WebGrid-Inline-Edit-and-Delete-of-data-in-ASP-NET
Check this as well - https://www.codeproject.com/Articles/1110431/Gridview-in-ASP-NET-MVC


text:
Q: Text pasted into textarea not being inserted into database I have a textarea that inserts into a database when submitted. It works when the text is typed, but sometimes does not work when the text was pasted into the textarea. Instead, it posts successfully, no errors,
Text copied from some webpages/websites work, for example text copied from blindtextgenerator.com, but not text copied from thebestpageintheuniverse.net (just for example.)
I'm not sure what the circumstance is that cause pasted text not to be inserted into the database. I've been running tests and I don't believe it's caused by links, tabs, new lines, or the size of the text.
Here is the relevant php file
 if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    header("/venue/index.php");

$title = $_POST['title'];
$post = $_POST['post'];
$title = htmlentities($title);
$post = htmlentities($post);
      $operation = "INSERT INTO talk (title, user, post)
                          VALUES('". $title ."','". $_SESSION['name'] ."', '". $post ."');";

$result = mysqli_query($con, $operation);

}

A: When I was copying and pasting into textarea it won't allowing me to insert value in database.
Now I found the solution
HTML ---   <textarea name="description"></textarea>
PHP ---
Please add addslashes like $text = addslashes($_POST['description']);
$query = "INSERT INTO addevent(event_description) VALUES ('$text')";
mysqli_query($conn,$query) or die('unsuccessful');

This worked for me. Let me know if this worked for you also.
Thanks

A: I had the same problem and this gave me a clue as to what was wrong: How can I prevent SQL injection in PHP? like Quentin said already.  There is a setting, probably a PHP setting that isn't allowing large amounts of text to be inserted without preparing sql statements.
I changed the way I was doing INSERTS and UPDATES to the ways mentioned in the link above and here : http://php.net/manual/en/mysqli-stmt.bind-param.php


text:
Q: Execute Python code with arguments inside YAML file I have a python code where I am passing arguments to a function using CLICK package. I have dockerized this code and using the image inside a yaml file to deploy this inside minikube on my Windows machine. It worked fine without the arguments but with argument passing, it is giving field immutable error.
import click
@click.command()
@click.option(
    "--host_name",
    required=True,
    help="The host name of the db",
)
@click.option(
    "--port",
    required=True,
    help="Port where db is deployed",
)
def cli_function(host_name, port):
    CONNECTION = (
        " host="
        + host_name
        + " port="
        + port
........
    )
if __name__ == "__main__":
    cli_function()

YAML file
spec:
      containers:
        - name: database
          image: docker image
          imagePullPolicy: Always
          command: ["/bin/bash", "-c"]
          args:
            [
              "python3 /database_connection.py --host_name db-service --port 5432;",
            ]

Complete Error
The Job "timescaledbingestor" is invalid: spec.template: Invalid value: core.PodTemplateSpec{ObjectMeta:v1.ObjectMeta{Name:"", GenerateName:"", Namespace:"", SelfLink:"", UID:"", ResourceVersion:"", Generation:0, CreationTimestamp:v1.Time{Time:time.Time{wall:0x0, ext:0, loc:(*time.Location)(nil)}}, DeletionTimestamp:(*v1.Time)(nil), DeletionGracePeriodSeconds:(*int64)(nil), Labels:map[string]string{"app":"timescaledbingestor", "controller-uid":"407ae300-1455-4e41-bf88-ca7e01fe3d70", "job-name":"timescaledbingestor"}, Annotations:map[string]string(nil), OwnerReferences:[]v1.OwnerReference(nil), Finalizers:[]string(nil), ClusterName:"", ManagedFields:[]v1.ManagedFieldsEntry(nil)}, Spec:core.PodSpec{Volumes:[]core.Volume(nil), InitContainers:[]core.Container(nil), Containers:[]core.Container{core.Container{Name:"timescaledbingestor-v1", Image:"628548651667.dkr.ecr.us-west-2.amazonaws.com/timescaledb-ingester", Command:[]string{"bash", "-c", "python3 data_sync.py --host_name timescaledb-service --port 5432 --user postgres --password password"}, Args:[]string(nil), WorkingDir:"", Ports:[]core.ContainerPort(nil), EnvFrom:[]core.EnvFromSource(nil), Env:[]core.EnvVar(nil), Resources:core.ResourceRequirements{Limits:core.ResourceList(nil), Requests:core.ResourceList(nil)}, VolumeMounts:[]core.VolumeMount(nil), VolumeDevices:[]core.VolumeDevice(nil), LivenessProbe:(*core.Probe)(nil), ReadinessProbe:(*core.Probe)(nil), StartupProbe:(*core.Probe)(nil), Lifecycle:(*core.Lifecycle)(nil), TerminationMessagePath:"/dev/termination-log", TerminationMessagePolicy:"File", ImagePullPolicy:"Always", SecurityContext:(*core.SecurityContext)(nil), Stdin:false, StdinOnce:false, TTY:false}}, EphemeralContainers:[]core.EphemeralContainer(nil), RestartPolicy:"Never", TerminationGracePeriodSeconds:(*int64)(0xc00b865cb0), ActiveDeadlineSeconds:(*int64)(nil), DNSPolicy:"ClusterFirst", NodeSelector:map[string]string(nil), ServiceAccountName:"", AutomountServiceAccountToken:(*bool)(nil), NodeName:"", SecurityContext:(*core.PodSecurityContext)(0xc005cd7f00), ImagePullSecrets:[]core.LocalObjectReference(nil), Hostname:"", Subdomain:"", SetHostnameAsFQDN:(*bool)(nil), Affinity:(*core.Affinity)(nil), SchedulerName:"default-scheduler", Tolerations:[]core.Toleration(nil), HostAliases:[]core.HostAlias(nil), PriorityClassName:"", Priority:(*int32)(nil), PreemptionPolicy:(*core.PreemptionPolicy)(nil), DNSConfig:(*core.PodDNSConfig)(nil), ReadinessGates:[]core.PodReadinessGate(nil), RuntimeClassName:(*string)(nil), Overhead:core.ResourceList(nil), EnableServiceLinks:(*bool)(nil), TopologySpreadConstraints:[]core.TopologySpreadConstraint(nil)}}: field is immutable

A: Problem
Author of the question made some changes in his Job. After the update he got a "field is immutable" error.
This is caused by the fact that .spec.template field in Job is immutable and can not be updated.
Solution
Delete the old Job and create a new one with necessary changes.


text:
Q: Как разбить докториновский Array collection по 10 элементов? Всем привет, подскажите пожалуйста как можно на уровне докториновской array colletion сделать данную разбивку?
есть коллекция из 500 объектов

не могу понять как сделать чтобы у меня было 50 Array collection по 10 объектов в каждой? как в array_chunk указал колличество и функция разбила плоский массив по указанному колличеству..

A: Можно использовать slice метод:
<?php

$collection = new ArrayCollection([1, 2, 3]);
$collections = [];

$perPage = 10;
$pages = count($collection) / $perPage;

for ($index = 0; $index <= $pages; $index++) {
   $collections[] = $collection->slice($index * $perPage, min($perPage, count($collection) - index * $perPage));
}

Процесс
Для каждой страницы, извлечь срез (массив) из оригинального массива, с началом номера страницы * кол-во на странице, с длиной кол-ва на странице, либо остатка до конца массива если осталось меньше.


text:
Q: IONIC Framework - template getting reloaded multiple times (Demo of issue added at CodePen, url given below)
In app.js I have my routings defined as..
$stateProvider
    .state('login', {
      url: '/login1',
          templateUrl: 'templates/login.html',
          controller: 'AuthSignUpCtrl'
    });

and in login.html just to test I have called a method
{{test()}}

and in controller I have just created a test fn which just consoles & it gets called for 9-10 times
Note: I have verified, controller is getting loaded only once not multiple times. Also, If I add more routes in app.js the number of print keeps increasing as well.
Hope someone can help.
EDIT: controller fn
.controller('AuthSignUpCtrl', function($scope, $state) {
  $scope.test = function() {
    console.log(44)
  };
});

Result:
controllers.js:72 44
controllers.js:72 44
2controllers.js:72 44
5controllers.js:72 44
controllers.js:72 44
controllers.js:72 44
4controllers.js:72 44
controllers.js:72 44
controllers.js:72 44

Issue demo: http://codepen.io/anon/pen/XXxxpM

A: Angular bindings will keep updating until it gets a stabilized value. Since your function is not returning anything and only doing a console, therefore it is being called multiple times. Try to return some string after console and it will not be called multiple times.


text:
Q: Consecutive numbering of data.frame segments I wanted to assign consecutive numbers to segments of my data.frame. I tried like so:
library(plyr)
ex1 <- mtcars
ehh <- ddply(.data=ex1, .variables=c("cyl"), transform, brx_j = c(1:nrow(cyl)))

But it's an "Error in data.frame(list(mpg = c(22.8, 24.4, 22.8, 32.4, 30.4, 33.9, 21.5,  :
  arguments imply differing number of rows: 11, 0".
What's my mistake here?

A: We need seq_along instead of 1:nrow as 'cyl' is a single column and not a data.frame.
ddply(.data=ex1, .variables=c("cyl"), transform, brx_j = seq_along(cyl))

and with dplyr, there is row_number() function to get the sequence after grouping by 'cyl'.
library(dplyr)
ex1 %>%
     group_by(cyl) %>%
     mutate(brx_j = row_number())

A: This will also work (base R):
ex1$brx_j <- ave(1:nrow(ex1), ex1$cyl, FUN=seq_along)
ex1[order(ex1$cyl),]


text:
Q: Oracle SQL Developer - Query results window with grid missing I've just made the switch from MS sql server to Oracle.  The query tool I am using is Oracle SQL Developer.  The problem I am having is that I cannot get the query results window to stick around. The query results window being the Grid view for the results.  It seems to show up arbitrarily when I open a new "sql worksheet".  But not always.  Then once I run a query, it disappears the next time I run one.
Can anyone point me to a consistent way to leave this results grid active? Thanks so much.

A: ok guys. figured it out.  I was hitting F5 (as in MSSQL query analyzer) to run the query.  That is "run script" in this client.  F9 or Ctrl + Enter get me to the query results grid view.  Hopefully this helps someone else in the future.

A: I also faced same issue. in Script output only line apearing was

PL/SQL procedure successfully completed.

set SERVEROUTPUT ON helped in this case.


text:
Q: Is it possible to get a list of all errors for non validated fields? I have a question about collecting validation errors using Waterline. For example, I have a User model with 2 required fields. I want to send an empty request and get a list of errors that 2 required fields are missing. Is it possible? Blueprints returns only one error that one required field is missing...

A: Yes, Waterline allows logging of Usage errors. Here's a list of Validations Rules that can be implemented and captured by your error log. For empty strings, use isNotEmptyString: true.


text:
Q: Header file included only once in entire program? I know this is a common question but I still can't fully get my head around it.
In a C or C++ program generated from multiple different source and header files, will each header file be only included once in the entire code when the header guards are used?
Someone told me previously that a header file (with include guards) will get included only once in one translation unit but multiple times in the entire code. Is this true?
If it gets included only once throughout the entire code, when one file wishes to include it and the preprocessor detects that it has already been included, how does that file that wishes to use it know whereabouts in the code it was previously included ?

A: A header file with appropriate include guards will be included only once per translation unit. Strictly speaking, it may be included multiple times, but the parts between the preprocessor #ifndef and #endif will be skipped on subsequent inclusions. If done correctly, this should be all (or most) of the file.
A translation unit usually corresponds to a "source file", although some obscure implementations may use a different definition. If a separately compiled source file includes the same header, the preprocessor has no way of knowing that another file had already included it, or that any other file was part of the same project.
Note that when you come to link together multiple source files (translation units) into a single binary, you may encounter problems with multiple definitions if the header does not consist only of declarations, templates, function definitions that are marked inline, or static variable definitions. To avoid this, you should declare functions in the header and define them in a separate source file, which you link together with your other source files.

A: This is the process:
source           header   source header header
   \           /        \   |      /   /
    \         /          \  |     /   /
  PREPROCESSOR            PREPROCESSOR
       |                      |
       V                      V
 preprocessed code      preprocessed code
       |                      |
    COMPILER               COMPILER
       |                      |
       V                      V
  object code              object code
             \            /
              \          /
               \        /
                 LINKER
                   |
                   V
               executable

Preprocessing
#include is for this first step. It instructs the preprocessor to processes the specified file, and insert the result into the output.
If A includes B and C, and B includes C, the preprocessor's output for A will include the processed text of C twice.
This is a problem, since it will result in duplicate declarations. A remedy is to use preprocessor variables track whether the source code has been included (aka header guards).
#ifndef EXAMPLE_H
#define EXAMPLE_H

// header contents

#endif

The first time, EXAMPLE_H is undefined, and the preprocessor will evaluate the contents within the ifndef/endif block.  The second time, it will skip that block. So the processed output changes, and the definitions are included only once.
This is so common that there is a non-standard directive implemented by some compilers that is shorter and does not require choosing a unique preprocessor variable:
#pragma once

// header contents

You can figure out how portable you want your C/C++ code, and which header guard to use.
Headers guards will ensure the contents of each header file are present at most once in the preprocessed code for a translation unit.
Compiling
The compiler generates machine code from your preprocessed C/C++.
Generally, the header files only include declarations, not the actual definitions (aka implementations). The compiler includes a symbol table for anything that is currently missing a definition.
Linking
The linker combines the object files. It matches up the definitions (aka implementations) with the references to the symbol table.
It may be that two object files provide the definition, and the linker will take one. This happens if you've put executable code in your headers. This generally does not happen in C, but it happens very frequently in C++, because of templates.
The header "code", whether declarations or definitions, is included multiple times across all object files but the linker merges all of that together, so that it is only present once in the executable. (I'm excluding inlined functions, which are present multiple times.)

A: The header file will be included once per translation unit, yes.  It can be included multiple times per program, as each translation unit is handled separately for the compile process.  They are brought together during the linking process to form a complete program.

A: A "header file" is actually inserted by the pre-processor before compilation starts. Just think of it as just "replacing" its #include directive.
The guard ...
#ifndef MY_HEADER_H
#define MY_HEADER_H

// the "guarded" part of the header file is here...

#endif

... is executed after the replacement. So, the header may actually be included multiple times, but the "guarded" part of the text is only passed to the compiler once by the preprocessor.
So, if there are any code-generation definitions in the header, they will - of course - be included into the object file of the compilation unit (aka "module"). If the same header is #includeded in multiple modules, these will appear multiple times.
For static definitions, this is no problem at all, as these will not be visible beyond the module (aka file scope). For program-global definitions, that is different and will result in "multiple definitions" error.
Note: this is mostly for C. For C++, there are significant differences, as classes, etc. add additional complexity to what/when multiple global objects are allowed.


text:
Q: Run Flutter Package Codes on Button Click I want to make an application for use in chemical engineering calculations. Calculations are quite difficult and complex. Therefore, instead of doing the calculations in the program, I want to send data to the excel table I created and show the result to the user. I use the [flutter excel package][1] for this. But I am newbie at flutter language so I am confused about where to write the codes for the package. The page code of the application is below.
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'dart:math';
import 'package:eoscalculator/models/emodal.dart' as emodal;

class EOSPage extends StatefulWidget {
  @override
  EOSPageState createState() {
    return EOSPageState();
  }
}

// Create a corresponding State class.
// This class holds data related to the form.
class EOSPageState extends State<EOSPage> {
  // Create a global key that uniquely identifies the Form widget
  // and allows validation of the form.
  //
  // Note: This is a GlobalKey<FormState>,
  // not a GlobalKey<EOSPageState>.
  final _formKey = GlobalKey<FormState>();
  double multiplyResult;

  @override
  Widget build(BuildContext context) {
    // Build a Form widget using the _formKey created above.

    final provider = Provider.of<AppStateProvider>(context);
    final multiplyFieldController = TextEditingController();
    final multiplyFieldController2 = TextEditingController();

    count() {
      setState(() {
        multiplyResult = double.parse(multiplyFieldController.text) *
            provider.currentCompound.pc;
      });
    }

    return Scaffold(
      appBar: AppBar(
        title: Text('EOS Calculating'),
      ),
      body: Builder(
        builder: (context) => Container(
          child: Form(
            key: _formKey,
            child: Padding(
              padding: const EdgeInsets.all(18.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text(
                        "Picked Compound: " + provider.currentCompound?.name ??
                            "-"),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text("PC value: " +
                        provider.currentCompound?.pc.toString()),
                  ),
                  // TextFormField(
                  //   validator: (value) {
                  //     if (value.isEmpty) {
                  //       return 'Please enter some text';
                  //     }
                  //     return null;
                  //   },
                  // ),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text("Heat Value"),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: TextFormField(
                      decoration: new InputDecoration(
                        fillColor: Colors.white,
                        border: new OutlineInputBorder(
                          borderRadius: new BorderRadius.circular(25.0),
                          borderSide: new BorderSide(),
                        ),
                        //fillColor: Colors.green
                      ),
                      keyboardType: TextInputType.number,
                      controller: multiplyFieldController,
                      validator: (value) {
                        if (value.isEmpty) {
                          return 'Enter Value';
                        }
                        return null;
                      },
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text("Pressure value"),
                  ),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: TextFormField(
                      decoration: new InputDecoration(
                        labelText: "Enter Pressure value",
                        fillColor: Colors.white,
                        border: new OutlineInputBorder(
                          borderRadius: new BorderRadius.circular(25.0),
                          borderSide: new BorderSide(),
                        ),
                        //fillColor: Colors.green
                      ),
                      keyboardType: TextInputType.number,
                      controller: multiplyFieldController2,
                      validator: (value2) {
                        if (value2.isEmpty) {
                          return 'Enter Value';
                        }
                        return null;
                      },
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.symmetric(vertical: 16.0),
                    child: ElevatedButton(
                      onPressed: () {
                        // Validate returns true if the form is valid, or false
                        // otherwise.
                        if (_formKey.currentState.validate()) {
                          // If the form is valid, display a Snackbar.

                          count();

                          Scaffold.of(context).showSnackBar(
                              SnackBar(content: Text('Calculating...')));
                        }
                      },
                      child: Text('Calculate'),
                    ),
                  ),
                  multiplyResult != null
                      ? Text("Result : " + multiplyResult.toString())
                      : Text(""),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}

For example I want to run the codes of the excel package when I press the calculate button on this page. Below is my sample excel package codes. How can i do this?
  ByteData data = await rootBundle.load("assets/existing_excel_file.xlsx");
  var bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
  var excel = Excel.decodeBytes(bytes, update: true);

  for (var table in excel.tables.keys) {
    print(table); //sheet Name
    print(excel.tables[table].maxCols);
    print(excel.tables[table].maxRows);
    for (var row in excel.tables[table].rows) {
      print("$row");
    }
  } ```

  [1]: https://pub.dev/packages/excel


text:
Q: Does encapsulating a statement in a transaction include the triggers it fires? I have an INSERT that will fire a TRIGGER which will UPDATE an attribute on another TABLE. I need to make sure that if the INSERT is successful and the UPDATE inside the TRIGGER isn't then the whole thing should be rolled back.
Does encapsulating the INSERT in a transaction guarantee this?
If not, how can I do this?

A: The effects of a trigger 'belong' to the statement that triggered it, so everything will be rolled back together (with or without explicit transactions):
> create table a(x int);
> create table b(y int check(y > 0));
> insert into b values(1);
> create function t() returns trigger as $$
  begin
    update b set y = -1;
    return null;
  end;
  $$ language plpgsql;
> create trigger at after insert on a execute procedure t();
> insert into a values(0);
ERROR:  new row for relation "b" violates check constraint "b_y_check"
DETAIL:  Failing row contains (-1).
CONTEXT:  SQL statement "update b set y = -1"
PL/pgSQL function t() line 1 at SQL statement
> select * from a;
 x
---
(0 rows)


text:
Q: Can Protractor and Karma be used together? If Protractor is replacing Angular Scenario Runner for E2E testing, does that mean I will still be able to use it with Karma as my E2E testing framework ?

A: UPDATE. Here is a simple package I've created to add minimal Karma setup to any project with one single command npm install min-karma.

I'd like to clarify some possible misconceptions about Karma and Protractor. Karma FAQ actually does refer to Adapter for Angular's Scenario Runner, which, however, seems to be abandoned, with Protractor being recommended instead.

Karma
Karma is a test runner that will run the JavaScript files specified in you configuration file explicitly or using node-globs. (For non-JavaScript external templates, Angular's Unit Testing Guide recommends using Karma html preprocessor to compile them into JavaScript first.)
These can be all your source files, some of them, some of them plus some additional files or files irrelevant to your project, only providing some extra configuration - you name it!
 You can have multiple karma config files for different purposes, which you can run in parallel or one-by-one. Each karma process launches its own set of browsers (these are currently available).
This feature of Karma to run only a set of files is what makes it perfect for fast tests running in background upon each source file edit, and get immediate feedback, which is brilliant! The only negative is the "noisy" error reporting that will hopefully improve!

Karma is not only for unit tests
Unit test is for a single unit of your source code. In Angular's case a typical unit is Angular Component (Service, Factory, Provider, Controller, Filter, Directive etc). Remember to keep your Controllers thin, so too many unit tests for latters is a red flag.
In a unit test, every other units of code, on which this unit depends (so-called unit's dependencies) should not be tested at the same time. Instead they should be "mocked", e.g. replaced by something simple like dummy instances. Angular provides great mock environment support. Ideally you want to see all those mocks directly inside your tests, so you never need to wonder where all those dependencies come from.
Karma is just as useful for Integration Tests, where a group of source code units is tested together, with only some of their dependencies being mocked. It is important to remember that any dependency is by default provided from your source code modules (as long as those modules either injected directly in your tests, or they are dependencies of other modules injected (in which case you don't need to inject them, but no harm to do so). The mocked dependencies will override the provided ones.
Running Fast and Frequent is the main feature of Karma. This means you want to avoid any server requests, any database queries, anything that can take longer than fractions of seconds. (Otherwise it will NOT be fast!) Those long processes are ones you want to mock. This also explains why it is a bad practice to put raw low level services like $http directly inside your controllers or any complicated business logic units. By wrapping those low level outside communication services into smaller dedicated services, you make it much easier to "mock them away".
What Karma does not do is running your site as it is, which is what End-to-End (E2E) testing is. In principle, you could use Angular's internal methods to recreate the site or its pieces. Which, for small pieces, can be useful, and a fast way e.g. to test directives.
It is, however, not recommended way to throw complicated code inside your tests. The more you do it, the more chance is that you make errors in that code instead of what you are actually testing.
That is why I personally dislike the often mentioned complicated way of testing methods using low level methods like $http. It works cleaner to isolate any reference to low level methods into dedicated methods of your own, whose single responsibility is to make http requests. These dedicated methods should be able to work with real backend, not a fake one! Which you can easily test - manually or even perfectly fine with Karma running with another special config, as long as you don't mix that config with the one usually used to run Karma regular and fast.
Now, having your dedicated small services tested, you can safely and easily mock them to test your other logic and put these tests into your regular Karma setup.

To summarize. Use Karma to run any set of JavaScript files. It is (should be) fast. You don't see your complete app, so can't test the final result effectively and reliably. Would I run it with Protractor? Why would I? Running Protractor would slow down my tests, defeating the purpose of Karma. It is easy to run Protractor separately.

Protractor
Protractor is:

an end-to-end test framework for AngularJS applications. Protractor runs tests against your application running in a real browser, interacting with it as a user would.

So Protractor does exactly what Karma doesn't - run your real final application. This reveals its both power and limitations:
Running complete application is the only reliable final test that your application works as expected. You can write up complete user story scenarios and put them into your tests!
But it is harder to track errors without isolating individual units of your source code. This is why you still need Karma to test your JavaScript code first.

Now would I want to run Protractor with Karma? I surely can run them in separate terminal windows, in parallel. I could, in principle, have them share test files if I need to, but normally I'd rather not. Why? Because I want to keep my tests small with single dedicated purpose.
The only exception would be a file defining testing macros useful for both runners. This, however, would not be a test file but a macro definition file.
Other than that, I like a clear separation between my tests. Those to be run frequently and fast, and those for the complete app. That makes a clear separation between when using Karma and when Protractor.

A: Not recommended by the current maintainer of Protractor:

https://github.com/angular/protractor/issues/9#issuecomment-19927049
Protractor and Karma should not be used together; instead they provide separate systems for running tests. Protractor and Karma cover different aspects of testing - Karma is intended mostly for unit tests, while Protractor should be used for end to end testing.
Protractor is built on top of WebDriverJS, which uses a Selenium/WebDriver server to provision browsers and drive test execution. Examples of pure WebDriverJS can be found here: http://code.google.com/p/selenium/wiki/WebDriverJs

And

https://github.com/angular/protractor/issues/9#issuecomment-19931154
Georgios - I think it makes sense to keep Protractor and Karma separate - for end to end tests, you want the native event driving and flexibility of webdriver, while for unit tests you want fast execution and autowatching of files.

A: Karma is a test runner provided by the Angular team, Karma will execute your tests in multiple browsers which shall ensure that our application is compatible in all browsers.
Unit Test for angular js can be used karma + jasmine
Jasmine is a javascript unit testing framework and will provide us with utilities to test our application. This works best on the Angular framework and thus, our choice of "automated unit testing tool".
https://github.com/shahing/testingangularjs
And Protractor is an end-to-end test framework for Angular and AngularJS applications.
   Protractor runs tests against your application running in a real browser, headless browsers , cross browser testing and can be hosted on saucelabs.
https://github.com/shahing/Protractor-Web-Automation

A: Yes, you can use karma and protractor together. Karma is used for unit testing the component you created using angular command you can test those components using karma.
Protractor is used for end to end test. It is mainly used for UI testing.


text:
Q: the if else if statement not working the way I thought would have worked I was making a winner checking system where, if I get 2 same numbers from a die than the innerHTML of the result should change from 'result' to 'you win!', if I didn't get same numbers, then the innerHTML of the 'p' should keep showing 'keep trying' but the if else if statement I was working with didn't give me the output I needed and instead of showing 'You win' or 'keep trying' in different cases, it keeps showing 'you win' when clearly my both numbers don't match with each other.
here's the js code:
var dice1 = document.getElementById('you');
var dice2 = document.getElementById('cpu');
var result = document.getElementById('rslt');
var button = document.getElementById('btn');

// Button Interaction

function randomNumbers() {
  document.getElementById('you').innerHTML = Math.floor(Math.random() * 6);
  document.getElementById('cpu').innerHTML = Math.floor(Math.random() * 6);
}

// Result

function checkWin() {
  if (you.innerHTML == cpu.innerHTML) {
    return rslt.innerHTML = "You Win!";

  } else if (you.innerHTML != cpu.innerHTML) {
    return rslt.innerHTML = "Keep on trying!";

  } else {

    return rslt.innerHTML = "Keep on trying!";
  }
}

checkWin();

Please tell me what mistake I did. I'm a novice in programming with javascript, so please dont bully me.
Thank you if you read this far!

A: Wrap into variables and then try to use if else or as you already did with dice1 and dice2
  var you = document.getElementById('you').innerHTML = Math.floor(Math.random()*6);
  var cpu = document.getElementById('cpu').innerHTML = Math.floor(Math.random()*6);

if(you == cpu)

A: You should call checkwin() when you button is pressed
Try this code
  var dice1 = document.getElementById('you');

    var dice2 = document.getElementById('cpu');

    var result = document.getElementById('rslt');

    var button = document.getElementById('btn');

    // Button Interaction

    function randomNumbers(){

    document.getElementById('you').innerHTML = Math.floor(Math.random()*6);
    document.getElementById('cpu').innerHTML = Math.floor(Math.random()*6);
    checkWin();
    }

    // Result

    function checkWin(){

    if(you.innerHTML == cpu.innerHTML)

    { return rslt.innerHTML = "You Win!";

    } else if (you.innerHTML != cpu.innerHTML)

    { return rslt.innerHTML = "Keep on trying!";

    } else {

        return rslt.innerHTML = "Keep on trying!";
    }

    }


text:
Q: Consulta sql sobre una relación Estaba intentado crear una consulta pero me es muy difícil, primero muestro la estructura y una parte de los datos de la tabla en cuestión.
mysql> desc rel_cat_videos;
+-------+---------+------+-----+---------+----------------+
| Field | Type    | Null | Key | Default | Extra          |
+-------+---------+------+-----+---------+----------------+
| id    | int(11) | NO   | PRI | NULL    | auto_increment |
| video | int(11) | NO   |     | NULL    |                |
| cat   | int(11) | NO   |     | NULL    |                |
+-------+---------+------+-----+---------+----------------+

mysql> SELECT * FROM rel_cat_videos LIMIT 20;
+----+-------+-----+
| id | video | cat |
+----+-------+-----+
|  1 |     1 |   5 |
|  2 |     1 |  73 |
|  3 |     1 |   2 |
|  4 |     1 |  15 |
|  5 |     2 |   5 |
|  6 |     2 |  69 |
|  7 |     2 |  78 |
|  8 |     2 |  80 |
|  9 |     3 |   5 |
| 10 |     3 |  36 |
| 11 |     3 |  38 |
| 12 |     3 |   6 |
| 13 |     3 |  34 |
| 14 |     3 |   3 |
| 15 |     4 |  74 |
| 16 |     4 |  87 |
| 17 |     4 |  29 |
| 18 |     4 |   9 |
| 19 |     5 |  56 |
| 20 |     5 |   2 |
+----+-------+-----+

Lo que intento conseguir es que me devuelva un video por cada categoría ("cat") pero a la vez que no se repita ningún video


text:
Q: Visual Studio Express ClickOnce - Can't Publish .NET 4.5 Offline Installer with application I'm trying to publish an application with a pre-req being .NET 4.5. I have Clicked create a setup program to install prereq components and I have selected to include .NET Framework 4.5
I have Selected download pre-req from the following location: and set a link to my server. This is the error when I try Publish it:
To enable 'Download prerequisites from the same location as my application' in the Prerequisites dialog box, you must download file 'DotNetFX45\dotNetFx45_Full_x86_x64.exe' for item 'Microsoft .NET Framework 4.5 (x86 and x64)' to your local machine. For more information, see http://go.microsoft.com/fwlink/?LinkId=239883.
I've tried with .NET 4.5 and .NET 4.5.1, downloaded to local PC and Server and still have the same issue.
Anyone know what the go is? Thanks.

A: I usually set it to get the files from MS so this is off the top of my head but I think that if you add the redist to the solution and than Click on the "Application Files" button in the Publish tab of your project properties and make sure that the .NET 4.5 redistributable is in the list and all the properties are set properly you should be good to go...

A: Have you followed the instructions in the link? http://msdn.microsoft.com/en-us/library/hh873130(v=vs.110).aspx
You need to download and place the installer in the appropriate directory then map it inside the XML (the instructions under heading "To add an installer package for the .NET Framework 4.5").


text:
Q: How to determine the output frequency of a full-wave rectifier using an oscilloscope?
Input frequency: 60 Hz.
Theoretically, I should get a 120 Hz output frequency.

A: How often does the waveform repeat? It looks like about every four divisions, or 8 ms. The frequency is the inverse of that, or about 125 Hz.
If you want a more accurate measurement, capture several cycles and measure the period as 1/n times the duration of n cycles.


text:
Q: Copy postgres table to another schema using liquibase I want to copy a set of tables from one schema to another schema on the same database. I use postgres v9 on Ubuntu and we use Liquibase for doing any changes to our database.
I am able to create new tables using code similar to below, but I need to create the new table as a select * from another table
<changeSet author="jDoe" id="1">
    <createTable tableName="abcproxy">
        <column name="errtime" type="datetime">
            <constraints primaryKey="true" nullable="false"/>
        </column>
        <column name="errmsg" type="varchar(255)">
            <constraints nullable="false"/>
        </column>
        <column name="version" type="integer">
            <constraints nullable="false"/>
        </column>
    </createTable>

I know we can do this via sql as mentioned here, but I want to do it via Liquibase XML configurations. Also, it would be great if we can get the grants/privileges to be copied over using liquibase config.
I can try to move the tables as mentioned here but as of now, my requirement is to copy and not move the tables.
Please let me know any suggestions to achieve the same. Thanks.

A: You can use sql tag inside your changeSet, e.g.:
<changeSet author="jDoe" id="1">
    <precondition onFail="MARK_RUN">
        <not>
            <tableExists tableName="abcproxy" schemaName="newSchema"/>
        </not>
    </precondition>
    <sql>create table newSchema.abcproxy as select * from oldSchema.abcproxy</sql>
</changeSet>

Althow, there's an issue with this approach: this changeSet will copy all the data from your table in old schema, but not the keys.


text:
Q: ptyhon mysql the query result is always the same (in loop) The Percentages tab is regularly updated every 60 seconds by another python process.
In the cycle every 10 seconds I check the table but I always have only one result.
from pickle import TRUE
import ccxt
import mysql.connector
from datetime import datetime, date
import time
mydb = mysql.connector.connect(
  host="127.0.0.1",
  user="xxxxx",
  password="xxxxxx",
  database="xxxx"
)
mycursor = mydb.cursor()

cl = 0
while True:
  now = datetime.now()
  date_time = now.strftime("%m/%d/%Y %H:%M:%S")
  cls = str(cl)
  print (date_time + ' start ' + cls + ' cycle\n')
  sql= "select * from Percentuali order by Id desc limit 1"
  mycursor.execute(sql)
  myresult = mycursor.fetchone()
  print (myresult)

# end ---------------

Output:
(203, datetime.datetime(2022, 4, 29, 12, 15, 11), -0.0222675, None)
(203, datetime.datetime(2022, 4, 29, 12, 15, 11), -0.0222675, None)
(203, datetime.datetime(2022, 4, 29, 12, 15, 11), -0.0222675, None)
(203, datetime.datetime(2022, 4, 29, 12, 15, 11), -0.0222675, None)

... every time.
I'm testing on a raspberry with mariadb 10 (10.0.28-MariaDB-2 + b1 Raspbian testing-staging) and use heidisql to verify that the update is successful

A: Resolved:
sql= "select * from Percentuali order by Id desc limit 1"
mycursor.execute(sql)
myresult = mycursor.fetchone()
mydb.commit()