text:
Q: save text on imageview when I share it I'm capturing an Image on my app & I'm writing text on top of the image but when I try to share it, It doesn't show like it has captured the Text on Image I only see an Image.
This app is like Meme generator app..any help would be appreciated.
btnShare.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                View content = findViewById(R.id.ivImage);
                content.setDrawingCacheEnabled(true);
                content.buildDrawingCache();
                Bitmap bitmap = ivImage.getDrawingCache();
                File root = Environment.getExternalStorageDirectory();
                File cachePath = new File(root.getAbsolutePath() + "/DCIM/Camera/image.jpg");
                try {
                    cachePath.createNewFile();
                    FileOutputStream ostream = new FileOutputStream(cachePath);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, ostream);
                    ostream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                Intent share = new Intent(Intent.ACTION_SEND);
                share.setType("image/*");
                share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(cachePath));
                startActivity(Intent.createChooser(share, "Share via"));

            }
        });

        ivImage = (ImageView) findViewById(R.id.ivImage);
        editText=(EditText)findViewById(R.id.editText);
        textView =(TextView)findViewById(R.id.textView);

A: Instead of ImageView you need to capture layout image.
Replace this
View content = findViewById(R.id.ivImage);

with
View content = findViewById(yourLayoutID);

yourLayoutId = layout which consists ImageView + TextView which you want to share.

A: String text= "Write your text on image";
 Paint textPaint = new Paint();
    textPaint.setColor(Color.GREEN);
    textPaint.setTextSize(25);
    textPaint.setTextAlign(Align.RIGHT);

     Bitmap bitmap = ivImage.getDrawingCache();

    Canvas canvas = new Canvas(bitmap);
    canvas.drawText(text, 880, 30, textPaint);

A: in your code you only call the image so the text doesn't show up, you can achieve to get all image from the layout that contains image and text using this code it will return Bitmap, and you can share it or pass it whatever you want,
private Bitmap getBitMapFromLayout(Context context ,Activity activity) {
        LayoutInflater mInflater = (LayoutInflater) activity.getSystemService(activity.LAYOUT_INFLATER_SERVICE);

        //Inflate the layout into a view and configure it the way you like
        RelativeLayout view = new RelativeLayout(activity);
        mInflater.inflate(R.layout.yourLayoutContainsImageAndTExt, view, true);

        //you can set Image or Text view here
        ImageView image = (ImageView) view.findViewById(R.id.image);
        TextView text = (TextView) view.findViewById(R.id.text);

        //Provide it with a layout params. It should necessarily be wrapping the
        //content as we not really going to have a parent for it.
        view.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT));

        //Pre-measure the view so that height and width don't remain null.
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

        //Assign a size and position to the view and all of its descendants
        view.layout(view.getMeasuredWidth(), view.getMeasuredHeight(), view.getMeasuredWidth(), view.getMeasuredHeight());

        //Create the bitmap
        Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(),
                view.getMeasuredHeight(),
                Bitmap.Config.ARGB_8888);
        //Create a canvas with the specified bitmap to draw into
        Canvas c = new Canvas(bitmap);

        //Render this view (and all of its children) to the given Canvas
        view.draw(c);
        return bitmap;
    }


text:
Q: PyBind11 Classes - method argument type conversion I am having trouble wrapping certain method.
The method expects one argument of type QString and in Python i am using PyQt5, which doesn't contain QString. Also for some reason it doesn't convert from Python string to QString automatically, which I read it should in Python3. So when I use the wrapped c++ method in python and pass python string as argument, it screams at me that it wants QString...
I do see a function type conversion in PyBind docs:
m.def("utf8_test",
    [](const std::string &s) {
        cout << "utf-8 is icing on the cake.\n";
        cout << s;
    }
);

This would work perfectly, if I was doing it for a function, but i need to do this for a method. I want to create an "in between" step that converts the given string to QString and then calls the method, but that is just my idea, I am sure there is a smarter solution. I had an idea to do it somehow like this:
pybind11::class_<myClass>(m,"myClass")
        .def("method",
        [](const std::string &s) {
            QString path = QString::fromStdString(*s);
            myClass::method(path); //nonsense, but you get the idea
        }
    );

But this obvisouly crashes to "cannot call member function ..... without object".
Excuse any possible syntax errors in the example above please, It's been a while since my last encounter with C++, I hope you get my point.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Object, Control and array I have the following code in VB.NET in which it will check for empty textboxes in an array. The code works fine but when I converted the code to C# it will no longer work. What do I miss? Please help.
Public Function CheckForEmptyTextBoxes(obj As Object()) As Boolean
    Dim QEmptyTextBox As Boolean
    For Each ctrl As Object In obj
        If TypeOf ctrl Is TextBox Then
            If CType(ctrl, TextBox).TextLength = 0 Then
                QEmptyTextBox = True
            Else
                QEmptyTextBox = False
            End If
        End If
    Next
    Return QEmptyTextBox
End Function

Code converted to C#
public bool CheckForEmptyTextBoxes(object[] obj)
 {
     bool QEmptyTextBox=false;
     foreach (object ctrl in obj)
     {
         if (ctrl is TextBox)
         {
             if ((TextBox)ctrl.TextLength == 0)
             {
                 QEmptyTextBox = true;
             }
             else
             {
                 QEmptyTextBox = false;
             }
         }
     }
     return QEmptyTextBox;
 }

A: You current code actually check if the last TextBox in the collection is empty:
     ...
     if (ctrl is TextBox)
     {
         if ((TextBox)ctrl.TextLength == 0)
         {
             QEmptyTextBox = true;  // <- please, notice absence of "break"
         }
         else
         {
             // this assigment can well overwrite empty TextBox found
             QEmptyTextBox = false;
         }
     }
     ...

To amend your current code:
 public bool CheckForEmptyTextBoxes(object[] obj) {
   foreach (object ctrl in obj) {
     TextBox box = ctrl as TextBox;

     if ((box != null) && (string.IsNullOrEmpty(box.Text)))
       return true; // <- Empty TextBox found
   }

   // We've scanned the entire collection and no empty TextBox has been found
   return false;
 }

If you want to check if there's at least one empty TextBox you can try Linq
using System.Linq;

...

public static bool CheckForEmptyTextBoxes(System.Collections.IEnumerable collection) {
  return collection
    .OfType<TextBox>()
    .Any(textBox => string.IsNullOrEmpty(textBox.Text));
}

...

if (CheckForEmptyTextBoxes(myPanel.Controls)) {
  // If there's an empty TextBox on myPanel
}


text:
Q: Same plugin to be used twice in a page without error I have a page that uses "Mac style bouncing menus" once on the left side panel and then again in the footer. Basically it's just the same plugin with different images.
Either one only works, even I tried jQuery.noConflict(true) , doesn't help.
My question is if we were to repeat the same plugin in a page ,what need to be done to avoid the conflict? from my understanding if various plugin to be used,jQuery.noConflict can solve it but for the same type of plugin?
test4.php

<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Test4</title>
        <link rel="stylesheet" href="css/style1.css" type="text/css">
        <link rel="stylesheet" href="css/side_style.css" type="text/css">

        <link href="css/bootstrap.css" rel="stylesheet" />
        <link href="http://getbootstrap.com/2.3.2/assets/js/google-code-prettify/prettify.css" rel="stylesheet" />

        <link href="http://getbootstrap.com/2.3.2/assets/css/bootstrap-responsive.css" rel="stylesheet" />

                <?php
                 include ('sidebar.php');

                ?>

                   <?php include('bottom_left.php');?>//1st Mac styled menu

           This is the Shop With Us Page of Indonesia

            <?php
          include ('footer.php');//2nd Mac styled menu
           ?>

          <?php
              include 'top-right.php';
              include 'side-ad.php';
          ?>

bottom-left.php

      Home
      About Us
      Contact Us

footer.php

      Home
      About Us
      Contact Us
      Home
      About Us
      Contact Us


text:
Q: What are other applications of difference equations in other branches of mathematics ?
*

*What are some of interesting results that arise from using difference equations in number theory , Combinatorics or any other field ?

A: Hrushovski used the model theory of difference fields to give another proof of the Manin-Mumford conjecture.

A: In analysis over fields of positive characteristic, the role of differential operators is played by special difference operators (the Carlitz derivative and its generalizations). In particular, the main special functions of that theory satisfy some difference equations. For the details see my book "Analysis in Positive Characteristic" (Cambridge University Press, 2009).

A: The three-term recurrence relation satisfied by a family of orthogonal polynomials is a crucial fact which brings together classical analysis, spectral theory and other branches of mathematics. This recurrence relation is obviously an example of a difference equation.

A: In signal processing, digital filtering, ARMA modelesation, use difference equations. In Linear prediction Coding, we seek a difference operator such that:
$x(n)=\sum_p{a(n)x(n-p)}+e(n)$
where $x(n)$ is for example a time serie (the uknown function in the difference equation). The goal of this coding is to find $a(n)$ by minimizing the error $e(n)$ so this is an example of an inverse problem for the difference operator given by the above equation. Like diffrential operators which are diagonalized by the Fourier transform, difference operators are diagonalized by the Z-Transform defined by:
$X(Z)= \sum_n{x(n)Z^{-n}}$
where $Z$ is a complex variable lying on the unit circle of the complex plane ($Z=\exp(-if)$). So a difference operator is transformed via the Z-transform to a multiplication operator by a polynom $P(Z)=\sum_p{a(p)Z^{-p}}$ and one method for the solution of the problem is the use of orthogonal polynoms over the unit circle.


