text:
Q: How to include table in linq There are two tables: KindergartenIssues_Users and Users. Now I'm getting fileds of first table.However I could not get full name of user by UserId from 'Users' table.
I got data from 'Kindergartenissues_Users' table. How to correctly write incude to get full name by foreign key of UserId field?
public static async Task<List<KindergartenIssues_UsersView>> GetKinderGartenIssues()
        {
            List<KindergartenIssues_UsersView> users = new List<KindergartenIssues_UsersView>();
            try
            {
                using (var entities = new WebPortalEntities())
                {
                    users = await entities.KindergartenIssues_Users
                        .Where(k => k.DeletedDate == null)
                        .Select(k => new KindergartenIssues_UsersView()
                        {
                            ID = k.ID,
                            UserId = k.UserId,
                            RegDateWithFoundation = k.RegDateWithFoundation,
                            Year = k.Year,
                            AuthorId = k.AuthorId,
                            CreatedDate = k.CreatedDate,
                            ModifiedDate = k.ModifiedDate,
                            EditorId = k.EditorId,
                            DeletedDate = k.DeletedDate,
                            Description = k.Description,
                            ChildBirthYear = k.ChildBirthYear,
                            isHistory = k.isHistory
                        }).ToListAsync();
                }
            }
            catch (Exception ex)
            {
                CommonHelper.WriteError($"GetKinderGartenIssues ERROR: {JsonConvert.SerializeObject(ex)}");
            }

            return users;
        }

A: Try this
        public static async Task<List<object>> GetKinderGartenIssues()
        {
            try
            {
                var users = new List<object>();
                using (var entities = new WebPortalEntities())
                {
                    users = await entities.KindergartenIssues_Users
                    .Where(k => k.DeletedDate == null)
                    .Join(entities.Users, o => o.UserId, i => i.UserId, (ki, u) => {
// You can obviously define your class somewhere instead of using anonymous object...
                        return new {
                            ID = ki.ID,
                            UserId = ki.UserId,
                            FullName = u.FullName
                            // etc...
                        };
                    }).ToListAsync();
                }
            }
            catch (Exception ex)
            {
                CommonHelper.WriteError($"GetKinderGartenIssues ERROR: {JsonConvert.SerializeObject(ex)}");
            }

            return users;
        }


text:
Q: Line wrapping not working in tabular with long numbers \documentclass{article}
\usepackage{graphicx}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{array}
\begin{document}
\begin{table}
\begin{center}
\caption{Results.}\label{tab1}
\begin{tabular}{|p{0.5cm}|p{0.5cm}|p{2cm}|p{2cm}|p{2cm}|p{2cm}|p{2cm}|p{0.5cm}|}
\hline
N & KS & g & n & C & $\lambda(n)$ & $\mu$ & R\\
\hline
1 &
 32 &
 1572324240 &
 1572324239 &
 943290716551438163 &
 1572244920 &
 1470930645&6\\
\hline
2 &
 64 &
 4159540661949250490 &
 4159540661949250489 &
 14726610731536157220276939497631624989 &
 4159171243689855120&3091093397568475626 &
 6\\
\hline
3 &
 96 &
 17921013728107489666861417152 &
 17921013728107489666861417151 &
 319644167630919465013897831470640254404402368723868992349 &
 17918883386300536523002183680&
 8310947063368032641748342092 &
 6\\
\hline
4 &
 128 &
 10960388158297871697330151881871037028 &
 10960388158297871697330151881871037027 &
 106925141663462215096945420078312037311355711106757002541655645931678791491 &
 10958297067198453652392990431562024960 &
 3253082388973481812242917579299455335 &
 6\\
\hline
5 &
 160 &
 11181085000393941012433719385538976929750386340 &
 11181085000393941012433719385538976929750386339 &
 79684675709633819762973841355295907051437943828599200481216296703376032895835669790667255501 &
 11178266769966960229108283302064411639808000000 &
 4208406996756154635702287087616339813762920102 &
 6\\
\hline
\end{tabular}
\end{center}
\end{table}
\end{document}

