text:
Q: Liferay Portlet and JSF : Redirect during Render Phase I have a problem to implement a simple HTTP redirection.
I use Liferay 6.0.6, our portlets are build with JSF2.0 / PortletFaces.
I want to call a redirection when a view is loaded (and not when an action is triggered). Currently, my function is called by the PreRenderView listener.
<f:metadata>
  <f:event listener="#{myControler.dispatch}" type="preRenderView" />
</f:metadata>

In this function, i can check the permissions, do other stuff, and in some cases I want to redirect the user to a new page (not another view).
I tried several methods, unsuccessfully.
Specifically, I thought that this method would work :
getFacesContext().getExternalContext().redirect(url);
getFacesContext().responseComplete()
// => Can only redirect during ACTION_PHASE

This error is logical, but is there a solution to force the redirection.
It could be realized in another function, called otherwise, I only need the Hibernate Session (set at the beginning of the Render Phase)
Have you ideas to resolve this problem?
Thanks!
ps : <redirect /> or ?faces-redirect don't work with the portlets.

A: You can't do this in the render phase by design. Reasons:

*

*It's possible that portlets are rendered asynchronously, so the page might already be displayed when your portlet is being rendered

*It's possible that parts of the page are already delivered to the client, so that the HTTP Headers are already sent - for this reason, by design you don't have access to them in the render phase

*What would be the expected outcome if two portlets rendered on the same page would decide that they'd like to forwards to another page? Who would win?

A hacky workaround is to render some javascript redirect, but this is veeeery un-portal-like and can mess up other's expectations (plus, parts of the page might already be rendered, causing your users to fill a form only to be redirected by your javascript routine.
Please rethink the problem and come up with a different solution - it's really worth doing this in a portal environment.

A: I use this and it works for me:
    public void preRenderView() throws IOException {

        if (!checkUtente()) {

              FacesContext fc = FacesContext.getCurrentInstance();

              NavigationHandler navigationHandler = fc.getApplication().getNavigationHandler();

              navigationHandler.handleNavigation(fc, null, "errore.xhtml?faces-redirect=true");

              fc.renderResponse();
        }

    }

A: Use the below method it will work
public static void redirect(final String url) throws IOException {

            final javax.portlet.PortletResponse portletResponse
            = getPortletResponse();

            if (portletResponse instanceof ActionResponse) {

                final javax.portlet.ActionResponse actionResponse
                = (javax.portlet.ActionResponse) portletResponse;

                actionResponse.sendRedirect(url);

            } else if (portletResponse instanceof ResourceResponse) {

                final FacesContext ctx = FacesContext.getCurrentInstance();
                if (ctx.getPartialViewContext().isPartialRequest()) {

                    final ResourceResponse portletResResp
                    = (ResourceResponse) portletResponse;
                    PartialResponseWriter pwriter;
                    final ResponseWriter writer = ctx.getResponseWriter();
                    if (writer instanceof PartialResponseWriter) {
                        pwriter = (PartialResponseWriter) writer;
                    } else {
                        pwriter = ctx.getPartialViewContext()
                        .getPartialResponseWriter();
                    }
                    portletResResp.setContentType(Constants.CONTENT_TYPE);
                    portletResResp.setCharacterEncoding(Constants.ENCODING_TYPE);
                    // addResponseHeader("Cache-Control", "no-cache");
                    pwriter.startDocument();
                    pwriter.redirect(url);
                    pwriter.endDocument();
                    ctx.responseComplete();
                } else {
                    throw new UnsupportedEncodingException(
                            "Can only redirect during RESOURCE_PHASE "
                            + "if a Partial-(JSF AJAX)-Request  has "
                            + "been triggered");
                }
            } else {
                throw new UnsupportedEncodingException(
                        "Can not redirect during the current phase: "
                        + portletResponse.getClass().getSimpleName());
            }
        }


text:
Q: How to get GTK syntax highlighting in GEdit? I just started using GTK to develop my GUI applications. I'm using GEdit as my text-editor, so how can I get the following to be included in the syntax highlighting:
GtkWidget *window;
GtkWidget *button
GtkWidget *box1;

gtk_init(&argc, &argv);

as if it were like this:
int x = 3;

A: You can extend Gedit's syntax with a .lang file which contains XML:
http://library.gnome.org/devel/gtksourceview-2.0/stable/lang-tutorial.html
http://library.gnome.org/devel/gtksourceview-2.0/stable/lang-reference.html
So you could change your C language file to add GTK+ data types. It wouldn't surprise me that someone already wrote it, though.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Real server-client C# program over internet Simple question, but after weeks of search no luck. I need to create a server-client program. Everything works well with localhost, but I need it over the internet. I work under Linux (Ubuntu).
Server:
public class SocketServer
{
    private const int PORT_NO = 8001;

    public SocketServer()
    {
        //---listen at the specified IP and port no.---
        var listener = new TcpListener(IPAddress.Any, PORT_NO);
        Console.WriteLine("Socket server started.");
        listener.Start();

        while (true)
        {
            //---incoming client connected---
            var client = listener.AcceptTcpClient();

            //---get the incoming data through a network stream---
            var nwStream = client.GetStream();
            var buffer = new byte[client.ReceiveBufferSize];

            //---read incoming stream---
            var bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);

            //---convert the data received into a string---
            var dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
            Console.WriteLine($"{dataReceived}");
            client.Close();
        }
    }
}

Client code:
public class Client
{
    private const int PORT_NO = 8001;
    private const string SERVER_IP = "xxx.xx.246.1";

    public void Run()
    {
        while (true)
        {
            var textToSend = Console.ReadLine();

            //---create a TCPClient object at the IP and port no.---
            var client = new TcpClient(SERVER_IP, PORT_NO);
            var nwStream = client.GetStream();
            var bytesToSend = Encoding.ASCII.GetBytes(textToSend ?? string.Empty);

            //---send the text---
            Console.WriteLine("Sending : " + textToSend);
            nwStream.Write(bytesToSend, 0, bytesToSend.Length);
        }
    }
}

For IP I used www.whatsmyip.org, and I got an error:
System.Net.Sockets.SocketException (0x80004005): Connection refused

What am I missing? Is there some real example, no just with localhost?