text:
Q: Kernel function from polynomial basis functions In chapter 3 & 6 of Bishop's Pattern Recognition and Machine Learning, he showed that the equivalent kernel based on eqn (3.62)
$$ k(x,x') = \beta \phi(x)^T (\alpha I + \beta \Phi^T \Phi )^{-1}\phi(x')$$
and the standard kernel based on the feature space mapping eqn (6.10),
$$ k(x,x') = \phi(x)^T \phi(x') = \sum_{j=1}^M \phi_j(x)\phi_j(x') $$
both of which have a sinc like behavior corresponding to Figures 3.11(left) and 6.1(left), see below.

This is quite impossible given that when $x=0$, all $\phi_j(x)=x^j=0$, which implies $\phi(x)^T\phi(x')=0\ \forall x'$.  Is my assumption that $\phi_j(x)=x^j$ wrong?
My understanding is that polynomial basis are global functions, so how can one arrive at the conclusion that its kernel have a local behavior, it's not obvious to me at this point.

A: I had the same question, and it turns out that the figure is wrong! The corrected one appears on the book errata: Link


text:
Q: How to add active class to anchor tag inside li element and change current element appearance? I want to add active class to current element, so that clicked element can inherit active style.
JQuery code doesn't work. :(

$('.side-track li').click(function() {
  $('.side-track li a.active').removeClass('active');
  $(this).find("a").addClass('active');
});
.side-track {
  font-family: 'GalanoGrotesque-Regular';
  font-size: .9rem;
  float: right;
  transform: rotate(180deg);
  color: var(--lightGray);
}

.side-track li {
  writing-mode: vertical-rl;
}

.active {
  padding-left: 3px;
  background: linear-gradient(0deg, rgba(181, 195, 186, 1) 53%, rgba(12, 138, 104, 1) 53%) no-repeat;
  background-size: 3px 100%;
  background-position: left right;
  color: var(--grassGreen);
  font-weight: 700;
}

Quick summary

Challenge

Solution

Technologies

Results

A: Something like this?
Adding preventDefault() stops the link

$('.side-track').on("click", "li", function(e) {
  e.preventDefault(); // stop link
  $(this).closest("li") // active is on the LI
    .addClass('active')
    .siblings().removeClass('active');
});
.side-track {
  font-family: 'GalanoGrotesque-Regular';
  font-size: .9rem;
  float: right;
  transform: rotate(180deg);
  color: var(--lightGray);
}

.side-track li {
  writing-mode: vertical-rl;
}

.active {
  padding-left: 3px;
  background: linear-gradient(0deg, rgba(181, 195, 186, 1) 53%, rgba(12, 138, 104, 1) 53%) no-repeat;
  background-size: 3px 100%;
  background-position: left right;
  color: var(--grassGreen);
  font-weight: 700;
}

Quick summary

Challenge

Solution

Technologies

Results


text:
Q: Importing from a LibreOffice Calc workbook I have a LibreOffice Calc workbook with three worksheets. I'm trying to import data from the third worksheet. I've tried both the readODS and rio packages, but they keep returning the same error message:
Error: .onLoad failed in loadNamespace() for cli; details:
call: fun(libname, pkgname)
error: object 'clic_start_thread' not found
The readODS package's get_num_sheets_in_ods and list_ods_sheets functions work as expected. But its read_ods command throws the error above.
In particular, read_ods(path = "data/myFile.ods", sheet="Foobar", skip=2, range= "A3:E184") throws the error message above.
OTOH, the rio package's convert and import commands, without anything fancy, also throw the error message reproduced above.
I suspect the CLI package is being used to parse commands in both packages, but I'm at a loss for how these two packages seem to be choking on the neighborhoods. How should I debug these error messages?

A: Kat,
Your hint led me to the solution! Thank you, thank you, thank you!!!
After I failed to replicate duckmayr's example, I realized the problem was my configuration. I searched the web for ".onLoad failed in loadNamespace() for 'cli' clic." While I didn't come up with anything specifically for the cli package, I came across several cases in which the solution was to reinstall or reconfigure the offending package.
So, I tried running install.packages("cli"), and this fixed the problem.
Funny how knowing what the solution is not can lead to understanding what the solution is.


text:
Q: Calculating entropy of known sequence like 0,1,2,3 ... If we apply Shannon's formula to a sequence of numbers that we know how to generate (for example, natural numbers), shouldn't entropy be 0?
Mine might be a too intuitive definition of entropy. But if something is predictable, does it have entropy at all? Notwithstanding this is the fact that it appears to have entropy. However, is '000000'  any different from '012345'? According to online entropy calculators it is.


text:
Q: Converting a list of tuples to dictionary using a function I am still learning python, so I tried to convert a list of tuples to a list of dictionaries using  a function:
 query_result= [(3, 'base-certificate', 8, 2022), (2, 'case-certificate', 8, 2022), (3, 'standard-certificate', 8, 2022)]

I wrote a function that looks like this:
 def convert_query_data_for_frontend(object, time):
            if time == "month":
                data = [
                    {
                        row[1]: row[0],
                        "date": [row[2], row[3]],
                    }
                    for row in object
                ]
                return data

The result of running this function was: convert_query_data_for_frontend(query_result, 'month')
[{'base-certificate': 3, 'date': [8, 2022]}, {'case-certificate': 2, 'date': [8, 2022]}, {'standard-certificate': 3, 'date': [8, 2022]}]

It is not yet the desired result should have only one date for different dates in this case the month could be september etc, instead it should return:
[{'base-certificate': 3, 'case-certificate': 2, 'standard-certificate': 3, 'date': [8, 2022]}]

I thought just looping over the object and defining the dict would give me the desired result but didnt please what can I add or do in this case?

A: You have two things you're trying to do here:

*

*convert from tuples to dictionaries

*merge dictionaries

So far you have been successful in the first one but you're missing the second.
Starting with the output of your first function we can merge items with a common key using itertools.groupby and then utilize functools.reduce to combine the dictionaries we have grouped by date.
Additionally, since your data only has 1 date included I added some more dates to show off the grouping aspect
from functools import reduce
from itertools import groupby

cert_dates = [
    {'base-certificate': 3, 'date': [8, 2022]}, {'case-certificate': 2, 'date': [8, 2022]}, {'standard-certificate': 3, 'date': [8, 2022]},
    {'base-certificate': 3, 'date': [9, 2022]}, {'case-certificate': 2, 'date': [9, 2022]}, {'standard-certificate': 3, 'date': [10, 2022]},
]
grouped_list = groupby(cert_dates, key=lambda x: x['date'])
output_records = []
for _, records in grouped_list:
    output_records.append(reduce(lambda x, y: {**x, **y}, records))

for x in output_records:
    print(x)
# {'base-certificate': 3, 'date': [8, 2022], 'case-certificate': 2, 'standard-certificate': 3}
# {'base-certificate': 3, 'date': [9, 2022], 'case-certificate': 2}
# {'standard-certificate': 3, 'date': [10, 2022]}


text:
Q: convert mp4 to gif - gif not moving I am using this command to convert my mp4 to gif
ffmpeg -i out.mp4 -pix_fmt rgb24 output.gif

but the resulting gif does not move. I also get many of this message
[gif @ 000002809f53ef00] Non-monotonous DTS in output stream 0:0; previous: 46, current: 16; changing to 47. This may result in incorrect timestamps in the output file.
[gif @ 000002809f53ef00] Non-monotonous DTS in output stream 0:0; previous: 47, current: 16; changing to 48. This may result in incorrect timestamps in the output file.
[gif @ 000002809f53ef00] Non-monotonous DTS in output stream 0:0; previous: 48, current: 16; changing to 49. This may result in incorrect timestamps in the output file.
[gif @ 000002809f53ef00] Non-monotonous DTS in output stream 0:0; previous: 49, current: 17; changing to 50. This may result in incorrect timestamps in the output file.
[gif @ 000002809f53ef00] Non-monotonous DTS in output stream 0:0; previous: 50, current: 17; changing to 51. This may result in incorrect timestamps in the output file.
[gif @ 000002809f53ef00] Non-monotonous DTS in output stream 0:0; previous: 51, current: 17; changing to 52. This may result in incorrect timestamps in the output file.

My video is 300 fps


text:
Q: Banco de dados H2 no Cronapp Recebi a seguinte mensagem ao tentar publicar a aplicação no CronApp:
"Seu projeto utiliza um banco de dados H2. Os dados persistidos nesse tipo de banco poderão ser perdidos, devido à arquitetura distribuída e sem estado do cloud. Sugerimos usar outro tipo de banco de dados. Mesmo assim deseja continuar?"
Como posso criar outro tipo de banco de dados?

A: O ambiente de desenvolvimento do CronApp utiliza o banco de dados do tipo H2, que utiliza memória para armazenamento em disco. Os containers onde são publicadas as aplicações no CronApp não possuem armazenamento em disco.
Dessa forma, quando sua aplicação for publicada, você poderá até utilizar o banco H2 e tudo irá funcionar inclusive a gravação e leitura de dados, porém ao parar a aplicação o container será desligado, e quando for novamente iniciado, os dados terão desaparecido, pois só estavam na memória do container inicial, que foi desligado.
Para criar um banco de dados na nuvem, utilizando o CronApp IDE siga os passos:

*

*Clicar em Fonte de Dados (abre a aba )

*Clicar no botão

*Clicar no link

*Você é redirecionado para o console que apresenta a lista de bancos
disponíveis

*Clicar no botão [+] para adicionar

*Informar o nome do novo banco de dados

*O nome do banco criado passa a aparecer na lista

*Voltar para a aba Fonte de Dados, clicando sobre ela

*Selecionar da lista de bancos de dados na nuvem o nome do banco criado

*Clicar em

*Banco de dados é criado e aparece na lista de fontes de dados do
 projeto

Note que, além de criar o banco de dados na nuvem, você precisa ajustar a sua aplicação para usar a nova fonte de dados criada. Se você está utilizando o mecanismo de geração de camada de persistência através do diagrama, entre no diagrama e altere a fonte de dados selecionando da lista disponível a nova fonte de dados que corresponde ao seu banco de dados na nuvem recém criado.
Você vai encontrar mais informações em: https://docs.cronapp.io/display/CRON2/Bancos+de+dados+na+Nuvem


text:
Q: Unexpected token (START_OBJECT), expected one of [..] for java.time.OffsetDateTime I am parsing this JSON object:
@Data
@AllArgsConstructor
@NoArgsConstructor
@SuperBuilder
public class HotelDataForCreate  {

    private OffsetDateTime fromDate;
    private OffsetDateTime toDate;

}

where I put these values:
OffsetDateTime start = OffsetDateTime.now();
OffsetDateTime end = start.plusMinutes(1);

but I am getting this error when parsing:
"message" : "JSON parse error: Unexpected token (START_OBJECT), expected one of [VALUE_STRING, VALUE_NUMBER_INT, VALUE_NUMBER_FLOAT] for java.time.OffsetDateTime value; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Unexpected token (START_OBJECT), expected one of [VALUE_STRING, VALUE_NUMBER_INT, VALUE_NUMBER_FLOAT] for java.time.OffsetDateTime value\n at [Source: java.io.PushbackInputStream@ac6960; line: 1, column: 1001] (through reference chain: com.pxs.weboffice.leads.crud.model.LeadDataForCreate["fromDate"])",
      "stackTrace" : "org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unexpected token (START_OBJECT), expected one of [VALUE_STRING, VALUE_NUMBER_INT, VALUE_NUMBER_FLOAT] for java.time.OffsetDateTime value; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Unexpected token (START_OBJECT), expected one of [VALUE_STRING, VALUE_NUMBER_INT, VALUE_NUMBER_FLOAT] for java.time.OffsetDateTime value\n at [Source: java.io.PushbackInputStream@ac6960; line: 1, column: 1001] (through reference chain: com.pxs.weboffice.leads.crud.model.LeadDataForCreate[\"fromDate\"])\r\n\tat org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:238)\r\n\tat org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:223)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver.readWithMessageConverters(AbstractMessageConverterMethodArgumentResolver.java:201)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.readWithMessageConverters(RequestResponseBodyMethodProcessor.java:150)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.resolveArgument(RequestResponseBodyMethodProcessor.java:128)\r\n\tat org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:158)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:128)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)\r\n\tat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)\r\n\tat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)\r\n\tat org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)\r\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:707)\r\n\tat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)\r\n\tat org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:71)\r\n\tat javax.servlet.http.HttpServlet

Here the Json :
{
    ...
    "fromDate":{"offset":{"totalSeconds":7200,"id":"+02:00","rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]}},"month":"JULY","year":2019,"hour":16,"minute":4,"nano":563000000,"second":38,"dayOfMonth":25,"dayOfWeek":"THURSDAY","dayOfYear":206,"monthValue":7},"toDate":{"offset":{"totalSeconds":7200,"id":"+02:00","rules":{"fixedOffset":true,"transitionRules":[],"transitions":[]}},"month":"JULY","year":2019,"hour":16,"minute":5,"nano":563000000,"second":38,"dayOfMonth":25,"dayOfWeek":"THURSDAY","dayOfYear":206,"monthValue":7}}


text:
Q: ReactJs : `npm run build` fails with Exit status 1 I have a Create React App, Single Page Application application.
When I fire npm run build command, I get following error :
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! roffice@0.1.0 build: `react-scripts build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the roffice@0.1.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

my package.json looks like this:
   {
  "name": "roffice",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "bootstrap": "^4.3.1",
    "chalk": "^2.4.2",
    "child_process": "^1.0.2",
    "jquery": "^3.4.1",
    "jquery-ui": "^1.12.1",
    "jquery-ui-dist": "^1.12.1",
    "list-react-files": "^0.2.0",
    "react": "^16.8.6",
    "react-bell-icon": "^1.0.0",
    "react-bootstrap": "^1.0.0-beta.9",
    "react-confirm-alert": "^2.4.0",
    "react-custom-scrollbars": "^4.2.1",
    "react-datepicker": "^2.7.0",
    "react-dom": "^16.8.6",
    "react-global-configuration": "^1.3.0",
    "react-idle-timer": "^4.2.5",
    "react-input-calendar": "^0.5.4",
    "react-modal": "^3.8.1",
    "react-popper": "^1.3.3",
    "react-router-dom": "^5.0.0",
    "react-scripts": "^3.0.1",
    "react-spinner-material": "^1.1.1",
    "rxjs": "^6.4.0",
    "rxjs-compat": "^6.4.0",
    "save-file": "^2.3.1",
    "sys": "0.0.1",
    "underscore": "^1.9.1"
  },
  "scripts": {
    "start": "set PORT=3006 && react-scripts start",
    "build": "react-scripts --max_old_space_size=8192 build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app",
    "globals": {
      "window": true,
      "ActiveXObject": true
    }
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ]
}

I have been through similar questions on SO, but they didn't help, so kindly don't mark it as duplicate.
I am stuck here, any help is appreciated.
EDIT :
complete error logs:
0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/bin/node', '/usr/local/bin/npm', 'run', 'build' ]
2 info using npm@6.4.1
3 info using node@v10.15.2
4 verbose run-script [ 'prebuild', 'build', 'postbuild' ]
5 info lifecycle roffice@0.1.0~prebuild: roffice@0.1.0
6 info lifecycle roffice@0.1.0~build: roffice@0.1.0
7 verbose lifecycle roffice@0.1.0~build: unsafe-perm in lifecycle true
8 verbose lifecycle roffice@0.1.0~build: PATH: /usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/Users/chandrani.chatterjee/Desktop/New_Roffice/ROffice_React/node_modules/.bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/share/dotnet:~/.dotnet/tools:/Users/chandrani.chatterjee/Library/Android/sdk/platform-tools/:/Users/chandrani.chatterjee/Desktop/sdk/platform-tools/:/Users/chandrani.chatterjee/Library/Android/sdk/platform-tools/:/Users/chandrani.chatterjee/Desktop/sdk/platform-tools/
9 verbose lifecycle roffice@0.1.0~build: CWD: /Users/chandrani.chatterjee/Desktop/New_Roffice/ROffice_React
10 silly lifecycle roffice@0.1.0~build: Args: [ '-c', 'react-scripts build' ]
11 silly lifecycle roffice@0.1.0~build: Returned: code: 1  signal: null
12 info lifecycle roffice@0.1.0~build: Failed to exec build script
13 verbose stack Error: roffice@0.1.0 build: `react-scripts build`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:301:16)
13 verbose stack     at EventEmitter.emit (events.js:189:13)
13 verbose stack     at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:189:13)
13 verbose stack     at maybeClose (internal/child_process.js:970:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
14 verbose pkgid roffice@0.1.0
15 verbose cwd /Users/chandrani.chatterjee/Desktop/New_Roffice/ROffice_React
16 verbose Darwin 17.7.0
17 verbose argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "build"
18 verbose node v10.15.2
19 verbose npm  v6.4.1
20 error code ELIFECYCLE
21 error errno 1
22 error roffice@0.1.0 build: `react-scripts build`
22 error Exit status 1
23 error Failed at the roffice@0.1.0 build script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]

EDIT2 :
After deleting node_modules and package-lock.json , did npm install -> npm audit fix -> npm run build
got following error:
FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
 1: 0x10003b1db node::Abort() [/usr/local/bin/node]
 2: 0x10003b3e5 node::OnFatalError(char const*, char const*) [/usr/local/bin/node]
 3: 0x1001a86b5 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, bool) [/usr/local/bin/node]
 4: 0x100573ad2 v8::internal::Heap::FatalProcessOutOfMemory(char const*) [/usr/local/bin/node]
 5: 0x1005765a5 v8::internal::Heap::CheckIneffectiveMarkCompact(unsigned long, double) [/usr/local/bin/node]
 6: 0x10057244f v8::internal::Heap::PerformGarbageCollection(v8::internal::GarbageCollector, v8::GCCallbackFlags) [/usr/local/bin/node]
 7: 0x100570624 v8::internal::Heap::CollectGarbage(v8::internal::AllocationSpace, v8::internal::GarbageCollectionReason, v8::GCCallbackFlags) [/usr/local/bin/node]
 8: 0x10057cebc v8::internal::Heap::AllocateRawWithLigthRetry(int, v8::internal::AllocationSpace, v8::internal::AllocationAlignment) [/usr/local/bin/node]
 9: 0x10057cf3f v8::internal::Heap::AllocateRawWithRetryOrFail(int, v8::internal::AllocationSpace, v8::internal::AllocationAlignment) [/usr/local/bin/node]
10: 0x10054c884 v8::internal::Factory::NewFillerObject(int, bool, v8::internal::AllocationSpace) [/usr/local/bin/node]
11: 0x1007d4894 v8::internal::Runtime_AllocateInNewSpace(int, v8::internal::Object**, v8::internal::Isolate*) [/usr/local/bin/node]
12: 0x3716a5cdbe3d

A: It looks like your application is getting out of memory when building.
Try adding this in your package.json:
"build": "node --max_old_space_size=8192 <entry_file_path> --progress --env.<dev/prod>"

You can change the 8GB space to 4GB and try building first, if it
  works, you should be fine with 4GB

A: step 1 - delete the react app completely
step 2 - open terminal and npm cache clean --force
step 3 - npm install -g update-node
step 4 - npm i -g npm-upgrade
step 5 - create react app and it works
Also add path to npm in your environment variables (C:\Program Files\nodejs\node_modules\npm\bin).

A: can you execute the same thing in the windows command line
if it does not work try to increase the space memory by adding
"build": "node --max_old_space_size=8192 node_modules/.bin/react-scripts start --progress --env.prod"


text:
Q: Display a video from a Blob Javascript I would like to display a video from a Javascript Blob/File object in the HTML5 video tag.
This code only works for small videos :
var reader = new FileReader();
reader.onload = function(e) {
    document.getElementById("video").src=reader.result;
 }
reader.readAsDataURL(vid);

I cannot use this for big videos (> 10MB).
Is there a solution to display a big video from a blob object in HTML 5?

A: I've found. It was so simple that I didnt even see it...

/**
 * @param {Blob} videoFile
 * @param {HTMLVideoElement} videoEl
 * @returns {void}
 */
function display( videoFile, videoEl ) {

    // Preconditions:
    if( !( videoFile instanceof Blob ) ) throw new Error( '`videoFile` must be a Blob or File object.' ); // The `File` prototype extends the `Blob` prototype, so `instanceof Blob` works for both.
    if( !( videoEl instanceof HTMLVideoElement ) ) throw new Error( '`videoEl` must be a <video> element.' );

    //

    const newObjectUrl = URL.createObjectURL( videoFile );

    // URLs created by `URL.createObjectURL` always use the `blob:` URI scheme: https://w3c.github.io/FileAPI/#dfn-createObjectURL
    const oldObjectUrl = videoEl.currentSrc;
    if( oldObjectUrl && oldObjectUrl.startsWith('blob:') ) {
        // It is very important to revoke the previous ObjectURL to prevent memory leaks. Un-set the `src` first.
        // See https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL

        videoEl.src = ''; // <-- Un-set the src property *before* revoking the object URL.
        URL.revokeObjectURL( oldObjectUrl );
    }

    // Then set the new URL:
    videoEl.src = newObjectUrl;

    // And load it:
    videoEl.load(); // https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/load

}

A: In some case blobObject.data should be provided in createObjectURL() method.
See this simple trick:
function playVideo(videoStream){ // as blob

 var video = document.querySelector('video');

 var videoUrl=window.URL.createObjectURL(videoStream.data);// blob.data gives actual data

 video.src = videoUrl;
}


text:
Q: Fourier transform on images with holes This is a problem in our lab work recently

*

*I would like to fourier transform an image with several "holes" on it.

*Those holes are ellipses and of different orientations.
E.g. an imgae with holes

*After fourier transform, some magnitudes would be modified.

*These holes must be kept intact when inversing the fourier transform, also those modifications would be recovered later.
so simply padding with zeros is not working because
1) Modifications will "contaminate" the holes when inversing the fourier transform.
2) Padding with zeros and putting the holes content back will make a complete recovery impossible.

So, would it be possible to do fourier transform on an image with holes?
or could we map or decompose the concave image into rectangle(s)?

A: Two answers depending on exactly what you want to do:
1- Can you find the spatial domain equivalent of your magnitude modification, and apply a 2D convolution on the image but the holes?
2- Can you follow an iterative approach, in which you replace the "holes" with an average value, do fft, apply your magnitude transformation, do ifft, replace the holes with the original content, and repeat until you get sufficient convergence?


text:
Q: Observable success method is not firing Can you tell me why this () success method is not firing? When I use forkjoin() it is working nicely.Success method must fire every time no? Hope it is like a final method on try-catch block.
Note: Please see the inline comments too.
.ts
 getAllBooksReadAndUnRead(id: number, loader?) {
        this.article.getAllBooksReadAndUnRead(id)
          .map((res: any) => res.json())
          .subscribe(res => {
               this.setAllData(res); //it comes to here
               this.loadingControllerService.dismissLoader(loader);//I have to put this here.Then no problem.But I think it is duplicate of work???
          },
          error => {this.loadingControllerService.dismissLoader(loader);},
          () => {this.loadingControllerService.dismissLoader(loader);}//not fire
       });
      }

Api call
 getAllBooksReadAndUnRead(bookId) {
        return this.apiSer.get(`${config.fromThisBook}?page=all&book[]=${bookId}`);
    }

Generic method:
get(api) {
        return new Observable(observer => {
            let header = new Headers();
            this.createHeader(header)
                .then(() => {
                    let options = new BaseRequestOptions();
                    options.withCredentials = true;
                    options.headers = header;
                    this.http.get(api, options)
                        .subscribe(response => {
                            observer.next(response);
                         }, (e) => {
                            observer.error(e);
                        });
                })
        })
    }

post()
post(url, params): Observable<any> {
        return new Observable(observer => {
            let header = new Headers();
            this.createHeader(header)
                .then(() => {
                    let options = new RequestOptions({ headers: header });
                    this.http.post(url, params, options)
                        .subscribe(response => {
                            observer.next(response);
                            observer.complete();
                        }, (e) => {
                            observer.error(e);
                        });
                })
        })
    }

A: The problem is that you never trigger complete in your custom producer. You need something like this:
  get(api) {
    return new Observable(observer => {
      let header = new Headers();
      this.createHeader(header)
        .then(() => {
          let options = new BaseRequestOptions();
          options.withCredentials = true;
          options.headers = header;
          this.http.get(api, options).subscribe(
            response => observer.next(response),
            (e) => observer.error(e),
            () => observer.complete();  <-------------------------
          );
        })
    })
  }

Also I think you don't need a custom producer, try like this:
  get(api) {
    return Observable.from(this.createHeader()).map((header) => {
      let options = new BaseRequestOptions();
      options.withCredentials = true;
      options.headers = header;
      return this.http.get(api, options);
    }).mergeAll();
  }

Here is how it works:

*

*Observable.from(this.createHeader()) returns an observable that will deliver values once the promise is resolved

*.map((header) => { observes the value that comes from returned promise and makes an HTTP request and returns the result in the form of the observable

*mergeAll() - since the previous operation returns and observable, we need to flatten it

A: I try to avoid wrapping code blocks in parentheses unless I have to, as it makes it easier to confuse their placement. For example, you have an extra closing } in your second to last line that may be causing an issue:
getAllBooksReadAndUnRead(id: number, loader?) {
    this.article.getAllBooksReadAndUnRead(id)
      .map((res: any) => res.json())
      .subscribe(res => {
           this.setAllData(res);//it comes to here
      },
      error => {this.loadingControllerService.dismissLoader(loader);},
      () => {this.loadingControllerService.dismissLoader(loader);}//not fire
   );
  }

I would be inclined to simplify the parentheses like this:
  getAllBooksReadAndUnRead(id: number, loader?) {
    this.article.getAllBooksReadAndUnRead(id)
      .map(res: any => res.json())
      .subscribe(res => {
           this.setAllData(res);//it comes to here
      },
      error => this.loadingControllerService.dismissLoader(loader),
      () => this.loadingControllerService.dismissLoader(loader)//not fire
   )};


text:
Q: Cursor for loop creating duplicate entries for nested XQUERY I have created a procedure which is parsing xml data into multiple tables. I am catching exception for primary key constraint, and if there is a duplicate found in result, it will be inserted into a table named as DUPLICATE.
Now when i use the cursor it tends to iterate more than the required number of times i.e. 1. Procedure
DECLARE
PER_ID varchar2(20);
    NAME varchar2(20);
SECTIONS_ID varchar2(20);
SECTIONS_NAME varchar2(20);
    var1 number;
    exception_var number;
CURSOR C1 IS
    select d.department_id
       , d.department_name
       , s.sections_id
      , s.sections_name
   from xml_unit_download t
     , xmltable(
         '/ROWSET/DATA'
         passing t.xml_file
         columns
           DEPARTMENT_ID   varchar2(20) path 'DEPARTMENT/DEPARTMENT_ID'
         , DEPARTMENT_NAME varchar2(30) path 'DEPARTMENT/DEPARTMENT_NAME'
         , SECTIONS        xmltype      path 'SECTIONS'
       ) d
     , xmltable(
         '/SECTIONS'
         passing d.sections
         columns
           SECTIONS_ID     varchar2(20) path 'SECTIONS_ID'
        , SECTIONS_NAME   varchar2(30) path 'SECTIONS_NAME'
      ) s
 where
  t.Status = 4;
  BEGIN

  FOR R_C1 IN C1 LOOP
      BEGIN
      insert into DEPARTMENT(id, name) values(R_C1.PER_ID, R_C1.name);
      insert into SECTIONS(id, name) values(R_C1.SECTIONS_ID, R_C1.SECTIONS_NAME);
      var1:= var1+1;
       dbms_output.put_line('Insert=' || var1);
      commit;
           --dbms_output.put_line('Duplicate='||var);
      EXCEPTION
         WHEN DUP_VAL_ON_INDEX THEN
         dbms_output.put_line('Duplicate=');
         insert into duplicate(id, name)values(R_C1.id, R_C1_name);
      END;
      END LOOP;
  END;

How am i going to handle this situation? I have tried using INSERT ALL also but it does not seem to work. Here is my try of INSERT ALL procedure
DECLARE
PER_ID varchar2(20);
    NAME varchar2(200);
    var1 number;
    exception_var number;

  BEGIN

      insert all
      into SECTIONS (id) values(department_id)

      --into sect (id, name) values(s.SECTIONS_ID, s.SECTIONS_NAME )
   select d.department_id
       , d.department_name
       , s.sections_id
      , s.sections_name
   from xml_unit_download t
     , xmltable(
         '/ROWSET/DATA'
         passing t.xml_file
         columns
           "DEPARTMENT_ID"   varchar2(20) path 'DEPARTMENT/DEPARTMENT_ID'
         , "DEPARTMENT_NAME" varchar2(30) path 'DEPARTMENT/DEPARTMENT_NAME'
         , "SECTIONS"        xmltype      path 'SECTIONS'
       ) d
     , xmltable(
         '/SECTIONS'
         passing d.sections
         columns
           "SECTIONS_ID"     varchar2(20) path 'SECTIONS_ID'
        , "SECTIONS_NAME"   varchar2(30) path 'SECTIONS_NAME'
      ) s
 where
  t.Status = 4;
  dbms_output.put_line('Insert=' || var1);
      var1:= var1+1;
       dbms_output.put_line('Insert=' || var1);
      commit;
           --dbms_output.put_line('Duplicate='||var);
      EXCEPTION
         WHEN DUP_VAL_ON_INDEX THEN
         --insert into
         dbms_output.put_line('Duplicate=');
  END;

The XML which is being queried contains data of DEPARTMENT and its SECTIONS. DEPARTMENT has one to many relationship with SECTIONS i.e. a DEPARTMENT can have one or multiple SECTIONS and there may be instances where DEPARTMENT will not have any SECTIONS.
Structure of XML is such that  tag identifies a DEPARTMENT and set of its corresponding SECTIONS.
XML
<ROWSET>
<DATA>
 <DEPARTMENT>
  <DEPARTMENT_ID>DEP1</DEPARTMENT_ID>
  <DEPARTMENT_NAME>myDEPARTMENT1</DEPARTMENT_NAME>
 </DEPARTMENT>
 <SECTIONS>
  <SECTIONS_ID>6390135666643567</SECTIONS_ID>
  <SECTIONS_NAME>mySection1</SECTIONS_NAME>
  </SECTIONS>
   <SECTIONS>
  <SECTIONS_ID>6390135666643567</SECTIONS_ID>
  <SECTIONS_NAME>mySection2</SECTIONS_NAME>
  </SECTIONS>
 </DATA>
 <DATA>
 <DEPARTMENT>
  <DEPARTMENT_ID>DEP2</DEPARTMENT_ID>
  <DEPARTMENT_NAME>myDEPARTMENT2</DEPARTMENT_NAME>
 </DEPARTMENT>
 <SECTIONS>
  <SECTIONS_ID>63902</SECTIONS_ID>
  <SECTIONS_NAME>mySection1</SECTIONS_NAME>
  </SECTIONS>
 </DATA>
<DATA>
 <DEPARTMENT>
  <DEPARTMENT_ID>DEP3</DEPARTMENT_ID>
  <DEPARTMENT_NAME>myDEPARTMENT3</DEPARTMENT_NAME>
 </DEPARTMENT>
</DATA>
</ROWSET>

A: Since you can have multiple sections in each department, you'll expect duplicates. You might be able to get what you want just by moving where you catch the exception, so it will still do the insert into sections:
  FOR R_C1 IN C1 LOOP
      BEGIN
         insert into DEPARTMENT(id, name)
            values(R_C1.department_id, R_C1.department_name);
      EXCEPTION
         WHEN DUP_VAL_ON_INDEX THEN
         dbms_output.put_line('Duplicate=');
         insert into duplicate(id, name)
            values(R_C1.department_id, R_C1.department_name);
      END;
      insert into SECTIONS(id, name)
         values(R_C1.SECTIONS_ID, R_C1.SECTIONS_NAME);
      var1:= var1+1;
      dbms_output.put_line('Insert=' || var1);
   END LOOP;

You could also use tracker variables (if you see a record with the same department_id as the previous one you saw, don't attempt to insert a department record, just do the sections insert), or you could use nested loops:
declare
   cursor dept_cur is
      select d.department_id
         , d.department_name
         , d.sections
      from xml_unit_download t
         , xmltable(
            '/ROWSET/DATA'
            passing t.xml_file
            columns
              "DEPARTMENT_ID"   varchar2(20) path 'DEPARTMENT/DEPARTMENT_ID'
            , "DEPARTMENT_NAME" varchar2(30) path 'DEPARTMENT/DEPARTMENT_NAME'
            , "SECTIONS"        xmltype      path 'SECTIONS'
         ) d
      where
         t.Status = 4;

   cursor sect_cur(sections xmltype) is
      select s.sections_id
         , s.sections_name
      from xmltable(
            '/SECTIONS'
            passing sections
            columns
              "SECTIONS_ID"     varchar2(20) path 'SECTIONS_ID'
           , "SECTIONS_NAME"   varchar2(30) path 'SECTIONS_NAME'
         ) s;
begin
   for dept in dept_cur loop
      insert into department(id, name)
         values (dept.department_id, dept.department_name);
      for sect in sect_cur(dept.sections) loop
         insert into sections(id, name, department_id)
            values (sect.sections_id, sect.sections_name, dept.department_id);
      end loop;
   end loop;
end;
/

PL/SQL procedure successfully completed.

This uses one loop to get the department info (which won't have duplicates) plus the XMLTYPE sections, and then passes the section to the second cursor to expand.
select * from department;

ID                             NAME
------------------------------ ------------------------------
DEP1                           myDEPARTMENT1
DEP2                           myDEPARTMENT2
DEP3                           myDEPARTMENT3

select * from sections;

ID                             NAME                           DEPARTMENT_ID
------------------------------ ------------------------------ ------------------------------
6390135666643567               mySection1                     DEP1
6390135666643567               mySection2                     DEP1
63902                          mySection1                     DEP2

You don't have to use PL/SQL, you could just do two inserts:
insert into department(id, name)
select d.department_id
   , d.department_name
from xml_unit_download t
   , xmltable(
      '/ROWSET/DATA'
      passing t.xml_file
      columns
        "DEPARTMENT_ID"   varchar2(20) path 'DEPARTMENT/DEPARTMENT_ID'
      , "DEPARTMENT_NAME" varchar2(30) path 'DEPARTMENT/DEPARTMENT_NAME'
   ) d
where
   t.Status = 4;

... and:
insert into sections(id, name, department_id)
select s.sections_id
   , s.sections_name
   , d.department_id
from xml_unit_download t
   , xmltable(
      '/ROWSET/DATA'
      passing t.xml_file
      columns
        "DEPARTMENT_ID"   varchar2(20) path 'DEPARTMENT/DEPARTMENT_ID'
      , "DEPARTMENT_NAME" varchar2(30) path 'DEPARTMENT/DEPARTMENT_NAME'
      , "SECTIONS"        xmltype      path 'SECTIONS'
   ) d
   , xmltable(
      '/SECTIONS'
      passing d.sections
      columns
        "SECTIONS_ID"     varchar2(20) path 'SECTIONS_ID'
     , "SECTIONS_NAME"   varchar2(30) path 'SECTIONS_NAME'
   ) s
where
   t.Status = 4;

... which put the same data in the tables as the PL/SQL block does.
In both I've assumed you want a column linking the two tables, but perhaps they aren't uniquely linked and you want separate section and department_section tables, which could easily be generated in the same way.
Also note that both approaches create a department record for DEP3, which your original wouldn't do, unless you used the outer joins from a previous answer; and then you'd have to notice there was no section info and not attempt the second insert.

A: This seems like a basic cardinality issue - if you have more than one section in a department, then you're going to get more than one row for each department in the results and therefore you'll see duplicate department information because of the program code rather than the input data.
Instead of trying to do this in one query, why not break it up into two cursor/for loops?
Something like this:
BEGIN

  <<department_loop>>
  FOR r_department IN (
    SELECT
      d.department_id
    , d.department_name
    , d.sections
    FROM xml_unit_download t
   , XMLTABLE(
     '/ROWSET/DATA'
     PASSING t.xml_file
     COLUMNS
       department_id   VARCHAR2(20) PATH 'DEPARTMENT/DEPARTMENT_ID'
     , department_name VARCHAR2(30) PATH 'DEPARTMENT/DEPARTMENT_NAME'
     , sections        XMLTYPE      path 'SECTIONS'
    ) d
    WHERE t.status = 4
  )
  LOOP

    BEGIN
      INSERT INTO departments (id, name)
      VALUES (r_department.department_id, r_department.department_name);
    EXCEPTION
      WHEN DUP_VAL_ON_INDEX THEN
        INSERT INTO department_duplicates (id, name)
        VALUES (r_department.department_id, r_department.department_name);
    END;

    <<section_loop>>
    FOR r_section IN (
      SELECT
        s.sections_id
      , s.sections_name
      FROM XMLTABLE (
      '/SECTIONS'
      PASSING r_department.sections
      COLUMNS
        sections_id   VARCHAR2(20) PATH 'SECTIONS_ID'
      , sections_name VARCHAR2(30) PATH 'SECTIONS_NAME'
      ) s
    )
    LOOP

      BEGIN
        INSERT INTO sections (id, name, department_id)
        VALUES (r_section.sections_id, r_section.sections_name, r_department.department_id);
      EXCEPTION
        WHEN DUP_VAL_ON_INDEX THEN
          INSERT INTO section_duplicates (id, name, department_id)
          VALUES (r_section.sections_id, r_section.sections_name, r_department.department_id);
      END;

    END LOOP section_loop;

  END LOOP department_loop;

END;
/

This has the following benefits:

*

*You're able to trap the individual duplicates (if found) fairly easily, in terms of both departments and sections.

*You're not introducing cardinality due to program code - any duplicates are true input data duplicates.

*You don't have to worry about tracking the rows you're using / have used, it's implicit in the nested loop structure.


text:
Q: Disappearing voltage I'm an 30 yr electrician. I have a problem neither I nor my co workers have ever seen nor can we find an answer to. Here's the situation.
In a particular 60' length of EMT, (metallic conduit), we had several circuits run. The load for one of the circuits was not working, we measured voltage at the load and the voltage was zero, measured at source and had 277vac. Somewhere in a pipe of 60' with no junctions or splices the voltage disappeared. Here's the best part we replaced the conductor with same result. We then added a conductor tied it in in parallel to the conductor with disappearing voltage and had full 277vac at the end, load lighting now working. Only one wire still had voltage. If we removed the parallel conductor voltage disappears. If we pulled the conductor out of the conduit laid it on the ground it would then carry the voltage. put back in conduit and no voltage at end.
Summary of details:

*

**System voltage- 277/480Y 3ph/4wire grounded.

*All conductors- #12 thhn copper

*All conductors passed continuity test.

*Circuit in question= 1 ungrounded ("hot") & 1 grounded (neutral). (2 wire)

*Multiple other 2wire 277v circuits in conduit of diverse phasing,(no problems that we knew of).

*All circuits terminated to 20amp breakers.

*Conduit mechanical continuity was checked, no loose parts or joints.

*Conduit on metal rack connected to steel structure, with several other metal conduits.

Anyone have any ideas?

A: It sounds like you're experiencing some sort of electrical interference that is causing the voltage to drop in the conduit. There could be a variety of causes, such as high levels of electromagnetic interference (EMI) or radio frequency interference (RFI) in the vicinity, or electrical interference from other conductors in the same conduit or nearby. The fact that adding a parallel conductor resolved the problem suggests that the issue is not with the conductor itself, but rather with the environment in which it is installed. I would recommend further investigation into the source of the interference, such as checking for high levels of EMI/RFI in the area, or performing a test to determine if there is electrical interference from other conductors in the vicinity.
I also suggest:
-Look for heavy equipment that is used at the location (heavy motors from close buildings).
-Try checking your installation at different times (at night maybe) the source of EMI noise might be gone at that time.
-Try using oscilloscope to see the input and output of your cable's supply. Even use spectrum analyzer if you can/have one. (Actually the spectrum analyzer should be the first one to suggest here. But its the most expensive option. You can find cheap hobbyist spectrum analyzers as well though.)
I have heard such strong EMI interferences happen, which were so strong that could run 220V motors that pumped water from lakes. (Yes this was a particular case/example I heard happened somewhere in Russia at the Soviet era)

A: If the wires themselves show continuity, then it's most likely that there's something wrong with the connections at one end.  Maybe a broken or high resistance joint.  Maybe the three phases and neutral haven't been wired to the right connections at one end.


text:
Q: Handle CData in Stax and jaxb I'm trying to write a XML fragment containing a CData element in Spring StaxtItemWriter and Jaxb marshaller. But the output is either:

*

*not wrap with <![CDATA[ ... ]]>

*or escaped: < and > replaced by < and >
First, the item writer:
<bean id="userAuthorizationErrorItemWriter"
    class="org.springframework.batch.item.xml.StaxEventItemWriter">
    <property name="rootTagName" value="UserAuthorizationEvent" />
    <property name="rootElementAttributes">
        <map>
            <entry key="xmlns:xsi" value="http://www.w3.org/2001/XMLSchema-instance" />
        </map>
    </property>
    <property name="marshaller" ref="userAuthorizationTypeMarshaller" />
    <property name="overwriteOutput" value="true" />
    <property name="resource" value="file://C:/TEMP/fichierOUT.xml" />
    <property name="transactional" value="false" />
</bean>

Then the JAXB marshaller
<bean id="userAuthorizationTypeMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
    <property name="contextPath" value="com.usecase1.xsd.model"/>
</bean>

The java class (simplified):
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "UserAuthorizationType", propOrder = {"action"})
@XmlRootElement(name = "UserAuthorization")
public class UserAuthorizationType {

    @XmlElement(name = "Action", required = true)
    protected String action;

    public String getAction() {
        return action;
    }

    public void setAction(String value) {
        this.action = value;
    }
}

When writing to file, I want that the Action value to be encapsulate into a <![CDATA[ ... ]]> block.
I tried using a @XmlJavaTypeAdapter(Adapter1.class) that return:
public String marshal(String value) {
    return "<![CDATA[" + value + "]]>";
}

But the output is escaped:
<UserAuthorization><Action><![CDATA[first, second, third]]></Action></UserAuthorization>

Do you have any idea?

A: You will have to create a custom XML marshaller and register the elements that should be output as CDATA. See if this example helps https://jaxb.java.net/faq/JaxbCDATASample.java


text:
Q: How to set different background color for settings window, other than Editor Background As the title suggests, I have specific color overrides in my settings.json.
There is editor.background, but I was wondering for those windows for when code isn't open? Like the settings window, etc.

A: AFAIK, there is no specific customization for the settings window background. They are all considered as an "editor" and are all affected by the same setting:
    "editor.background": "#282a36",

The only colors related to the settings window are these:
    "settings.checkboxBackground": "#ffb86c",
    "settings.checkboxBorder": "#191a21",
    "settings.checkboxForeground": "#f6f6f4",
    "settings.dropdownBackground": "#262626",
    "settings.dropdownBorder": "#191a21",
    "settings.dropdownForeground": "#f6f6f4",
    "settings.headerForeground": "#f6f6f4",
    "settings.modifiedItemIndicator": "#ffb86c",
    "settings.numberInputBackground": "#262626",
    "settings.numberInputBorder": "#191a21",
    "settings.numberInputForeground": "#f6f6f4",
    "settings.textInputBackground": "#262626",
    "settings.textInputBorder": "#191a21",
    "settings.textInputForeground": "#f6f6f4",


text:
Q: Latex different appendix section label \documentclass[12pt]{report}
\usepackage[margin=1.5cm, noheadfoot]{geometry}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[magyar]{babel}

\usepackage{graphicx}
\usepackage{float}

\begin{document}

\counterwithout{figure}{chapter}

\tableofcontents\vfill

\chapter{First}
\section{First section}
\begin{figure}[H]
    \centering
    \includegraphics{example-image}
    \caption{Caption}
    \label{fig:ex}
\end{figure}

\clearpage
\pagenumbering{roman}
\renewcommand\thefigure{F.\arabic{figure}}
\setcounter{figure}{0}
\appendix
\chapter*{Függelék}
\refstepcounter{chapter}
\addcontentsline{toc}{chapter}{Függelék}
\section{First section in Ap}
\begin{figure}[H]
    \centering
    \includegraphics{example-image}
    \caption{Caption}
    \label{fig:ap-ex}
\end{figure}
\section{Second section in Ap}

\end{document}

As you can see in the Appendix (Függelék means Appendix in my native laguage), my Appendix section label is A.1. and A.2., how could I change letter A to letter F? So appendix section label should be F.1. and F.2.
The label should change in the toc as well.
I only what one Appendix chapter.

A: I suggest you insert the instruction
\renewcommand\thesection{F.\arabic{section}}

immediately before the first \section directive following the \appendix directive.

\documentclass[12pt]{report}
\usepackage[margin=1.5cm, noheadfoot]{geometry}

%%\usepackage[utf8]{inputenc} %  that's the default nowadays
\usepackage[T1]{fontenc}
\usepackage[magyar]{babel}

\usepackage{graphicx}
%%\usepackage{float}

\counterwithout{figure}{chapter}

\begin{document}

\tableofcontents%\vfill % \vfill isn't needed

\listoffigures

\chapter{First chapter}
\section{First section in chapter 1}

\begin{figure}[h]
    \centering
    \includegraphics{example-image}
    \caption{Caption}
    \label{fig:ex}
\end{figure}

\clearpage
\pagenumbering{roman}
\renewcommand\thefigure{F.\arabic{figure}}
\setcounter{figure}{0}
\appendix
\chapter*{Függelék}
\refstepcounter{chapter}

\addcontentsline{toc}{chapter}{Függelék}
\renewcommand\thesection{F.\arabic{section}} % <-- new

\section{First section in Appendix}

\begin{figure}[h]
    \centering
    \includegraphics{example-image}
    \caption{Caption text}
    \label{fig:ap-ex}
\end{figure}

\section{Second section in Apppendix}

\end{document}


text:
Q: How is geolocation determined in a browser on a deskop computer? http://diveintohtml5.info/geolocation.html
I see geolocation. How does it work for a desktop computer? Is it just by IP address? On a desktop computer, I see it complains that the geolocation can not be determined in a browser. So it sounds like it does not just use IP addresses. How does geolocation work in this case?


text:
Q: VBA Access Textbox populate without clicking I have my textbox populating correctly with the below code. The only problem is, I need the textbox to populate on its own without the user clicking, entering or doing anything.
Private Sub Text1106_Click()

Dim Chip As Variant

 Chip = DLookup("ExtMaintChip", "TableDataPave", "[YrRated] = Forms![FormsFormattedPave]![YrRated] And [RdSecNo] = Forms![FormsFormattedPave]![TextRdSecNo]")

If Chip = 0 Then
    Me.Text1106 = 0
ElseIf Chip = 1 Then
    Me.Text1106 = "<10"
ElseIf Chip = 2 Then
    Me.Text1106 = "10-20"
ElseIf Chip = 3 Then
    Me.Text1106 = "20-50"
ElseIf Chip = 4 Then
    Me.Text1106 = "50-80"
ElseIf Chip = 5 Then
    Me.Text1106 = ">80"
End If

End Sub

A: It all depends on whether you want to populate that text only the first time the form loads, or every time a new record is loaded, in which case you'd want to use the Form_current() event.
To run the code only the first time, you might use something like this:
Private Sub Form_Load()
   Text1106_Click()
End Sub

Or to run it for every record, like this:
Private Sub Form_Current()
   Text1106_Click()
End Sub


text:
Q: why c++wt is not integrated with ExtJs 3.x ? and how is it possible to integrate it with that? I just wondering why wt (the WebToolkit for c++) is not integrated with ExtJs 3.x whereas it is still using extJs 2.x.
and how is it possible to integrated it with the updated version of extjs I want to use some updated widget out of extjs 3.0 with the help of wt but unfortunately there is no chance :(
regards.

A: My understanding is that they're not so happy about Ext JS style widgets anymore, and prefer to use their own widgets.
I think it's the answer to most open source support questions. It's like nobody that's working on the project is interested in upgrading all the code to the latest version; if you really want it, do it yourself, or pay someone :)
There is some interest in it and more info here: http://sourceforge.net/mailarchive/message.php?msg_id=26058692
The summary there for not upgrading is basically:

No, I think they're not ..  some
  boring  licencing  stuff  no one
  actually cares about  except for  the
  Emweb guys :) And the fact that ExtJS
  is getting really buggy :-)


text:
Q: Migrating old mbox format to maildir- preserving UIDL values I am attempting to migrate several hundred email accounts from an old server running sendmail 8.13.6/dovecot 0.99.14 (mbox format) to a new server running postfix 2.6.6/dovecot 2.0.9 (maildir format).
I tried migrating a couple mailboxes with dsync and also tried with imapsync, but in both cases the message UIDLs are being changed, which will obviously cause pop desktop clients to re-download all messages in their pop inbox, which in turn will yield a lot of angry calls and emails from my users.
The strange part is that apparently in the old dovecot 0.99.14, a different UIDL format was used: example old format UIDLs: 1391619175.6 and 1391619175.7 for two consecutive messages.  New format UIDLs assigned to these two messages upon import: 0000000152f30760 and 0000000252f30760 using the format %08Xu%08Xv defined in dovecot.conf
And I am not seeing an option in the 0.9 version's dovdcot.conf file to indicate what format this is, so I'm not sure how to configure the new installation to mimic this format.
Any insight into a good way of preserving the old UIDLs would be greatly appreciated.

A: the uidl change from one version to another may be addressed using the same "pop3_uidl_format" option on the target host as on the source host.
the old default seems to be %v.%u, according to
http://wiki1.dovecot.org/POP3Server
Try it...
Also, if I were in your site I would take a look at dovecotadm copy to see if it gives any better results (in term of performances), though you would have to use it from the target system as it was probably not part of 0.99.
You'll probably have to mount the FS of the old server to the new one, but once done, you could use something like:
doveadm import -u sam@middle.earth maildir:/var/mailmeo/middle.earth/f/frodo/MailDir . ALL

A: Take a look at POP3 migration in dovecots wiki.
You may:
Make dovecot use UIDL based on maildir file name: pop3_uidl_format = %f
OR
Make dovecot use UIDL based on X-UIDL: header : pop3_reuse_xuidl=yes
I suggest file name based way.


text:
Q: Questions about actionscript I have a few different question and i have decided to put them in one. So the first question : If i have one and the same code(for example):
buttonsA.buton1a.addEventListener(MouseEvent.MOUSE_DOWN , buton1a_function);
buttonsA.buton2a.addEventListener(MouseEvent.MOUSE_DOWN , buton2a_function);
buttonsA.buton3a.addEventListener(MouseEvent.MOUSE_DOWN , buton3a_function);
buttonsA.buton4a.addEventListener(MouseEvent.MOUSE_DOWN , buton4a_function);
buttonsA.buton5a.addEventListener(MouseEvent.MOUSE_DOWN , buton5a_function);
buttonsA.buton6a.addEventListener(MouseEvent.MOUSE_DOWN , buton6a_function);
buttonsA.buton7a.addEventListener(MouseEvent.MOUSE_DOWN , buton7a_function);
buttonsA.buton8a.addEventListener(MouseEvent.MOUSE_DOWN , buton8a_function);
buttonsA.buton9a.addEventListener(MouseEvent.MOUSE_DOWN , buton9a_function);
buttonsA.buton10a.addEventListener(MouseEvent.MOUSE_DOWN , buton10a_function);

and i want to put it in several places(in different conditions) can i put them in a function a call a function instead a copying a large amout of text (I thought about 'include' from a different file but i want to keep all the information in one file).
The second question is about arrays : In my situation i have an array and i  .push() a different numbers in it.But it could be "1,51,11,2,13' or "1,2,3,4,5" so every time place of numbers (and numbers themselves) are different. How can i say to AS3 in function to remove(.splice) exactly the number 5 or 6 (in spite of their place in the array).
The third question is again about the "code" that is upper in the question. Can i maybe with the loop for to make all these 10 addEventListen with a fewer code (i think it should be something like that:)
    for(var i:int = 1; i <= 100; i++){
   //buttonsA.buton'i'a.addEventListener(MouseEvent.MOUSE_DOWN , buton'i'a_function);
    }

Long story short maybe i didn't have to put so much question and maybe my thoughts are not correct, but i think that my questions are easy but i can't solve them. Any decisions and replies are welcomed :) Thanks.

A: First Question:
Not sure I understand your first question. I'll take a stab at it and say you're wanting the functionality of the button mouse down to be enabled during different contexts of your application state, but you don't want to repeat all the event listeners all the time?
if so, you should make a subclass for all your button to inherit from. It could look something like this:
public class ButtonSubClass extends Sprite {  //or simple button, or whatever
    public function ButtonSubClass():void {
        this.addEventListener(MouseEvent.MOUSE_DOWN,downHandler,false,0,true);
    }

    private function downHandler(e:MouseEvent):void {
        //do something common to all your buttons here
    }
}

Then, have all your buttons inherit from this class.
Second Question:
function removeFromArray(elementVal:*):void {
    var index:int = array.indexOf(elementVal);  //get the index of the first element whose value is the passed parameter;
    if(index >= 0){
        array.splice(index,1); //remove that element/index from the array.
    }
}

Third Question:
If ButtonA is a sprite whose only children are all the buttons you want the listener for, then you can do this:
var i:int = buttonA.numChildren;
while(i--){
    buttonsA.getChildAt(i).addEventListener(MouseEvent.MOUSE_DOWN , button_function);
}

function button_function(e:Event):void {
    switch(e.currentTarget){
        case button1a:
            //do something with button 1a
            break;

        case button2a
            //do something with button 2a
            break;
    }
}

OR, more sloppily and less efficient and not recommended, this:
for(var i:int=1;i<=10;i++){
    this["buton" + i.toString() + "a"].addEventListener(MouseEvent.MOUSE_DOWN, this["buton" + i.toString() + "a_function"]);
}


text:
Q: django - Extending `auth.models.User` and usering login, logout If I create a CustomUser model which inherits from django.contrib.auth.models.User, like so:
in models.py
class CustomUser(django.contrib.auth.models.User):
    customfield = TextField()
    ...

Should I still be able to use
django.contrib.auth.{authenticate, login, logout} in the normal way? Do I have to make some additional configuration change? I know these methods only work on User objects, but technically my CustomUser is-a User.
Currently, authenticate(username=u, password=p) is always returning None, even with valid credentials.

A: Since Django 1.5 (officially but it doesn't worked for me) and "stable" in 1.6 there is a functionality to extend the User model in a clean way.
At first:
-> Take care that you load the User model only via:
from django.contrib.auth import get_user_model
User = get_user_model()

-> Once you have built the database theres no easy way to change the User model. The database relations will break and Django / South isn't able to fix it.
-> third party modules have to be compatible with that new layout and refer in it's models to "get_user_model()", too.
You have to add some Code for the admin to respect your new model:
See: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#extending-the-existing-user-model
To Override the model you need to inherit from AbstractBaseUser:
from django.contrib.auth.models import AbstractBaseUser

class MyUser(AbstractBaseUser):
    ...
    date_of_birth = models.DateField()
    height = models.FloatField()
    ...
    REQUIRED_FIELDS = ['date_of_birth', 'height']

AbstractBaseUser provides you all attributes of the default user model. So you don't have to take care of email, username, first_name, last_name, password etc.
More info about overriding the user model: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#django.contrib.auth.models.CustomUser
In your settings link your new model:
AUTH_USER_MODEL = 'customauth.MyUser'

Please read the whole documentation of customizing the user model, there are some interesting hints for overriding the default manager, admin forms etc. Just remember that bigger changes in an existing project can be a big pain.

A: A short overview:
- Extend models.AbstractUser
- Set AUTH_USER_MODEL in settings.py
All details can be found here: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#specifying-a-custom-user-model


text:
Q: Styleci fixes phpdoc comments at file level I specify phpdoc for $factory variable in ModelFactory for completion in PhpStorm.
/**
 * @var Illuminate\Database\Eloquent\Factory $factory
 */
$factory->define(App\Models\User::class, function (Faker\Generator $faker) {

However, when I push commit to github, styleci send me such pull request
-/**
+/*
  * @var Illuminate\Database\Eloquent\Factory $factory
  */
 $factory->define(App\Models\User::class, function (Faker\Generator $faker) {

But PhpStorm doesn't recognize such comments and there is no completion. Is it possible to tell styleci not to fix phpdoc comments at file level?
My .styleci looks like this
preset: recommended
risky: true
linting: true
disabled:
  - align_double_arrow

A: I do not have experience with StyleCI, and this is not tested, but a quick glance at the documentation shows this fixer:

phpdoc_to_comment
Docblocks should only be used on structural elements.

To me, it sounds like this fixer is responsible for changing your PHPDoc comment to a plain comment, since it is not describing a structural element. I would try adding this fixer to your disabled list.


text:
Q: Extends User plugin by adding a profile does not render tab either new added fields in OctoberCMS I've follow all the steps on the Extending User plugin screencast but for some reason I can not see "Profile" tab and either new added fields. Since I used the second approach, the easy one, this is what I've done:

*

*Create the plugin and models and so on under Alomicuba namespace

*Create and make the needed changes to the files as explained in video:
Plugin.php

<?php namespace Alomicuba\Profile;

use System\Classes\PluginBase;
use RainLab\User\Models\User as UserModel;
use RainLab\User\Controllers\Users as UsersController;

/**
 * Profile Plugin Information File
 */
class Plugin extends PluginBase
{
    public $requires = ['RainLab.User'];

    /**
     * Returns information about this plugin.
     *
     * @return array
     */
    public function pluginDetails()
    {
        return [
            'name'        => 'Profile',
            'description' => 'Add extra functionalities for Alomicuba WS by extends RainLab User',
            'author'      => 'DTS',
            'icon'        => 'icon-users'
        ];
    }

    public function boot()
    {
        UserModel::extend(function($model){
            $model->hasOne['profile'] = ['Alomicuba\Profile\Models\Profile'];
        });

        UsersController::extendFormFields(function ($form, $model, $context){
            if ($model instanceof UserModel)
                return;

            $form->addTabFields([
                'pinCode' => [
                    'label' => 'PIN',
                    'tab' => 'Profile'
                ],
                'phone2' => [
                    'label' => 'Teléfono (2)',
                    'tab' => 'Profile'
                ],
                'phone3' => [
                    'label' => 'Teléfono (3)',
                    'tab' => 'Profile'
                ],
                'phone4' => [
                    'label' => 'Teléfono (4)',
                    'tab' => 'Profile'
                ]
            ]);
        });
    }
}

add_profiles_fields_to_user_table.php

<?php namespace Alomicuba\Profile\Updates;

use Schema;
use October\Rain\Database\Updates\Migration;

class AddProfilesFieldsToUserTable extends Migration
{

    public function up()
    {
        Schema::table('users', function($table)
        {
            $table->integer('pinCode')->unsigned();
            $table->dateTime('pinCodeDateTime');
            $table->integer('phone2')->unsigned()->nullable();
            $table->integer('phone3')->unsigned()->nullable();
            $table->integer('phone4')->unsigned()->nullable();
        });
    }

    public function down()
    {
        $table->dropDown([
            'pinCode',
            'pinCodeDateTime',
            'phone2',
            'phone3',
            'phone4'
        ]);
    }
}

version.yaml
1.0.1: First version of Profile
1.0.2:
    - Created profiles table
    - create_profiles_table.php
    - add_profiles_fields_to_user_table.php

Profile.php (Model)
<?php namespace Alomicuba\Profile\Models;

use Model;

/**
 * Profile Model
 */
class Profile extends Model
{
    /**
     * @var string The database table used by the model.
     */
    public $table = 'alomicuba_profile_profiles';

    /**
     * @var array Relations
     */
    public $belongsTo = [
        'user' => ['RainLab\User\Models\User']
    ];

    // This method is not need anymore since I'll use the second approach
    public static function getFromUser($user)
    {
        if ($user->profile)
            return $user->profile;

        $profile = new static;
        $profile->user = $user;
        $profile->save();

        $user->profile = $profile;

        return $profile;
    }
}

But when I edit a existent user I didn't see the 'Profile' tab and also didn't see any new added field. See image below:

Any advice around this? Did I miss something?
Also I have a few question around plugin extends:

*

*How do I add a required field to the register form?

*How do I display each new added field on the account form?

A: I haved tested your code on my machine you need to write
$require instead of $requires in plugin.php
please check documentation
http://octobercms.com/docs/plugin/registration#dependency-definitions
and when extendFormFields() method called for UserController you need to specify that you only want to extends fields for UserModel not for other
if (!$model instanceof UserModel)
    return;

so plugin.php code look like this
<?php namespace Alomicuba\Profile;

use System\Classes\PluginBase;
use RainLab\User\Models\User as UserModel;
use RainLab\User\Controllers\Users as UsersController;

/**
 * Profile Plugin Information File
 */
class Plugin extends PluginBase
{
    public $require = ['RainLab.User'];

    /**
     * Returns information about this plugin.
     *
     * @return array
     */
    public function pluginDetails()
    {
        return [
            'name'        => 'Profile',
            'description' => 'Add extra functionalities for Alomicuba WS by extends RainLab User',
            'author'      => 'DTS',
            'icon'        => 'icon-users'
        ];
    }

    public function boot()
    {
        UserModel::extend(function($model){
            $model->hasOne['profile'] = ['Alomicuba\Profile\Models\Profile'];

        });

        UsersController::extendFormFields(function ($form, $model, $context){
            if (!$model instanceof UserModel)
                return;

            $form->addTabFields([
                'pinCode' => [
                    'label' => 'PIN',
                    'tab' => 'Profile'
                ],
                'phone2' => [
                    'label' => 'Teléfono (2)',
                    'tab' => 'Profile'
                ],
                'phone3' => [
                    'label' => 'Teléfono (3)',
                    'tab' => 'Profile'
                ],
                'phone4' => [
                    'label' => 'Teléfono (4)',
                    'tab' => 'Profile'
                ]
            ]);
        });
    }
}

and in add_profiles_fields_to_user_table.php
for dropping column write following code
Schema::table('users', function($table)
{
        $table->dropDown([
            'pinCode',
            'pinCodeDateTime',
            'phone2',
            'phone3',
            'phone4'
        ]);
}


text:
Q: delete statement not deleting records Anyone know why its not deleting the records from the student table. When the table is empty and i first run the anonymous block it runs fine, but then when i run it again i get errors about duplicate primary keys, but this shouldn't matter as each time i run the block it should delete all records from the table?? I'm relatively new to SQL so any help is appreciated.
I should add, the procedure seems to work fine as the dopl appears when i run the code.
This is my function:
 CREATE OR REPLACE FUNCTION DELETE_ALL_STUDENTS RETURN NUMBER AS
    BEGIN
    DELETE FROM STUDENTS;
    END;

and this is my procedure:
 create or replace PROCEDURE DELETE_ALL_STUDENTS_VIASQLDEV AS
    BEGIN
    dbms_output.put_line('--------------------------------------------');
    dbms_output.put_line('Deleting all student rows');

    END;

and this is the anonymous block i was running to see if it worked:
begin
DELETE_ALL_STUDENTS_VIASQLDEV;
ADD_STUDENT_VIASQLDEV(1,'Fred   Smith');
ADD_STUDENT_VIASQLDEV(2,'Sue    Davis');
ADD_STUDENT_VIASQLDEV(3,'Emma   Jones');
end;

A:
"doesnt my function carry out the deleting?"

It would if you called it, but alas you don't.
This is not a SQL problem, it's a logic problem. If we don't do the washing up the dishes remain dirty. Similarly if you don't call the routine which deletes the records the records are not deleted.
You need to call the function in the procedure. Not sure why you've made it a function, and it won't compile anyway, because it doesn't have a RETURN clause. So, let's fix that too.
CREATE OR REPLACE FUNCTION DELETE_ALL_STUDENTS RETURN NUMBER AS
BEGIN
    DELETE FROM STUDENTS;
    return sql%rowcount; -- how many rows were deleted
END;
/

Now we call it:
create or replace PROCEDURE DELETE_ALL_STUDENTS_VIASQLDEV AS
    n number;
BEGIN
    dbms_output.put_line('--------------------------------------------');
    dbms_output.put_line('Deleting all student rows');
    n := DELETE_ALL_STUDENTS;
    dbms_output.put_line('No of students deleted = '|| to_char(n));
END;

So, when you run your anonymous block the existing students will be deleted and replaced with the new ones.


text:
Q: How can the surface of a conducting shell be equipotential when a charge is introduced inside the cavity? Here is the confusion.
Take a spherical conducting shell of a certain thickness.
When a postive charge is introduced into the shell the inside surface collects negative charges and the outter surface postive charges. So far so good.
Now gauss' law tells be there is no field in the conducting shell and thus its outter and inner surfaces must be equipotential.
However the inside surface has negative charges and thus is at a negative potential and the outter surface has postive charges thus is at a postive potential. And thus the inner and outter surfaces have opposite signs for potential and thus are different.
This seems to falsely contradict the earlier gauss' law conclusion which I know is correct.
Where did I go wrong?

A:
When a positive charge is introduced into the shell the inside surface collects negative charges and the outer surface positive charges.

These are induced charges and the magnitudes of the positive and negative induced charges are the same.
These induced charges set up electric fields inside the conducting shell which exactly cancel out the electric field produced inside the conducting shell by the positive charge.
Thus there is no potential difference between the inner and outer surfaces of the conductor.
Even though there are negative charges on the inside surface of the conducting sphere the potential of that inside surface would be positive relative to infinity (taken as the zero of potential) as a test positive charge would have to do no work whilst moving though the conducting shell and the outside of the shell is at a positive potential.


text:
Q: ^[[3~ try again error in kde konsole I am trying to enter in admin by sudo su. But after entering sudo password and pressing enter terminal automatically printing some character and showing try again.
^[[3~floki@aspire:~$ sudo su
[sudo] password for floki:
^[[3~^[[3~^[[3~^[[3~^[[3~^[[3~^[[3~^[[3~Sorry, try again.
[sudo] password for floki:
sudo: 1 incorrect password attempt
floki@aspire:~$ ~~~~~~^[[3~^[[3~^[[3


text:
Q: Dockers call by http request i'm new of docker's world. I'm trying to import two Dockers model downloaded from peltarion on Ubuntu version 20.04.
I download docker, setup the two images and create the first container with command
docker run -p 8000:8000 model-export
when i call xxx.xx.xx.xx:8000 with http request i receive answer by it.
My problem is that when i create the second container
docker run -p 8090:8090 model-export
I get the following configuration on the port
enter image description here
At this point i try to call with xxx.xx.xx.xx:8090, but no response.
How can i configure the container so i can call it with http request?
Thanks in advance to anyone who helps me

A: TLDR: your parameter values should be -p 8090:8000.

The order of -p/--publish parameter values should be:
published_port:container_exposed_port

*

*published_port is a port used by host (your machine), where Docker is installed. And that can be used outside like a public-available service. For example it can be visible by other computers in your local network, or by Internet.

*container_exposed_port is a port that is exposed from Docker container to Docker host by image (for example by EXPOSE 8000 instruction in image Dockerfile). It's visible only for your Docker host, or for other Docker containers (Docker networking) too.


text:
Q: What is known about this type of generalisation of de Rham cohomology? I will describe a certain generalisation of de Rham cohomology; things could be generalised further but I will stick to a concrete example. A $0$-double-form is a function on the complex plane $\mathbb{C}$. Using $z,\bar{z}$ as coordinates, the $1$-double-forms are spanned by $\eth z$ and $\eth \bar{z}$, where
$$
\eth z = \mathrm{d}z\otimes\mathrm{d}z,\qquad \eth \bar{z} = \mathrm{d}\bar z\otimes\mathrm{d}\bar z.
$$
The $2$-double-forms are spanned by
$$
\eth z\wedge \eth \bar{z}= \left(\mathrm{d}z\otimes\mathrm{d}z\right) \otimes \left(\mathrm{d}\bar z\otimes\mathrm{d}\bar z\right) - \left(\mathrm{d}\bar z\otimes\mathrm{d}\bar z\right) \otimes \left(\mathrm{d}z\otimes\mathrm{d}z\right).
$$
The wedge operator is here defined to have all the expected properties. We can use the double exterior derivative $\eth$ to go from a $p$-double-form to a $(p+1)$-double-form. In particular, if $C$ is a $0$-double-form and $K=K_{zz}\eth z + K_{\bar{z}\bar{z}}\eth \bar{z}$ is a $1$-double-form, we define
$$
\eth C = \partial_z\partial_z C \eth z + \partial_{\bar{z}}\partial_{\bar{z}} C \eth\bar{z}
$$
and
$$
\eth K = (\partial_z\partial_z K_{\bar{z}\bar{z}} - \partial_{\bar{z}}\partial_{\bar{z}} K_{zz})\eth z \wedge \eth \bar{z}.
$$
Clearly $\eth^2=0$. These notions can easily be extended to a higher dimensional space, or to triple-forms, quadruple-forms, and so on.
My question is about the general nature of this cohomology. Is it well studied, and if so what is it called? How well does Poincare's Lemma extend to this cohomology? Can we integrate double-forms? If so, what are the generalisations of things like Stokes' theorem?
Some background on why I am interested: gauge field theories are formulated in terms of forms, and it seems like general relativity might be able to be described in a similar way in terms of double-forms.


text:
Q: applying a window to audio samples screws the output Using arm_mult_f32 to multiply two arrays produces unexpected(garbage) results.
I have been reading up about dsp. I am creating Hann coefficients to apply to sampled PCM data, before the FFT.
THe hanning function is from hann.m matlab example i found, the only difference being that the stm32f4 only has a single precision FPU, so I am using uint32_t
for the data fields rather than double.
first off, the definitions.
FFT_LEN = 256;

float32_t FFTBuf[FFT_LEN * 2];   // data set twice the fft length as output

                                 //symetrically repeated
float32_t FFTMagBuf[FFT_LEN];    //

float32_t * hann_window;
float32_t * hann_buff;
float32_t * hanning(uint32_t, uint8_t)

call the hanning function to populate the window.
hann_window = hanning(FFT_LEN * 2, 2);    // creates a dynamic array and
                                          //populates it with coeffs.

hann_buff = (float32_t *)calloc(FFT_LEN * 2, (sizeof(float32_t)));
memset(hann_buff, 0, FFT_LEN * 2 * sizeof(float32_t));   //intermediate
                                                         //buffer

then when all pcm samples are read

arm_mult_f32(FFTBuf, &hann_window[0], &hann_buff[0], (FFT_LEN * 2)); //

arm_cfft_f32(&arm_cfft_sR_f32_len256, &hann_buff[0], 0, 1);

arm_cmplx_mag_f32(&hann_buff[0], FFTMagBuf, FFT_LEN);

The hann function is as follows
float32_t *hanning(uint32_t N, uint8_t itype)
  {
    uint32_t half, i, idx, n;
    float32_t *w;

    w = (float32_t *)calloc(N, sizeof(float32_t));
    memset(w, 0, N * sizeof(float32_t));

    if (itype == 1) //periodic function
      n = N - 1;
    else
      n = N;

    if (n % 2 == 0)
    {
  half = n / 2;
  for (i = 0; i < half; i++) //CALC_HANNING   Calculates Hanning window samples.
    w[i] = 0.5 * (1 - cos(2 * PI * (i + 1) / (n + 1)));

  idx = half - 1;
  for (i = half; i < n; i++)
  {
    w[i] = w[idx];
    idx--;
  }
}
else
{
  half = (n + 1) / 2;
  for (i = 0; i < half; i++) //CALC_HANNING   Calculates Hanning window samples.
    w[i] = 0.5 * (1 - cos(2 * PI * (i + 1) / (n + 1)));

  idx = half - 2;
  for (i = half; i < n; i++)
  {
    w[i] = w[idx];
    idx--;
  }
}

if (itype == 1) //periodic function
{
  for (i = N - 1; i >= 1; i--)
    w[i] = w[i - 1];
  w[0] = 0.0;
}
return (w);
  }

With out the windowing function I get nice values, I have tested the code with
a 4khz sine wave, and it gives the correct result(without the hann window stuff)
A sample of the new output doesn't look so good.
{1.10114283e-019, 0 <repeats 48 times>, 35050560, inf, 0.0352631919,
1.08468142e-019, 2.84188939e-009, inf, 143872, 142068.25, 3.31743232e+010,
8800024, 3.29058877e+010, 0, 1.53397155e-019, 4.58692708e-013, 61631.5938,
0, inf, 1154.63733, inf, inf, inf, inf, inf, inf, inf, 1.14477244e+011,

As per suggestion, removed dynamic allocation.
New ouput looks pretty, and makes sense. Will normalize input next, and continue my journey.
{6120297, 4445404.5, 1772673.5, 1041102.38, 659743.438, 484291.75,
513112.688, 289598.594, 668016.812, 487091.375, 315217.875, 585517.562,
513285.281, 268263.375, 69867.4531, 108220.406, 85955.2031, 75381.0234,
124448.68, 559070.812, 996484.75, 1008192.25, 515462.312, 316204.938,
124825.734,


text:
Q: How to get only 1 column data in JsonResult response in ASP.NET Core 3.1 This is my code:
[HttpGet]
[Route("CourseWeeks/{id}")]
public JsonResult GetCourseWeeks(int id)
{
    // return new JsonResult(db.CourseWeeks.ToList());
    var courseWeek = db.CourseWeeks
        .Where(c => c.CourseId == id);
        return new JsonResult(courseWeek);
}

Currently it's returning all the columns in db.CourseWeeks which match the id, but I only want it to return a single column's data only.

A: You can linque to select single column as below I need to check the syntax.
var courseWeek = db.CourseWeeks
    .Where(c => c.CourseId == id).select (c=>c.columnname);


text:
Q: Running Haskell servant over https with nginx I'm trying to figure how I can properly run Servant API endpoint over https with nginx.
So to go through what I've done. So I thought I would probably need to setup Servant so it would communicate over https. So I added this to my code
  Development -> run port $ logStdoutDev $ corsWithContentType $ app cfg
  Production  -> runTLS (tlsSettings "./certs/fullchain1.pem" "./certs/privkey1.pem")
                        (setPort port defaultSettings)
                        (corsWithContentType $ app cfg)

So the Production clause here is what runs on my production server. I then have this in nginx
upstream api_server {
    server 127.0.0.1:8081;
}

location /api {
    proxy_set_header Host $host;
    proxy_pass http://api_server;
}

listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/xxx/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/xxx/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

With this setup I perform an ajax request from the page (which is properly running over https). However when I do this I get a response from the Servant server
InsecureConnectionDenied

As if my ajax request is insecure. It was my belief that if I'm making an ajax request form a page with https that request is secure.
If I skip all of this and just run Servant without TLS I get a 405 Method Not Allowed when trying to post. I know this is connected to the https because when I perform a request straight to the IP:PORT of the api it works. What could be the issue here?

A: This was because of my "/api" prefix in the nginx config. The request got sent to Servant as "/api/registrations" but should have been "/registrations". Misconfiguration in nginx, nothing to do with Servant and https.


text:
Q: Why is my min_free_kbytes larger than the documented calculation (and larger than the documented maximum)? My machine has roughly 8GB of RAM.  Why is min_free_kbytes set to 67584?  The kernel code comment says I should expect to see min_free_kbytes set to around 11584.  It also says the largest it would set it to is 65536.
$ cat /proc/sys/vm/min_free_kbytes
67584

$ free -h
              total        used        free      shared  buff/cache   available
Mem:          7.7Gi       3.2Gi       615Mi       510Mi       3.9Gi       3.7Gi
Swap:         2.0Gi       707Mi       1.3Gi

$ grep -r min_free_kbytes /etc/sysctl*  # No manual configuration
$

$ uname -r  # My kernel version
5.0.17-200.fc29.x86_64

https://elixir.bootlin.com/linux/v5.0.17/source/mm/page_alloc.c#L7567
/*
 * Initialise min_free_kbytes.
 *
 * For small machines we want it small (128k min).  For large machines
 * we want it large (64MB max).  But it is not linear, because network
 * bandwidth does not increase linearly with machine size.  We use
 *
 *  min_free_kbytes = 4 * sqrt(lowmem_kbytes), for better accuracy:
 *  min_free_kbytes = sqrt(lowmem_kbytes * 16)
 *
 * which yields
 *
 * 16MB:    512k
 * 32MB:    724k
 * 64MB:    1024k
 * 128MB:   1448k
 * 256MB:   2048k
 * 512MB:   2896k
 * 1024MB:  4096k
 * 2048MB:  5792k
 * 4096MB:  8192k
 * 8192MB:  11584k
 * 16384MB: 16384k
 */

A:
On systems using
  huge pages, it is recommended that min_free_kbytes is higher and it is tuned
  with hugeadm --set-recommended-min_free_kbytes. With the introduction of
  transparent huge page support, this recommended value is also applied [...]
On X86-64 with 4G of memory, min_free_kbytes becomes 67584.

https://www.spinics.net/lists/linux-mm/msg14044.html
/* Ensure 2 pageblocks are free to assist fragmentation avoidance */
recommended_min = pageblock_nr_pages * nr_zones * 2;

/*
 * Make sure that on average at least two pageblocks are almost free
 * of another type, one for a migratetype to fall back to and a
 * second to avoid subsequent fallbacks of other types There are 3
 * MIGRATE_TYPES we care about.
 */
recommended_min += pageblock_nr_pages * nr_zones *
           MIGRATE_PCPTYPES * MIGRATE_PCPTYPES;

linux-5.0.17/mm//mm/khugepaged.c:1862
A "pageblock" is a potential huge page: 2MiB on x86-64.  This calculation says min_free is 2MiB * 11 * nr_zones.  "With 4G of memory" you have at least three zones: "normal", "DMA32", and "DMA" (DMA16).
2 * 11 * 3 = 66 MiB.
66 MiB = 66 * 1024 = 67584 KiB.
The reason separate "normal" and DMA32 zones appear even on 4G systems is: "the tiny pci32 zone that materialize on 4g systems that relocate some little memory over 4g to make space for the pci32 mmio."