A: I defined a new column type, which introduces a valid break point after each token in a cell. Funny enough this is very similar to an answer provided in the link AML posted (that I've seen after writing the code):
\documentclass{article}

\usepackage{graphicx}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{array}
\usepackage{collcell}

\newcolumntype{N}[1]{>{\collectcell\everytokenbreak}p{#1}<{\endcollectcell}}
\makeatletter
\newcommand\everytokenbreak[1]
  {%
    \everytokenbreak@#1&%
  }
\long\def\everytokenbreak@#1%
  {%
    \ifx&#1
    \else
      #1\hspace{0pt plus 1pt minus 1pt}%
      \expandafter\everytokenbreak@
    \fi
  }
\makeatother

\begin{document}
\begin{table}
\begin{center}
\caption{Results.}\label{tab1}
\begin{tabular}{|N{0.5cm}|N{0.5cm}|N{2cm}|N{2cm}|N{2cm}|N{2cm}|N{2cm}|N{0.5cm}|}
\hline
N & KS & g & n & C & $\lambda(n)$ & $\mu$ & R\\
\hline
1 &
 32 &
 1572324240 &
 1572324239 &
 943290716551438163 &
 1572244920 &
 1470930645&6\\
\hline
2 &
 64 &
 4159540661949250490 &
 4159540661949250489 &
 14726610731536157220276939497631624989 &
 4159171243689855120&3091093397568475626 &
 6\\
\hline
3 &
 96 &
 17921013728107489666861417152 &
 17921013728107489666861417151 &
 319644167630919465013897831470640254404402368723868992349 &
 17918883386300536523002183680&
 8310947063368032641748342092 &
 6\\
\hline
4 &
 128 &
 10960388158297871697330151881871037028 &
 10960388158297871697330151881871037027 &
 106925141663462215096945420078312037311355711106757002541655645931678791491 &
 10958297067198453652392990431562024960 &
 3253082388973481812242917579299455335 &
 6\\
\hline
5 &
 160 &
 11181085000393941012433719385538976929750386340 &
 11181085000393941012433719385538976929750386339 &
 79684675709633819762973841355295907051437943828599200481216296703376032895835669790667255501 &
 11178266769966960229108283302064411639808000000 &
 4208406996756154635702287087616339813762920102 &
 6\\
\hline
\end{tabular}
\end{center}
\end{table}
\end{document}

A: You can also load the seqsplit package and that wrap big numbers in \seqsplit{} as demonstrated here.
\documentclass{article}
\usepackage{graphicx}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{array}
\usepackage{seqsplit} % added this package
\begin{document}
\begin{table}
\begin{center}
\caption{Results.}\label{tab1}
\begin{tabular}{|p{0.5cm}|p{0.5cm}|p{2cm}|p{2cm}|p{2cm}|p{2cm}|p{2cm}|p{0.5cm}|}
\hline
N & KS & g & n & C & $\lambda(n)$ & $\mu$ & R\\
\hline
1 &
 32 &
 1572324240 &
 1572324239 &
 \seqsplit{943290716551438163} &
 1572244920 &
 1470930645&6\\
\hline
2 &
 64 &
 \seqsplit{4159540661949250490} &
 \seqsplit{4159540661949250489} &
 \seqsplit{14726610731536157220276939497631624989} &
 \seqsplit{4159171243689855120} & \seqsplit{3091093397568475626} &
 6\\
\hline
3 &
 96 &
 \seqsplit{17921013728107489666861417152} &
 \seqsplit{17921013728107489666861417151} &
 \seqsplit{319644167630919465013897831470640254404402368723868992349} &
 \seqsplit{17918883386300536523002183680} &
 \seqsplit{8310947063368032641748342092} &
 6\\
\hline
4 &
 128 &
 \seqsplit{10960388158297871697330151881871037028} &
 \seqsplit{10960388158297871697330151881871037027} &
 \seqsplit{106925141663462215096945420078312037311355711106757002541655645931678791491} &
 \seqsplit{10958297067198453652392990431562024960} &
 \seqsplit{3253082388973481812242917579299455335} &
 6\\
\hline
5 &
 160 &
 \seqsplit{11181085000393941012433719385538976929750386340} &
 \seqsplit{11181085000393941012433719385538976929750386339} &
 \seqsplit{79684675709633819762973841355295907051437943828599200481216296703376032895835669790667255501} &
 \seqsplit{11178266769966960229108283302064411639808000000} &
 \seqsplit{4208406996756154635702287087616339813762920102} &
 6\\
\hline
\end{tabular}
\end{center}
\end{table}
\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Multiple mysql inserts from one Form I want to be able to track prescribed medications taken on a daily basis. I am not sure if how I'm trying to do this is the right strategy, as I'm just learning. The strategy I'm currently using is to use one table to track each prescribed item by date and using a foreign key to the prescribed items details in a second table.
My immediate question is it possible to some how group each prescribed item on a single form to collect the taken amounts and then insert each into mysql?
This is what I have so far. This works fine for just one item, but I want to have multiple items for each date. Is it possible to  have multiple groups of inputs on a page to create multiple inserts? Maybe my strategy is all wrong. Is this possible or is another strategy necessary?
<form method="post" action="db_insert.php">
    <?php
        $date = "2016-15-16";
    ?>
    <?php echo "Date " . $date; ?>
    <input type="hidden" name="prescribedid" value="1">

    Prescribed #1 Amount: 200 <input type="checkbox" name="taken_amount" value="200">
    Prescribed #1 Units: mg <input type="checkbox" name="units" value="mg">
    Prescribed #1 Frequency: daily <input type="checkbox" name="frequency" value="1">
    <input type="hidden" name="prescribedid" value="2">

    Prescribed #2 Amount: 200 <input type="checkbox" name="taken_amount" value="200">
    Prescribed #2 Units: mg <input type="checkbox" name="units" value="mg">
    Prescribed #2 Frequency: daily <input type="checkbox" name="frequency" value="1">

    <input type="submit" name="Submit">
    </form>

db_insert.php
<?php
$date = "2016-08-15";
$date = date('Y-m-d',strtotime($date));

echo $date . "
";

$prescribedid = $_POST["prescribedid"];
$taken_amount = $_POST["taken_amount"];
$units        = $_POST["units"];
$frequency    = $_POST["frequency"];

// 1st Insert
$query[] = "INSERT INTO `tracked_db` (`takenid`, `date`, `prescribedid`, `taken_amount`, `taken_units`, `frequency`)";
$query .= " VALUES (NULL, '{$date}', '${prescribedid}', '{$taken_amount}', '{$units}', '{$frequency}')";

// 2nd insert
$query[] = "INSERT INTO `tracked_db` (`takenid`, `date`, `prescribedid`, `taken_amount`, `taken_units`, `frequency`)";
$query .= " VALUES (NULL, '{$date}', '${prescribedid}', '{$taken_amount}', '{$units}', '{$frequency}')";

$result = mysqli_query($connection, $query);
?>

foreach the queries to insert.

A: If you want to submit multiple input with same name then you have to give name of the inputs with [].
Eg:
<input type="checkbox" name="taken_amount[]" value="200">

And in the server side, they will be received or treated as array.
Eg: Here $taken_amount = $_POST["taken_amount"]; $taken_amount is an array containing values of all inputs with the name taken_amount. Then you can iterate through this array to retrieve the value.
In your case iterate through any of your parameters and append/concatenate the $query so all the rows can be inserted at once.
Eg:
$query='';
for($i=0;$i<count($taken_amount);$i++){
    $query .= "INSERT INTO `tracked_db` (`takenid`, `date`, `prescribedid`,   `taken_amount`, `taken_units`, `frequency`)
              " VALUES(NULL, '{$date}', '{$prescribedid[$i]}', '{$taken_amount[$i]}', '{$units[$i]}', '{$frequency[$i]}')";
}

A: Those hidden inputs are useless. You need to designate your form fields individually, not try to group them under a hidden field. Start here:
<form method="post" action="db_insert.php">
<?php
    $date = "2016-15-16";
?>
<?php echo "Date " . $date; ?>

    Prescribed #1 Amount: 200 <input type="checkbox" name="p1taken_amount" value="200">
Prescribed #1 Units: mg <input type="checkbox" name="p1units" value="mg">
Prescribed #1 Frequency: daily <input type="checkbox" name="p1frequency" value="1">

Prescribed #2 Amount: 200 <input type="checkbox" name="p2taken_amount" value="200">
Prescribed #2 Units: mg <input type="checkbox" name="p2units" value="mg">
Prescribed #2 Frequency: daily <input type="checkbox" name="p2frequency" value="1">

<input type="submit" name="Submit">
</form>


text:
Q: I am trying to make this mineflayer bot attack specific players mentioned in chat Is there a way to give the bot a command, and type someone's username in chat with the command, for example, "attack (username)", and have it attack that player?

A: const target = bot.players[username] ? bot.players[username].entity : null;
if(!target){
     //action if requested player doesn't exist
}
bot.attack(target);


text:
Q: Importing python modules using sublime text3 I'm learning Python 3.7, and Sublime Text3. Most programs run fine using control + b, but when I try to import a module from the standard library like random, I get the following error(Please note that I am not  running the program from OneDrive, but from my own computer!)
Traceback (most recent call last):
  File "C:\Users\chris\OneDrive\Documents\Python Programs\guess.py", line 1, in <module>
    import random
  File "C:\Users\chris\OneDrive\Documents\Python Programs\random.py", line 1
    >>> import os
     ^
SyntaxError: invalid syntax

Obviously the OneDrive thing is a problem ,but what can I do?
Many thanks.

A: The part of the error message that you want to focus on here is the last part of the stack trace, which is showing you the line that has the problem and where the problem is, i.e.:
    >>> import os
     ^
SyntaxError: invalid syntax

Based on this, your input file has the characters >>> in front of the import statement which, as the message indicates, is not valid Python syntax. Removing those characters should solve the problem for you. The line immediately above the error is showing you the name of the file that has the problem (in this case random.py).
The >>> is the prompt that the interactive Python interpreter gives you when you run it, as it's prompting you for what text to enter. That's not something that should appear in your code at all.

A: Check the random.py file, as the error message states, it's a syntax error due to the the >>> repl symbol in there.


text:
Q: ASP.NET Core Web Application + Services: Automate deployments In my old projects I was deploying asp.net applications to different environments with Octopus deployment tool.
I have a new project - Asp.net Core App with couple of Services.
There is a Azure Dev Ops pipeline that builds and deploys applications into docker hub.
I found thousands of tutorials how one can deploy applications into Azure App-Service but this is not what I need. I need to make an automated deployment to on premise servers (not into Azure) with Azure DevOps release pipeline.
How do I do this ? Do I still need to use Docker/Compose or not ? Where do I start ?
Thank you in advance.

A: I'm no expert, but I'll try to help - I've seen the pipeline that does that in the past. I hope this helps but please keep in mind this is deployment to on-prem machine and not a docker container. I'll assume that the process is going to be similar.

*

*You need an agent installed on a target machine (docs)

*Create a Deployment group (docs) (Deployment Groups are logical groups of deployment target machines with agents installed on each of them)

*There should be a Stage in Azure Release pipelines called IIS website deployment
(Deployment Group: Deploy an ASP.NET or ASP.NET Core web application to an IIS website on physical or virtual machines (VM).) - I think that's the one, but just search for IIS in Stages and choose whatever suits you.

*This will create a Stage with 2 tasks in it. In the stage settings (IIS Deployment), select the deployment group you've created.


text:
Q: How is String.fromCharCode() implemented? var x = String.fromCharCode(65);

console.log(x);  //returns "A"

It accepts an integer and returns corresponding character (string), but that character's code is exactly equal to the input!
What happens under the hood here? Does it really just returns what it accepted? or is there any additional logic?

A: have a look @ spidermonkey source code
fromCharCode is defined in jsstr.cpp
it uses a unitStringTable for the mapping. The table is defined via preprocessor directives...

A: I believe it just maintains a dictionary of ASCII codes and return character {value} for input integer{key}

A: fromCharCode is used to convert a Unicode number into a character. Unicode 65 is character A. So String.fromCharCode(65) returns A.
What happens under the hood here?
The implementation may be HashMap with key-value pair, where Unicode value is mapped to corresponding character or it may be switch statement which takes Unicode and returns character.
Pseudocode of implementation using switch:
function fromCharCode(*args)
{
   return args.map(unicodeToChar).join('')
}

function unicodeTochar(unicode)
{
   switch(unicode)
   {
      //something

      case 65:
        return 'A'
      case 66:
        return 'B'

     //something
   }
}


text:
Q: personalizar excepcion - gestion de excepciones VB.NET Estoy realizando una aplicación que carga un archivo excel al servidor a través de un input fileupload, cuando se sube el archivo se insertan los campos del archivo excel a una BD.
Cuando hay campos que ya han sido cargados (duplicados) no inserta ningun registro de excel (ni duplicados, ni no duplicados), ahora bien cuando hay registros duplicados manda un mensaje en ingles.
¿Se puede traducir?, tambien envia que id's estan duplicados. ¿Cómo los puedo obtener para armar un mensaje mas personalizado?

Public Class Cargador
    Inherits System.Web.UI.Page

    Dim mifichero As HttpPostedFile
    Dim nombreArchivoUsuario As String
    Dim sSheetName As String

    Protected Sub btnAdjuntar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdjuntar.Click

Try
            If (subirArchivos.HasFile) Then
                'Sube el archivo seleccionado a la carpeta adjuntos del servidor
                subirArchivos.SaveAs(MapPath("./adjuntos/" + subirArchivos.FileName))
                mifichero = subirArchivos.PostedFile
                'Obtiene el nombre del archivo que se ha subido
                nombreArchivoUsuario = mifichero.FileName
                lbmostrardv.visible = True
                lbadjuntardv.visible = False
                lbadjuntar.Text = ""
                lbmostrar.Text = nombreArchivoUsuario
                lbmostrare.Text = ""

                '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
                Dim cn As SqlClient.SqlConnection = New SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("reportes").ConnectionString)
                Dim sql1 As SqlClient.SqlCommand
                Dim dr As SqlClient.SqlDataReader
                cn.Open()
                sql1 = New SqlClient.SqlCommand("select nombreCargador from CHIP where nombreCargador='" & nombreArchivoUsuario & "'", cn)
                dr = sql1.ExecuteReader()
                ''------------ Verifica que el archivo no se haya cargado ----------------------------
                If dr.HasRows Then
                    ClientScript.RegisterStartupScript(Me.GetType(), "alert", "")
                Else

                    Dim cadconex As String = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
                                        "Data Source=C:\Inetpub\wwwroot\01\adjuntos\" & nombreArchivoUsuario & "; Extended Properties=""Excel 8.0;HDR=Yes"""

                    Dim conn As OleDbConnection
                    conn = New OleDbConnection(cadconex)
                    conn.Open()

                    ''OBTENEMOS NOMBRE DE LA PRIMER HOJA
                    Dim dtExcelSchema As DataTable
                    dtExcelSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
                    Dim SheetName As String = dtExcelSchema.Rows(0)("TABLE_NAME").ToString()

                    ''SELECCIONAMOS TODO LO QUE CONTENGA LA PRIMER HOJA
                    Dim comand As OleDbCommand
                    comand = New OleDbCommand("select * from [Hoja1$]", conn)
                    Dim adapter As New OleDbDataAdapter
                    adapter.SelectCommand = comand
                    Dim ds As DataSet
                    ds = New DataSet
                    adapter.Fill(ds)
                    conn.Close()

                    ''INSERTAMOS EN LA BASE DE DATOS LO OBTENIDO DEL EXCEL
                    Dim conectsql As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("reportes").ConnectionString)
                    conectsql.Open()
                    Dim importar As SqlBulkCopy

                    importar = New SqlBulkCopy(conectsql)
                    importar.DestinationTableName = "CHIP"
                    importar.WriteToServer(ds.Tables(0))
                    lbimportar.Text = "Se adjuntaron e insertaron correctamente los datos del archivo seleccionado"
                    conectsql.Close()

                    '------------ Bandera de control para que no se carguen archivos de nueva cuenta ----------------------------
                    Dim cn2 As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("reportes").ConnectionString)
                    Dim sql2 As SqlClient.SqlCommand
                    cn2.Open()
                    sql2 = New SqlClient.SqlCommand("update dbo.CHIP set nombreCargador='" + nombreArchivoUsuario + "' WHERE nombreCargador is null ", cn2)
                    sql2.ExecuteNonQuery()
                    cn2.Close()
                End If
                dr.Close()
                cn.Close()
                'Catch ex As Exception
                'System.Web.HttpContext.Current.Response.Write("
" & ex.Message & "
")
                'End Try

                '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
            Else
                lbmostrardv.visible = False
                lbadjuntardv.visible = True
                lbadjuntar.Text = "Error al cargar el archivo. Asegurese de que sea un archivo válido"
                lbmostrar.Text = ""
                lbmostrare.Text = ""
            End If
        Catch ex As Exception
            System.Web.HttpContext.Current.Response.Write("
" & ex.Message & "
")
            lbmostrar.Text = ex.ToString()
        End Try
    End Sub
End Class

A: el ex.ToString() te va a devolver toda la excepcion como tal, información que el usuario no necesita, eso te sirve a ti, pero no al usuario.
Entonces yo prefiero hacer esto.
Throw New Exception("Aqui tu texto personalizado : " + ex.Message)

el ex.Message le va a mostrar al usuario que fallo, que en este caso seria "cannot insert duplicate etc"
El tema del idioma depende del CurrentUICulture

A: Podrías colocar las siguientes instrucciones:
Catch ex As Exception
    Thread.CurrentThread.CurrentCulture = New CultureInfo("es-MX")
    Thread.CurrentThread.CurrentUICulture = New CultureInfo("es-MX")

    lbmostrar.Text = ex.Message.ToString()
End Try

Debes tener en cuenta que debes tener instalado el paquete de idiomas de .NET Framework para que te muestre en el idioma necesario.


text:
Q: Google Data studio dynamic data source connection Is there a way in Google Data Studio to dynamically add data source to a visualisation.
I'm able to create a line chart visualisation by making a Google Cloud Storage data connection.
But can i make that data connection dynamic?

A: If you are using the Cloud Storage Connector for Google Data Studio, the data should be always up to date although you might not see it due to the cache.
This is mentioned in this document, you can also check if you can alter the "Data Freshness" of the connector by following these instructions.
Hope you find this useful!


text:
Q: Stupid people, itchy fingers, simple questions and database explosions Probably the most vague title in SO, but it is basically what I am up against (and by up against I only mean this thought in my head) I have a webform (form A) takes data puts it in the database makes reports the world goes round and people are happy.
Now I am tasked with taking a similar form that has all of the original forms inputs, but it is for a different section of people.
Form A - For Foos,
Form B - For Bars
Now Form A and Form B are VERY similar Form A has more information than form B so this statement can be made.
All necessary information needed for form B can be obtained from a completed form A.
Now here is where it gets tricky. Foos and Bars data cannot be stored together in the same databases.
So (and here is where database explosions and my general lack of experience in web design and dealing with end users comes into play) if i give users the option of a checkbox to decide wether or not this report is for a Foo or a Bar how many support calls am I going to take because stupid people and itchy fingers couldnt answer simple questions. Oviously this is not an exact answer more of a generalization, but I am more curious as to learn from the experience of others.
I will more than likely just end up making a new webform for the second report, but this question got stuck in my head the moment i realized how similar they were to each other.
Thank you for your time and shared experiences.
* Edit and thanks to ashray for a great answer.
This data is not input by foos or bars, but by someone trained to insert their information from written reports. A slightly different set of circumstances but ones that change the dynamic of the user.

A: In web development and infact anywhere that you deal with end users, you cannot possibly imagine the twisted/unintuitive ways that users will find to use your system. Just yesterday a guy wanted to show me a picture on his iPhone, here's what he did:

*

*Click on the Camera app.

*Click a picture

*Click on the new picture thumbnail.

*Click on Camera Roll

*Found the picture he wanted and opened it up to show me.

As you can see, this is probably not the way Apple intended it to work ;) However, what this highlights is the fact that you cannot realistically rely on Foos to identify themselves as such and Bars to do so as well, via a web form.


text:
Q: Simplifying the Boolean expression $A'BC' + AB'C + ABC' + ABC$ I have this Boolean to simplify.
$\bar AB\bar C + A\bar BC + AB\bar C + ABC$
I checked the final answer here. It gives the final simplification is $B\bar C + AC$
but I am confused here :
$\bar AB\bar C + A\bar BC + AB\bar C + ABC$
$\bar AB\bar C + A\bar BC + AB(\bar C+C)$
$\bar AB\bar C + A\bar BC + AB$
$\bar AB\bar C + A(\bar BC + B)$
$\bar AB\bar C + A(C + B)$
$\bar AB\bar C + AC + AB$
$B(\bar A\bar C + A) + AC$ (1st and 3rd considered)
$B(\bar C + A) + AC$
$B\bar C + AB + AC$
Here, How can I go further to simplify $B\bar C + AB + AC$    to $B\bar C + AC$
How to remove $AB$ ?

A: I suggest you swap $AB'C$ and $ABC'$ before simplifying:
$$\begin{align}&A'BC' + ABC' + AB'C + ABC
\\=& (A'+A)BC' + (B'+B)AC
\\=& BC' + AC.
\end{align}$$

A: Since we have AB = ABC' + ABC, it follows that
BC' + AB + AC
= BC' + ABC' + ABC + AC
= BC' + AC

The Karnaugh map is given by

from which it is visually clear that AB is covered by the other two, which lends itself to showing you can split AB into two parts and combine them with AC and BC'.

A: I learned Veitch diagrams back in the early 70's and I find them easier to understand than the Karnaugh maps that are popular today. Here is an example using your problem. You fill in the squares and then see what they add up to. Note, the light gray area is $AC$ and the slightly darker gray is $BC'$. Note also how $B'$ spans part of $A$ and the rest of $B$ is under $A'$ so $AB$ is eliminated.


text:
Q: Injective functions and sufficient statistics I'm trying to prove that for a random sample $X_1,\ldots,X_n$ that depends on $\theta$, if $T$ is a sufficient statistic for $\theta$, then so is $T'=f\circ T$, for any injective function $f$.
My attempt:
Since $f$ is injective, if we restrict the target space of $f$ to $\operatorname{range}(f)$, then we can consider $f$ as bijective. Now $T'\in \operatorname{range}(f)$ since $T'=f\circ T$, so $T=f^{-1}\circ T'$. Define $\phi'(u(\vec{x}),\theta)=\phi(f^{-1}\circ u(\vec{x}),\theta)$. Since $T$ is sufficient, we have that $f(\vec{x};\theta)=\phi(T(\vec{x};\theta))h(\vec{x})=\phi(f^{-1}\circ T'(\vec{x};\theta))h(\vec{x})=\phi'(T'(\vec{x};\theta))h(\vec{x})$. Hence, $T'$ is also sufficient.
Does this look alright?

A: I believe your argument works, although it's a bit more on the notation-intensive side than what I am comfortable with.
But here's how I would do it:
It is enough to prove that the conditional probability distribution of $X_1,\ldots,X_n$ given $f(T(X_1,\ldots,X_n))$ does not depend on $\theta$.  To do that, it suffices to show that the conditional probability distribution of $X_1,\ldots,X_n$ given $f(T(X_1,\ldots,X_n))$ is the same as the conditional probability distribution of $X_1,\ldots,X_n$ given $T(X_1,\ldots,X_n)$.  And that follows from the fact that the event that $f(T(X_1,\ldots,X_n))=\text{some particular number or vector or whatever}$ is the same as the event that $T(X_1,\ldots,X_n)=\text{some particular number}\ldots\text{(the inverse-image)}\  {}$.  Or, if you want to talk about conditioning on a sigma-algebra, etc., then you can say that the event that $f(T(X_1,\ldots,X_n))\in\text{some particular set}$ is the same as the event that $T(X_1,\ldots,X_n)\in\text{some particular set}$.
(Rather than "a random sample $X_1,\ldots,X_n$ that depends on $\theta$", it would be better to refer to "a random sample $X_1,\ldots,X_n$ whose probability distribution depends on $\theta$".)


text:
Q: RabbitMQ retry logic on fanout exchange Current system arch around RabbitMQ
We have a cluster of queues and exchanges to support a message.

*

*Main exchange: This is where messages are received from message producers for processing the first time. This can be a topic or fanout (Current issue is about the fanouts)

*Main Queue(s): This is the queue from which the consumer picks the message for processing.

*Dead exchange and queue: Simple basic setup for the bad messages.

*Delay queue: This is the queue which gets the messages from the consumer if needs to be re-tried. Messages in this queue have a specific ttl and the dead exchange for this queue is "Main exchange". Nobody listen to this queue, message just sit to expire and moved to "Main exchange".

*Error Queue: The messages which unable to process even after retry goes here. Again currently nobody listen to them.

Problem Scenario with above setup:
Say I have a fanout "foo-exchange" which sends messages to queues "bar" and "baz". Let's say a message comes in, and it's valid, and "bar" processes it successfully, but "baz" fails for some reason (maybe an external service is down) and we want to retry it after 5 minutes. The message from "baz" is sent to back to "foo-exchange" (via the delay queue) which then not only sends it back to "baz", but "bar" as well.
Current implemented solution (we want something better than this!)
We have an exchange per queue to send the retried message back to a specific queue after the retry timeout period.
In this scenario, we have 3 exchanges ("foo-exchange", "foo-exchange-dead", "Baz-exchange-retry (1 per queue to fanout exchange)" and 3 queues ("baz-queue", "baz-queue-delay", "baz-queue-error" and 1 dead queue for whole exchange ("foo-queue-dead).
This setup is for 1 queue to fanout and will increase considerably which a fanout exchange have multiple consumer queues.
So, we need a solution which can decrease this complex setup into some manageable queues and exchanges
Things we already looked into:

*

*x-delay-exchange: This is not a good solution for us as this doesn't tell how many messages are waiting to process again. We need to know how many to retry in case of external failure. (https://github.com/rabbitmq/rabbitmq-delayed-message-exchange)

*Message ttl to main queue: This blocks all messages behind the delayed message.

A: Every queue is also bound to the default exchange ("") with the routing key equal to the queue name.
You can simply route your expired dead letters directly to the original queue.

A: One of the options is to decorate the message with Destination details before putting into Delay queue and then when message  wait duration expires, message is unwrapped to obtain destination and the original message and sent to the destination.


text:
Q: Permanent receiving of sent XML over TCP C# Form .Net 4.7
A client app should receive XML data from an external payment machine. The XML is automatically sent after each deposit. It's about receiving it at any time and displaying it in a TextBox.
Sending takes place via TCP

*

*The machine opens the connection to the external system at the specified port

*Sends the data

*Waits for confirmation on the same connection if necessary

*Closes the connection

Since the client has to be able to receive the data at any time, I thought about a listener. But I'm not sure if this approach is the right one. What I did here doesn't work. I wanted to test that with a localhost. There is sure to be a simple solution. But since I'm not a network specialist, I can't find it. Does anyone know how to do it best?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace TCPListener
{
   public partial class Form1 : Form
   {
      public Form1()
      {
          InitializeComponent();
      }

      TcpListener Listener = null;
      Int32 port = 8080;
      IPAddress localAddr = IPAddress.Parse("127.0.0.1");

      private void button1_Click(object sender, EventArgs e)
      {
          Listener = new TcpListener(localAddr, port);

          byte[] receiveBuffer = new byte[10025];

          while (true)
          {
              int requestCount = 0;
              Listener.Start();
              MessageBox.Show(" >> Listener Started");
              using (var tcpClient = Listener.AcceptTcpClient())
              {
                  MessageBox.Show(" >> Accepted connection from client");

                  using (var networkStream = tcpClient.GetStream())
                  {
                      while (true)
                      {
                          try
                          {
                              requestCount = requestCount++;
                              var bytesRead = networkStream.Read(receiveBuffer, 0, (int)tcpClient.ReceiveBufferSize);
                              if (bytesRead == 0)
                              {
                                  // Read returns 0 if the client closes the connection
                                  break;
                              }

                              string dataFromClient = System.Text.Encoding.ASCII.GetString(receiveBuffer, 0, bytesRead);

                              XmlDocument xm = new XmlDocument();
                              xm.LoadXml(string.Format("<root>{0}</root>", dataFromClient));
                              XmlElement root = xm.DocumentElement;
                              string rootName = root.FirstChild.Name;
                              textBox1.Text = (rootName, dataFromClient);
                          }
                          catch (Exception ex)
                          {
                              MessageBox.Show("ReceivePortMessages: " + ex.ToString());
                              break;
                          }
                      }
                  }
                  MessageBox.Show(" >> stopped read loop");
              }
              Listener.Stop();
           }
        }
     }
 }


text:
Q: Getting JSON file from WordPress through Cloud9 returns a Cloud9 html file I have been using Cloud9 to make an Ionic app.
So far, the frontend of the app is doing fine. I use the ionic-framework through Cloud9.
My backend is another Cloud9 project. It uses WordPress to make a specific custom post type with advanced custom fields. It then uses WP REST API to generate that data in a json format. I can access my custom post type and its fields when I run the WordPress on Cloud9 using its /wp-json/posts?type=[specific type].
The problem is, when using a $http.get request in my ionic app, it doesn't work at all. If I use $http.get on a json file I downloaded from my WordPress and added in the workspace of my ionic app, everything works fine.
So, I have a problem getting json data from a WordPress site hosted using Cloud9 through an ionic app, also in a Cloud9 workspace.
Both workspaces are separated and run at the same time.
My code to load the json file is the following :

var defer = $q.defer();

$http.get('LINK TO .../wp-json/posts?type=[post type]', { cache: 'true'})
    .success(function(data) {
           defer.resolve(data);
    });

return defer.promise;

As mentionned, when I replace the link with [name of json file].json, a file that was directly downloaded from the REST API generated json and so that is identical to the site I'm trying to get, it doesn't work.
When I console.log(data), instead of logging the data for each custom post (what happens with the download .json), it logs this :

<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>Sign-in | Cloud9 IDE - Ajax.org</title>
        <meta name="description" content="Meet Cloud9, development-as-a-service for Javascripters and other developers"/>
        <meta name="keywords" content=""/>

        <link rel="icon" type="image/gif" href="https://cdn.c9.io/nc-3.1.2733-9ac8c40a/static/homepage/favicon.ico" />

        <link href="https://cdn.c9.io/nc-3.1.2733-9ac8c40a/static/oldclient/homepage/style/signin.css" rel="stylesheet" type="text/css" />

                    Tweet

                        <form id="resetPasswordForm">

Reset password

                                    Username or email address

                                        <input type="text" id="inpResetPassword" name="inpResetPassword" disabled2="disabled" />

                        </form>

Go back

Reset my password

Your password will be reset and you will receive an email with a new password.

                        <form id="signinForm">

Please sign in

                                    Username or email address

                                        <input type="text" id="inpUsernameEmail" name="inpUsernameEmail" tabindex="1" />

                                    Password
                                    Forgot?

                                        <input type="password" id="inpPassword" name="inpPassword" tabindex="2" />

Remember my login

Sign in

                        </form>

Or sign in with:

                            <form id="activationlinkForm">

Activation email

                                        Username or email address

                                            <input type="text" id="inpResendConfirmation" name="inpResendConfirmation" />

                            </form>

Go back

Resend activation email

                    SIGN UP FOR YOUR ACCOUNT

            Resend my activation email

Home

|

Talk to us at Twitter and Facebook

|

Cloud9 IDE, Inc © 2011

Also, since I use chrome as a debugger for my app, I use an extension for Access-Control-Expose-Headers. Without this extension, I get another error for the header.

A: In order to allow services to make API calls to your app (or Wordpress) you'll need to open the Share menu in the top right and make your app public.
In this case, you can lock down your app with authentication in the API so the publicness of your app shouldn't be an issue.


text:
Q: EditTexts in Gallery and focus issue i am trying to add few EditText in a gallery view. i could manage the scrolling by overriding the onInterceptTouchEvent but i am facing issue in geting focus to the edit texts.
Most of the time even though the softkey board is visible, its not showing the typed text in the visible edit text in the screen.
I tried seting onclick listner for the edit text to set focus on the clicked view but still it doesn't work.
Any suggestion ?

A: Try using this property,
android:descendantFocusability="blocksDescendants"


text:
Q: Прервать функцию с горутинами , если выполняется слишком долго Задача, в функции нужно запустить несколько горутин с вычислениями и дождаться их окончания, но если функция будет работать больше указанного количества секунд прервать ее выполнение
минимальный пример
package main

import (
"fmt"
"sync"
)

func FibonacciRecursion(n int) int {
    if n <= 1 {
        return n
    }
    return FibonacciRecursion(n-1) + FibonacciRecursion(n-2)
}

func f(i int, wg *sync.WaitGroup) {
    defer wg.Done()
    fmt.Println(FibonacciRecursion(45 + i))
}

func fun() {
    var wg sync.WaitGroup
    for i := 0; i < 3; i++ {
        go f(i, &wg)
       wg.Add(1)
    }
    wg.Wait()
    println("Function ended")
}

func main() {
    fun()
}

Надо прервать выполнение функции fun, как это сделать?

A: Ну, для таких целей используется пакет context
Вот тут подробно на русском Разбираемся с пакетом Context в Golang
package main

import (
    "context"
    "fmt"
    "sync"
    "time"
)

func main() {
    timeLimit := time.Second * 10
    ctx, cancel := context.WithTimeout(context.Background(), timeLimit)
    defer cancel()
    fun(ctx)
}

func isDone(ctx context.Context) bool {
    select {
    case <-ctx.Done():
        return true
    default:
        return false
    }
}

func FibonacciRecursion(ctx context.Context, n int) int {
    if n <= 1 || isDone(ctx) {
        return n
    }
    return FibonacciRecursion(ctx, n-1) + FibonacciRecursion(ctx, n-2)
}

func f(ctx context.Context, i int, wg *sync.WaitGroup) {
    defer wg.Done()
    fmt.Println(FibonacciRecursion(ctx, 45+i))
}

func fun(ctx context.Context) {
    var wg sync.WaitGroup
    for i := 0; i < 3; i++ {
        wg.Add(1)
        go f(ctx, i, &wg)
    }
    wg.Wait()
    println("Function ended")
}


text: Q: Finding a Devices Security Mode I am conducting a project into bluetooth security and would appreciate if someone could clear this up for me. When is comes to finding out which security mode a device implements where would find find this out? Would it be in the drivers for the device or stored on the hardware?


text:
Q: LibGDX - Missing LabelStyle font error I have a folder named UI and inside it, it contains a button.pack and a button.png (I created this with the GDX texture packer). Here is the line of code for the .pack.
    atlas = new TextureAtlas(Gdx.files.internal("ui/button.pack"));
    skin = new Skin(atlas);

But when I run the application it gives me this error:
Exception in thread "LWJGL Application" java.lang.IllegalArgumentException: Missing LabelStyle font.

Am I doing something wrong? What is the excact problem?


text:
Q: Fractional CSS Pixel Sizes on High Resolution Displays (I've seen this already; I do not believe this is a duplicate: Are the decimal places in a CSS width respected?)
I set the size of an object as follows:
.foo {
  height: 10.5px;
  width: 10.5px;
}

Normally, that rounds down; you can't use half a pixel.
That said, the latest Nexus 7 has 320dpi, and a CSS pixel on an Android device is defined as 160dpi.  A 10px by 10px image is drawn on the Nexus 7 using 400 pixels, not 100.
So on high-pixel density devices - those where window.devicePixelRatio > 1.0 - are fractional pixels useful, or just discarded anyways?
(Thanks!)
Edit, for a somewhat real-world example.
I have a MacBook Retina.  I have a image file that's 21x21 px.  I want this to display on my retina without rescaling in any way; I want each pixel in the file to correspond to one pixel on the screen.  CSS pixels aren't linked to hardware pixels, and 1 px in CSS corresponds to 4px (2 wide, 2 high) on a Retina display or Nexus 7/10.
I want to be able to specify the exact size of the image, so that it's not rescaled, and so that the page doesn't reflow once the image is loaded.  I can do this by putting the image into an div that's set to 11x11, and having the image display as 100%, but that's adding an extra div, and I'm a touch OCD about page size.

A: They are discarded.
I think I get what you are trying to achieve with the fractional pixels, but really the route you need to go is using higher resolution images for the higher density displays. That should do what you want, no?
I can't think of any reason you would ever need the fractional pixel, or anything similar to it.
That being said, fractional pixels don't work, but fractional percentages do.
.foo {
    height: 10.5%;
    width: 10.5%;
}

This will work and should do whatever you would need fractional pixels for (you would need to change the percentage obviously from the example).


text:
Q: d3 rollup on each csv columns I am trying to use d3.rollup to get the summation of each column.
data.csv looks like this:
DateTime, A, B, C
2020/2/27 7:16  3   0   1
2020/2/26 23:44 1   0   4
2020/2/26 21:35 1   1   0
2020/2/26 15:14 1   0   3
2020/2/25 20:35 1   1   0
2020/2/25 16:10 1   0   3

Desired output:
2020/2/27   3   0   1
2020/2/26   3   1   7
2020/2/25   2   1   3

I would like to group my data on a daily basis. I am trying to nest the data using d3.nest but failing to map the data on each column.
I do not want to call out the columns by name such as d3.sum(d.A). Instead, I want to map the data to all columns.
var nested = d3.nest()
  .key(function(c) {return parseDate(new Date(c.datetime)); })//parseDate

To get date by month:
.rollup(function(d){return {
  values: d3.sum(d.map(function(v) {
  return +v[d];}))};})
.entries(data);

Any help would be appreciated. I've just started with js and d3.

A: I'll give an answer with vanilla js and I'll try to come back and give a d3 answer once I've read enough of the docs.
You can do it like this:
csv:
DateTime, A, B, C
2020/2/27 7:16,  3,   0,   1
2020/2/26 23:44, 1,   0,   4
2020/2/26 21:35, 1,   1,   0
2020/2/26 15:14, 1,   0,   3
2020/2/25 20:35, 1,   1,   0
2020/2/25 16:10, 1,   0,   3

Which we could convert to a JSON / JavaScript array many ways, such as:
Taken from: https://stackoverflow.com/a/61080978/9792594:

const csv2json = (str, delimiter = ',') => {
  const titles = str.slice(0, str.indexOf('\n')).split(delimiter);
  const rows = str.slice(str.indexOf('\n') + 1).split('\n');
  return rows.map(row => {
    const values = row.split(delimiter);
    return titles.reduce((object, curr, i) => (object[curr.trim()] = values[i].trim(), object), {})
  });
};

let csv =
`DateTime, A, B, C
2020/2/27 7:16,  3,   0,   1
2020/2/26 23:44, 1,   0,   4
2020/2/26 21:35, 1,   1,   0
2020/2/26 15:14, 1,   0,   3
2020/2/25 20:35, 1,   1,   0
2020/2/25 16:10, 1,   0,   3`;

let word_array = csv2json(csv,',');
console.log(word_array)
.as-console-wrapper { max-height: 100% !important; top: 0; }

JSON / JavaScript Array:
[
  {
    "DateTime": "2020/2/27 7:16",
    "A": 3,
    "B": 0,
    "C": 1
  },
  {
    "DateTime": "2020/2/26 23:44",
    "A": 1,
    "B": 0,
    "C": 4
  },
  {
    "DateTime": "2020/2/26 21:35",
    "A": 1,
    "B": 1,
    "C": 0
  },
  {
    "DateTime": "2020/2/26 15:14",
    "A": 1,
    "B": 0,
    "C": 3
  },
  {
    "DateTime": "2020/2/25 20:35",
    "A": 1,
    "B": 1,
    "C": 0
  },
  {
    "DateTime": "2020/2/25 16:10",
    "A": 1,
    "B": 0,
    "C": 3
  }
]

Answer to your question (aggregate data based on date):

*

*use reduce, to create an object with each day as a key (parse date)

*when the key already exists, merge the values on A, B, C

*convert Object to an array with Object.values

const myData = [{"DateTime":"2020/2/27 7:16","A":3,"B":0,"C":1},{"DateTime":"2020/2/26 23:44","A":1,"B":0,"C":4},{"DateTime":"2020/2/26 21:35","A":1,"B":1,"C":0},{"DateTime":"2020/2/26 15:14","A":1,"B":0,"C":3},{"DateTime":"2020/2/25 20:35","A":1,"B":1,"C":0},{"DateTime":"2020/2/25 16:10","A":1,"B":0,"C":3}];

const groupedData = Object.values(myData.reduce((aggObj, item) => {

  const dateOnly = new Date(item.DateTime).toLocaleDateString();

  if (aggObj.hasOwnProperty(dateOnly)){
    Object.entries(aggObj[dateOnly]).forEach(([key,val]) => {
      if (key != 'DateTime'){
        aggObj[dateOnly][key] = val + item[key];
      }
    });
  } else {
    aggObj[dateOnly] = {...item, "DateTime": dateOnly};
  }

  return aggObj;

}, {}));

console.log(groupedData);
.as-console-wrapper { max-height: 100% !important; top: 0; }


text:
Q: I am getting an response of 500 when trying to make an ajax call to rest service by passing the parameters I have an html text box that takes the input and that input is passed to restful webservice through the ajax call.But I am getting an error of 500.
This is my service:
@Path("/Reportees")
public class ReporteesService {
         ReporteeList   reportee = new ReporteeList();

     @GET
     @Produces(MediaType.APPLICATION_JSON)
         public Map<Object, Object> getList(String empid) throws Exception {
            System.out.println("id is"+empid);
        Map<Object, Object> map=reportee.getReportees(empid);  //error in this line also
        Collection c=map.values();
        String value="";
        for (Iterator iterator = c.iterator(); iterator.hasNext();)
        {
            value = (String) iterator.next();
            Map<Object, Object> mapData=jiraservice.getJiras(value);
            System.out.println(value);

        }
        System.out.println("returning map");
        return map;
    }

}

This is my resource:
public class ReporteeList {
       public Map<Object, Object> getReportees(String idOfEmp) throws Exception {
        System.out.println(idOfEmp);
        String msg = "error";
        String api = "https://connect.ucern.com/api/core/v3/people/";
        String id = idOfEmp;
        String ext = "/@reports";
        String url = api + id + ext;
        String name = "*********";
        String password = "*********";
        String authString = name + ":" + password;
        String authStringEnc = new BASE64Encoder().encode(authString.getBytes());
        System.out.println("Base64 encoded auth string: " + authStringEnc);
        Client restClient = Client.create();
        WebResource webResource = restClient.resource(url);
        ClientResponse resp = webResource.accept("application/json").header("Authorization", "Basic " + authStringEnc)
                .get(ClientResponse.class);
        if (resp.getStatus() != 200) {
            System.err.println("Unable to connect to the server");
        }
        String output = resp.getEntity(String.class);

        // JSONParser reads the data from string object and break each data into key
        // value pairs
        JSONParser parse = new JSONParser();
        // Type caste the parsed json data in json object
        JSONObject jobj = (JSONObject) parse.parse(output);
        // Store the JSON object in JSON array as objects (For level 1 array element i.e list)

        JSONArray jsonarr_s = (JSONArray) jobj.get("list");
        Map<Object, Object> map = new HashMap<Object, Object>(); //error in this line

                if (jsonarr_s.size() > 0) {

            // Get data for List array
        for (int i = 0; i < jsonarr_s.size(); i++) {
                JSONObject jsonobj_1 = (JSONObject) jsonarr_s.get(i);
            JSONObject jive = (JSONObject) jsonobj_1.get("jive");
                Object names = jsonobj_1.get("displayName");
        Object userid = jive.get("username");
                 map.put(names, userid);
            }

            return map;
        } else {
            map.put("errorcheck", msg);
        }
        return map;
    }
}

I am getting error message as:
 The RuntimeException could not be mapped to a response, re-throwing to the HTTP container
java.lang.NullPointerException
My ajax call:
$(function() {
    var empid = document.getElementById("ManagerId").value;

    $('#submit').click(function(){
        $.ajax({
            crossDomain : true,
             type: "GET",
             dataType: "json",
            url: "http://localhost:8088/JirasTrackingApp/reporter/Reportees?empid="+empid,

             success: function(result){
                console.log(result);
                document.write(empid.value);
             }
         });
        });

    });

Stack trace:
id is
Base64 encoded auth string:*********
Unable to connect to the server

 Jan 22, 2019 10:23:51 PM com.sun.jersey.spi.container.ContainerResponse     mapMappableContainerException
SEVERE: The RuntimeException could not be mapped to a response, re- throwing    to the HTTP container
 java.lang.NullPointerException
 at com.JiraTrackerApp.ReporteeList.getReportees(ReporteeList.java:48)
 at com.JiraTrackerApp.ReporteesService.getList(ReporteesService.java:33)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
 at java.lang.reflect.Method.invoke(Unknown Source)
 at  com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvok erFactory.java:60)
 at      com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatc hProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java :185)
at  com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher. dispatch(ResourceJavaMethodDispatcher.java:75)
at  com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1542)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1473)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:558)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:733)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at   org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:670)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)

 Jan 22, 2019 10:23:51 PM org.apache.catalina.core.StandardWrapperValve  invoke
  SEVERE: Servlet.service() for servlet [Jersey Webapp Application] in  context with path [/JirasTrackingApp] threw exception
  java.lang.NullPointerException
  at com.JiraTrackerApp.ReporteeList.getReportees(ReporteeList.java:48)
  at com.JiraTrackerApp.ReporteesService.getList(ReporteesService.java:33)
  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
 at java.lang.reflect.Method.invoke(Unknown Source)
 at  com.sun.jersey.spi.container.JavaMethodInvokerFactory$1.invoke(JavaMethodInvokerFactory.java:60)
at   com.sun.jersey.server.impl.model.method.dispatch.AbstractResourceMethodDispatchProvider$TypeOutInvoker._dispatch(AbstractResourceMethodDispatchProvider.java:185)
at  com.sun.jersey.server.impl.model.method.dispatch.ResourceJavaMethodDispatcher.dispatch(ResourceJavaMethodDispatcher.java:75)
at com.sun.jersey.server.impl.uri.rules.HttpMethodRule.accept(HttpMethodRule.java:302)
at com.sun.jersey.server.impl.uri.rules.ResourceClassRule.accept(ResourceClassRule.java:108)
at com.sun.jersey.server.impl.uri.rules.RightHandPathRule.accept(RightHandPathRule.java:147)
at com.sun.jersey.server.impl.uri.rules.RootResourceClassesRule.accept(RootResourceClassesRule.java:84)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1542)
at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1473)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1419)
at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1409)
at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:409)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:558)
at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:733)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:670)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)


text:
Q: Separate BigDecimal Fraction Part I need to separate fractional part from BigDecimal and convert to Integer.
Eg:
1.05(BigDecimal) => 5(int)
1.30(BigDecimal) => 30(int)

Note: Decimal part won't exceed 2 digits

A: Try this:
int i = bigDecimal
    .minus(new BigDecimal(bigDecimal.intValue())
    .multiply(new BigDecimal(100))
    .intValue();

A: Maybe there is an easier way but this works:
BigDecimal a = new BigDecimal("1.05");
BigDecimal b = new BigDecimal("1.3");
System.out.println(a.movePointRight(2).intValue() % 100);
System.out.println(b.movePointRight(2).intValue() % 100);

>> 5
>> 30

A: Try this code:
BigDecimal big = new BigDecimal("1.5");
BigDecimal fraction =big.remainder(BigDecimal.ONE);

System.out.println(fraction.multiply(new BigDecimal(10).pow(big.precision()-1)).intValue());


text:
Q: Form inside a foreach loop not working properly I'm creating a testing blog site in laravel 5.2 and trying to create a page to manage all the categories.
So far everything is working fine, but I'd like to have a table with a list of the categories and edit each one inline. Usually I create a table and a foreach loop inside it with a form for every row, but this time it's not working properly. I read around that the form inside a table is a bad practice, so I tried to make it just with divs, but it doesn't work either.
Here is the code of the view:
@foreach($categories as $category)
 <form action="/blog/categories/edit/{{ $category->id }}" method="post">

   <input type="hidden" name="_token" value="{{ csrf_token() }}">

<input type="text" value="{{ $category->id }}" name="id" class="category-input-id" readonly="readonly">

{{ $category->created_at }}

{{ $category->updated_at }}

    <input type="submit" id="edit" name="edit" class="hidden" />

    <input type="submit" id="delete" name="delete" class="hidden" />

</form>
@endforeach

In the controller:
public function editcategory (Request $request, $id)
{

    dd($request->all());
}

I didn't paste all the code to get the datas because I don't receive the right datas here.
The output is only the first row in the loop!
Whenever I click, it only gets the first element.
array:5 [▼
  "_token" => "wUhnsw8AoAuUDsuElALg8nM91bFG4EkUHTEAkkjp"
  "id" => "16"
  "name" => "Category Name"
  "description" => "desc test"
  "edit" => "Send"
]

Where I go wrong ?
I also tried to put the form outside the loop and use arrays for the elements (like name="description[]" etc.. ) but I don't know how to get the right one once I pass all the arrays !
Thanks

A: in your case you don't need the form, you can do this easily by  tag, and also you can output your categories in a table like this:
@foreach($categories as $category)

            {{$category->field1}}
            {{$category->field2}}
            {{$category->field3}}
            {{$category->field4}}

            id)}}">{{ Lang::get('global.edit')}}
            id)}}">{{ Lang::get('global.delete')}}

@endforeach

you need to pass the token <input type="hidden" name="_token" value="{{ csrf_token() }}"> when you send the post for security issues, but in your case you don't need post just get by  tag


text:
Q: Meteor forbidClientAccountCreation doesn't prevent oAuth account creation Accounts.config({
  forbidClientAccountCreation: true
});

In lib, so both client and server.  Reset the database, then go to the client and try to login with accounts-google and useraccounts:core packages. Login is successful.
Expected behavior: Account not found, login denied.

A: From the Meteor-Docs:

forbidClientAccountCreation Boolean
Calls to createUser from the client will be rejected. In addition, if
  you are using accounts-ui, the "Create account" link will not be
  available.

The Google-package will create the account via Meteor.loginWithGoogle, so that will work, even if you set forbidClientAccountCreation to true.
What you could do to disable account creation overall is to change the onCreateUser function to something like this:
Accounts.onCreateUser(function (options, user) {
    throw new Meteor.Error('account_creation_disabled', 'Creation of new accounts is currently disabled');
});


text:
Q: Why is ClassLoader created from specific class when holds global information? I just came to realise that this will sometimes return null (print null in console):
package myproject;
public class A {
   public static void main(String[] args) throws Exception
   {
     System.out.println(A.class.getClassLoader().getResource("A.class"));
   }
}

Even though the ClassLoader is created from A.class it has nothing to do with it. It will load resources from the currently running classpath.
I realised this when I was running Maven test classes which run, by default, in project/target/test-classes while the normal classes, like A above, are in project/target/classes/.
I think this is very confusing. Why don't we get something like Class.getClassLoader to make it obvious that this is a global thing? Also, since ClassLoader is useless, what do developers use to load resources relative to their projects? If you include .jar dependency it works, resources included.

A: First of all: two different classes can be loaded by different class loaders. So, when you do:
ClassLoader forA = A.class.getClassLoader();
ClassLoader forB = B.class.getClassLoader();

it is very much possible that
if (forA.equals(forB)) {
  print equal
} else {
  print not equal
}

will print not equal!
Therefore your idea of using a single global Class.getClassLoader() breaks immediately: as there isn't a single entity that this method call could possibly return.
And for the other part - about access resources ... have a look at this SO question.

A: Each class is associated with the class loader that loaded the class. It makes perfect sense to let Class have an getClassLoader instance method.
It's nothing "wrong" with having multiple different objects return the same object through a get method.
It's like having, say person.getAddress(). All persons in a family may return the same address, but that doesn't mean it makes sense to have a static Person.getAddress.


text:
Q: Building caffe, error linking google::protobuf, Debian 9.1 I have this problem, I am trying to build caffe on debian machine, I will build everything but at the end at linking I get multiple undefined references to google::protobuf::...
I am attaching file with build log, containing error messages (build_caffe.txt).
Both libprotobuf-dev and protoc are installled. (output of dpkg -s is in proto.txt)
Here is how I build caffe.
export CXX=g++-4.9
export CC=gcc-4.9
cmake -D CUDA_HOST_COMPILER=/usr/bin/x86_64-linux-gnu-gcc-4.9 -D CUDA_USE_STATIC_CUDA_RUNTIME=OFF ..
make all

Does anyone know a solution for this problem please?
proto.txt
build_caffe.txt

A: Looks like your protobuf was compiled using a different version of gcc. Try to remove protobuf from your system and install it from sources, using the same gcc version you would like to use fro Caffe. (/usr/bin/x86_64-linux-gnu-gcc-4.9 according to your command).
EDIT:
If you can't install the updated protobuf, edit $CAFFE_ROOT/cmake/ProtoBuf.cmake and make the following changes:
#find_package( Protobuf REQUIRED ) # 1. Comment out this line
# 2. explicitly define protobuf's directories
set(PROTOBUF_INCLUDE_DIR path_to_protobuf/src/google/protobuf)
set(PROTOBUF_LIBRARIES path_to_where_protobuf_libs_are_built_to)
# 3. Explicitly set the full path to protoc executable
set(PROTOBUF_PROTOC_EXECUTABLE path_to_where_the_new_protoc_executable_is_build_to)
# ... Continue as usual
list(APPEND Caffe_INCLUDE_DIRS PUBLIC ${PROTOBUF_INCLUDE_DIR})
list(APPEND Caffe_LINKER_LIBS PUBLIC ${PROTOBUF_LIBRARIES})
#...


text:
Q: Trying to understand a two-tailed paired t-test I have two data sets $M$ and $N$ that are equally large. They have different averages and medians and I want to prove that, with 5% significance, the values don't differ solely out of chance.
I'm trying to understand what the two-tailed paired t-test really tells me. I've performed such a test using Google Sheets built-in function TTEST() and it returns the value 0.03. Does this mean that it's a 3% chance that the values differed as they did solely out of chance and that I've successfully proved (at a 5% significance level) that they in fact differ?

A: Yes. This is the so-called $p$-value. And if you get $0.03<0.05$ then the hypothesis that the means are equal should be rejected at $5\%$ significance level since there is only $3\%$ of chances that data sets with the same means show such difference of averages.


text:
Q: Unable to Configure Quotas in RHEL6 & CentOS6- quotecheck returns error message Unable to Configure Quotas in RHEL6 & CentOS6- quotecheck returns error message
I've created new partition(/dev/sda6) and mounted it(on /hulk).
Edited /etc/fstab file to give quotas on the partition with following line
/dev/sda6   /hulk   ext4   defaults,usrquota,grpquota    0 0

and gave the following commands
[root@localhost ~]# mount -o remount,rw /hulk

[root@localhost ~]# mount|grep hulk
/dev/sda6 on /hulk type ext4 (rw,usrquota,grpquota)

[root@localhost ~]# cd /hulk

[root@localhost hulk]# ls
lost+found

and as i use the quotacheck command, it gives me the following error message
[root@localhost hulk]# quotacheck -cug /hulk
quotacheck: Cannot create new quotafile /hulk/aquota.user.new: Permission denied
quotacheck: Cannot initialize IO on new quotafile: Permission denied
quotacheck: Cannot create new quotafile /hulk/aquota.group.new: Permission denied
quotacheck: Cannot initialize IO on new quotafile: Permission denied

A: Before you run quota check command you need to disable SELinux. Run the below command:
[root@localhost hulk]# setenforce 0

now execute quota check command:
[root@localhost hulk]# quotacheck -cug /hulk


text:
Q: How to copy a file fron windows os to cloudera ? I also want to import the .csv file in to the hive, how can i do that? How to copy a file from windows OS to cloudera ? I also want to import the .csv file in to the hive, how can i do that ? Please help me to get it done.

A: To get the file into Linux you will need to either ftp it to the CentOS CLoudera box or mount a file share and copy it from there.
Once on the CentOS/Cloudera box you can open the web browser and log into Cloudera Manager and Hue which is the user interface to Hive/Pig etc. There are icons across the top with the third from the left being Beeswax/Hive. Click on that icon and start from there.
Your other choice once you have the file on the Cloudera box is to use the Hadoop fs commands found HERE specifically copyFromLocal
To load your file into Hive you can do one of two things. Load it into a single large staging field and then parse it into fields you want using offsets like so:
LOAD DATA INPATH '/user/xyz/Inbound/files/target.csv' INTO TABLE 'myTable'

This loads the entire record into a single field. Then you would do the following once loaded.
INSERT OVERWRITE TABLE myTable SELECT
regexp_extract(col_value, '^(?:([^,]*)\,?)(1)', 1) New_Field_name1
regexp_extract(col_value, '^(?:([^,]*)\,?)(5)', 1) New_Field_name2
......
FROM myTable;

The syntax looks challenging but it is not bad, you will just have to read up on HiveQL
Hue also allows you to load a CSV into the individual fields but you have to add the field names yourself. I have never done that before though.


text:
Q: How to pass JSON to SwaggerUIBundle? Is there a way to pass OpenAPI JSON contents directly to Swagger UI's SwaggerUIBundle instead of passing an URL?
I need to use Swagger UI in a React 16 app, but swagger-ui doesn't support React 16 so I'm using SwaggerUIBundle instead. Does anyone know how to use swagger-ui in React version 16+ or pass JSON into SwaggerUIBundle?

A: To pass the spec as JSON, use the spec parameter:
const ui = SwaggerUIBundle({
  // BEGIN SPEC
  spec: {
    swagger: '2.0',
    info: {
      title: "test",
      version: '1.0.0'
    },
    paths: {
      '/foo': {
        get: {
          responses: {
            '200': {
              description: 'OK'
            }
          }
        }
      }
    }
  },
  // END SPEC

  dom_id: '#swagger-ui',
  ...

Please anyone know either how to use swagger-ui in react version 16+

Use swagger-ui-react.


text:
Q: Getting the next leafnode in a binary search tree using an iterator I have some problems when it comes to the next()-method in my LeafNodeIterator-class.
First of all a leaf node is a node with no children in a binary search tree.(Not sure if leafnode is the right english word for it...)
In the constructor I've moved my pointer p to the first leafnode using this method:
  private BladnodeIterator()  // constructor
{
  if(root == null) return;
  firstleafnode(root);
}

private void firstleafnode(Node<T> p)
{
    while(p != null)
    {
        if(p.left == null && p.right == null)
            return;

        p = nextInorder(p);
    }
}

The "nextInorder(p)"-method just moves p to the next Node in Inorder-order.

My question when it comes to the next()-method, which is supposed to return a leafnode-value, and move p to the next leafnode(or null if there are no more leafnodes), is how to code it? Either way I try it I end up doing it wrong.
My apologies if the question or code is unclear.
EDIT:
The code for the nextinorder-method:
    private static <T> Node<T> nextInorder(Node<T> p)
  {
      if(p.right != null)
      {
          p = p.right;
          while(p.left != null)
          {
              p = p.left;
          }
          return p;
      }
      while(p != null)
      {
          if(p.parent != null && p.parent.left == p)
          {
              return p.parent;
          }
           p = p.parent;
      }
      return p;
  }


text:
Q: d3.js force layout increase linkDistance How to increase linkDistance without affecting the node alignment,
example: http://mbostock.github.com/d3/talk/20110921/force.html
when I try to increase the circle radius and linkDistance
the it collapse
<script type="text/javascript">

var w = 1280,
    h = 800,
    z = d3.scale.category20c();

var force = d3.layout.force()
    .size([w, h]);

var svg = d3.select("#chart").append("svg:svg")
    .attr("width", w)
    .attr("height", h);

svg.append("svg:rect")
    .attr("width", w)
    .attr("height", h);

d3.json("flare.json", function(root) {
  var nodes = flatten(root),
      links = d3.layout.tree().links(nodes);

  force
      .nodes(nodes)
      .links(links)
      .start();

  var link = svg.selectAll("line")
      .data(links)
    .enter().insert("svg:line")
      .style("stroke", "#999")
      .style("stroke-width", "1px");

  var node = svg.selectAll("circle.node")
      .data(nodes)
    .enter().append("svg:circle")
      .attr("r", 4.5)
      .style("fill", function(d) { return z(d.parent && d.parent.name); })
      .style("stroke", "#000")
      .call(force.drag);

  force.on("tick", function(e) {
    link.attr("x1", function(d) { return d.source.x; })
        .attr("y1", function(d) { return d.source.y; })
        .attr("x2", function(d) { return d.target.x; })
        .attr("y2", function(d) { return d.target.y; });

    node.attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; });
  });
});

function flatten(root) {
  var nodes = [];
  function recurse(node, depth) {
    if (node.children) {
      node.children.forEach(function(child) {
        child.parent = node;
        recurse(child, depth + 1);
      });
    }
    node.depth = depth;
    nodes.push(node);
  }
  recurse(root, 1);
  return nodes;
}

    </script>

A: Play around with the .charge parameter. It defines how much the nodes repel each other.


text:
Q: Python, XML Structure to Dictionary I have an xml file as follows:
<?xml version="1.0"?>
<max:SyncObject xmlns:max="http://www.ibm.com/max">
  <max:ObjectSet>
    <max:PARENT action="AddChange">
      <max:FIELD1>string</max:FIELD1>
      <max:FIELD2>string</max:FIELD2>
      <max:FIELD3>string</max:FIELD3>
      <max:FIELD4>string</max:FIELD4>
      <max:FIELD5>string</max:FIELD5>
      <max:FIELD6>string</max:FIELD6>
      <max:FIELD7>string</max:FIELD7>
      <max:CHILD1 action="Ignored">
        <max:CH1FIELD1 action="Ignored">
          <max:CH1SUB1>string</max:CH1SUB1>
        <max:CH1FIELD2>string</max:CH1FIELD2>
      </max:CHILD1>
      <max:CHILD2 action="Ignored">
        <max:CH2FIELD1>string</max:CH2FIELD1>
      </max:CHILD2>
    </max:PARENT>
  </max:ObjectSet>
</max:SyncObject>

and my end result that I want to achieve is as follows:
{'PARENT': ['FIELD1', 'FIELD2', 'FIELD3', 'FIELD4', 'FILED5', 'FIELD6', 'FIELD7', 'CHILD1', 'CHILD2']}, {'CHILD1': ['CH1FIELD1', 'CH1FIELD2'], 'CHILD2': ['CH2FIELD1'], 'CH1FIELD1':['CH1SUB1']}

So I have tried several different methods of extracting the FIELD1, FIELD2... tags from the XML file while still maintaining the structure, as you can see the PARENT dictionary is separate from the rest and contains all tags exactly one level below. This is also true for the children tags. The action attrib is not needed as this will be specified by another means within the class.
It seems that most lxml and elementtree are geared toward extracting the attributes from the XML tags and not the tags themselves.
Could anyone point me in the correct direction of extracting the tag (FIELD NAMES) without the prefix, value, or any attributes and preserve the structure?
THANKS!

A: First of all, your XML data is not well-formed, there is a missing closing </max:CH1FIELD1>.
To convert it to a python data structure, use xmltodict:
import xmltodict

data = """<?xml version="1.0"?>
<max:SyncObject xmlns:max="http://www.ibm.com/max">
  <max:ObjectSet>
    <max:PARENT action="AddChange">
      <max:FIELD1>string</max:FIELD1>
      <max:FIELD2>string</max:FIELD2>
      <max:FIELD3>string</max:FIELD3>
      <max:FIELD4>string</max:FIELD4>
      <max:FIELD5>string</max:FIELD5>
      <max:FIELD6>string</max:FIELD6>
      <max:FIELD7>string</max:FIELD7>
      <max:CHILD1 action="Ignored">
        <max:CH1FIELD1 action="Ignored">
          <max:CH1SUB1>string</max:CH1SUB1>
        <max:CH1FIELD2>string</max:CH1FIELD2>
        </max:CH1FIELD1>
      </max:CHILD1>
      <max:CHILD2 action="Ignored">
        <max:CH2FIELD1>string</max:CH2FIELD1>
      </max:CHILD2>
    </max:PARENT>
  </max:ObjectSet>
</max:SyncObject>"""

d = xmltodict.parse(data,
                    process_namespaces=True,
                    namespaces={'http://www.ibm.com/max': None})
print d


text:
Q: App cannot see module's activities I'm working with Android Studio.
I have working application "AppForAdd", that I want to include to another app "ExampleApp" as a module.
"AppForAdd" is using some modules and libraries.
"ExampleApp" is very simple app, that has only one button for opening "AppForAdd" module.
What I've already did:

*

*-> Created "ExampleApp";

*-> Added "AppForAdd" as a module and modules/libraries that are needed to "AppForAdd";

*-> Tried to compile - success;
Now I am trying to make "AppForAdd" actually work in "ExampleApp", so I've added dependency "compile project(':AppForAddModule')". Then compiled - success. Then I was trying to import class to "ExampleApp.MainActivity" by adding this "import com.appforadd.launch.Loader". But unfortunately Android Studio IDE says that "cannot resolve symbol 'Loader'". If I delete ".Loader", then it says "cannot resolve symbol 'launch'". In other words "ExampleApp" cannot see module. I don't know what I miss and what to do to solve this problem, maybe you can give some suggestions?
Thank you.
I hope that you will understand my problem, but if not, please ask.
P.S. It is very strange because:

*

*List item when I am starting to type "import com." in ExampleApp.MainActivity, Android Studio suggests only "com.exampleapp."

*List item when I am starting to type "import com.*" in AppForAdd.MainActivity, Android Studio suggests a lot of suggestions

Looks like that ExampleApp and AppForAdd are living completely different lives.

A: Upgrade to Android Studio 0.4.3. Many bugs related to this were fixed in that version.

A: I've found solution by making AppForAdd as android-library in build.gradle apply plugin: 'android-library'


text:
Q: Problems with Flask-openid in Python 3 I am trying to get Flask-openid working, but keep hitting this error when trying to log in
ValueError: Unicode strings with encoding declaration are not supported. Please use bytes input or XML fragments without declaration.

It happens when using this function
oid.try_login(openid, ask_for=['email', 'fullname', 'nickname'])

This is where the function is used:
@app.route('/login', methods=['GET', 'POST'])
@oid.loginhandler
def login():
    """Does the login via OpenID.  Has to call into `oid.try_login`
    to start the OpenID machinery.
    """
    # if we are already logged in, go back to were we came from
    if g.user is not None:
        app.logger.info('logged-in: ' + oid.get_next_url())
        return redirect(oid.get_next_url())
    if request.method == 'POST':
        openid = request.form.get('openid_identifier')
        if openid:
            app.logger.info(request.form)
            app.logger.info('logging-in: ' + oid.get_next_url())
            return oid.try_login(openid, ask_for=['email', 'fullname',
                                                  'nickname'])
    app.logger.info('not-logged-in: ' + oid.get_next_url())
    return render_template('login.html', next=oid.get_next_url(),
                           error=oid.fetch_error())

and actually seems to be an issue with lxml that Flask-openid uses:
  File "C:\Python33\lib\site-packages\openid\yadis\etxrd.py", line 69, in parseXRDS
    element = ElementTree.XML(text)
  File "lxml.etree.pyx", line 3012, in lxml.etree.XML (src\lxml\lxml.etree.c:67876)
  File "parser.pxi", line 1781, in lxml.etree._parseMemoryDocument (src\lxml\lxml.etree.c:102435)

I have tried a couple of example projects on github, but they all have the same issue. Is there some way I can get Flask-openid to work in Python 3?

A: I'm only just learning Flask myself, so I'm not of much help.
However take a look at http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-v-user-logins
The author mentions

Note that due to the differences in unicode handling between Python 2 and 3 we have to provide two alternative versions of this method.

He uses a str instead of unicode
def get_id(self):
    try:
        return unicode(self.id)  # python 2
    except NameError:
        return str(self.id)  # python 3

I might be completely wrong! In which case i'm sorry, worth a try though.

A: Its much more than just string.  Its based on an older python-openid package That is not Python3 compatible.  There is a new version of python-openid specifically for Python3.
https://pypi.python.org/pypi/python3-openid/3.0.1
Same blog mentioned earlier also detail this:
http://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-v-user-logins
"Unfortunately version 1.2.1 of Flask-OpenID (the current official version) does not work well with Python 3. Check what version you have by running the following command:"


text:
Q: Linq to SQL error - Member Access not legal. What is causing this? I'm trying to use Linq To Sql and have hit a problem when attempting to execute the following query in my web application:
var query = from t in teamsTable
            where t.SeasonTeams.All(x => x.SeasonID != 4)
            select t;

return query.ToList();

At this point, i receive the following error:

Member access 'Int32 SeasonID' of
  'DomainModel.Entities.SeasonTeam' not
  legal on type
  'System.Collections.Generic.IList`1[DomainModel.Entities.SeasonTeam].

Using LINQPad, the exact same query works. I've included the classes with Linq Mappings below.  I'd really appreciate some help both solving the problem and explaining what is causing it.
[Table(Name = "Teams")]
public class Team
{
    [Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
    public int TeamID { get; set; }

    [Column]
    public string Name { get; set; }

    [Association(OtherKey = "TeamID")]
    private EntitySet<Player> _players = new EntitySet<Player>();
    public IList<Player> TeamPlayers { get { return _players.ToList(); } }

    [Association(OtherKey = "HomeTeamID")]
    private EntitySet<Fixture> _homeFixtures = new EntitySet<Fixture>();
    public IList<Fixture> HomeFixtures { get { return _homeFixtures.ToList(); } }

    [Association(OtherKey = "AwayTeamID")]
    private EntitySet<Fixture> _awayFixtures = new EntitySet<Fixture>();
    public IList<Fixture> AwayFixtures { get { return _awayFixtures.ToList(); } }

    [Association(OtherKey="TeamID")]
    private EntitySet<SeasonTeam> _seasonteams = new EntitySet<SeasonTeam>();
    public IList<SeasonTeam> SeasonTeams { get { return _seasonteams.ToList(); } }

}

[Table(Name = "Seasons")]
public class Season
{
    [Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
    public int SeasonID { get; set; }

    [Column]
    public DateTime StartDate { get; set; }

    [Column]
    public DateTime EndDate { get; set; }

    [Column]
    public int LeagueID { get; set; }

    [System.Data.Linq.Mapping.Association(OtherKey = "SeasonID")]
    private EntitySet<Fixture> _fixtures = new EntitySet<Fixture>();
    public IList<Fixture> Fixtures { get { return _fixtures.ToList().AsReadOnly(); } }

    [System.Data.Linq.Mapping.Association(OtherKey = "SeasonID")]
    private EntitySet<SeasonTeam> _seasonteams = new EntitySet<SeasonTeam>();
    public IList<SeasonTeam> SeasonTeams { get { return _seasonteams.ToList().AsReadOnly(); } }

    internal EntityRef<League> _league;
    [System.Data.Linq.Mapping.Association(ThisKey = "LeagueID", Storage = "_league")]
    public League League
    {
        get { return _league.Entity; }
        internal set { _league.Entity = value; LeagueID = value.LeagueID; }
    }
}

[Table(Name="SeasonTeams")]
public class SeasonTeam
{
    [Column(IsDbGenerated = true, IsPrimaryKey = true, AutoSync = AutoSync.OnInsert)]
    public int SeasonTeamID { get; set; }

    [Column]
    public int TeamID { get; set; }

    [Column]
    public int SeasonID { get; set; }

    internal EntityRef<Team> _team;
    [Association(ThisKey = "TeamID", Storage = "_team")]
    public Team Team
    {
        get { return _team.Entity; }
        set { _team.Entity = value; TeamID = value.TeamID; }
    }

    internal EntityRef<Season> _season;
    [Association(ThisKey = "SeasonID", Storage = "_season")]
    public Season Season
    {
        get { return _season.Entity; }
        set { _season.Entity = value; SeasonID = value.SeasonID; }
    }
}


text:
Q: Why won't text on a label show up on an actual device but will in the simulator? (Xcode) Running :
 - Latest version of Xcode
 - Catalina 10.15.2
 - Base model MacBook Pro 13 inch
I'm having an issue where when I have text in a label show up on the simulator but when I try running it on my iPad, it is just blank. The text is currently being shown on the simulator because that is what I have just typed in on the label on the main.storyboard.
I have tried setting the label text manually by doing myLabel.text = "myText" but that didn't work either. Each device is up to date in terms of the software and I have chosen iOS 13/iPad OS for what software the simulator should run on also. I'm thinking it is just some weird iOS 13 bug because I can't find a fix for it.
On iPad

on Simulator

A: Please check if Dark mode is enabled or not on the actual device, if it is then try changing the color of the text to something else like: BlackColor because if the text color is labelColor then on devices with dark mode enabled it will appear white.


text:
Q: Uncountable product of separable spaces is separable? I am asking to what extent this problem is true:

Uncountable product of separable spaces is separable.

I need these statements to be explained if possible:

*

*How to construct a countable subset of uncountable product of separable spaces.

*Counterexample for the contradicted case.

A: A product $X=\prod_{\alpha\in A}X_\alpha$ of non-trivial separable spaces is separable if and only if $|A|\le 2^\omega=\mathfrak{c}$. (By non-trivial I mean that a space does not have the indiscrete topology; for $T_1$ spaces this simply means that it has at least two points.) This is the countable case of the Hewitt-Marczewski-Pondiczery theorem. Hewitt's original paper can be found here. This result itself is Theorem $16.4$c in Willard's General Topology; it is also proved here at Ask a Topologist by Henno Brandsma.
Added: Here's a sketch of the construction of a countable dense subset of $X$ when $|A|\le 2^\omega$. Without loss of generality assume that $|A|=2^\omega$, and identify $A$ with $\Bbb R$. For $\alpha\in\Bbb R$ let $D_\alpha=\{y_\alpha(k):k\in\Bbb N\}$ be a countable dense subset of $X_\alpha$. Let $F=\{q_1,\ldots,q_n\}$ be any finite set of rational numbers with $q_1<\ldots<q_n$, and let $\sigma=\langle m_0,\ldots,m_n\rangle\in\Bbb N^{n+1}$ be any $(n+1)$-tuple of natural numbers. Define a point $x^{F,\sigma}=\langle x_\alpha^{F,\sigma}:\alpha\in\Bbb R\rangle\in X$ as follows:
$$x_\alpha^{F,\sigma}=\begin{cases}
y_\alpha(m_0),&\text{if }\alpha<q_1\\
y_\alpha(m_k),&\text{if }q_k\le\alpha<q_{k+1}\text{ for some }k\in\{1,\ldots,n-1\}\\
y_\alpha(m_n),&\text{if }q_n\le\alpha\;.
\end{cases}$$
Then
$$D=\left\{x^{F,\sigma}:F\subseteq\Bbb Q\text{ is finite and }\sigma\in\Bbb N^{|F|+1}\right\}$$
is a countable dense subset of $X$.


text:
Q: .htaccess: Removing /index.php/foo I have a site built with Contao. I just turned on URL rewriting and now index.php/foo returns a 404 error. I tried to rewrite /index.php/foo to /foo with
RewriteCond %{REQUEST_URI} ^/index\.php/
RewriteRule ^index.php/(.*) /$1 [R,L]

but it does not help.
Here's the rewrite part of the contao factory .htaccess with my additions in it's entirety (I edited out all the commented stuff to make it shorter):
<IfModule mod_rewrite.c>

  RewriteEngine On

  RewriteBase /

  RewriteCond %{REQUEST_URI} ^/index\.php/ # My rule here
  RewriteRule ^index.php/(.*) /$1 [R,L]    # My rule here

  <FilesMatch "\.(png|gif|jpe?g|js|css|ico|php|xml|csv|txt|gz|swf|flv|eot|woff|svg|ttf|htm)$">
  RewriteEngine Off
  </FilesMatch>

  RewriteRule .*\.html$ index.php [L]

  RewriteRule ^[a-z]{2}/$ index.php [L]
  RewriteRule ^([a-z]{2})$ $1/ [R=301,L]

</IfModule>

What am I not getting here?

A: Never mind. I found the answer.
<FilesMatch "\.(png|gif|jpe?g|js|css|ico|THIS HERE CAUSED IT: --> ***php***|xml|csv|txt|gz|swf|flv|eot|woff|svg|ttf|htm)$">
RewriteEngine Off
</FilesMatch>


text:
Q: Unix code is working only in one server Unix code below, is working only on one server. On other servers I am not getting any error but I am getting empty mail. What could be the possible issue with it?
(
 echo "Subject: $SUBJECT"
 echo "MIME-Version: 1.0"
 echo "Content-Type: text/html"
 echo "Content-Disposition: inline"
 cat $CONTENT ) | /usr/sbin/sendmail $MAILTO

A: Looks like on "other servers" the variable $CONTENT is not set or does not name an existing file, or maybe references a non-existing directory.
Are you sure that $CONTENT has/causes an empty line between mail header and message body?


text:
Q: is it normal to get an exception? I'm using asp.net and when I press the play button to start debugging, all works fine. The page I'm debugging makes ajax calls to a web service. Then, I press stop. When I trigger another call from the page in the browser, I get an error back.
Am I getting this error because something broke in the back-end (but since I stopped debugging I can't see what it it) or is it that when you press the stop button, the entire application stops? The reason I'm asking is that when I press the preview button on the same page, the ajax calls work fine even thought the app in not being debugged.
Thanks,

A: Try to look at the process explorer to see which process is starting/ending when you press "start/stop debug".
If the back end is yours and you've got source codes, than start another Visual Studio instance and run the backend in the debug mode to see what's happening there...


text:
Q: Test a function by passing it as props in Router using Jest I'm new to writing testcases for functioanl components in react. I have a below functional component where I need to write a test case for checkCreated() function, it calls a useState function inside it.
function TestComponent() {
 const [Icon, setIcon] = useState(false);
 const checkCreated = status => {
   setIcon(status);
   };

<Router>
  <Route exact path="/test" component={test} />
  <Route exact path="/sample1" render={props => ( <Sample1 {...props} checkCreated ={ checkCreated } /> )} />
  <Route exact path="/sample2" render={props => ( <Sample2 {...props} checkCreated ={ checkCreated } /> )} />
  />
  </Router>
export default TestComponent;

Can someone please help me in writing testcase to cover checkCreated() using Router.


text:
Q: Print html code with angular2 I'm trying to print a button in html passing it as a parameter in angular2 but angular2 never translate it.
modal.component.ts
this.footer = `<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>`

modal.component.html

output html

Close

A: Should be innerHtml instead of innerHTML. It is case sensitive.
For example :


text:
Q: How to use FLAG_DISMISS_KEYGUARD with fingerprint sensor Applying the FLAG_DISMISS_KEYGUARD on an activity till date would unlock the unsecure keyguard. And in case of secure keyguard it would present pin code prompt.
On devices with fingerprint sensor like Nexus 6P or 5X (Marshmallow 6.0), the flag causes pin lock prompt to be shown, while prompt is shown, fingerprint sensor vibrates but doesn't work to unlock.
So is there an official way to go about using the flag on Fingerprint sensor devices?
EDIT : I'm not exactly sure if pin lock prompt is shown, I can't test specifically as I don't have a device. But I'm sure the flag is not incorporating the fingerprint sensor logic

A: I think your problem has to do with this issue.
It has high priority since December '15, but no fix so far..


text:
Q: Detect if mouse button is down I am new to c++ and I am trying to activate a line of code only when the left mouse button is held down. In this example, my code works but it seems that it just toggles it. When I click, it spams the H key then, when I click again, it stops.
Currently I have this code:
if ((GetKeyState(VK_LBUTTON)))
{
    keybd_event(VkKeyScan('H'),0,0,0);
    Sleep ( 30 );
}

Edit:
I have inside the function:
int WINAPI WinMain ( HINSTANCE hInst, HINSTANCE P, LPSTR CMD, int nShowCmd );

A: The application can catch messages and process being sent to your window indicating a state change of any mouse button.
When the left button is pressed a
WM_LBUTTONDOWN

is sent.
When it is released
WM_LBUTTONUP

is sent.
Please read here for various messages being sent to indicate mouse events.

A: Use the below to detect left mouse button press
if(GetAsyncKeyState(VK_LBUTTON)){
   //your code controls here
 }

You can find more controls here : https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getasynckeystate
Also if the GetAsyncKeyState(VK_LBUTTON)shows a syntax error, try including winuser.h by adding #include <winuser.h> in the includes of your code.
Here is an example
if(GetKeyState(VK_LBUTTON))
    {   //finding clicked position
        HWND hWnd = FindWindowA(0,("Motion Paths"));
        ::GetWindowThreadProcessId(hWnd,&pid);
        if (hWnd) { cout << "Found" << endl;}

            POINT p;
            GetCursorPos(&p);
            if (ScreenToClient(hWnd, &p))
            {
                int mouseX = p.x;
                int mouseY = p.y;
                cout<< p.x << " "<< p.y <<endl;
            }
    }

A: Use this to determine if the button is pressed.
if((GetKeyState(VK_LBUTTON) & 0x8000) != 0)

http://vcpptips.wordpress.com/tag/vk_lbutton/

A: In first - need DEFINE BUTTON ID(or another object ID) in begin code:
#define ID_BUTTON1      105

Then AFTER creationale of hWnd - we make button:
   HWND HwndButton1 = CreateWindow(
    L"BUTTON",  // Predefined class; Unicode assumed
    L"OK",      // Button text
    WS_TABSTOP | WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,  // Styles
    10,         // x position
    10,         // y position
    100,        // Button width
    100,        // Button height
    hWnd,     // Parent window
   (HMENU) ID_BUTTON1, // ID кнопки в меню
    NULL,            // Сущность мне неведомая 8-)
    NULL);         // Pointer not needed.

And then add trigger in function:
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    int wmId=0, wmEvent;  //wmId NEED DEFINE null - if he is not available in event, else be ашипка
    PAINTSTRUCT ps;
    HDC hdc;

    switch (message)
    {
    case WM_COMMAND:
        wmEvent = HIWORD(wParam);  //  Name of EVENT - имя события
        wmId    = LOWORD(wParam);  // ID element for event - элемент с которым оно случилось

        case WM_LBUTTONDOWN: MessageBox(NULL, L"MouseL_Click", L"WndHeader", MB_OK | MB_ICONEXCLAMATION);  // Left Mouse Button pressed

        if( LOWORD(wParam) == 105 && WM_COMMAND == WM_LBUTTONDOWN){ // Клик по ID_BUTTON1 левым мышком
        EndDialog(hWnd,0);
        }
................  // Many another function
}