text:
Q: Using Curl To Download Files I am currently trying to learn how to use the curl command to download some data and have run into some difficulty. So I have a list of stock symbols (eg AAPL, GOOG, TGT, ...) and I want to use this link (http://ichart.finance.yahoo.com/table.csv?s=YHOO&d=0&e=28&f=2010&g=d&a=3&b=12&c=1996&ignore=.csv) to download the data I need into a csv file. I got the idea from another stackoverflow questions top answer (source of historical stock data).
So here is my attempt
$ for i in $(cat ticker.txt); do curl -o $i.csv http://ichart.finance.yahoo.com
/table.csv?s=$i&d=0&e=28&f=2010&g=d&a=3&b=12&c=1996&ignore=.csv; done

So I have a text file with all of the tickers I'm interested in and this downloads some files, but then the process seems to hang up and just stops at the end. Also, the correct information doesn't seem to be downloaded (ie instead of getting data from 2010 to 1996 I get all available data starting from 2014 to some random year).
I am using Git Bash because I'm running Windows 7 and don't have a UNIX style OS to practice these different commands with. Can someone out there help me with this issue and maybe point out what I'm doing wrong?

A: You should quote the URL:
for i in $(cat ticker.txt); do curl -o $i.csv "http://ichart.finance.yahoo.com
/table.csv?s=$i&d=0&e=28&f=2010&g=d&a=3&b=12&c=1996&ignore=.csv"; done

I don't know the length of URL in this thread


text:
Q: making a map of two separate continuous data sets I need to map two separate data sets, methane and ethane emissions, on the same map using ggmap. Here's a head of the data:
    DateTime     CH4(ppm)      C2H6(ppb) Latitude Longitude
1 2021-08-03 07:44:03 2.17380  -9.98494 44.26121 -88.40225
2 2021-08-03 07:44:03 2.16387  -9.39870 44.26121 -88.40225
3 2021-08-03 07:44:03 2.17527  -8.66678 44.26121 -88.40225
4 2021-08-03 07:44:03 2.17296 -10.03360 44.26121 -88.40225
5 2021-08-03 07:44:03 2.17209  -8.59478 44.26121 -88.40225
6 2021-08-03 07:44:03 2.17254  -8.43455 44.26121 -88.40225

My attempt thus far has been to try to separate the data into two different data frames with the following code:
Methane_Data <- aeris_data[,-c(1:33,35:45)] %>%
  mutate(species = "Methane")
colnames(Methane_Data) <- c("Concentration", "Latitude", "Longitude", "Species")

Ethane_Data <-  aeris_data[,-c(1:35,37:45)] %>%
  mutate(species = "Ethane")
colnames(Ethane_Data) <- c("Concentration", "Latitude", "Longitude", "Species")

and then attempting to rbind them like this:
Species_Data <- rbind(Methane_Data, Ethane_Data)

However, this only produces a map with one giant emissions scale that combines two different units (ppb and ppm), and understandably so. I just don't know how to go about this code other than this.
For reference, here's the map code I'm using:
Map <- get_map(location=c(lon=map_long, lat=map_lat), source="google", maptype="satellite", zoom=map_zoom)

Map_Plot <-ggmap(Map, extent = "panel", ylab = "Latitude", xlab = "Longitude")
Map_Plot + geom_point(data = Species_Data, aes(x = as.numeric(Longitude), y = as.numeric(Latitude), color = Concentration), size = 1, alpha = 0.5) +
  scale_colour_gradientn(colours = myPalette(100), name = map_color_units_ethane) +
  labs( y = "Latitude", x = "Longitude", title = "Ethane 08-03-2021") +
  theme(plot.title = element_text(size = rel(2))) +
  theme(axis.title.x = element_text(size = rel(1.5))) +
  theme(axis.text.x = element_text(size = rel(1))) +
  theme(axis.ticks.length = unit(1, "cm")) +
  theme(axis.text.y = element_text(size = rel(1))) +
  theme(axis.title.y = element_text(size = rel(1.5), angle = 90)) +
  theme(legend.position = c(1.3, .5))

Thanks to anyone who can help.


text:
Q: Looking for MySQL Default yesterday date I am using MySql via terminal. Below is the command I have used to create table but it is showing date in YYYY-MM-DD HH:MM:SS (example: 2018-05-25 14:12:47)
create table test (foo int, ts timestamp default CURRENT_TIMESTAMP);

But I want by default it take yesterday date every time I insert data in (YYYY-MM-DD) format.
Please help me to find the command.
Thanks,
Amit

A: According to the official MySQL documentation https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add, you can do like this:
If you want to store the "yesterday" on creation:
ts TIMESTAMP NOT NULL DEFAULT NOW() - INTERVAL 1 DAY

If you want to store the "yesterday" on every update:
ts TIMESTAMP NOT NULL DEFAULT NOW() ON UPDATE NOW() - INTERVAL 1 DAY

According to this answer Select records from NOW() -1 Day:

NOW() returns a DATETIME.
And INTERVAL works as named, e.g. INTERVAL 1 DAY = 24 hours.
So if your script is cron'd to run at 03:00, it will miss the first
  three hours of records from the 'oldest' day.
To get the whole day use CURDATE() - INTERVAL 1 DAY. This will get
  back to the beginning of the previous day regardless of when the
  script is run.

Hope it helps!

A: DEFAULT values in MySQL must be constants. They can't be functions or expressions (with the exception of CURRENT_TIMESTAMP).
Source: http://dev.mysql.com/doc/refman/5.6/en/data-type-defaults.html
In addition you can add a trigger to your table for your requirement
Simply Create a Table without constraint
create table test (foo int, ts timestamp );

Then add a trigger to this table
CREATE TRIGGER settime
BEFORE INSERT on test
FOR EACH ROW BEGIN
   IF new.`ts ` is null THEN
    SET new.`ts ` = DATE_ADD(NOW(), INTERVAL -1 DAY);
    END IF;
END;


text:
Q: foreach to foreach array in angularjs I am trying to update specific data of an array that is being displayed thru ng-repeat.
Given the datas:
$scope.cartItems = [];
$scope.items = [{code: 'ABC', cash:'20.00', charge: '25.00'},
{code: 'DEF', cash:'10.00', charge: '15.00'},{code:
'GHI',cash:'30.00', charge: '35.00'}];

then i have this table
Item | Price | Action
ABC  | 20.00 | Add
DEF  | 10.00 | Add

ng-click="add(Item,Price)"
$scope.add = function(Item,Price){
var itemscart = {};
itemscart.code = Item;
itemscart.price = Price;

$scope.cartItems.push(itemscart)
}

and is being displayed like this thru html table.
ng-repeat="cart in cartItems"
Item | price | bracket
ABC  | 20.00 | Cash //dropdown
DEF  | 10.00 | Cash //dropdown

And i have this dropdown select tag with option value; "Cash" or "Charge"
If in the dropdown i selected charge. The expected output of the html table must be:
Item | price | braket
ABC  | 25.00 | Charge //dropdown
DEF  | 15.00 | Charge //dropdown

I have tried:
if($scope.optionval == 'Charge'){
  var price = 0;
  $scope.cartItems.forEach(function(v){
    if(v.code == ($scope.items.forEach(function(c){c.code; price =
c.charge; })))
      v.PRICE = price;
    console.log(v.PRICE) //gets the last row
    console.log(price) //null

  });
}

A: As per your displayed and expected table, you can try something like:

*

*On change of CASH to CHARGE, make a function call on ng-change in
which pass the selected object with selected 'braket'.

*Then in function call you can filter data.

A: In my opinion you could use a different approach, like using ng-show or ng-if directives to get the results you are trying to achieve
Try adding a custom field in your $scope in order to store which price should be shown, then you have two choices: to modify every field or separately:
Display independiently:
app.js
$scope.items = [{code: 'ABC', cash:'20.00', charge: '25.00', displaying:'cash'},{...}

HTML

    Item
    Price

   {{cart.item}}
   {{cart.cash}}
   {{cart.charge}}
   {{cart.displaying}}
   *Dropdown to modify this specific 'displaying' field*

Every field at the same time:
app.js
$scope.displayingitems = 'cash'

HTML
*Dropdown to modify this specific 'displaying' field*

    Item
    Price

   {{cart.item}}
   {{cart.cash}}
   {{cart.charge}}
   {{displayingitems}}


text:
Q: How to show Login link when user is not login? I am using ASP.NET Core Blazor server-side, .NET 5 version 5.0.100-preview.8.20417.9 , Microsoft SQLServer 2019 database, ASP.NET Core Identity, Microsoft Visual Studio Community 2019 Preview - Version 16.8.0 Preview 2.1 . I want when no user login, show Login link. When user login success, show web-app. My code is below.
File MainLayout.razor
@inherits LayoutComponentBase
@implements IDisposable

@inject Microsoft.AspNetCore.Components.NavigationManager NavigationManager
@inject IJSRuntime JSRuntime

@using Microsoft.JSInterop;
<AuthorizeView>
    <Authorized>

        <button class="navbar-toggler" @onclick="@ToggleNavMenu">

        </button>

        @*

*@

        <NavMenu />

Foo

        @Body

<ThemeSwitcher @bind-Shown="@ThemeSwitcherShown"></ThemeSwitcher>
    </Authorized>
</AuthorizeView>

@if(!HttpContext.User.Identity.IsAuthenticated)
{
    Log in
}

@code {
    string NavMenuCssClass { get; set; } = "";

    void ToggleNavMenu()
    {
        NavMenuCssClass = string.IsNullOrEmpty(NavMenuCssClass) || NavMenuCssClass.Contains("d-none") ? "d-block d-xl-none" : "d-none d-xl-flex";
        ThemeSwitcherShown = false;
    }

    bool themeSwitcherShown = false;
    bool ThemeSwitcherShown
    {
        get => themeSwitcherShown;
        set
        {
            themeSwitcherShown = value;
            InvokeAsync(StateHasChanged);
        }
    }

    void ToggleThemeSwitcherPanel()
    {
        ThemeSwitcherShown = !ThemeSwitcherShown;
    }

    string UriFragment { get; set; } = "";

    void OnLocationChanged(object sender, LocationChangedEventArgs args)
    {
        if (!string.IsNullOrEmpty(NavMenuCssClass))
        {
            NavMenuCssClass = "";
            InvokeAsync(StateHasChanged);
        }
    }

    protected override void OnInitialized()
    {
        base.OnInitialized();
        NavigationManager.LocationChanged += OnLocationChanged;
    }

    protected override Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            JSRuntime.InvokeAsync<string>("ScrollToTarget");
        }
        return base.OnAfterRenderAsync(firstRender);
    }

    void IDisposable.Dispose()
    {
        NavigationManager.LocationChanged -= OnLocationChanged;
    }
}

My idea focus at these lines
<AuthorizeView>
    <Authorized>

    </Authorized>
</AuthorizeView>

@if(!HttpContext.User.Identity.IsAuthenticated)
{
    Đăng nhập
}

but error at
@if(!HttpContext.User.Identity.IsAuthenticated)

(help me fix this part)
Error

How to show Login link when user is not login?

A: This is demonstrated in LoginDisplay.razor from the template.
    <AuthorizeView>
        <Authorized>

        </Authorized>
        <NotAuthorized>
             Đăng nhập
        </NotAuthorized>
    </AuthorizeView>


text:
Q: splitting strings in R with backslash I am trying to parse out a file address and want to extract both the file location and the file name.  For example, I want this:
"C:\Users\carriebrown\Desktop\test\Project_8754.csv"

to become this:
"C:\Users\carriebrown\Desktop\test\" and "Project_8754.csv"

I am attempting to use:
strsplit(file,'\\', fixed=TRUE)

But continue to the get the error:

Error in strsplit(file, "\", fixed = TRUE) : non-character argument

Is there a way to do this in R with strsplit? If not, is there a way to do it in a different manner?

A: How about this?
path <- unlist(strsplit('C:\\Users\\carriebrown\\Desktop\\test\\Project_8754.csv','\\',
                        fixed=TRUE))
file <- path[length(path)]
path <- paste(path[-length(path)], collapse='\\')
path
#[1] "C:\\Users\\carriebrown\\Desktop\\test"
file
#[1] "Project_8754.cs


text:
Q: Add a class on hover remove class on second hover I want to add a class on hover but not remove it when mouse leaves. Instead it must be removed on the second mouse hover. So on mouse hover add class. Mouse leaves class remains. Mouse hovers again class is removed.
This code adds the class but if the mouse leaves the class is removed which is not what I'm trying to achieve.
jQuery('.menuButton').hover(function(){
  jQuery('.mainMenuDrop').addClass('show')
}, function() {
  jQuery('.mainMenuDrop').removeClass('show')
});

A: To achieve your requirement of add on first entry and remove on second entry, you can change your existing code:
jQuery('.menuButton').hover(function(){
  jQuery('.mainMenuDrop').addClass('show')
}, function() {
  jQuery('.mainMenuDrop').removeClass('show')
});

to use .toggleClass
jQuery('.menuButton').hover(function(){
  jQuery('.mainMenuDrop').toggleClass('show')
}, function() {
  // nothing here
});

As jquery .hover binding is just syntax for mouseenter and mouseleave and you don't need mouseleave, this can be simplified to:

jQuery('.menuButton').on("mouseenter", function() {
  jQuery('.mainMenuDrop').toggleClass('show');
});
div { border: 1px solid black; padding: 20px; width: 100px; }
.show { background-color: pink; }

point at me

changes here


text:
Q: Usuário sem duplicação Bom galera, tenho uma tela de registrar usurário mas quero fazer com que só exista um usuário com tal matricula e e-mail, porem não sei por onde começa a programa essa parte, alguém da uma força ai!!!
<?php

include("includes/conexao.php");//conexão com o banco

$query = "INSERT INTO usuario (nome, sobrenome, matricula, email, senha)
      VALUES (:nome, :sobrenome, :matricula, :email, :senha)";

$statement = $connection->prepare($query);

$valores = array();
$valores[':nome'] = (isset($_POST['primeiroNome']) ? $_POST['primeiroNome'] : '');
$valores[':sobrenome'] = (isset($_POST['sobrenome']) ? $_POST['sobrenome'] : '');
$valores[':matricula'] = (isset($_POST['matricula']) ? $_POST['matricula'] : '');
$valores[':email'] = (isset($_POST['email']) ? $_POST['email'] : '');
$valores[':senha'] = (isset($_POST['senha']) ? $_POST['senha'] : '');

        /*--Aqui mostra se a-s senhas se correspondem se sim, ela não faz nada, se não, execulta o script abaixo d-o head*/
    if($_POST) {
            $senha           = $_POST['senha'];
            $confirma_senha  = $_POST['confirma_senha'];
            if ($senha == "") {
                $mensagem = "Aviso: Senha não foi alterada!";
            } else if ($senha == $confirma_senha && $statement->execute($valores)) {

            } else {

            }

        }

?>

script  para ver se deu certo cadastrar o usuário

Aqui está o meu formulário
<form method="POST" action="registro.php" onsubmit="return validarSenha()"name="formulario">

                     Primeiro nome
                     <input type="text" class="form-control" id="primeiroNome" name="primeiroNome" placeholder="Digite seu primeiro nome" required="required">

                     Sobrenome
                     <input type="text" class="form-control" id="Sobrenome" name="sobrenome" placeholder="Digite seu Sobrenome" required="required" autofocus="autofocus">

               Matrícula
               <input type="text" class="form-control"  name="matricula" placeholder="Digite sua matrícula" required="required" autofocus="autofocus">

               E-mail
               <input type="email" class="form-control" id="email" name="email" placeholder="Digite seu email" required="required" autofocus="autofocus">

                     Senha
                     <input type="password" class="form-control" id="senha" name="senha" placeholder="Digite sua senha" required="required" autofocus="autofocus">

                     confirmar senha
                     <input type="password"  class="form-control" id="confirmaSenha" name="confirma_senha" placeholder="Confirme sua senha" required="required" autofocus="autofocus">

               <input type="submit" class="btn btn-primary btn-block" value="Registra-se"/>

               Esqueceu sua senha?
               Login?

         </form>

A: É só você verificar se já existe alguém no banco com a mesma matricula ou email, segue o código:
include("includes/conexao.php");//conexão com o banco

$query = "INSERT INTO usuario (nome, sobrenome, matricula, email, senha)
      VALUES (:nome, :sobrenome, :matricula, :email, :senha)";

$statement = $connection->prepare($query);

$valores = array();
$valores[':nome'] = (isset($_POST['primeiroNome']) ? $_POST['primeiroNome'] : '');
$valores[':sobrenome'] = (isset($_POST['sobrenome']) ? $_POST['sobrenome'] : '');
$valores[':matricula'] = (isset($_POST['matricula']) ? $_POST['matricula'] : '');
$valores[':email'] = (isset($_POST['email']) ? $_POST['email'] : '');
$valores[':senha'] = (isset($_POST['senha']) ? $_POST['senha'] : '');

if($_POST) {
    //Busca no banco a quantidade de usuarios que tenham a mesma matricula OU o mesmo email
    $querySelect = "SELECT count(*) FROM usuarios WHERE matricula = {$valores[':matricula']} or email = {$valores[':email']}";

    //Executa a query
    $check = $pdo->query($querySelect);

    //Obtem o resultado
    $result = $check->fetch(PDO::FETCH_ASSOC);

    //Verificase o valor retornado é 0 (Nenhum usuário igual cadastrado)
    if($result['total'] == 0){

        $senha           = $_POST['senha'];
        $confirma_senha  = $_POST['confirma_senha'];
        if ($senha == "") {
            $mensagem = "Aviso: Senha não foi alterada!";
        } else if ($senha == $confirma_senha && $statement->execute($valores)) {

        } else {

        }

    }else{
        $mensagem = "Erro: Email ou matricula ja cadastrado!";
    }

}


text:
Q: Serialize many-to-many relationship in django rest framework I am trying to serialize database with the following relations:

*

*Each Client can have one ore more Boxes

*Each Box can contain one or more Products. Box and products have many-to-many relationship implementen through table BoxContent

*Each Product has one ore more Questions related to it

*Each Question has one or more Options

Take a look on ER diagram

So far I managed to obtain following results:
  [
  {
    "id": 1,
    "tax_code": "client_1_tax_code",
    "email": "client_1_email",
    "box_set": [
      {
        "id": 1,
        "edition_name": "first_edition"
      },
      {
        "id": 2,
        "edition_name": "first_edition"
      }
    ]
  },
  {
    "id": 2,
    "tax_code": "client_2_tax_code",
    "email": "client_2_email",
    "box_set": [
      {
        "id": 3,
        "edition_name": "first_edition"
      }
    ]
  }
]

box_set is a collection of boxes that one particular client received. Ideally, I would like to have a collection of products and related questions under each item of box_set, like below:
[
  {
    "id": 1,
    "tax_code": "client_1_tax_code",
    "email": "client_1_email",
    "box_set": [
      {
        "id": 1,
        "edition_name": "first_edition",
        "product_set": [
          {
            "product_id_1": {
              "id_company": "id_company",
              "sku": "product_sku",
              "question_set": [
                {
                  "question_id": 1,
                  "question_text": "Question about product",
                  "option_set": [
                    {
                      "option_id": 1,
                      "option_text": "Some text for option 1",
                      "option_type": "radio",
                      "image_url": null
                    }
                  ]
                },
                {
                  "question_id": 2,
                  "question_text": "Question 2 about product",
                  "option_set": [
                    {
                      "option_id": 1,
                      "option_text": "Some text for option 1",
                      "option_type": "radio",
                      "image_url": null
                    },
                    {
                      "option_id": 2,
                      "option_text": "Some text for option 2",
                      "option_type": "radio",
                      "image_url": null
                    }
                  ]
                }
              ]
            }
          }
        ]
      },
      {
        "id": 2,
        "edition_name": "first_edition",
        "product_set": [
          {
            "product_id_1": {
              "id_company": "id_company",
              "sku": "product_sku",
              "question_set": [
                {
                  "question_id": 1,
                  "question_text": "Question about product",
                  "option_set": [
                    {
                      "option_id": 1,
                      "option_text": "Some text for option 1",
                      "option_type": "radio",
                      "image_url": null
                    }
                  ]
                },
                {
                  "question_id": 2,
                  "question_text": "Question 2 about product",
                  "option_set": [
                    {
                      "option_id": 1,
                      "option_text": "Some text for option 1",
                      "option_type": "radio",
                      "image_url": null
                    },
                    {
                      "option_id": 2,
                      "option_text": "Some text for option 2",
                      "option_type": "radio",
                      "image_url": null
                    }
                  ]
                }
              ]
            }
          }
        ]
      }
    ]
  },
  {
    "id": 2,
    "tax_code": "client_2_tax_code",
    "email": "client_2_email",
    "box_set": [
      {
        "id": 3,
        "edition_name": "first_edition",
        "product_set": [
          {
            "product_id_1": {
              "id_company": "id_company",
              "sku": "product_sku",
              "question_set": [
                {
                  "question_id": 1,
                  "question_text": "Question about product",
                  "option_set": [
                    {
                      "option_id": 1,
                      "option_text": "Some text for option 1",
                      "option_type": "radio",
                      "image_url": null
                    }
                  ]
                },
                {
                  "question_id": 2,
                  "question_text": "Question 2 about product",
                  "option_set": [
                    {
                      "option_id": 1,
                      "option_text": "Some text for option 1",
                      "option_type": "radio",
                      "image_url": null
                    },
                    {
                      "option_id": 2,
                      "option_text": "Some text for option 2",
                      "option_type": "radio",
                      "image_url": null
                    }
                  ]
                }
              ]
            }
          }
        ]
      }
    ]
  }
]

Here is my serializers.py
from rest_framework import serializers
from .models import Question, Option, ResearchCampaign
from nude_client_area.models import Product, Client, Box, BoxContent

class ProductSerializer(serializers.ModelSerializer):
    name = serializers.CharField(required=True)
    company_id =serializers.IntegerField(required=True)
    class Meta:
        model = Product
        fields = ["id", "name", "company_id"]

class OptionSerializer(serializers.ModelSerializer):
    option_type = serializers.CharField(required=True)
    answer_text = serializers.CharField(required=True, min_length=16)
    class Meta:
        model = Option
        fields = [
            "id",
            "id_question",
            "next_question_id",
            "answer_text",
            "option_type",
            "image_url",
        ]

class QuestionSerializer(serializers.ModelSerializer):
    options_set = OptionSerializer(many=True, read_only=True)
    question_text = serializers.CharField(min_length=2, required=True)
    product_set = ProductSerializer(many=True, read_only=True)
    question_details = serializers.CharField(min_length=2, required=True)
    class Meta:
        model = Question
        fields = [
            "id",
            "question_text",
            "question_details",
            "research_campaign",
            "options_set",
            "client_set",
            "product_set"
        ]
class BoxContentSerializer(serializers.ModelSerializer):
    class Meta:
        model = BoxContent
        fields = ["id", 'product_id']

class BoxSerializer(serializers.ModelSerializer):
    box_content_set = BoxContentSerializer(many=True, read_only=True)
    class Meta:
        model = Box
        fields = ["id", "edition_name", "box_content_set"]

class ClientSerializer(serializers.ModelSerializer):
    box_set = BoxSerializer(many=True, read_only=True)
    class Meta:
        model = Client
        fields = ["id", "tax_code", "email", "box_set"]
        depth = 1

and my models.py. In my code I import Client, Product, Box and BoxContent form another Django app, but I put them all in one place just for demonstration purpose.
class Client(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=32)
    last_name = models.CharField(max_length=32)
    birth_date = models.DateField()
    email = models.EmailField(max_length=128)
    tax_code = models.CharField(max_length=11)
    phone = models.CharField(max_length=15)
    is_partner = models.BooleanField(default=False)
    beauty_profile_filled = models.CharField(max_length=32, default='UNCOMPLETE')
    client_notes = models.TextField(null=True)
    created_at = models.DateTimeField(auto_now=True)
    updated_at = models.DateTimeField(auto_now_add=True, null=True)
    def __str__(self):
        return self.first_name + " " + self.last_name + " " + self.tax_code
    class Meta:
        unique_together = ['email', 'tax_code'
        ]

class Box(models.Model):
    client = models.ForeignKey(Client, on_delete=models.CASCADE)
    edition_name = models.CharField(max_length=32)
    created_at = models.DateTimeField(auto_now=True)

class Product(models.Model):
    company = models.ForeignKey(Company, on_delete=models.CASCADE)
    name = models.CharField(max_length=64)
    sku = models.CharField(max_length=64)
    created_at = models.DateTimeField(auto_now=True)
    updated_at = models.DateTimeField(auto_now=True)

class BoxContent(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    box = models.ForeignKey(Box, on_delete=models.CASCADE)
    quantity = models.IntegerField()
    created_at = models.DateTimeField(auto_now=True)
    updated_at = models.DateTimeField(auto_now=True)

class Question(models.Model):
    product = models.ForeignKey(to='nude_client_area.Product', on_delete=models.CASCADE)
    research_campaign = models.ForeignKey(ResearchCampaign, on_delete=models.CASCADE)
    question_text = models.CharField(max_length=255, blank=False, null=False)
    question_details = models.CharField(max_length=255, blank=True, null=True)
    created_at = models.DateTimeField(default=now, blank=False, null=False)
    updated_at = models.DateTimeField(default=now, blank=False, null=True)
    is_active = models.BooleanField(default=True, blank=False, null=False)

    def __str__(self):
        return self.question_text

class Option(models.Model):
    id_question = models.ForeignKey(Question, related_name='options_set', on_delete=models.CASCADE) # TODO understand option_set name. It looks like confusing
    next_question = models.ForeignKey(Question, related_name='questions_set', on_delete=models.CASCADE)
    answer_text = models.CharField(max_length=255, blank=False, null=False)
    image_url = models.CharField(max_length=255, blank=True, null=True)
    option_type = models.CharField(max_length=32, default="radio", blank=False, null=False)
    created_at = models.DateTimeField(default=now, blank=False, null=False)
    updated_at = models.DateTimeField(default=now, blank=False, null=False)

    def __str__(self):
        return self.answer_text

And my api_views.py
class QuestionList(ListAPIView):
    queryset = Client.objects.all()
    permission_classes = [permissions.IsAuthenticatedOrReadOnly]
    serializer_class = ClientSerializer
    filter_backends = (SearchFilter, DjangoFilterBackend)
    filterset_fields = ['id',]
    logger.debug("My message")

A: In the end I took advantage of this post with help of SerializerMethodField()
models.py and api_views.py stayed pretty much the same. I just added custom get_product_list() method to my BoxSerializer():
class BoxSerializer(serializers.ModelSerializer):
    product_list = serializers.SerializerMethodField()
    class Meta:
        model = Box
        fields = ["id", "edition_name", "product_list" ]
        depth = 1

    def get_product_list(self, obj):
        product_ids = obj.boxcontent_set.values('product_id').all()
        product_list = Product.objects.filter(id__in=product_ids)
        product_questions = ProductSerializer(product_list, many=True).data
        return product_questions

basically, this method access BoxContent values and get only product_ids.
After that I fetch all products from Product table and pass it to ProductSerializer where I link with QuestionSerializer. For those who interested, take a look at complete serializers.py:
from rest_framework import serializers
from .models import Question, Option, ResearchCampaign
from nude_client_area.models import Product, Client, Box, BoxContent

class OptionSerializer(serializers.ModelSerializer):
    option_type = serializers.CharField(required=True)
    answer_text = serializers.CharField(required=True, min_length=16)
    class Meta:
        model = Option
        fields = [
            "id",
            "id_question",
            "next_question",
            "answer_text",
            "option_type",
            "image_url",
        ]

class QuestionSerializer(serializers.ModelSerializer):
    question_text = serializers.CharField(min_length=2, required=True)
    question_details = serializers.CharField(min_length=2, required=True)
    class Meta:
        model = Question
        fields = [
            "product_id",
            "id",
            "question_text",
            "question_details",
            "research_campaign_id",
            "option_set",
        ]
        depth = 1

class ProductSerializer(serializers.ModelSerializer):
    option_set = OptionSerializer(many=True, read_only=True)
    question_set = QuestionSerializer(many=True, read_only=True)
    class Meta:
        model = Product
        fields = ["id", "name", "option_set", "question_set" ]
        depth = 1

class BoxSerializer(serializers.ModelSerializer):
    product_list = serializers.SerializerMethodField()
    class Meta:
        model = Box
        fields = ["id", "edition_name", "product_list" ]
        depth = 1

    def get_product_list(self, obj):
        product_ids = obj.boxcontent_set.values('product_id').all()
        product_list = Product.objects.filter(id__in=product_ids)
        product_questions = ProductSerializer(product_list, many=True).data
        return product_questions

class ClientSerializer(serializers.ModelSerializer):
    box_set = BoxSerializer(many=True, read_only=True)
    class Meta:
        model = Client
        fields = ["id", "tax_code", "first_name", "email", "box_set",]
        depth = 1

In this way I was able to fetch specific products of each box the client has ever received.


text:
Q: VB.NET directory.EnumerateFiles: Access to path X is denied Ok so I am trying to write a program to find a specific file on the C drive and get its location. However the following code does not work! I've researched this a lot and gone from GetFiles to Directory.enumerateFiles. However I keep running into an exception claiming that I have no access, simply ignoring the message (closing it/pressing ok) does not continue the search and instead stops it altogether, I need a way of bypassing this if possible, so If a directory causes an exception it will skip it and move along with no error on screen if possible.
Currently the manifest file is set to "requireAdministrator" so I know thats not the issue. Running VB as administrator does not solve, and running the compiled file as admin does not work either. Hope someone can help!
Note: I'm using Visual Basic 2010 Express and have no plans to upgrade to a newever version due to hardware limitation and operating system.
Imports System.IO

Public Class GuardianScanner
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    TextBox1.ReadOnly = True
    TextBox1.ScrollBars = ScrollBars.Vertical

    Button1.Enabled = False
    TextBox1.AppendText(Environment.NewLine & "[INFO] Please wait while scanning. This can take a few minutes")
    Try

        For Each file As String In Directory.EnumerateFiles("C:\", "GodlyNorris.exe", SearchOption.AllDirectories)

                TextBox1.AppendText(Environment.NewLine & "[INFO] Found virus: AUTONORRIS: " & file.ToString)

        Next file

    Catch ex As Exception
        MsgBox(ex.Message)
    End Try

End Sub

A: I tried posting this as a comment but it's pretty messy. This should work, basically it tries to create a directory out of every subdirectory in the C drive, and if it fails with the unauthorized access exception, it moves on to the next subdirectory.
For Each directory In New DirectoryInfo("C:\").GetDirectories()
    Try
        For Each file In directory.GetFiles("*", SearchOption.AllDirectories)
            Try
                TextBox1.Text += Environment.NewLine + file.Name
            Catch ex As Exception
                'MsgBox(ex.Message)
                Continue For
            End Try
        Next
    Catch ex As Exception
        'MsgBox(ex.Message)
        Continue For
    End Try
Next


text:
Q: How to update the client's object properties in ? I'm developing a dashboard web app (ASP MVC Net Core 3.1), like the common dashboard app, some info will be processed at the backend and will update the dashboard periodically.
example:
Monitoring CPU usage %

CPU Usage

Current Process % ${cpuUsage}.

we use WebSocket to communicate with the clients, so if for example, the client receives a string 'UPDATE_CPU_USAGE;30' then the dashboard value should be updated to 30 (in this case aria-valuenow must be updated to 30). Currently the client already able to receive the strings from websocket, but I don't have an idea on how to update the client's object properties in
updated
the websocket listener is on the main page, how to update the '
' and  the aria-valuenow of the other page in that located in javascript?
need an idea.
thanks

A: Set an Id to your progressbar

using javascript, once the value is received, you can do
var progressBar = document.getElementById('progress-bar');
    if (progressBar != undefined) {
        progressBar.setAttribute('aria-valuenow', 30); // replace your value instead of 30
    }


text:
Q: Get result from select exists, execute insert query based on the response of it I have to insert unique value for a row but has to put check on 3 columns collectively ((unique value(col1 && col2 && col3) == true)
I found a solution here it is
query = select exists(select 1 from titles where "col1"='${col1}' AND "col2"='${col2}' AND "col3"='${col3}');

This query would return true or false based on the entries of the table
if(query == true)

execute insert into table values ('col1','col2','col3','col4','col5');
I am inserting multiple records from a json file using promises.
Is there any way to execute this in single sequelize.query().

A: Create a UNIQUE index or constraint on (col1, col2, col3) - if you don't have one already.
Then use INSERT ... ON CONFLICT ... DO NOTHING. That's simpler, faster and more reliable, and unlike the route you had in mind, it's also safe against race conditions.
Related:

*

*What does a CONSTRAINT have to do with my unique index?

*What happens with duplicates when inserting multiple rows?
Be aware of NULL handling:

*

*PostgreSQL multi-column unique constraint and NULL values


text:
Q: Creating encrypted Zip files that are compatible with the TrueZip Java Library (Winzip AES?) Is try to create an encrypted ZIP file which is compatible with the TrueZIP java library.
I tried 7z
7za -tzip -mem=AES256 a out.myzip -pFoo in.file

but when decrypting in TrueZIP I get the exception:
W/System.err: de.schlichtherle.truezip.io.InputException:
 java.util.zip.ZipException: in.file (encrypted compression method 8
 is not supported)

A: It worked using
 7z -tzip -mm=Deflate -mem=AES256 a ....

and
    @Override
    public AesKeyStrength getKeyStrength(String arg0)
            throws ZipKeyException {
        return AesKeyStrength.BITS_256;
    }

on the Java side.


text:
Q: Extract Data from Salesforce from command line I want to extract data from Salesforce from command line. I can use data loader by creating process-config file but I need to automate this process using windows batch file. For example, I have 5 different objects in SF from where I need to pull data regularly. The data pull from those 5 objects will always be from a several orgs (not a single org). Is there a way to extract data from salesforce for those 5 objects without having to create a map file. The reason for not creating map file is that the 5 objects may differ from org to org. Hard coding the SOQL will not work for my requirement. Any suggestions as to how I can achieve this in Salesforce?

A: I had a similar project for a client.
I used DataLoader + Batch script file to automate extract / import data from/to Salesforce.
Look a this amazing tutorial to Setting up Automated DataLoader.
http://www.developerforce.com/media/Cheatsheet_Setting_Up_Automated_Data_Loader_9_0.pdf
At the end you'll be able to launch a script (.bat file).
Then you can create a Scheduled Task on your server to automate all your processes.
I remember that i had to hard code my SOQL query in the process-conf.xml and my map files. I used Node.js to run some script to read/write DataLoader process-conf.xml file and to create some map file etc... (Another exemple : Creating log files...)
For your MAP FILES :

*

*EXTRACT : It's not mandatory to use a map file (Your .csv header will be filed by your fields API's names)

*IMPORT : If you specify field API NAME in the header of your .csv file, Salesforce will automatically map your fields with SalesForce.

I hope it will help you !


text:
Q: gdalwarp to geographic coordinate system I'm getting the folllowing Error when trying to re-project a raster from NAD_1983_Albers to GCS_North_American_1983.  I used the proj4 defenition from going to Properties in QGIS of the layer whose CRS I want to match and copied the CRS def I found in the Coordinate Reference System Selector.

gdalwarp -t_srs +proj=longlat +ellps=GRS80 +tow
    gs84=0,0,0,0,0,0,0 +no_defs RipBuf100_09.tif RipBuf100WGS_09.tif
    ERROR 4: `+ellps=GRS80' does not exist in the file system,
    and is not recognised as a supported dataset name.

A: Using the EPSG works:

gdalwarp -t_srs EPSG:4269 RipBuf100_09.tif RipB
    uf100WGS_09.tif
Creating output file that is 55104P x 24192L.
    Processing input file RipBuf100_09.tif.
    Using internal nodata values (e.g. -2.14748e+009) for image RipBuf100_09.tif.
    Copying nodata values from source RipBuf100_09.tif to destination RipBuf100WGS_0
    9.tif.
    0...10...20...30...40...50...60...70...80...90...100 - done.

A: shot in the dark, but maybe use the EPSG instead of the actual CRS label

A: Put the proj4 string between quotes. Now the string gets split at parsing and GDAL thinks that the +ellps is a name of the source file.


text:
Q: crash course for Facebook SDK (Login and Post) What am I supposed to use for a "Login with facebook"? I want also to create posts on the users wall and like subsites of my website if he votes them up.
I tried about 10 hours now. Still don't know how to begin. I find only specific answers but no answer on how to start.
The authentication I did like this http://developers.facebook.com/docs/authentication/server-side/
But I could also do it with http://developers.facebook.com/docs/reference/php/ the PHP SDK.
Which variant should I use?
And how can I realize "I want also to create posts on the users wall and like subsites of my website if he votes them up."
I am not asking for the full code, just for hints how to start, what to use. The whole facebook documentation doesn't help to answer this, the most important and easiest questions.

A: Can you tell us what is the problem again? What do you mean by 'What am I supposed to use for a "Login with facebook"'?
For start up, I suggest you to read this link first. It is a very good facebook tutorial on PHP SDK and Javascript. They also teach you how to post to user wall and checking on like status.
Hope this help!

A: You can also give these tutorials a try, covering the basics of facebook js/php sdk integration
http://thinkdiff.net/facebook/graph-api-javascript-base-facebook-connect-tutorial/
http://thinkdiff.net/facebook/php-sdk-3-0-graph-api-base-facebook-connect-tutorial/


text:
Q: flutter timing problems on stateful widget after API call I am running into timing problems, I am getting data from a api, then creating a list from the JSON.  I think use the length of the resulting list as the item count in my listview.  However it throws a null error on the itemcount and then completes processing and presents the listview.  I am trying to find where the timing problem is and how items and widgets are processed so that I can avoid the error.  My code is below if anyone has any ideas where my code is flawed.
class Specialty extends StatefulWidget {
  Specialty({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _SpecialtyState createState() => new _SpecialtyState();
}

class _SpecialtyState extends State<Specialty> {

  bool _dataReceived = false;
  bool _authenticated = false;
  SharedPreferences prefs;
  List mylist;

  @override
  void initState() {
    super.initState();

    _getPrefs();
    _getSpecialty();
  }

  _getPrefs() async {
    prefs = await SharedPreferences.getInstance();
    _authenticated = prefs.getBool('authenticated');
    print('AUTH2: ' + _authenticated.toString());
    print('AUTHCODE2: ' + prefs.getString('authcode'));

  }

  _getSpecialty() async {
    var _url = 'http://$baseurl:8080/support/specialty';

    var http = createHttpClient();
    var response = await http.get(_url);

    var specialties = jsonCodec.decode(response.body);

    mylist = specialties.toList();
    //_dataReceived = true;

    setState(() {
      _dataReceived = true;
    });
  }

  Future<Null> _onRefresh() {
    Completer<Null> completer = new Completer<Null>();
    Timer timer = new Timer(new Duration(seconds: 3), () {
      completer.complete();
    });
    return completer.future;
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        body: new RefreshIndicator(
          child: new ListView.builder(
            itemBuilder: _itemBuilder,
            itemCount: mylist.length,
          ),
          onRefresh: _onRefresh,

        ));
  }

  Widget _itemBuilder(BuildContext context, int index) {
    Specialties spec = getSpec(index);
    return new SpecialtyWidget(spec: spec,);
  }

  Specialties getSpec(int index) {
    return new Specialties(
        mylist[index]['id'], mylist[index]['name'], mylist[index]['details'],
        new Photo('lib/images/' + mylist[index]['image'], mylist[index]['name'],
            mylist[index]['name']));
    //return new Specialties.fromMap(mylist[index]);

  }

  var jsonCodec = const JsonCodec();

}

A: You should use await when invoking your async methods. You can mark initState as async, it will still override.
Make sure to call setState() whenever you mutate member variables.
Check if (mounted) before setState if you are doing it after an async wait, because the widget may no longer be visible.
Consider using FutureBuilder instead of setState when doing async programming.


text:
Q: How to take two-dimensional array of ints and return two-dimensional array of chars? I'm hoping to read in the int values and create a new array with char values corresponding to each int value. Could anyone point me in the right direction / or recommend something for me to study/read?
I'm over my head trying to understand how to write this.  Here is what I have so far.
    int[][] Grades = {{90, 54, 32, 25}, {65, 80, 72, 26}};

    for (int i = 0; i < Grades.length; i++) {

        for (int j = 0; j < Grades[i].length; j++) {

            if (Grades[i][j] >= 90) {

            }
            if (Grades[i][j] >= 80) {

            }
            if (Grades[i][j] >= 70) {

            }
            if (Grades[i][j] >= 60) {

            } else {

            }
            System.out.print(Grades[i][j] + "\t");

        }
    }
}
}

A: Declare a two dimensional char array and save the corresponding grade char.
    int[][] Grades = {{90, 54, 32, 25}, {65, 80, 72, 26}};
    char[][] result=new char[Grades.length][4];

    for (int i = 0; i < Grades.length; i++) {
       for (int j = 0; j < Grades[i].length; j++) {

            if (Grades[i][j] >= 90) {
               result[i][j]='A';
            }
            ....
       }
     }

A: You can create character array in this way,
char output[][] = new char[Grades.length][4];

and assign values to it in this way,
output[i][j] = 'A';

A:
You must use "else if".

char[][] r = new char[Grades.length][4];

for (int i = 0; i < Grades.length; i++) {

    for (int j = 0; j < Grades[i].length; j++) {

        if (Grades[i][j] >= 90) {
           r[i][j] = 'A';
        }
        else if (Grades[i][j] >= 80) {
           r[i][j] = 'B';
        }
        else if (Grades[i][j] >= 70) {
          r[i][j] = 'C';
        }

A: Is this all inside one function? I think you should be building a new two dimensional char array and then returning that from a function. Take the two dimensional int array as a parameter.


text:
Q: MS Word 2010 over double RDP is lagging Quick back story, a user has a desktop in my office, and they have an old laptop at home, which they use to RDP onto their desktop. We could not give them a direct link to their desktop, however we have a server which they could RDP onto first, and then RDP onto their machine. The issue we're having, is that certain word documents take a long time to open, and sometimes crash.
They can open the documents fine on their own machine when they're in the office, and can open them when they use the laptop on the internal link to their desktop as well. Its not the internet connection cause chances are it would have dropped out instead of crashing word, its not the laptop cause it shouldn't be playing a factor in this, its not the desktop cause they use it all the time with no problems, and its not the server they hop onto first cause its used by many other users who also experience no problems.
At this point, I'm at a loss because I have no idea whats going wrong. Anybody else know or have any suggestions?


text:
Q: Isn't $[0,1]$ orientable? It's not possible to put an atlas (of manifold with boundary) on $[0,1]$ because any chart whose domain contains $0$ has to have a positive derivative while any chart whose domain contains $1$ has to have a negative derivative (taking charts of $n$-manifold with boundary to have values in $\mathbb{R}_+\times\mathbb{R}^{n-1}$). Yet it has to be orientable: what's the catch?
There's an answer here: Is $[0,1]$ an *oriented* manifold with boundary? (and Stokes theorem), but I find it very distasteful. Is there a problem with defining an orientation of a manifold with boundary to be an orientation of the manifold of its interior points? Wouldn't that be a more kosher approach?

A: This is, afaik, the usual approach to defining an orientation on a manifold with boundary: take an orientation on the interior, which then induces an orientation on the boundary. The problem that you ran into when trying to find an oriented atlas for a manifold with boundary on $[0, 1]$ is reflective of how the induced orientation is determined. The points $0$ and $1$ end up having opposite orientations.
An orientation on an orientable manifold can be described by an ordered basis of the tangent space to a point. Say, if $(v_1, ..., v_n)$ is a basis for $T_pM,$  where $M$ is orientable, one orientation of $M$ is given by $[v_1, ..., v_n];$ the other is given by $[-v_1, ..., v_n] = [v_2, v_1, v_3, ..., v_n].$ You may have a definition of an orientation on an $n$-dimensional manifold $M$ as a nowhere-vanishing $n$-form $\omega.$ These definitions are equivalent - the orientation determined by $\omega$ is the orientation $[v_1, ..., v_n]$ iff $\omega(v_1, ..., v_n)>0.$
Then, to define the induced orientation on the boundary of $M,$ let $p\in\partial M$ and let $\varphi: U\to \mathbb{H}^n$ be a chart from a neighborhood of $p$ to the $n$-dimensional upper half-space $\mathbb{H}^n,$ i.e. $\mathbb{R}^{n-1} \times \mathbb{R}_{\ge 0}.$
Then, the orientation on $\partial M$ is $[u_1, ..., u_{n-1}],$ where $(u_1, ..., u_{n-1})$ is a basis of $T_p\partial M$ such that $[\varphi^*(0, 0, ..., 0, -1), u_1, ..., u_{n-1}]$ is the orientation on $M.$ ($\varphi^*(0, 0, ..., 0, -1)$ is the pullback of the vector $(0, ..., 0, -1),$ which can be visualized as a vector in the tangent space $T_pM$ pointing away from $T_p\partial M.$ The "outward normal vector" can also be used in place of this vector in this construction.) It takes a little bit of work to show that this is well-defined, but it is.
In your specific example, the vector $\varphi^*(0, 0, ..., 0, -1)$ points in different directions when $\varphi$ is a chart in a neighborhood of $0$ or $1,$ so the induced orientations at $0$ and $1$ are different.


text:
Q: Application Insights Wizard Failure I tried to use the Visual Studio Wizard to add Application Insights to my application.  When I did it on my office computer it worked fine.  But when I tried to do it at home, it failed with the following error message:

---------------------------
Microsoft Visual Studio
---------------------------
Could not add Application Insights to project.

Failed to install package:
Microsoft.ApplicationInsights.Web

with error:
Unable to resolve dependencies.  'Microsoft.ApplicationInsights 2.5.0' is not compatible with

'Microsoft.ApplicationInsights.DependencyCollector 2.4.1 constraint: Microsoft.ApplicationInsights (= 2.4.0)',
'Microsoft.ApplicationInsights.PerfCounterCollector 2.4.1 constraint: Microsoft.ApplicationInsights (= 2.4.0)',
'Microsoft.ApplicationInsights.Web 2.4.1 constraint: Microsoft.ApplicationInsights (= 2.4.0)',
'Microsoft.ApplicationInsights.WindowsServer 2.4.1 constraint: Microsoft.ApplicationInsights (= 2.4.0)',
'Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel 2.4.0 constraint: Microsoft.ApplicationInsights (= 2.4.0)'.

It would seem that I have 2.5.0 installed in some parts, and 2.4 installed in other parts.  But I don't know what would cause this...  I just ran the wizard.  I had not installed anything but Visual Studio (in relation to App Insights).
I did try installing the Application Insights Status Monitor afterward, but it did not affect the error.
Any idea on how to deal with this error would be appreciated...
Details:

*

*I am running a Web API project

*I am running on the full .net framework (version 4.5.2)

A: According to How NuGet resolves package dependencies.

Any time a package is installed or reinstalled, which includes being
  installed as part of a restore process, NuGet also installs any
  additional packages on which that first package depends.
Those immediate dependencies might then also have dependencies on
  their own, which can continue to an arbitrary depth. This produces
  what's called a dependency graph that describes the relationships
  between packages at all levels.

During a package restore operation, you may see the error "One or more
  packages are not compatible..." or that a package "is not compatible"
  with the project's target framework.
This error occurs when one or more of the packages referenced in your
  project do not indicate that they support the project's target
  framework; that is, the package does not contain a suitable DLL in its
  lib folder for a target framework that is compatible with the project.

So, I think this is because of dependency issues of packages.
According to nuget.org, Microsoft.ApplicationInsights.DependencyCollector 2.4.1, Microsoft.ApplicationInsights.PerfCounterCollector 2.4.1, Microsoft.ApplicationInsights.Web 2.4.1, Microsoft.ApplicationInsights.WindowsServer 2.4.1 and Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel 2.4.0 require exactly i.e. = not >= Microsoft.ApplicationInsights 2.4.0 but you have Microsoft.ApplicationInsights 2.5.0
So you need to downgrade the Microsoft.ApplicationInsights 2.5.0 to Microsoft.ApplicationInsights 2.4.0.
To downgrade the Microsoft.ApplicationInsights 2.5.0 you can uninstall the package and install the required version of the package. You can follow the following command.
Uninstall-Package Microsoft.ApplicationInsights -Force
Install-Package Microsoft.ApplicationInsights -Version 2.4.0

Note the -Force parameter. Forces a package to be uninstalled, even if other packages depend on it.
Or you can try to reinstall Microsoft.ApplicationInsights package
Update-Package -Reinstall Microsoft.ApplicationInsights

Or you can upgrade all the dependencies of Microsoft.ApplicationInsights
Update-Package Microsoft.ApplicationInsights.DependencyCollector -Version 2.5.0
Update-Package Microsoft.ApplicationInsights.PerfCounterCollector -Version 2.5.0
Update-Package Microsoft.ApplicationInsights.Web -Version 2.5.0
Update-Package Microsoft.ApplicationInsights.WindowsServer -Version 2.5.0
Update-Package Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel -Version 2.5.0


text:
Q: Scala - How to iterate over tuples on RDD? I have an RDD that contains tuples like this

(A, List(2,5,6,7))
(B, List(2,8,9,10))

and I would like to get the index of the first element where a specific condition between value and index holds.
So far I have tried this on a single tuple test  and it works fine:
test._2.zipWithIndex.indexWhere { case (v, i) => SOME_CONDITION}

I just can't find how to iterate over all tuples in the list.. I have tried:
val result= test._._2.zipWithIndex.indexWhere { case (v, i) => SOME_CONDITION}

A: First, "iterate" is the wrong concept here - it comes from the realm of imperative programming, where you actually iterate over the data structure yourself. Spark uses a functional paradigm, which let's you pass a function to handle each record in the RDD (using some higher-order function like map, foreach...).
In this case, sounds like you want to map each element into a new element.
To map only the right-hand side of your tuples (without changing the left-hand side), you can use mapValues:
// mapValues will map the "values" (of type List[Int]) to new values (of type Int)
rdd.mapValues(list => list.zipWithIndex.indexWhere {
  case (v, i) => someCondition(v, i)
})

Or, alternatively, using plain map:
rdd.map {
  case (key, list) => (key, list.zipWithIndex.indexWhere {
    case (v, i) => someCondition(v, i)
  })
}


text:
Q: Open contacts app from react-native app and get the selected contact info I want to open contacts app in IOS from a react-native app that I am developing. Also, I want to get the list of contacts which the user selects. Is there any way to do it in react native?
I went through this stack overflow link: Opening the Settings app from another app and learnt that we could do it in IOS by using URL schemes. I searched google for URL scheme of Contacts app but couldn't find one. Even if I find one, how to get a callback ?
I have implemented react-native-contacts library to get list of contacts. But I would rather like my users to navigate to contacts app and select contacts. Can we do it in react-native ?


text:
Q: Unable to modify or delete text file created by my .jar executable after closing and relaunching the executable I have a fairly simple Java project that opens (creates if doesn't exist) a text file in the current directory (somewhere within my Documents folder), reads the data with BufferedReader, then modifies with PrintWriter. The code works fine in Eclipse. But when exported to a runnable .jar file the resulting .jar executable can only modify a file that it itself created (created because it didn't exist before). If I then close and re-launch the .jar as a new instance to modify the file it created last launch I get

java.io.FileNotFoundException: Data.txt (Access is denied)
    at java.base/java.io.FileOutputStream.open0(Native Method)
    at java.base/java.io.FileOutputStream.open(FileOutputStream.java:293)
    at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:235)
    at java.base/java.io.FileOutputStream.<init>(FileOutputStream.java:184)
    at java.base/java.io.PrintWriter.<init>(PrintWriter.java:309)
    at project.file.LocalStorageFile.setList(LocalStorageFile.java:136)
    ...

So to reiterate:

*

*Run in eclipse - works fine

*Export to runnable jar

*Run jar

*If file doesn't exist it creates one

*Reads file

*if it created the file in step 4 - writes successfully, but if file already existed - exception

When looking into this exception the answers suggest:

*

*restricted directory on disk C (which can't be it for me, as mine is a perfectly accessible (at least once) folder in Documents, and the folder's permissions seem to be in order)

*forgetting to close streams (I close both reader and writer streams in a finally block and make sure they were closed with some console print lines)

*file is being used (the problem persists after a computer restart and even after an OS re-installation I had to do earlier)

*lack of admin rights (I've launched CMD as administrator and used it to "java -jar project.jar" with same results)

*tried deleting file using file.delete() which equals false

*tried flushing the print writer

*tried setting file to readable and writable with file.setReadable(true) and file.setWritable(true)

I am using gradle to build my .jar because I need some libs I get from there for other functions. but even if I "export as runnable jar" using Eclipse itself I get the same issue. And of course when I run the program directly from Eclipse multiple times I get no problem accessing and modifying the same file.
Here are is my LocalStorageFile class with the read and write functions if you want to test it on your machine:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.TreeMap;

/**
 * Store keywords and strings in a local file.
 *
 * Format: keyword1, keyword2 \t string1 \n keyword3, keyword4 \t string2
 * \n
 */
public class LocalStorageFile {
    private static final String FILE_PATH = "Data.txt"; // current directory
    private static final String KEY_SEP = "\t"; // key/value separator
    private static final String LINE_SEP = "\n"; // line separator

    private static File file;

    public LocalStorageFile() {
        file = new File(FILE_PATH);

        // Create file if it doesn't exist
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * Retrieve list from file "Data.txt" in local directory.
     *
     * @return TreeMap of keys and strings.
     */
    public static TreeMap<String, String> getList() {
        System.out.println("Retrieving list data.");
        TreeMap<String, String> myList = new TreeMap<String, String>();

        File file = new File(FILE_PATH);
        if (!file.exists()) {
            try {
                file.createNewFile(); // if file already exists will do nothing
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

        BufferedReader br = null;
        // Read file line by line and add to myList
        try {
            file.setReadable(true);
            file.setWritable(true);
            br = new BufferedReader(new FileReader(file));
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println("  Now reading line:" + line);
                String[] keyValuePair = line.split(KEY_SEP);
                if (keyValuePair.length == 2) { // avoid any error lines
                    // Re-insert tabs and newlines
                    String key = keyValuePair[0].replaceAll("\\\\t", "\t")
                            .replaceAll("\\\\n", "\n");
                    String value = keyValuePair[1].replaceAll("\\\\t", "\t")
                            .replaceAll("\\\\n", "\n");
                    // Put data into map
                    myList.put(key, value);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                    System.out.println("Buffered reader closed.");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return myList;
    }

    /**
     * Rewrite list to file "Data.txt" in local directory.
     *
     * @param myList
     *            TreeMap of keys and strings.
     * @return 1 on success, 0 on fail.
     */
    public static int setList(TreeMap<String, String> myList) {
        System.out.println("Saving list data.");
        String textData = "";
        int result = 0;

        // Construct textData using myList
        for (String key : myList.keySet()) {
            String value = myList.get(key);

            // Sanitize strings
            String keyClean = key.replaceAll("\t", "\\\\t").replaceAll("\n",
                    "\\\\n");
            String valueClean = value.replaceAll("\t", "\\\\t").replaceAll(
                    "\n", "\\\\n");

            // Assemble line with separators
            String line = keyClean + KEY_SEP + valueClean + LINE_SEP;

            System.out.println("  Now saving line:" + line);
            textData += line;
        }

        // Replace file content with textData
        PrintWriter prw = null;
        File file = new File(FILE_PATH);
        if (file.exists()) {
            boolean delStatus = file.delete();
            System.out.println("File deleted? " + delStatus);
            // file.setReadable(true);
            // file.setWritable(true);
        } else {
            System.out.println("File doesn't exist");
        }
        try {
            file.createNewFile();

            prw = new PrintWriter(file); // <- this is line 136 from the exception
            prw.println(textData);
            prw.flush();
            result = 1;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (prw != null) {
                prw.close();
                System.out.println("Print writer closed.");
            }
        }
        return result;
    }

}

It doesn't seem to be an issue with the code, but perhaps something with my system?
Any clues on where I should be digging will be greatly appreciated.

A: OK. I've gotten it to work finally. I had to turn off my Avast Antivirus temporarily and I was able to edit existing files. Specifically "Ransomware Protection" was protecting my Documents folder.
Thank you, commenters, for the help, couldn't have reached this conclusion without you! An answer in this question mentioned Comodo antivirus causing this same issue. I will create a new working directory in an unprotected folder, because Avast doesn't allow me to add a non-exe file as an exception.


text:
Q: Python class containing a temporary file I would like to create a Python class which contains a temporary file.
If I use the usual tempfile.TemporaryFile() with a context manager to create a member variable in the constructor, then the context manager will close/delete the temporary file when the constructor exits. This is no good because I want the file to exist for the lifetime of the class.
I see that I could create my own context managed class using __enter__ and __exit__ methods, does anyone have any examples of this? (Maybe I just need to add a line to delete the file to the example in the link?)
Or maybe there's a better way of doing this?

A: I came up with the following
class TemporaryFile:
  def __init__(self, *, data: str):
      self._data = data

  def __enter__(self):
      self._file = NamedTemporaryFile()
      self._file.write(data)
      self._file.flush()
      return self

  def __exit__(self, exc_type, exc_value, exc_tb):
      self._file.close()

  def sample_method():
      pass

Which is used like so:
with TemporaryFile(data=data) as file:
   file.sample_method()


text:
Q: jQuery селекторы, выбрать всё кроме Делаю шапку сайта, где есть выплывающее меню регистрации, в котором в свою очередь тоже выплывающие фрагменты имеются. Для правильной работы jQuery кода (чтобы выглядело так как мне нужно) мне надо обобрать все элементы, кроме одного. Хочу сделать блок div, выплывающий при клике на кнопку и скрывающийся при клике на любое место за ним.
Вот код jQuery:
//Выплывает рамка для ввода контактной информации)

var i = true;

var j = false;

$('#contaks').click(function(){
  j = true;
  // alert(j);
});
$('#registrationForm:not(#contaks + div)').click(function(){ //СЮДА НУЖНО ОТОБРАТЬ ВСЁ, КРОМЕ #contaksFormSlide!!!!! И КРОМЕ ПОЛЕЙ e-mail и номер Телефона которые находятся в данном блоке div

  if(j){
    $('#contaksFormSlide').slideToggle(500, function(){
      if(i){
        $("#contaks").html('Контактная информация');
        i = !i;
      }
      else{
        $("#contaks").removeClass('ALERT').addClass('forContaks').html('Контактная информация');
        i = !i;
        j = false;
      }
    });
  }

});

Вот код Html:

  <form>

      <input id="name" type="text" value="Имя" class="forFIO"/>
      <input id="surname" type="text" value="Фамилия" class="forFIO"/>
      <input id="patronymic" type="text" value="Отчество" class="forFIO"/>

        <button id="contaks" type="button" class="forContaks">Контактная информация</button>

          <input type="text" value="e-male"/>

          <input type="text" value="Номер Вашего телефона" />

  </form>

Пробовал
#registrationForm:not(#contaks + div)
#registrationForm:not(#contaksFormSlide)

И кучу других методов, не фильтруется.
Версия jQuery 2.0.2

A: Как вариант, повесить онклик на body, и проверять, если e.target - нужный нам элемент - то показывать регистрацию, иначе скрывать


text:
Q: Пытался установить отдельно PIL Хотел отдельно установить Pil, потому что при команде runserver выходила ошибка cannot import name 'image' from 'PIL'.

A: pip install pillow #python 2

pip3 install pillow # python 3

A: python -m pip install pillow
from PIL import Image

A: python3 -m pip install --upgrade pip
python3 -m pip install --upgrade Pillow

https://pillow.readthedocs.io/en/stable/installation.html


text:
Q: GetOptions and Command Line (Perl) I'm currently having an issue using GetOptions.
Let's say I have this chunk of code:
my $var1;
my $var2;

GetOptions (
    'option1=s' => \$var1,
    'option2=s' => \$var2,
);

When I'm running my script on the command line, I'm trying to avoid this particular case.

myprog.pl --option1 --option2 arg1 arg2 (so on and so forth)

where option1 would be assigned --option2 in $var1, which is obviously not my intentions as I want:

myprog.pl --option1 something --option2 somethingElse ...

Any suggestions?

A: So you want the value of --option1 to be optional?  Use :s instead of =s.
my $var1;
my $var2;

GetOptions (
    'option1:s' => \$var1,
    'option2=s' => \$var2,
);


text:
Q: Issue testing multiple spring cloud stream apps Scenario: I have 3 spring cloud streaming apps

*

*1'st: unmarshalls XML payload into JAXB object

*2'nd: Converts JAXB payload into our domain POJO

*3'rd: Validate domain object

I am trying to test the 3'rd app. I have included the 1'st and 2'nd applications as test dependencies. I have added:
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-stream-test-support</artifactId>
        <scope>test</scope>
    </dependency>

Now I have about 20 xml files with various validation scenario's. The first test works fine. I am able pick up the expected message of the channel using:
    final Message<PaymentInstruction> mceMessage =
            (Message<PaymentInstruction>) collector.forChannel(
                    validationBindings.mce()).take();

The 2'nd test that is run is where I have an issue. The test just sits at 'take'.
I have done some digging in the spring-integration-core-4.3.8.jar and have traced the issue to org.springframework.integration.dispatcher.AbstractDispatcher:
@Override
public synchronized boolean addHandler(MessageHandler handler) {
    Assert.notNull(handler, "handler must not be null");
    Assert.isTrue(this.handlers.size() < this.maxSubscribers, "Maximum subscribers exceeded");
    boolean added = this.handlers.add(handler);
    if (this.handlers.size() == 1) {
        this.theOneHandler = handler;
    }
    else {
        this.theOneHandler = null;
    }
    return added;
}

There is a handler that was added for the first test, so it assigns null to 'this.theOneHandler'
My options are:

*

*Refactor the code in the other 2 projects so that I can do the unmarshalling and creating of my domain object without the need for the spring cloud app code

*I can create an individual unit test class per test case, however I'd rather not go this route as the startup time for spring boot will be high that will be multiplied by the number of test cases

*Do I have some missing configuration that would allow me to have these multiple handlers or am I breaking the way I want to use spring cloud streaming?

Environment:

*

*Java 8 Update 131

*org.springframework.cloud:spring-cloud-dependencies:Dalston.RELEASE

*org.springframework.boot:spring-boot-dependencies:1.5.2.RELEASE

A: theOneHandler is a dispatching optimization used when a channel has only one subscriber.
It sounds like you are binding all your services to the same channel, which is not what you want.
Bottom line is you can't do what you are trying to do because each of the services are using the same channel name (presumably input).
You would need to load each service in a separate application context and wire them together with bridges.
EDIT
You could also test them using an aggregated application.


text:
Q: How can an outgoing OpenVPN connection fail when an additional incoming OpenVPN connection is added? I have the very strange behavior that my VPN-connection to a remote location "restarts" every couple of minutes when I logged on to the connecting machine via another VPN tunnel. When I sit in front of the machine everything is fine.
I wonder how this can be? How can an incoming connection through an VPN gateway influence the quality/state of an outgoing VPN connection at all?
So, while I doubt that anyone can solve my problem without further details, logfile analysis and careful retracing of steps, you might help me in explaining to me how technically it is at all possible that the VPN-connection is influenced at all? Where should I look for hints?
Details
The normal and working scenario is like thus:
 +----+            +--------+      +--------+
 | PC | ===tun1=== | VPN-GW |      | Remote |
 +----+ ---ssh------>      ------->| Server |    Ok.
/______\ ========= |        |      |        |
                   +--------+      +--------+

When I log into the PC (ssh) via another VPN-GW the above VPN connection restarts every 1-3 minutes with a message on the console "Inactivity timeout (--ping-restart), restarting"!? Since I am using the connection all the time, and the connection breaks down even while typing on the remote server, it can't be a "real" timeout, can it?
+---------+              +----+
| VPN-GW2 | /==tun2===== |Home|
|        <--------ssh--- +----+
|         | \========== /______\
+---|-----+
    |
    V
 +----+            +--------+      +--------+
 | PC | ==X=tun1=\ | VPN-GW |      | Remote |
 +----+ ---ssh------>      ------->| Server |    X: tun1 becomes unreliable!
/______\ =X======/ |        |      |        |
                   +--------+      +--------+

Home, PC, and Remote Server are all Ubuntu 12.04, The VPN GW are some linux boxes, I suppose. I use the openvpn standard ubuntu package.

A: I came across something recently which could explain this.  It seems that by default OpenVPN uses the same port for incoming and outgoing data, and, of-course, when acting as a server binds the port for outgoing data.    This, combined with the fact that by default the server users UDP could be your problem.
You may be able to fix it by assigning a different port for your server (and, of-course, updating the client), or you might be able to get away with just specifying an "lport" parameter with a value other then 1195.

A:
How can an incoming connection through an VPN gateway influence the quality/state of an outgoing VPN connection at all?

VPNs change the routing table.  When the second connection is started one of the route tables is almost certainly getting changed in a way that breaks your connection.
Look at the route table before and after the VPN connects.  Look at your logs and you will see the routes that get added.
Once you know what changes then fire up traceroute if the solution isn't obvious.


text:
Q: Multiply Values from Col1 to Number of Columns in SQL If I have a dataset in SQL like this:
ColA    ColB    ColC     ColD     ColE
   4       8       9        1       10

How do I multiply each column value together but by indexing rather then typing out the column names such as:
1:number_of_columns(dataset)
Multiply all values together

The reason I want to index this is because the number of columns will not always be the same length and indexing this dataset would solve this problem in a dynamic fashion.
Final Output:
ColA    ColB    ColC     ColD     ColE      Total
   4       8       9        1       10      2,880

This final code though should be able to solve a dataset even like this:
ColE    ColG    ColD
   45     33      44

Result:
ColE    ColG    ColD       Total
   45     33      44      65,340

A: Your query should just look like
SELECT ColA,
       ColB,
       ColC,
       ColD,
       ColE,
       ColA * ColB * ColC * ColD * ColE AS product
FROM   T

And create it dynamically if necessary.
It is possible without dynamic SQL but not efficient or simple.
SELECT T.*, product
FROM   T
       CROSS APPLY (SELECT T.*
                    FOR XML PATH('X'), TYPE) CA(X)
       CROSS APPLY(SELECT CASE
                            --https://stackoverflow.com/a/5416205/73226
                            WHEN MIN(abs(n.value('.', 'int'))) = 0
                              THEN 0
                            ELSE EXP(SUM(Log(abs(NULLIF(n.value('.', 'int'), 0))))) -- the base mathematics
                                  * round(0.5 - count(NULLIF(sign(sign(n.value('.', 'int')) + 0.5), 1))%2, 0) -- pairs up negatives
                          END
                   FROM   X.nodes('/X/*') N(n)) ca2(product)


text:
Q: Java Map compute() Example on Java 1.6 I have to work on Java 1.6. I have difficulty converting the following code running on Java 1.8.
Map<String, Double> maksimum = new HashMap<>();
List<Record> records;
for (Record record : records) {
    record.getFeatures().forEach((key, value) -> {
        maksimum.compute(key, (k1, max) -> max == null || value > max ? value : max);
    });
}

what I have transformed is as follows. I wonder where I'm doing wrong.
for(Record rec : records) {
    for (Map.Entry<String, Double> entry : rec.getFeatures().entrySet()) {
        if (entry.getKey()==null || maksimum.containsKey(entry.getKey())) {
            maksimum.replace(entry.getKey(), maksimum.get(entry.getValue()));
        }
    }
}

A: If I understand correctly your initial code in Java 8, you want to store the maximum value for every key in your Map. Here is the code that should do that in Java 6:
Map<String, Double> maksimum = new HashMap<String, Double>();

for (Record record : records) {
    for (Map.Entry<String, Double> recordEntry : record.getFeatures().entrySet()) {
        String key = recordEntry.getKey();
        Double value = recordEntry.getValue();

        Double initialValue = maksimum.get(key);
        if (initialValue == null) {
            maksimum.put(key, value);
        } else {
            maksimum.put(key, Math.max(value, initialValue));
        }
    }
}

Note that the replace function that you've used in your example was introduced in Java 8. Docs: https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#replace-K-V-


text:
Q: pyqt- how to create clicked signal for QLabel class? i've created a image button class from QLabel. Now i wanna add a clicked signal to that. now, what to do?
 class PicButton(QLabel):

    def __init__(self,pixmap1,pixmap2,parent=None):
        QLabel.__init__(self, parent)
        self.pic = pixmap1
        imageSize = self.pic.size()
        imageSize.setWidth(imageSize.width()*.7)
        imageSize.setHeight(imageSize.height()*.7)
        self.pic = self.pic.scaled(imageSize,Qt.KeepAspectRatioByExpanding)

        self.pic2 = pixmap2
        imageSize2 = self.pic2.size()
        imageSize2.setWidth(imageSize2.width()*.7)
        imageSize2.setHeight(imageSize2.height()*.7)
        self.pic2 = self.pic2.scaled(imageSize2,Qt.KeepAspectRatioByExpanding)

    def enterEvent(self, event):
        self.setPixmap(self.pic2)
        event.accept()

    def leaveEvent(self, event):
        """ When the mouse leave this widget, destroy it. """
        self.setPixmap(self.pic)
        self.destroy()

i make a button :
  ImageButton2 = PicButton(QPixmap("image/buy.png"),QPixmap("image/buy_Hover.png"))
  ImageButton2.clicked.connect(self.addStuff)  # but this class has not  clicked signal

A: QLabels have no default clicked signal. If you want to have one, you must add it yourself and emit it on the correct event.
To dectect the event you can:

*

*override one or more of

*

*QLabel.mouseDoubleClickEvent

*QLabel.mousePressEvent

*QLabel.mouseReleaseEvent

*install an event filter

*Override QLabel.event


text:
Q: Which username 'etckeeper' uses to push? Just want to know which username (or under which user) etckeeper using for git push.
I've setup a alerting system to MS Teams for each pus, but it gives my username while pushing even the push is done by root user.

A: etckeeper can indeed push automatically to a remote Git repository.
The commits pushed can have their own associated user.name / user.email: check /etc/.git/config and see if said commits are done with your username.
If that is the case, even though the push are done by root, the commits would still retain their authorship.


text:
Q: Unable to create databases when running RavenDB on IISExpress As the title says. (Cross post from the mailing list: https://groups.google.com/forum/#!topic/ravendb/hxP3REWVMdg)
The iisexpress process is running as the currently logged in user, but I'm only getting Unauthorized error messages when trying to create databases.
Accessing /debug/user-info only gives the following message:
{"Remark":"Using anonymous user","AnonymousAreAdmins":false}

A: Courtesy of Fitzchak Yitzchaki, I got the answer on the RavenDB mailing list:
https://groups.google.com/forum/?fromgroups=#!topic/ravendb/hxP3REWVMdg
The correct way of doing it was to set the AnonymousAccess setting in web.config to Admin:
<add key="Raven/AnonymousAccess" value="Admin"/>

The AnonymousAccess setting is not well documented, but it tells RavenDB how to treat anonymous users. In this instance, it treats all as admin and should therefore only be used in development. For production, it should be reset to the default value which is All.

A: Try this.
var store = new EmbeddableDocumentStore
            {
                Configuration = { Port = 8081 },
                DataDirectory = "~\\App_Data\\Raven",
                UseEmbeddedHttpServer = true
            };
store.Initialize();

Using "App_Data" will probably make it work for you.


text:
Q: Duplicate Keys Desktop Hybris SmartEdit error We have recently migrated from Hybris 6.4 to 1905 version and have setup smartedit . We are getting the below exception on opening homepage inside smartedit.
There is no error on console . However the homepage view is filled with red boxes

Can anyone please help as to what could be causing these ?


text:
Q: Artin L-series for non-geometric extensions of global function fields There is a theorem of A. Weil on Artin L-series (Page 129 of Number Theory in Function Fields):

Let $L/K$ be a geometric, Galois extension of global function fields. Denote by $q$ the number of elements in the constant field. Let $L(s,\chi)$ be a corresponding Artin L-series and assume that $\chi$ is irreducible and non-trivial. Then $L(s,\chi)$ is a polynomial in $q^{-s}$. In particular, this implies that $L(s,\chi)$ has a holomorphic continuation to the whole complex plane. Moreover, denoting by $m$ the degree of $L(s,\chi)$ in $q^{-s}$, we
have
$$L(s,\chi)=\prod_{i=1}^m(1-\pi_i(\chi)q^{-s}),$$
where for each $i$ with $1\le i\le m$, $|\pi_i(\chi)|=\sqrt q$.

Here $L/K$ being geometric means the constant field of $L$ is the same as $K$. For the general case that $L/K$ is not geometric, I wonder if there is a similar formula for $L(s,\chi)$, but I found no references. Any help will be appreciated.


text:
Q: Laravel computed field on the relation's of a model like a model attribute I have a model for Flights.
The Flight have a relationship with payments_log.
In the payments_log table there are two fields: amount and type(Input/Output or add/sub).
I want to add a field on the Flight model for example Total_amount.
The total_amount on the Flight model will be a field that computed from relationship.
type   amount
I       5.0
I       10.0
O       2

Total_amount = I+I-O = 13

What is the best practice?

A: Create a accessor method on your Flight model that sums the amount column from the logs table:
public function getTotalAmountAttribute()
{
    // Sum log records of type I (add)
    // and substract the sum of all log records of type ) (sub)
    return $this->paymentsLog()->where('type', 'I')->sum('amount') - $this->paymentsLog()->where('type', 'O')->sum('amount');
}

Then you can access it using:
$flight->total_amount;


text:
Q: I want to execute this script every minute and send me a message every time it changes state I am working on a raspberrypi, I want to put this code in crontab to be exectuted every minute, it should low the gpio from 19:00 to 19:minute_max (and this part works) then it should send me an email when it changes the state of the GPIO. I'm able to send me an email when its set to LOW. Whit this code:
from time import localtime
import  RPi.GPIO as  GPIO

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(26, GPIO.OUT)

ore = 19
minuti_max=30
minuti = range(0,minuti_max)

if (localtime()[3]==ore) and (localtime()[4] in minuti):
    if GPIO.input(26)==1:
        GPIO.output(26, GPIO.LOW)
        #send_mail_to_me("ON","yeye")
        print("on")
else:
    GPIO.output(26, GPIO.HIGH)

If I put a send_mail_to_me function in the else statement it will send me it every minute. But I want that it is send only when it set the gpio high for the first time.
I tried the following but it doesn't work:
from time import localtime
import  RPi.GPIO as  GPIO

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(26, GPIO.OUT)

ore = 19
minuti_max=30
minuti = range(0,minuti_max)

if (localtime()[3]==ore) and (localtime()[4] in minuti):
    if GPIO.input(26)==1:
        GPIO.output(26, GPIO.LOW)
        #send_mail_to_me("ON","yeye")
        print("on")
        flag=1
elif (localtime()[4] not in minuti) and flag==1:
    GPIO.output(26, GPIO.HIGH)
    #send_mail_to_me("OFF","yoyo")
    print("off")
    flag=0
else:
    GPIO.output(26, GPIO.HIGH)


text:
Q: Filter flickr images I'm developing an iPhone app where I need to have some images. Particulary I have to retrive some images from internet and then show them in a specific cell.
For example: tapping the cell numb. 1 i have to show some images about an object A, tapping the cell numb. 2 about an object B and so on.
Do you think the best web site to store the images is Flickr?
Do you think it is possibile "matching" a Flickr tag to an iPhone request?
What could be the best solution for my needs?
Thank a lot

A: Your 'iPhone' app will be composing the 'request' based on a web server's published API.  The Flick API looks workable for this.  And, here is an Objective-C Framework for the Flickr API.


text:
Q: Proof that $3^c + 7^c - 2$ by induction I'm trying to prove the for every $c \in \mathbb{N}$, $3^c + 7^c - 2$ is a multiple of $8$. $\mathbb{N} = \{1,2,3,\ldots\}$
Base case: $c = 1$
$(3^1 + 7^1 - 2) = 8$ Base case is true.
Now assume this is true for $c=k$.
Now I prove this holds for $c=k+1$ $(3^{k+1}+7^{k+1}-2)$.
$(3^{k+1}+7^{k+1}-2)$
$(3^k*3+7^k*7-2)$
But now I'm stuck...

A: Notice
\begin{align}
3^k\cdot 3+7^k\cdot 7-2&=3^k\cdot(3+4)-3^k\cdot 4+7^k\cdot 7-2\cdot 7 +2\cdot 7-2\\
&=7(3^k+7^k-2)-3^k\cdot 4+2\cdot 7-2\\
&=7(3^k+7^k-2)-3^k\cdot 4+12\\
&=7(3^k+7^k-2)-12\cdot(3^{k-1}-1)\\
\end{align}
by hypothesis $8$ divides $3^k+7^k-2$, and for $k\ge 1$ the number $3^{k-1}-1$ is even, then $8$ divides $12\cdot(3^{k-1}-1)$. Therefore  $8$ divides $3^k\cdot 3+7^k\cdot 7-2.$

A: We have $3^{k+2}=9\cdot 3^k=3^k+8\cdot 3^k$ and $7^{k+2}=7^k+(8)(6)7^k$. Make separate arguments for $c$ odd and $c$ even, using base cases $c=1$ and $c=2$ respectively.
Or else (essentially the same idea) use strong induction.

A: By the induction hypothesis,
$$
3^k+7^k-2=8m
$$
for some integer $m$. Then $3^k=8m+2-7^k$ and so
\begin{align}
3^{k+1}+7^{k+1}-2
&=3\cdot 3^k+7^{k+1}-2\\
&=3(8m+2-7^k)+7\cdot7^{k}-2\\
&=24m+6-3\cdot7^k+7\cdot7^{k}-2\\
&=4(6m+1+7^k)
\end{align}
Can you finish up?

A: $(3^{k+1}+7^{k+1}-2)=3^k+7^k-2+2\cdot3^k+6\cdot7^k$
So, it is enough to show that $8$ divides $2\cdot3^k+6\cdot7^k=6\cdot3^{k-1}+6\cdot7^k$
Also, $3^{odd}=3$mod$(8)$ ,  $3^{even}=-1$mod$(8)$
$7^{odd}=-1$mod$(8)$, $7^{even}=1$mod$(8)$.
implies $6\cdot3^{k-1}+6\cdot7^k=0$mod$(8)$.


text:
Q: How can i hide my data from sniffing? I use this code to connect to fileserve.com using my premium account i want to share my program but they can easly snif username and password using "HTTP Analyzer" is there a way to hide my username and password from sniffing ?i use delphi 2007.
procedure TForm1.Button1Click(Sender: TObject);
var
  i:integer;
  Data, Page : TStringList;
begin
  IdHTTP1.OnRedirect := nil;
  IdHTTP1.AllowCookies := True;
  IdHTTP1.HandleRedirects := True;
  IdHTTP1.ProtocolVersion := pv1_1;
  IdHTTP1.CookieManager := IdCookieManager1;
  IdHTTP1.RedirectMaximum := 15;
  IdHTTP1.Request.UserAgent := 'Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 5.1)';

  Data := TStringList.Create;
  try
    Data.Add('loginUserName=[user]');
    Data.Add('loginUserPassword=[pass]');
    Data.Add('autoLogin=');
    Data.Add('loginFormSubmit=Login');
    IdHTTP1.Post('http://www.fileserve.com/login.php', Data);
  finally
    Data.Free;
  end;

  IdHTTP1.HandleRedirects := False;
  IdHTTP1.OnRedirect := IdHTTP1Redirect;
  IdHTTP1.Get('http://www.fileserve.com/file/aYkRqp3');

  Edit1.Text := idHTTP1.Response.Location;
  for i := 0 to IdCookieManager1.CookieCollection.Count - 1 do
    Memo2.Lines.Add(IdCookieManager1.CookieCollection.Items[i].CookieText);
end;

A: There's no way to hide bits you're transmitting from sniffing.  The only thing you can do is encrypt the bits so that even if someone gets ahold of them, they can't figure out what they mean.  See if the website you're connecting to has an HTTPS version available, and try using that (and Indy's HTTPS protocol handlers) instead of the HTTP version.


text:
Q: Need to find the sum of all even numbers in 2D array (then divide it on the amount of all even numbers to get the average value) I think there's some stupid mistake of mine when I initialized two-dimensional array in 'while' or something
#include <iostream>
#include <iomanip>
using namespace std;
int sumOfEvenNumbers(int arr[], int Rows, int Columns) {
    int s = 0;
    for (int i = 0; i < Rows; i++) {
        for (int j = 0; j < Columns; j++)
            while (arr[i][j] % 2 == 0)
                s += arr[i * Columns + j];
    }
    return s;
}
void main() {
    const int rowCount = 4, colCount = 5;
    int b[rowCount][colCount] = { { 2, 5, 6, 7, 0 }, { 8, 6, 4, 7, 1 }, { 3, 6, 1, 9, 5 }, { 5, 6, 7, 3, 2 } };
    for (int i = 0; i < rowCount; i++) {
        for (int j = 0; j < colCount; j++)
            cout << setw(6) << b[i][j];
        cout << endl;
    }
    cout << endl;
    cout << "Sum = " << sumOfEvenNumbers(&b[0][0], rowCount, colCount);
}

Debugging details
What am I doing wrong?

A: Replace
while (arr[i][j] % 2 == 0)

with
if (arr[i * Columns + j] % 2 == 0)

As has been commented, you could also just use one loop:
for (i = 0; i < Columns * Rows; ++i)