text:
Q: Is there a way to run a daily batch file in Windows and get notified if the command returns (or doesn't return) a certain string? What I'd like to do is run a command line daily in Windows (I know how to do that with task scheduler) and then if the result contains (or doesn't contain) a certain string, get notified in Windows.
Is there an easy way to do this?


text:
Q: Java Casting to superclass not change object type? I don't understand why this code outputs false. Java uses the object type (not reference) to choose the [instance] method to execute, in this case, initial object type is Owl (with method returns false), anyway, We cast this type to "Nocturnal" (not necessary, but We do). I have isBlind() method in the interface and the class.
Why our Owl converted to Nocturnal using a explicit Cast prints false, if the object type now is Nocturnal and the Nocturnal method prints true?
interface Nocturnal {
    default boolean isBlind() {
        return true;
    }
}

public class Owl implements Nocturnal {
    public boolean isBlind() {
        return false;
    }

    public static void main(String[] args) {
        Nocturnal nocturnal = (Nocturnal) new Owl();
        System.out.println(nocturnal.isBlind());
    }
}

A: A powerful way to think about OO programming is to think of method calls as message passing. You send a message to the object "please give me the result of the isBlind() method". The object goes "OK, I know how to do isBlind(), does it, then sends a message to the caller containing the result.
Your Owl object receives that message asking to run isBlind(). It doesn't care where it came from. It doesn't know what the caller knows about it. It just runs its own version of isBlind() and sends the result back.
When you cast to a superclass (or an interface) in the caller, the caller "forgets" that it's talking to an Owl, but the Owl doesn't know that. It just keeps handling messages in the same way it always does.
This is the core of what makes polymorphism so powerful. It means you can put your Owl into a collection of Nocturnal, and call isBlind() on each one, getting the correct result:
  List<Nocturnal> animals = new ArrayList<>();
  animals.add(new Owl());
  animals.add(new Bat());

  for(Nocturnal animal : animals) {
      System.out.println(
           "Name: " + animal.getName() +
           " Blind: " + animal.isBlind());
  }

As you progress with object-oriented programming, you will encounter tons of situations where this is invaluable. Not least, unit testing, in which you can substitute a test double (sometimes a mock) for the objects that collaborate with the object you're testing.
Note that modern Java programmers tend not to subclass all that often, preferring to to implement interfaces much of the time. "Prefer composition to inheritance". The same principles apply regarding polymorphism.

A: Though you cast Owl to Nocturnal still the Owl object contains the its methods. And that's why its printing false -
Nocturnal nocturnal = (Nocturnal) new Owl();

The casting here just make the newly created Owl object compatible for Nocturnal references - "nocturnal"
So when you call the method of isBlind() you are actually calling the isBlind() of Owl object which is just referenced by (or stored in) nocturnal of type Nocturnal. Here we say dynamic polymorphic is happen.

A: When a sub class overrides a method of its base class then each invocation of the overridden method from outside the sub class (including the base class) will always result in invoking the overriden method.
The casting has no impact on the behavior of the method. If its overriden its overridden for the outside world.
Only way to invoke the method as per behavior provided by base class is by using super keyword with . ( dot operator ) from inside the instance method of the sub class.

redpajama_set_name: RedPajamaStackExchange


text:
Q: que utilizar para generar pdf con c# disculpen, necesito generar el formato de un calendario maya con c#, esta formado por imágenes y no se que puedo utilizar para hacerlo, no es un reporte de base de datos, son 10 imágenes que necesito imprimir. es algo un formato como este http://maya.nmai.si.edu/sites/all/themes/mayatime/img/calendar-system/es/9.jpg

A: Una librerias ampliamente usada para generar pdf en .net es iTextSharp
iTextSharp - Working with images
PdfWriter.GetInstance(doc, new FileStream(pdfpath + "/Images.pdf", FileMode.Create));
doc.Open();

doc.Add(new Paragraph("GIF"));

Image gif = Image.GetInstance(imagepath + "/nombreimagen.gif");
doc.Add(gif);

Es bastante simple de entender el código, solo agregas una imagen en el parrafo del pdf. En el artículo encontraras mas ejemplo con otros formatos de imagen.

A:
iTextSharp

es un librería con una cantidad impresionante de funciones y muy fácil de utilizar.
Te recomiendo utilizarla, ya que podrás personalizar el documento de la manera que desees.
Acá podrás encontrar un tutorial básico de desarrollo. -- > Creando archivo PDF con iTextSharp
Así mismo desde ahí podrás descargar las librerías necesarias.
¡Mucha Suerte! :D


text:
Q: Apache Core Dump file deletes itself on physical machine restart I am having an issue which there must be a simple solution I am not seeing, but I have googled and googled to no avail.
The issue I am having is when I do a server (physical machine) restart, every time Apache tells me that /tmp/apache2-gbd-dump doesn't exist and to check the httpd.conf file. Well I check the conf file, and sure enough it's calling to a /tmp/apache2-gbd-dump for Core Dump. The issue is this file does not in fact exist. When I look at the logs, that is the only warning/error that is associated with the start failure.
So I've tried to create the file, chown it to www-data:www-data and chmod it to 777. And this works, in that I can now sudo service apache2 start. As soon as I restart the physical machine, the Core Dump file disappears, and I have to recreate the file again manually to get Apache to start, since it fials it's automatic start up. This obviously will not work when this turns into a production server. Has anyone any insight as to what I can look into to find out why this is happening? Here is the code inside the conf file if anyone sees a pertinent issue, can you please point it out?
CoreDumpDirectory /tmp/apache2-gdb-dump

LockFile ${APACHE_LOCK_DIR}/accept.lock

PidFile ${APACHE_PID_FILE}

Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5

<IfModule mpm_prefork_module>
    StartServers          5
    MinSpareServers       5
    MaxSpareServers      10
    MaxClients          150
    MaxRequestsPerChild   0
</IfModule>

<IfModule mpm_worker_module>
    StartServers          2
    MinSpareThreads      25
    MaxSpareThreads      75
    ThreadLimit          64
    ThreadsPerChild      25
    MaxClients          150
    MaxRequestsPerChild   0
</IfModule>

<IfModule mpm_event_module>
    StartServers          2
    MinSpareThreads      25
    MaxSpareThreads      75
    ThreadLimit          64
    ThreadsPerChild      25
    MaxClients          150
    MaxRequestsPerChild   0
</IfModule>

User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}
AccessFileName .htaccess

<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
    Satisfy all
</Files>

DefaultType None
HostnameLookups Off

ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn

Include mods-enabled/*.load
Include mods-enabled/*.conf
Include httpd.conf
Include ports.conf

LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent

Include conf.d/
Include sites-enabled/

A: I think that your /tmp is a tmpfs mount. You need to change the core path to be in /var or somewhere else.
See core_pattern in the man core page.


text:
Q: UISegmentedControl works on iPhone but not iPad? I use a UISegmentedControl, with 2 segments that spans the width of the screen.
This works as expected on iPhone. Tapping cat mode switches the highlight to cat mode, and the appropriate functions take place. However, on iPad, tapping Cat Mode does nothing. No highlight switch, no functions. If I start the highlight on Cat Mode, the same thing happens in reverse (all good on iPhone, Dog Mode can't be selected on iPad).
I use obviously one storyboard for both iPhone and iPad with Autolayout, and I'm not varying anything related to this segmented control for traits, so I have no clue what's going on. All other functions perform properly on iPhone and iPad.
Please let me know if I can provide additional info to help solve this question.
Thanks!

A: There was a Google Ad Banner blocking it. View debugger helped me see that. Thanks @matt for the suggestion to try it.


text:
Q: JSON Bad String Error I am creating an JSON file which stores some Physics equation, which will be rendered using MathJax.
"equations": [
    "$w = F.s\cos\theta$"
 ]

I am getting a bad string error. I have tried adding another backslash before the slashes but that changes the equations drastically.
Is there any way to fix this issue without changing the equation

A: There were two issues you were falling over.
Firstly, a valid JSON file will have { and } around it (as David Gatti mentions in his answer, it is an object after all). Secondly, certain characters - including backslashes - will need to be escaped. When you parse it back into an object, the additional backslashes will be removed.
Your corrected JSON should read:
{
    "equations": [
        "$w = F.s\\cos\\theta$ "
    ]
}

A: JSON is an encoding of structured data. You write
{
  "equations": [
    "$w = F.s\\cos\\theta$"
  ]
}

to mean an object with a property named equations with an array with a single string:
$w = F.s\cos\theta$

The escaped backslashes (\) does not change the underlying data. They get removed by the receiver when the JSON gets decoded into the object graph.


text:
Q: Excel Last Date based on account number I currently have a formula which is supposed to identify the Last Payment Date per account number, where several payments are shown per account number. The LastPmtDate and Docdate is the same.
{MAX(COLUMN($D1:$D10000)*($D$1:$D$10000=D2))}

The data looks as follows, starting from A1 in the spreadsheet.
AccountCode Amt Amt2 DocDate DocType LastPmtDate
1            10                      2017/05/02
1            12                      2017/06/01

The formula should pick up the 2017/06/01 date in the column to the right of the LastPmtDate so I can quickly pick it up.

A: Assuming a reference cell of H1 (which contains the account number you're looking for), use this formula and format it as date:
=MAX(INDEX(($A$2:$A$10000=H1)*$F$2:$F$10000,))


text:
Q: Is "transaction.atomic" same as "transaction.commit_on_success"? Django 1.6 proposes @transaction.atomic as part of the rehaul in the transaction management from 1.5.
I have a function which is called by a Django management command which is in turn called by cron, i.e. no HTTP request triggering transactions in this case. Snippet:
from django.db import transaction

@transaction.commit_on_success
def my_function():
    # code here

In the above code block commit_on_success uses a single transaction for all the work done in my_function.
Does replacing @transaction.commit_on_success with @transaction.atomic result in the identical behaviour? @transaction.atomic docs state:

Atomicity is the defining property of database transactions. atomic
allows us to create a block of code within which the atomicity on the
database is guaranteed. If the block of code is successfully
completed, the changes are committed to the database. If there is an
exception, the changes are rolled back.

I take it that they result in the same behaviour; correct?

A: Based on the documentation I have read on the subject, there is a significant difference when these decorators are nested.
Nesting two atomic blocks does not work the same as nesting two commit_on_success blocks.
The problem is that there are two guarantees that you would like to have from these blocks.

*

*You would like the content of the block to be atomic, either everything inside the block is committed, or nothing is committed.

*You would like durability, once you have left the block without an exception you are guaranteed, that everything you wrote inside the block is persistent.

It is impossible to provide both guarantees when blocks are nested. If an exception is raised after leaving the innermost block but before leaving the outermost block, you will have to fail in one of two ways:

*

*Fail to provide durability for the innermost block.

*Fail to provide atomicity for the outermost block.

Here is where you find the difference. Using commit_on_success would give durability for the innermost block, but no atomicity for the outermost block. Using atomic would give atomicity for the outermost block, but no durability for the innermost block.
Simply raising an exception in case of nesting could prevent you from running into the problem. The innermost block would always raise an exception, thus it never promises any durability. But this loses some flexibility.
A better solution would be to have more granularity about what you are asking for. If you can separately ask for atomicity and durability, then you can perform nesting. You just have to ensure that every block requesting durability is outside those requesting atomicity. Requesting durability inside a block requesting atomicity would have to raise an exception.
atomic is supposed to provide the atomicity part. As far as I can tell django 1.6.1 does not have a decorator, which can ask for durability. I tried to write one, and posted it on codereview.

A: Yes. You should use atomic in the places where you previously used commit_on_success.
Since the new transaction system is designed to be more robust and consistent, though, it's possible that you could see different behavior. For example, if you catch database errors and try to continue on you will see a TransactionManagementError, whereas the previous behavior was undefined and probably case-dependent.
But, if you're doing things properly, everything should continue to work the same way.


text:
Q: Форма обратной связи на сайте Сделал форму обратной связи на сайте. Форма приходит. Она состоит из 2 input и 1 textarea.Данные, которые введены в input отображаются в письме, а данные введенные в поле textarea - нет
html код:
<form action="test.php" class="form" method="post">

               <div class="input-group">
                   <input  placeholder="Имя*" class="input__form input__name" name="userName" type="text" data-aos="fade-right" data-aos-delay="300">
                   <input placeholder="e-mail*" class="input__form input__email" name="userEmail" type="text" data-aos="fade-right" data-aos-delay="450" required>
               </div>
                 <textarea class="textarea" placeholder="Сообщение*" name="сообщение" id="textarea" name="message" cols="30" rows="10" data-aos="fade-right" data-aos-delay="600"></textarea>

<!--              <button type="submit" class="button__form" data-aos="fade-right" data-aos-delay="750">Отправить</button>-->

               <input type="submit" class="button__form" data-aos="fade-right" data-aos-delay="750" placeholder="Отправить">

            </form>

PHP Код
<?php

//Получим ланные с элемента формы

   $name = $_POST['userName'];
   $userEmail = $_POST['userEmail'];
   $message = $_POST['message'];

//обработаем полученные данные

   $name = htmlspecialchars($name);
   $userEmail = htmlspecialchars($userEmail);
   $message = htmlspecialchars($message);

   $name = urldecode($name);
   $userEmail = urldecode($userEmail);
   $message = urldecode($message);

   $name = trim($name);
   $userEmail = trim($userEmail);
   $message = trim($message);

//отправляем данные

   if (mail("fetishev.konstantin@yandex.ru",
           "Новое письмо с сайта",
           "Логин: ".$name."\n".
           "Почта: ".$userEmail."\n".
           "Сообщение: ".$message."\n".
           "From: kon.alex.fet@yandex.ru \r\n")
      ){
      echo("Письмо успешно отправленно");
   } else {
      echo("Есть ошибки! проверьте данные");
   }

?>

A: Потому что дублируется атрибут name. <textarea class="textarea" placeholder="Сообщение*" name="сообщение" id="textarea" name="message". В данном случае: сообщение и message. Если инфо не приходит в POST[message], значит оно находится в POST[сообщение]


text:
Q: The Fermat-Catalan conjecture with exponents $(2,n,4)$, $n\ge4$ The Fermat-Catalan conjecture is that for coprime $x,y,z$ and positive integers $a,b,c$ with $1/a+1/b+1/c<1$, the generalized Fermat equation $x^a + y^b = z^c$ has only finitely many solutions. I'm considering exponent triples $(a,b,c)$ which are solved.
Table 1 of [BCDY] surveys known results and states that $(2,n,4)$, $n\ge4$ has been solved completely and that this is 'Immediate from Bennett–Skinner [BS], Bruin [Br3]'. [Br3] covers the case $n=5$. Fermat dealt with $n=4$.
This leaves $n=6, 9$ and prime $n\ge7$, but I can't see how [BS] is relevant to that. Can someone explain and/or point me to the relevant part of [BS].
[BCDY] 'Generalized Fermat equations: A miscellany', Bennett, Chen, Dahmen, Yazdani, International Journal of Number Theory, Vol. 11, No. 1 (2015)
[BS] 'Ternary Diophantine Equations via Galois Representations and Modular Forms', Bennett, Skinner, Canad. J. Math. Vol. 56(1), 2004 p23-54.
[Br3] 'Chabauty methods using elliptic curves', Bruin, J.reine angew. Math. 562 (2003), 27-49.

A: I reposted this question in MO, and have copied this answer from there.
[Br2] Theorem 1 covers the case $n=6$. So this leaves $n=9$ and prime $n\ge7$.
As suggested in a comment on MO, I contacted Michael Bennett directly and he kindly explained the rest to me:
We have $x^2+y^n=z^4$ with $x,y,z$ coprime integers.
So $(z^2 - x)(z^2 + x) = y^n$.
The gcd of $(z^2 - x)$ and $(z^2 + x)$ is $1$ or $2$.
For a gcd of $1$ we have $x$ and $z$ of opposite parity, and can write
$z^2-x = u^n$ and $z^2+x = v^n$
so that $u^n+v^n = 2z^2$.
This is solved for coprime integer $u,v,z$ for $n\ge4$ by [BS] Theorem 1.1.
For a gcd of $2$ we have $x$ and $z$ both odd, and one of
$z^2-x = 2 u^n$ and $z^2+x = 2^{n-1}v^n$, or
$z^2+x = 2 u^n$ and $z^2-x = 2^{n-1}v^n$.
In either case, $u^n + 2^{n-2} v^n = z^2$.
This is solved for coprime integer $u,v,z$ for prime $n\ge7$ by [BS] Theorem 1.2.
This leaves the case $n=9$ with $y$ even.
Going back to the original equation, we have
$x^2+y^9=z^4$.
[Co, Section 14.4.1] gives complete parametrizations of
$x^2+w^3=z^4$
in terms of $s$ and $t$. In our case, $w$ is an even cube and from this and the parity constraints on $s$ and $t$ given in [Co] it follows that there exist coprime integers $s$ and $t$ with
$s t (s^3 - 16 t^3) (s^3 + 2 t^3)$ a cube.
The factors on the left hand side are pairwise coprime. ($s^3-16t^3$ and $s^3+2t^3$ could possibly have a common factor of $3$, but if they do, the whole expression is divisible by $9$ but not by $27$, and hence is not a cube.)
Since the factors are pairwise coprime, $s^3+2t^3$ is a cube.
This corresponds to a rational point on the curve $A^3+2B^3$=1 which is isomorphic to the elliptic curve $Y^2=X^3-1728$ via standard transformations. The latter curve has rank $0$ (and only the rational points corresponding to the point at infinity and $(X,Y)=(12,0)$). Tracing these back to $A^3+2B^3=1$, we find that $(A,B)=(1,0)$ or $(A,B)=(-1,1)$.
These points lead to either $t=0$ (which gives $z=0$ in $x^2+y^9=z^4$) or to $st = -1$ (which does not make $s t (s^3 - 16 t^3) (s^3 + 2 t^3)$ equal to a cube).
[Br2] 'The Diophantine Equations $x^2 \pm y^4 = \pm z^6$ and $x^2 + y^8 = z^3$', Bruin, Compositio Mathematica 118: 305-321, 1999.
[Co]  'Number Theory Volume II: Analytic and Modern Tools', Henri Cohen


text:
Q: find command exec {} matching folder empty - Fish shell When running a simple find and attempting to -exec some commands on the result I get an empty value for {}
For example:
$ find ~/folder-with-files -exec echo {} \;

on a folder containing 3 files returns empty
$
$
$

I'm using the Fish shell on MacOS.

A: When using Fish shell the {} variable must be wrapped in quotes "{}"
find ~/folder-with-files -exec echo "{}" \;

Returns correctly in both bash and fish shells
$ file1.txt
$ file2.txt
$ file3.txt


text:
Q: Kong Gateway setup SSL certificate I got Kong Gateway running and would like to change/setup SSL certificate:

I managed to accomplish it via curl, following guide ( https://support.konghq.com/support/s/article/How-to-setup-Kong-to-serve-an-SSL-certificate-for-API-requests ).
However, is there a way to setup/change SSL certificate via helm configuration? Perhaps attach secret volume and pass certificate that way?
Thank you.

A: After digging around and asking Kong support for help, I got 2 ways to setup the cert.
If you want to experiment, you can generate self-cert via:
openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout admin.key -out admin.crt -subj "/CN=example.com"
First way:

*

*Create secret: kubectl create secret tls kong-admin-tls --cert=./admin.crt --key=./admin.key

*Add tls: kong-admin-tls under admin ingress to values.yaml, example:
kong:
...
  admin:
    ingress:
      tls: kong-admin-tls

Second way:

*

*Create secret: kubectl create secret tls kong-admin-tls --cert=./admin.crt --key=./admin.key

*Add secretVolumes to values.yaml:
kong:
...
  secretVolumes:
  - kong-proxy-tls

*Add env params to values.yaml:
kong:
...
  env:
    ssl_cert: /etc/secrets/kong-proxy-tls/tls.crt
    ssl_cert_key: /etc/secrets/kong-proxy-tls/tls.key

*Add tls enabled under admin:
kong:
...
  admin:
    tls:
      enabled: true

*If you need other certs (optional that are not need for admin ssl):
kong:
...
  secretVolumes:
    - kong-proxy-tls
    - kong-admin-tls
    - kong-mngr-tls
  env:
    ssl_cert: /etc/secrets/kong-proxy-tls/tls.crt
    ssl_cert_key: /etc/secrets/kong-proxy-tls/tls.key
    admin_ssl_cert: /etc/secrets/kong-admin-tls/tls.crt
    admin_ssl_cert_key: /etc/secrets/kong-admin-tls/tls.key
    admin_gui_ssl_cert: /etc/secrets/kong-mngr-tls/tls.crt
    admin_gui_ssl_cert_key: /etc/secrets/kong-mngr-tls/tls.key

  admin:
    tls:
      enabled: true


text:
Q: bin/magento error after update Hello i have updated from 2.2.8 to 2.3.1 now php bin/magento is not working:
php bin/magento list
Fatal error: Uncaught Error: Class 'Zend\Mvc\Controller\LazyControllerAbstractFactory' not found in .../vendor/zendframework/zend-servicemanager/src/ServiceManager.php:314
Stack trace:
#0 .../vendor/zendframework/zend-servicemanager/src/Config.php(137): Zend\ServiceManager\ServiceManager->addAbstractFactory('Zend\\Mvc\\Contro...')
#1 .../vendor/zendframework/zend-modulemanager/src/Listener/ServiceListener.php(225): Zend\ServiceManager\Config->configureServiceManager(Object(Zend\Mvc\Controller\ControllerManager))
#2 [internal function]: Zend\ModuleManager\Listener\ServiceListener->onLoadModulesPost(Object(Zend\ModuleManager\ModuleEvent))
#3 .../vendor/zendframework/zend-eventmanager/src/EventManager.php(490): call_user_func(Array, Object(Zend\ModuleManager\ModuleEvent))
#4 .../vendor/zendframework/zend-eventmanager/src/EventManager.php(248): Zend\EventManager\EventManager->trigger in .../vendor/zendframework/zend-servicemanager/src/ServiceManager.php on line 314

A: The issue can be fixed by manually editing composer.json autoload section to
"autoload": {
    "psr-4": {
        "Magento\\Framework\\": "lib/internal/Magento/Framework/",
        "Magento\\Setup\\": "setup/src/Magento/Setup/",
        "Magento\\": "app/code/Magento/",
        "Zend\\Mvc\\Controller\\": "setup/src/Zend/Mvc/Controller/"
    }
}

and then run
composer dumpautoload
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento setup:static-content:deploy

It will work.

A: Following the upgrade instructions here https://devdocs.magento.com/guides/v2.3/comp-mgr/cli/cli-upgrade.html should take care of this issue. In particular for this error make sure to update your autoload section.

A: You need to add "Zend\\Mvc\\Controller\\": "setup/src/Zend/Mvc/Controller/" in autoload -> psr-4 in composer.json
"autoload": {
"psr-4": {
  "Magento\\Framework\\": "lib/internal/Magento/Framework/",
  "Magento\\Setup\\": "setup/src/Magento/Setup/",
  "Magento\\": "app/code/Magento/",
  "Zend\\Mvc\\Controller\\": "setup/src/Zend/Mvc/Controller/"
},
"psr-0": {
  "": [
    "app/code/",
    "generated/code/"
  ]
},
"files": [
  "app/etc/NonComposerComponentRegistration.php"
],
"exclude-from-classmap": [
  "**/dev/**",
  "**/update/**",
  "**/Test/**"
]
},

Don't forget to :
composer update

And other Magento commands like as
bin/magento setup:upgrade
bin/magento cache:clean


text:
Q: Flutter - TextEditingController used after being disposed I made following simple class to allow entering a string:
import 'package:flutter/material.dart';

class MyDialog {
  late TextEditingController _controller;

  Future<String> showMyDialog(BuildContext context) async {
    _controller = TextEditingController();

    final result = await showDialog(
      context: context,
      builder: (BuildContext context) => _buildMyDialog(context),
    );

    _controller.dispose();
    return result;
  }

  Widget _buildMyDialog(BuildContext context) {
    return AlertDialog(
      title: const Text('Enter string: '),
      content: TextField(
        autofocus: true,
        controller: _controller,
      ),
      actions: [
        TextButton(
          onPressed: () {
            Navigator.of(context).pop(_controller.text);
          },
          child: const Text('OK'),
        ),
      ],
    );
  }
}

and I call it like this:
final dialog = MyDialog();
final result = await dialog.showMyDialog(context);

Unfortunately I get following error:

A TextEditingController was used after being disposed.

Why does it happen and how to fix it? I don't use the controller anywhere after disposing it after all.

A: My concern with Yeasin's answer (at time of writing) is that you are not calling dispose() on the controller and I'm not 100% certain what nulling out the instance does in that regard. It may avoid the error, but maybe there is a memory leak or other problem (hypothetically).
Another approach I can suggest would be to turn your AlertDialog into a StatefulWidget so that you can take advantage of the built-in dispose() method for Widgets. This would allow you to avoid micro-managing the controller. Instead, you call the dispose method for the controller inside the dispose method of the Widget in which it is contained.
Here is what your code could look like to take advantage of this feature of Flutter and it does not change how you call the code to bring up the dialog:
class MyDialog {

    Future<String> showMyDialog(BuildContext context) async {
      final result = await showDialog(
        context: context,
        builder: (BuildContext context) => MyAlertDialog(),
      );
      return result;
    }

}

class MyAlertDialog extends StatefulWidget {
    @override
    State<MyAlertDialog> createState() => MyAlertDialogState();
}

class MyAlertDialogState extends State<MyAlertDialog> {

        // for this example, it's safe to instantiate the controller inline
        TextEditingController _controller = new TextEditingController();

        @override
        void dispose() {
            // attempt to dispose controller when Widget is disposed
            try { _controller.dispose(); } catch (e) {}
            super.dispose();
        }

        Widget build(BuildContext context) {
            return AlertDialog(
                title: const Text('Enter string: '),
                content: TextField(
                    autofocus: true,
                    controller: _controller,
                ),
                actions: [
                    TextButton(
                        onPressed: () {
                            Navigator.of(context).pop(_controller.text);
                        },
                        child: const Text('OK'),
                    ),
                ],
            );
        }

}

A: On showMyDialog it is getting new TextEditingController every time, we can comment _controller.dispose();. Also, it is possible to get null on this method, therefore it will be better  using
Future<String?> showMyDialog(...){...}

Another thing we can do making it nullable
class MyDialog {
  TextEditingController? _controller;

  Future<String?> showMyDialog(BuildContext context) async {
    _controller = TextEditingController();

    final String? result = await showDialog(
      context: context,
      builder: (BuildContext context) => _buildMyDialog(context),
    );
    _controller = null;
    return result;
  }
//....

You can check about _dependents.isEmpty': is not true


text:
Q: Find Users who worked for 5 consecutive days with date-range in output I have a table has data similar to below
  Emp  Date        Code
  ---  --------    ----
  E1  11/1/2012    W
  E1  11/1/2012    V
  E2  11/1/2012    W
  E1  11/2/2012    W
  E1  11/3/2012    W
  E1  11/4/2012    W
  E1  11/5/2012    W

I want to get list of employees between a date range(say for the last 3 months) who worked for code W conescutively for 5 days with the date range in the output. Each employee can have multiple records for a single day with different codes.
Expected Output is
Emp   Date-Range
---   ----------
 E1   11/1 -11/5

Below is what I tried but I didn't come close at all to the output I seek
 SELECT distinct user, MIN(date) startdate, MAX(date) enddate
FROM (SELECT user, date, (TRUNC(date) - ROWNUM) tmpcol
      FROM (SELECT user, date
              FROM tablename
             where date between to_date('10/01/2012','mm/dd/yyyy') and to_date('10/03/2012','mm/dd/yyyy')
             ORDER BY user, date) ot) t
 GROUP BY user, tmpcol
 ORDER BY user, startdate;

If Emp E1 has worked for 10 consecutive days, he should be listed twice in the output with both date ranges. If E1 has worked for 9 days consecutively(11/1 to 11/9), he should be listed only once with the date range 11/1 to 11/9.
I have already seen questions which are similar but none of them exactly worked out for me. My database is Oracle 10G and no PL/SQL.

A: You may start from here:
select
emp, count(*) over (partition by emp, code order by date_worked range interval '5' day preceding) as days_worked_last_5_days
from table
where code='W';

those rows with days_worked_last_5_days=5 are what you search.
See this fiddle.

A: I'm not sure I understood everything correctly, but something like this might get you started:
select emp,
       sum(diff) as days,
       to_char(min(workdate), 'yyyy-mm-dd') as work_start,
       to_char(max(workdate), 'yyyy-mm-dd') as work_end
from (
  select *
  from (
    select emp,
           workdate,
           code,
           nvl(workdate - lag(workdate) over (partition by emp, code order by workdate),1) as diff
    from tablename
    where code = 'W'
     and workdate between ...
  ) t1
  where diff = 1 -- only consecutive rows
) t2
group by emp
having sum(diff) = 5

SQLFiddle: http://sqlfiddle.com/#!4/ad7ae/3
Note that I used workdate instead of the date as it is a bad idea to use a reserved word as a column name.

A: Select emp, data-5, data from (SELECT EMP, DATA, WORK,lag, lead, row_number() over(PARTITION BY emp--, DATA
ORDER BY DATA asc) rn
  FROM (SELECT emp,
               data,
               work,
               LAG (data) OVER (PARTITION BY emp ORDER BY data ASC) LAG,
               LEAD (data) OVER (PARTITION BY emp ORDER BY data ASC) LEAD
          FROM (SELECT emp,
                       data,
                       work,
                       ROW_NUMBER ()
                           OVER (PARTITION BY emp, data ORDER BY data ASC)
                           rn
                  FROM example)
         WHERE rn = 1) a
WHERE a.data + 1 = LEAD AND a.data - 1 = LAG
) WHERE rn = 5

Where table example is :
EMP(varchar2), date, 'W' or 'F'

A: SELECT * FROM (
SELECT USERID,USEDATE,WRK,RANK() OVER (PARTITION BY USERID,WRK ORDER BY USEDATE ) AS RNK1 FROM USER1  )U1 JOIN
(
SELECT USERID,USEDATE,WRK,RANK() OVER (PARTITION BY USERID,WRK ORDER BY USEDATE ) AS RNK2 FROM USER1  )U2 ON U1.USERID=U2.USERID AND U1.RNK1+3=U2.RNK2 AND U2.USEDATE-U1.USEDATE=3;


text:
Q: Check field is updatable I have object and field name, but don't understand how to check if that field isUpdatable. It gives me the error:

Variable does not exist: fields

SObjectType objectType = Schema.getGlobalDescribe().get('Account');
objectType.fields.getMap().get('Name').getDescribe().isUpdateable();

A: You are missing getDescribe() for objectType
SObjectType objectType = Schema.getGlobalDescribe().get('Account');
objectType.getDescribe().fields.getMap().get('Name').getDescribe().isUpdateable();

Also pay attention, that Schema.getGlobalDescribe() is an expensive call in terms of server resource, so it is better to cache first invokation of it. Why is Schema.describeSObjects(types) Slower Than Schema.getGlobalDescribe()?
if you don't want to cache it, use Type.forName
SObjectType objectType = ((SObject)Type.forName('Schema', 'Account').newInstance()).getSObjectType();
objectType.getDescribe().fields.getMap().get('Name').getDescribe().isUpdateable();

A: I don't think you are using the right class, at least I've not done it that way before. Here's an quick, inelegant working alternative.
List<String> objNames = new List<String>{'Account'};
List<Schema.DescribeSobjectResult> dors = Schema.describeSObjects(objNames);
Schema.DescribeSobjectResult dor = dors[0];
Map<String, Schema.SObjectField> fieldMap =  dor.fields.getMap();
system.debug(fieldMap.get('Name').getDescribe().isUpdateable());


text:
Q: CSS and HTML will not link I have been using external stylesheets just fine until a couple days ago. I don't know why I am no longer able to link to external stylesheets from my HTML since I have had no problems with it earlier. I absolutely cannot find the issue.
It will probably be obvious, but right now I am really frustrated.
Please Help!
My File Structure:

-Tutorial (folder)
  - index.html
  - stylesheet.css

h1 {
  color: green;
}
<!doctype html>

  <title>Hello</title>
  <link rel="stylesheet" href="stylesheet.css">

Testing...

Note: It may run fine here on the snippet... but it will not link correctly in my HTML.

A: use

<link rel="stylesheet" href="./stylesheet.css">

A: Thanks you guys for the help! I found that I had this in my head:
<link rel="stylsheet" href="stylesheet.css">

I had spelled stylesheet wrong in the 'rel'.
It works fine now!


text:
Q: JavaScript operators precedence algorithm I have an example:
let x = 4
console.log(x++ + ++x + x--)

it's returns 16 but I don't understand how.
If we will look in MDN there is an operators precedence table.
So there is a precedence like this:

*

*Postfix increment

*Postfix decrement

*Prefix increment

*Addition

With this logic it should return 14

*

*x++ = 4 - (5) -> remembers for next call

*x-- = 5 - (4) -> remembers for next call

*++x = 5

*+
4 + 5 + 5 = 14
Can some one explain, how operators parser algorithm works with unary and binary operators?

A: Once operator precedence is applied, the grouping looks like:
((x++) + (++x)) + (x--)

The interpreter will evaluate the two +s left-to-right, and resolve the inner expressions as it comes across them. The increments/decrements don't run immediately and before the +s - they only run once the interpreter has determined that their expression needs to be evaluated. This is what happens, in order:
x is 4
((x++) + (++x)) + (x--)

evaluate postfix increment: insert 4, x increases to 5
(4 + (++x)) + (x--)

evaluate prefix increment: x increases to 6, insert 6
(4 + 6) + (x--)

simplify:
10 + (x--)

evaluate postfix decrement: insert 6, x decreases to 5
10 + 6

Resulting in a final value of 16.

A: You could take a table for the values, one for x with values for the actual/post or pre and actual value.
Then take according to the order of opperends the value and add this values.
let x = 4
console.log(x++ + ++x + x--); // 16
            post  pre   post  increment
x           4 5   5 6   6 5   different values
value       4       6   6     values for addition

let x = 4
console.log(x++ + ++x + x--); // 16

A: The order is completely consistent. You are evaluating left-to-right and apply the precedence. I'll break it down in steps:
1. Post-increment x++
//x = 4
x++ + ++x + x--
^^^
  |
  --> expression = 4
  --> x = 5

First off we evaluate x++. Postfix increment has higher precedence than the addition, so we have to solve it first. This expression produces 4 (value of x at the time) however, the value of x is also incremented for future reads.
2. Pre-increment ++x
//x = 5
4 + ++x + x--
    ^^^
      |
      --> x = 6
      --> expression = 5

Next ++x is evaluated, as prefix increment also has higher precedence than the addition, so we have to resolve it before the expression a + b. We aren't concerned with x-- yet, since we've not gotten to it.
Thus, the prefix increment will increase the value of x from 5 to 6 and then return that new value.
3. Addition (x++) + (++x)
//x = 6
4 + 6 + x--
^^^^^
    |
    --> expression = 10

We've resolved the higher priority expressions, so it's time for the addition. Which is simple 4 + 6 = 10.
4. Post-decrement x--
//x = 6
10 + x--
     ^^^
       |
       --> expression = 6
       --> x = 5

We're reached another a + b construct but the postfix decrement x-- is higher priority, so we solve that first. Current value of x is 6 and we return that, then do the decrement of x to 5.
5. Addition ((x++) + (++x)) + (x--)
//x = 5
10 + 6
^^^^^^
     |
     --> expression = 16

Finally, another simple addition after everything with higher precedence is resolved: 10 + 6 = 16


text:
Q: 'polar' forms of quaternions We call a quaternion $q = q_0 + q_1 i + q_2 j +q_3 k$ purely imaginary if $q_0=0$.
Here $q_0,q_1,q_2,q_3$ are real numbers, and $i, j, k$ the three imaginary units.
Is there a reference for the fact that any quaternion $q$ can be written as the product of a purely imaginary one $p$ times a phase $\psi\in (0,2\pi]$,
$$q = p e^{i \psi}$$
or a discussion/proof available?

A: There is a $\psi\in [0,2\pi)$ such that $(q_0 + q_1 i)e^{-i \psi}$ is purely imaginary.  Since $(q_2 j + q_3 k)e^{-i \psi}$ is of the form $rj+sk$, it follows that $p=qe^{-i \psi}$ is purely imaginary.


text:
Q: Forcing a terminal not to print Ctrl hotkeys when signals are caught Good day,
I'm writing my own shell in C for my school which has to resemble bash as closely as possible.
I have to handle signals such as Ctrl-\ and Ctrl-C as bash does; for this reason I'm allowed to use signal function. It works fine, but the thing is whenever a Ctrl-C signal is caught (starting from the second catch), a ^C is printed.
On the net, I've found a workaround suggesting printing "\b \b\b \b\nminishell$ " whenever a Ctrl-C is caught, which will devour the two symbols. The thing is, since at the very first time ^C is not printed, the print devours two symbols of my prompting, making it just minishell instead of minishell$ , with the cursor incorrectly displayed.
Now I've come up with another workaround for this workaround which is to declare a static boolean to not print the baskspaces at the very first call. This doesn't help in case of Ctrl-\ though; Ctrl-\ proceeds to move my cursor to right when I attempt to write the two whitespaces that must replace the ^\.
I don't like these workarounds and would like to know whether there is a way to instruct the terminal not to output this stuff? I'm allowed to use tgetent, tgetflag, tgetnum, tgetstr, tgoto, tputs, tcsetattr, tcgetattr, have read their man pages but nothing seems to be helpful.

A: When you type a key on a terminal, two things happen

*

*the character is echoed (displayed) on this terminal

*the character is sent (over the line) to the attached program

Both these actions can be controlled via termios/tcsetattr(): a different character(s) can be sent or echoed, some can be suppressed, etc. (some/most of these actions take place in the terminal-driver , but this is not relevant here)
Demonstration: using tcsetattr() to control the echoing of the terminal:

#include <stdio.h>
#include <stdlib.h>

#define _SVID_SOURCE 1
#include <termios.h>
#include <unistd.h>
#include <signal.h>

struct termios termios_save;

void reset_the_terminal(void)
{
tcsetattr(0, 0, &termios_save );
}

sig_atomic_t the_flag = 0;
void handle_the_stuff(int num)
{
char buff[4];
buff[0] = '[';
buff[2] = '0' + num%10;
num /= 10;
buff[1] = '0' + num%10;
buff[3] = ']';
write(0, buff, sizeof buff);
the_flag = 1;
}

int main (void)
{
int rc;
int ch;
struct termios termios_new;

rc = tcgetattr(0, &termios_save );
if (rc) {perror("tcgetattr"); exit(1); }

rc = atexit(reset_the_terminal);
if (rc) {perror("atexit"); exit(1); }

termios_new = termios_save;
termios_new.c_lflag &= ~ECHOCTL;
rc = tcsetattr(0, 0, &termios_new );
if (rc) {perror("tcsetattr"); exit(1); }

signal(SIGINT, handle_the_stuff);

printf("(pseudoshell)Start typing:\n" );
while(1) {
        ch = getc(stdin);
        if (the_flag) {
                printf("Saw the signal, last character was %02x\n", (unsigned) ch);
                break;
                }
        }

exit (0);
}

A: The way to set the console such a SW may intercept all typed chars is to set the terminal in RAW MODE. The problems this way may present are that all keys that aren't in the ASCII 0-255 space, such as è, ì, à will be received from the console as a bytes sequence and all the function and control keys included cursors and backspace will not accomplish any action, some code such as CR, LF and some ANSI sequence may accomplish actions when are read from the input channel and rewritten on the output channel.
To set the terminal in raw mode you have to use the function cfmakeraw followed by the function tcsetattr.
The code below implements a simple but not very good implemented terminal, anyway I think this code is a good point to start. In any case, the code flow and the error control must be at least better arranged.
The code writes all sequence of ASCII char that enter into the console when a key is typed. All chars that have value smaller then 32 or greater then 126 will be written as [HEX-CODE]
I.E. hitting Esc on the console will be written [1B], the code of Ctrl+C will be written as [03], F1 will be [1B]OP, F11 will be [1B][23~, Enter will be [0D].
If you will hit Ctrl+X [18] will be written and the program stops, but this behaviour is under SW control as you can see in the code.
Here the code:
#include <stdio.h>      // Standard input/output definitions
#include <string.h>     // String function definitions
#include <unistd.h>     // UNIX standard function definitions
#include <fcntl.h>      // File control definitions
#include <errno.h>      // Error number definitions
#include <termios.h>    // POSIX terminal control definitions (struct termios)

#include <sys/ioctl.h> // Used for TCGETS2, which is required for custom baud rates
#include <sys/select.h> // might be used to manage select

int setAttr(int ch, int resetToOld);

#define IN 0
#define OUT 1

typedef struct TermCap
{
    int fd;
    struct termios oldTermios;
    struct termios newTermios;
    // fd_set fds; // might be used to manage select
} TermCap;

TermCap m_termCap[2];

int main()
{
    int i,ex=0;
    char msg;
    char buff[20];

    m_termCap[IN].fd=STDIN_FILENO;
    m_termCap[OUT].fd=STDOUT_FILENO;

    // Gets STDIN config and set raw config
    setAttr(IN,0);

    // Gets STDOUT config and set raw config
    setAttr(OUT,0);

    // Console loop ... the console terminates when ^X is intercepted.
    do {
        do {
            i=read(m_termCap[IN].fd,&msg,1);
            if (i>0){
                if (msg<32 || msg>126) {
                    sprintf(buff,"[%02X]",(unsigned char)msg);
                    write(m_termCap[OUT].fd,buff,4);
                    if (msg==24)
                        ex=1;
                }else{
                    write(m_termCap[OUT].fd,&msg,i);
                }
            }
            usleep(10000); // a minimal delay of 10 millisec
        } while(i>0 && !ex);
    } while(!ex);

    // Reset console to initial state.
    setAttr(IN,1);
    setAttr(OUT,1);

    printf("\r\n\nThe end!");
    return 0;
}

int setAttr(int ch, int resetToOld)
{
    int retVal=0;
    int i;

    if (!resetToOld) {
        // Read old term config
        i=tcgetattr(m_termCap[ch].fd, &m_termCap[ch].oldTermios);
        if (i==-1) {
            return 1;
        }
    }

    m_termCap[ch].newTermios = m_termCap[ch].oldTermios;

    if (!resetToOld) {
        // Terminal in raw mode
        cfmakeraw(&m_termCap[ch].newTermios);
    }

    i=tcsetattr(m_termCap[ch].fd, TCSANOW, &m_termCap[ch].newTermios);

    if (i==-1) {
        retVal = 2;
    }

    return retVal;
}

A: Wouldn't this work?
void signalHandler(int signo){
 if(signo==SIGINT){
  printf("\b\b  \b\b");
  fflush(NULL);
  printf("\nHello World\n");
 }
}

In my shell it seems to work fine. The first printf and fflush is what you have to implement in your handler. The printf after that is just a way for me to show you that you can, then, do whatever you want after the ^C not appearing.
Why does this make it not appear? In the first printf I erase the characters by using backspaces and spaces. As stdout is buffered by default and I didn't want to use a newline character, I flushed the buffer manually.


text:
Q: Gitlab CI/CD workflow rule variables only allow one if condition I am currently trying to structure my .gitlab-ci.yml file like following:

*

*There is one pipeline called "a" which should run only from the develop branch

*There is one pipeline called "b" which should run only from the develop branch but only when triggered from the web

In order to avoid putting these rules in the jobs directly (in reality there are about 30 jobs) I want to reuse those rules globally. I could not find a better way other than using workflow:rules.
workflow:
  rules:
    - if $CI_COMMIT_BRANCH == "develop"
      variables:
        RUN_A: "true"
    - if $CI_COMMIT_BRANCH == "develop" && $CI_PIPELINE_SOURCE == "web"
      variables:
        RUN_B: "true"

job-a:
  rules:
    - if: $RUN_A == "true"
  script:
    - exit 0

job-b:
  rules:
    - if: $RUN_B == "true"
  script:
    - exit 0

The problem is, that if there is a web trigger on develop, it will not set "RUN_B" to true. It will just have "RUN_A" with true. I added another job to print out the variables just to make sure:
test:
  image: alpine
  script:
    - echo $RUN_A
    - echo $RUN_B

This will only print true for RUN_A but nothing for RUN_B. I could not find anything in Gitlabs documentation that states it will only use the first matching rule. Anyhow, is there a better way to handle this? What am I missing?

A: Because GitLab ci Rules evaluated in order until the first match.
in your first rule if $CI_COMMIT_BRANCH == "develop" is match, the pipeline is create, in this times variable RUN_A: "true" is set, but variable RUN_B is undefined.
In your case, you can modify your .gitlab-ci.yml. variable setting and rules order.
workflow:
  rules:
    - if: $CI_COMMIT_BRANCH == "develop" && $CI_PIPELINE_SOURCE == "web"
      variables:
        RUN_B: "true"
        RUN_A: "true"
    - if: $CI_COMMIT_BRANCH == "develop"
      variables:
        RUN_A: "true"

default:
  image: alpine

job-a:
  rules:
    - if: $RUN_A == "true"
  script:
    - exit 0

job-b:
  rules:
    - if: $RUN_B == "true"
  script:
    - exit 0

test:
  script:
    - echo $RUN_A
    - echo $RUN_B


text: Q: Import changes from javax.* imports to jakarta.* doesnt work I was getting errors in my java class after migrating from Java 8 to Java 11. Error that said javax.xml.soap doesn't exist and similar, To resolve this issue, I downloaded jakarta.xml.ws:jakarta.xml.ws-api:2.3.2 and added to my libraries in intellij. However I still cant import jakarta in my classes as it says package doesnt exist. I also see the below screen shot where I see jakarta internally using using javax. I can do import javax, but doesnt compile in java 11.


text:
Q: With react and material-ui, can I have some paper expand to full width outside a Container? If I have:
   <Container maxWidth='lg'>
    <Grid container spacing={3}>
      <Grid item xs={12} md={6} >
        <Image src="/img/undraw_programming_2svr.png" color='transparent' aspectRatio={1041 / 554} />
      </Grid>
<SomeElement />
    </Container>

How can I have SomeElement expand to full width?

A: First, A few things that were already mentioned, Your grid tagging is wrong and I understand that it's a mistake and probably not essential to your question.
The answer to your question is no, the point of the container is to stop SomeElement from expanding. A simple fix, however, would be to stop the container, render SomeElement, and then start a new container.
<Container>
...
</Container>

<SomeElement />

<Container>
...


text:
Q: Showing the matrix 1-norm equals the maximum of a sum I want to show:
$$\|A\|_{1} := \max_{x\neq 0}\frac{\|Ax\|_{1}}{\|x\|_{1}} = \max_{1\leqslant j \leqslant n}\sum_{i=1}^{n}|a_{ij}|$$
My attempt to show it directly by applying the definition of $\|A\|_{1}$ has failed several times. I'm looking for some useful tips and or hints. Many thanks.

A: Note first that
$$ ||A||_1 = \max_{x \neq 0} \frac{||Ax||_1}{||x||_1} = \max_{x \neq 0} \left| \left| A \left( \frac{x}{||x||_1} \right) \right| \right|_{1} = \max_{||y||_1 = 1} ||Ay||_1. $$
Denote the standard basis vectors of $\mathbb{R}^n$ by $e_j$. Then $||e_j||_1 = 1$ and
$$ ||Ae_j||_1 = ||(a_{1j}, \ldots, a_{nj})^T||_1 = \sum_{i=1}^n |a_{ij}|. $$
Thus, we have
$$ ||A||_1 \geq \max_{1 \leq j \leq n} ||Ae_j||_1 = \max_{1 \leq j \leq n} \sum_{i=1}^n |a_{ij}|. $$
For the other direction, if $y \in \mathbb{R}^n$ with $||y||_1 = 1$ then by the triangle inequality and the linearity we have
$$ ||Ay||_1 = \left| \left| A \left( \sum_{j=1}^n y_j e_j \right) \right| \right|_1 = \left| \left| \sum_{j=1}^n y_j A(e_j) \right| \right|_1 \leq \sum_{j=1}^n |y_j| \cdot ||Ae_j||_1 \leq \sum_{j=1}^n |y_j| \cdot \max_{1 \leq j \leq n} ||Ae_j||_1 = \max_{1 \leq j \leq n} ||Ae_j||_1 = \max_{1 \leq j \leq n} \sum_{i=1}^n |a_{ij}|. $$


text:
Q: Conversion of integer to filename incorrect fore more than one digit Program main
use ifport

implicit none
integer ii,fileid
double precision pi
logical result
character*256 path,filename,fileNum
pi = 4.d0*datan(1.d0)
ii = 20
path = './testforlder'

result = makedirqq(path)

Do ii = 1, 11

fileid = 1 + ii
write(fileNum,"(A10,I1,A4)") "/TimeStep-",ii,".txt"
filename = trim(path)//trim(fileNum)
open(unit = fileid,file=filename,status='unknown')
write(fileid,*) "The result is:", ii,pi,2*pi
close(fileid)

End Do

pause
End Program

My code is written as above. When the loop step is less than 10, it works. However, when the loop step >= 10 (for example: 11), it fails.


text:
Q: Get errors when using R package aws.s3 I am trying to upload a file to s3 with the function aws.s3::s3write_using() but it prints an error on the console. This error contains truncated parts so I can't inspect it with the detail I want. How can I save this error (formatted as a list) to an object?
For example:
aws.s3::s3write_using(iris, FUN = fwrite, sep = ";", object = "iris", bucket = "non_existing_bucket")

Throws an error and prints the following:
List of 5
 $ Code      : chr "NoSuchBucket"
 $ Message   : chr "The specified bucket does not exist"
 $ BucketName: chr "non_existing_bucket"
 $ RequestId : chr "N3H55KTQNCFDW8YH"
 $ HostId    : chr "8GyUqcYR0GqjQifuCSOC9Zqc35Be1aE5cfUuDOBFGpb0LzlNQxaIvbvJzfmmxRSXSb7iV7rnv94="
 - attr(*, "headers")=List of 7
  ..$ x-amz-request-id : chr "N3H55KTQNCFDW8YH"
  ..$ x-amz-id-2       : chr "8GyUqcYR0GqjQifuCSOC9Zqc35Be1aE5cfUuDOBFGpb0LzlNQxaIvbvJzfmmxRSXSb7iV7rnv94="
  ..$ content-type     : chr "application/xml"
  ..$ transfer-encoding: chr "chunked"
  ..$ date             : chr "Thu, 06 May 2021 10:17:11 GMT"
  ..$ server           : chr "AmazonS3"
  ..$ connection       : chr "close"
  ..- attr(*, "class")= chr [1:2] "insensitive" "list"
 - attr(*, "class")= chr "aws_error"
 - attr(*, "request_canonical")= chr "PUT\n/non_existing_bucket/iris\n\ncontent-length:3867\nhost:s3.amazonaws.com\nx-amz-acl:private\nx-amz-date:202"| __truncated__
 - attr(*, "request_string_to_sign")= chr "AWS4-HMAC-SHA256\n20210506T101611Z\n20210506/us-east-1/s3/aws4_request\nf889bc56946eed90f7d83382881ede47d3b8453"| __truncated__
 - attr(*, "request_signature")= chr "AWS4-HMAC-SHA256 Credential=AKIAWLC3MSZDR2UM7O7Q/20210506/us-east-1/s3/aws4_request,SignedHeaders=content-lengt"| __truncated__
NULL
Error in parse_aws_s3_response(r, Sig, verbose = verbose) :
  Not Found (HTTP 404).

What I need is to save that list to an R object.


text:
Q: OData over a "View" of unioned data in Entity Framework I'm developing an OData service which exposes a model created with Entity Framework 6.  These entities are read only and are quite large to load. (Several gigabytes)
To accomplish this I'm using Microsoft.OData.EntityFrameworkProvider, (I'm not currently using WebAPI) This is mostly working fine, however I have a new requirement that needs to expose an entity which is actually a union of multiple other entities for convenience to our EndUser / customer.
EF Context Snippet
    ...
    public DbSet<Foo> FooRecs { get; set; }
    public DbSet<Bar> BarRecs { get; set; }
    public IQueryable<FooBarRec> FooBarRecs
    {
        get
        {
            return FooRecs.Select(f => new FooBarRec() { Id = f.Id, Description =  f.Description })
                .Union(
                BarRecs.Select(b => new FooBarRec() { Id = b.Id, Description = b.Description })
                );
        }
    }
    ...

I'm unable to expose this IQueryable property through odata as it appears that the EntityFrameworkProvider only exposes DbSets and not any IQueryable object, which makes sense.
My question is, what is the best approach to accomplish this with OData?
I'd like to avoid loading duplicate data into a third intermediate table as the data can be large, and the time to load that data which is done nightly.  It appears that QueryInterceptor only lets you subfilter data which is already queried so that doesn't seem to work.
I tried doing crazy things like extend DbSet and make my own DbViewSet which takes both sets in it's constructor, but couldn't find a way to close the loop.
What is the best way to accomplish something analogous to a view with OData and EF6?
Thanks!

A: I create an example with Web API & OData. It looks very simple and can meet your requirement:
First, I define the following CLR classes to mapping your types and needn't create any view:
public class FooBarRec
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Foo FooRec { get; set; }
    public Bar BarRec { get; set; }
}

public class Foo
{
    public int FooId { get; set; }
    public string FooName { get; set; }
}

public class Bar
{
    public int BarId { get; set; }
    public string BarName { get; set; }
}

Next, I create an OData EdmModel based on the above CLR types:
private static IEdmModel GetEdmModel()
{
    ODataModelBuilder builder = new ODataConventionModelBuilder();
    builder.EntitySet<FooBarRec>("FooBarRecs");
    builder.EntitySet<Foo>("Foos");
    builder.EntitySet<Bar>("Bars");
    return builder.GetEdmModel();
}

Next, I create OData controllers to handle the OData URI query:
 // Controller
 public class FoosController : ODataController
 {
     public const int Num = 10;
     public static IList<Foo> foos = Enumerable.Range(0, Num).Select(i =>
            new Foo
            {
                FooId = 100 + i,
                FooName = "Foo #" + (100 + i)
            }).ToList();

     [EnableQuery]
     public IHttpActionResult Get()
     {
         return Ok(foos);
     }
 }

 public class BarsController : ODataController
 {
     public const int Num = 10;
     public static IList<Bar> bars = Enumerable.Range(0, Num).Select(i =>
            new Bar
            {
                BarId = 1000 + i,
                BarName = "Bar #" + (1000 + i)
            }).ToList();

    [EnableQuery]
    public IHttpActionResult Get()
    {
        return Ok(bars);
    }
 }

 public class FooBarRecsController : ODataController
 {
     public const int Num = 10;
     public static IList<FooBarRec> fooBarRecs = Enumerable.Range(0, Num).Select(i =>
             new FooBarRec
             {
                   Id = i,
                   Name = "ForBarRec #" + i
              }).ToList();

     static FooBarRecsController()
     {
        for(int i = 0; i < Num; i++)
        {
            fooBarRecs[i].FooRec = FoosController.foos[i];
            fooBarRecs[i].BarRec = BarsController.bars[i];
        }
     }

     [EnableQuery]
     public IHttpActionResult Get()
     {
         return Ok(fooBarRecs);
     }
 }

Note: In FooBarRec, I create two properties (FooRec and BarRec) and use them to build a relationship between FooBarRec, Foo and Bar.
Now, we can provide any data what the EndUser want.
For example, The EndUser can use the following two URIs to query the single data:

*

*~/odata/Foos

*~/odata/Bars
Or, He can use the following URI to query the Union data:

*

*~/odata/FooBarRecs?$expand=FooRec,BarRec

That's all.

A: As Jodrell stated in the comments.
The only approach to make this work is to make a DbSet to represent a SQL View.
The only way I could get Entity Framework to handle the model binding appropriately was to drop the table after it was created and create then create the view.
Because it was a unioned view I had to handle this after the model was done initializing because otherwise it will try to force a clustered index on a view which is not possible if the view contains a union.


text:
Q: What went wrong: Execution failed for task ':stripe_android:parseDebugLocalResources' I have this error when debugging my application. I already updated almost everything but error persists.
> /snap/flutter/131/usr/lib/x86_64-linux-gnu/gdk-pixbuf-2.0/../../../../lib/x86_64-linux-gnu/libc.so.6:
> version `GLIBC_2.33' not found (required by
> /usr/lib/x86_64-linux-gnu/gio/modules/libgvfsdbus.so) Failed to load
> module: /usr/lib/x86_64-linux-gnu/gio/modules/libgvfsdbus.so Launching
> lib/main.dart on sdk gphone x86 in debug mode... lib/main.dart:1
> Building with Flutter multidex support enabled.
> /snap/flutter/131/usr/lib/x86_64-linux-gnu/gdk-pixbuf-2.0/../../../../lib/x86_64-linux-gnu/libc.so.6:
> version `GLIBC_2.33' not found (required by
> /usr/lib/x86_64-linux-gnu/gio/modules/libgvfsdbus.so) Failed to load
> module: /usr/lib/x86_64-linux-gnu/gio/modules/libgvfsdbus.so
>
> FAILURE: Build failed with an exception.
>
> * What went wrong: Execution failed for task ':stripe_android:parseDebugLocalResources'.
> > Could not resolve all files for configuration ':stripe_android:androidApis'.

can you give me a clue.


text:
Q: How to connect Nokia Lumia 520 to Ubuntu 12.04 I have done the following steps:
sudo add-apt-repository ppa:langdalepl/gvfs-mtp
sudo apt-get update

and updated some packages from update manager. After doing above steps I am able to see lumia phone name in file system. But when I try to mount device I am getting following errors:
Unable to mount RM-914|Nokia Lumia 520
Unable to open MTP device '[usb:001,010]'

Is there any way to solve these problem?

A: Make a new udev rule
sudo emacs -nw /etc/udev/rules.d/69-libmtp.rules
And add the following line
ATTR{idVendor}=="01b1", ATTR{idProduct}=="01b1", SYMLINK+="libmtp",
MODE="660", GROUP="audio", ENV{ID_MTP_DEVICE}="1", ENV{ID_MEDIA_PLAYER}="1"

You need to refresh the udev rules and unplug/replug the device and it will work. :-)

A: These are my steps to connect the Nokia Lumia 920 (WP8):
1. Add the MTP file system in Ubuntu:
sudo add-apt-repository ppa:langdalepl/gvfs-mtp
sudo apt-get update

2. Make a new udev rule:
2.1 Create the rule file:
sudo nano /etc/udev/rules.d/69-libmtp.rules

2.2 Add the following line to the file:
ATTRS{idVendor}=="01b1", ATTRS{idProduct}=="01b1", SYMLINK+="libmtp", MODE="660", ENV{ID_MTP_DEVICE}="1"

2.3 Save the file (Ctrl+O)
3. Reload udev rules:
# udevadm control --reload-rules

4. Connect (or reconnect) the device.

A: Plug the phone in, then reboot the phone while it's plugged in.
Worked for me using Ubuntu 13.10 and Lumia 520.

A: Did you check with lock screen disabled?
I remember earlier when I hadn't kept the password lock screen - the file browser used to show the device and I could access it.
However, now that I have kept the password lock screen - the devices are visible but cannot be opened via file browser.
Of course there is one more additional thing: earlier I was using Ubuntu 12.04, now I use 14.04 - so I don't know if the issue is because of change of ubuntu version - I don't think so.


text:
Q: adding android:tragetSdkVersion= "14" in maifest for application developed for 2.3.3 version, is it a good idea? I want to add android:tragetSdkVersion= "14" in my manifest but I'm consufed as initially I developed my application for 2.3.3 version. So I used TabActivity for that. But TabActivity is deprecated in 4.0 version and according to the documentation, including android:tragetSdkVersion= "14" means system will not impose any forward compatibility to the app. So I wonder if it is good idea to include android:tragetSdkVersion= "14" in my manifest.

A: If you want to make it working on sdk 14, why are you leaving TabActivity in your code?
Otherwise, don't make sdk14 your target, and better to prevent users with version 4.0 or higher to install your application

A: You should use the v4 support libraries if you target higher SDK versions and also provide a minSdk:
<uses-sdk android:minSdkVersion="integer"
          android:targetSdkVersion="integer"
          android:maxSdkVersion="integer" />

here is info about the support libraries
http://developer.android.com/tools/support-library/index.html


text:
Q: get request data in Django form Is it possible to get request.user data in a form class?  I want to clean an email address to make sure that it's unique, but if it's the current users email address then it should pass.
This is what I currently have which works great for creating new users, but if I want to edit a user I run into the problem of their email not validating, because it comes up as being taken already.  If I could check that it's their email using request.user.email then I would be able to solve my problem, but I'm not sure how to do that.
class editUserForm(forms.Form):
    email_address = forms.EmailField(widget=forms.TextInput(attrs={'class':'required'}))

    def clean_email_address(self):
        this_email = self.cleaned_data['email_address']
        test = UserProfiles.objects.filter(email = this_email)
        if len(test)>0:
            raise ValidationError("A user with that email already exists.")
        else:
            return this_email

A: As ars and Diarmuid have pointed out, you can pass request.user into your form, and use it in validating the email. Diarmuid's code, however, is wrong. The code should actually read:
from django import forms

class UserForm(forms.Form):
    email_address = forms.EmailField(
        widget=forms.TextInput(
            attrs={
                'class': 'required'
            }
        )
    )

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super(UserForm, self).__init__(*args, **kwargs)

    def clean_email_address(self):
        email = self.cleaned_data.get('email_address')

        if self.user and self.user.email == email:
            return email

        if UserProfile.objects.filter(email=email).count():
            raise forms.ValidationError(
                u'That email address already exists.'
            )

        return email

Then, in your view, you can use it like so:
def someview(request):
    if request.method == 'POST':
        form = UserForm(request.POST, user=request.user)
        if form.is_valid():
            # Do something with the data
            pass
    else:
        form = UserForm(user=request.user)
    # Rest of your view follows

Note that you should pass request.POST as a keyword argument, since your constructor expects 'user' as the first positional argument.
Doing it this way, you need to pass user as a keyword argument. You can either pass request.POST as a positional argument, or a keyword argument (via data=request.POST).

A: Here's the way to get the user in your form when using generic views:
In the view, pass the request.user to the form using get_form_kwargs:
class SampleView(View):
    def get_form_kwargs(self):
        kwargs = super(SampleView, self).get_form_kwargs()
        kwargs['user'] = self.request.user
        return kwargs

In the form you will receive the user with the __init__ function:
class SampleForm(Form):
    def __init__(self, user, *args, **kwargs):
        super(SampleForm, self).__init__(*args, **kwargs)
        self.user = user

A: Just so you know, with Django 1.4 and generic class based CreateView and UpdateView, a self.instance is populated on each model form, which allows you to compare the POSTed email vs the current user email.
Here is a code sample, using mixin
class EmailUniqueMixin(object):
    """
    Ensure each User's email is unique
    on the form level
    """
    def clean_email(self):
        email = self.cleaned_data['email']
        existing_email = User.objects.filter(email=email).exclude(pk=self.instance.id)
        if existing_email:
            raise forms.ValidationError('That email address already exists')
        else:
            return email

A: Not that I'm aware of.  One way to handle this is have your Form class's __init__ take an optional email parameter, which it can store as an attribute.  If supplied at form creation time, it can use that during validation for the comparison you're interested in.

A: When you instantiate the form in the view, it is possible to pass an instance by parameter and use it inside the form.
form = YourModelForm(request.POST, instance=request.user)

In the form, you must access this way:
 if *self.instance.email* == email:
    return email

A: We can use get_form method:
class SampleView(View):
    def get_form(self, request, *args, **kwargs):
        form = super().get_form(request, *args, **kwargs)
        form.request_user = request.user
        return form

class SampleForm(Form):
    def clean_email_address(self):
        email = self.cleaned_data['email_address']

        if self.request_user and self.request_user.email==email:


text:
Q: Cannot chroot mounted volume to reset root password ( hangs ) I am trying to reset the root password on my instance. I boot it in rescue mode and mount the primary disk.
fdisk -l
sudo mount /dev/sdb1 /mnt
sudo chroot /mnt

The prompt just hangs here and it never gives me a new prompt so I can passwd and reset it.

A: I could not figure out why it was not successfully chrooting the mounted volume but I fixed it by just manually editing /etc/shadow.
Just generate a new hash & salt using ONE of the below commands:
(they both do the same thing)
mkpasswd -m sha-512 PASSWORD SALT
python -c 'import crypt; print crypt.crypt("password", "$6$saltsalt$")'

Now edit /etc/shadow with your favorite editor.
You will see a long list of accounts. Find the one corresponding to your user.
admin:$6$IcQdmmXO$GQcrQ3Jrqj8CyTKlBPPMD.8760XEOPpgEjSZX3Q.Ah9uRjmuRqs9c4632vzH3FiIg2flH7VWNbTXfVh04gRQR1:16977:0:99999:7:::
It will look like the above. Paste the hash/salt combo generated by the mkpasswd command in between the first set of :
Example:
admin:newHashHere:16977:0:99999:7:::


text:
Q: Automatic paragraph numbering within subsections I'm attempting to create a similar format to a word document (example attached) within LaTeX but I'm having a lot of issues with achieving. The document is an article and every single single paragraph requires numbering and indenting by 20mm so it would be desirable to declare this setup once rather than introducing every paragraph with \paragraph or similar.

My MWE is below:
\documentclass[11pt, twoside]{article}
\usepackage[top=2.5cm,bottom=2.5cm,right=1.8cm,left=1.8cm]{geometry}
\usepackage{fontspec} % Needed to run XeLaTeX
\setmainfont{Arial}
\usepackage{titlesec}
\titleformat{\section}
    {\normalfont\huge}{\makebox[2cm][l]{\thesection}}{0pt}{}
\titleformat{\subsection}
    {\normalfont\bfseries}{\makebox[2cm][l]{\thesubsection}}{0pt}{}
\titleformat{\subsubsection}
    {\normalfont\bfseries}{\makebox[2cm][l]{\thesubsubsection}}{0pt}{}

\titleformat{\paragraph}
    {\normalfont}{\makebox[2cm][l]{\theparagraph}}{0pt}{}

\setcounter{secnumdepth}{5}

\begin{document}
\section{This Section Header}
\paragraph{Main text.}
\subsection{Sub Section header}
\paragraph{Sub section text}
\subsubsection{Sub Sub Section header}
\paragraph{Sub Sub section text part 1}
\paragraph{Sub Sub section text part 2}
\end{document}

Which produces:

But I'm not sure how to automate the paragraph numbering. Any help would be much appreciated!


text:
Q: Laravel angular2-jwt template requests I've an interesting question. I have setup a project using Laravel 5 and Angular2 with angular2-jwt. Laravel uses a JWT authentication library (https://github.com/tymondesigns/jwt-auth) and produces tokens upon login, which are then sent over the vast Internet and saved to localStorage.setItem('id_token', response.token) the local machine.
Everything is working fine, but my Laravel controllers use jwt.auth, which requires my Angular2 component template requests to send with them the token. I'm a little lost here, since I seemingly cannot integrate the angular2-jwt library into my @component: templateUrl requests.
This means that I cannot request templates that should only be visible to logged in users, because the template request doesn't contain the token and thus is not authenticated to request those templates.
Can anybody advise or give me directions?
example component that I need to request a template for from Laravel with the jwt token attached to.
@Component ({
    selector: 'app-page',
    templateUrl: '/templates/Main.base',
    directives: [
        ROUTER_DIRECTIVES,
        HeaderComponent,
        UsersComponent,
        ProductsComponent
    ]
})

A: The best way for handling JWT with JS frameworks that run on the same domain is to place the JWT token inside the session cookie, then the cookie will be sent by the browser with each request, and you do not have to handle anything else.


text:
Q: Backbone's model prototype fetch vs backbone fetch I was looking at a website's model code and I had a question regarding the prototype. I understand that is's useful for inheritance in Javascript.
In this example...
define([], function () {

    "use strict";

    /**
     * Data Model
     *
     * @type {Backbone.Model}
     */
    var DataModel = Backbone.Model.extend({

        defaults : {

        },

        urlRoot : '/api/..../../..',

        fetch : function() {
            Backbone.Model.prototype.fetch.apply(this, arguments);
        }
    });

    return Datamodel;
});

Why do we need to do Backbone.Model.prototype.fetch.apply(this, arguments); instead of plain old Model.fetch();
I'm super duper confused. Why even use prototype in order to fetch something? I can't understand the usecase here.
Please help.

A: This is done in order to do some pre-prosessing before invoking the actual fetch method. On in other words, we override the models fetch method with our custom logic which eventually invokes the original fetch method if needed.
For example:
fetch : function(options) {
    if(options.someFlag){
           var dfd = jQuery.Deferred();
           // fetch the data from localStorage
           // dfd.resolve(resultingDataFromLocalStorage);
           return dfd.promise();
    }
    return Backbone.Model.prototype.fetch.apply(this, arguments);
}

This is a better solution than having the code for deciding how the fetch should proceed in all the view's that's invoking model.fetch().
Of course, without custom logic in there, as in your example this is pretty unnecessary.


text:
Q: stored proc from multiple select statements in Tsql -> I want to write a stored proc which outputs the columns from 2 select statements
->the columns from one select statement will be the inputs to the second select statement
create procedure sp_proc
@inputId int
As
Begin

Select t1.ticketId AS ticket,
t2.name AS NAME,
t3.status AS STATUS,
t2.id ID
from table1 t1
Inner JOIN table2 t2 ON  t1.ticketId= t2.ticketId
INNER JOIN table3 t3 on t3.name = t2.name
WHERE t1.ticketId IS NOT NULL
AND t2.id = @inputId

Select t1.ticketId, t2.name , D.desc, t2.id
from table1 t1
Inner JOIN table2 t2 ON  t1.ticketId= t2.ticketId
INNER JOIN( SELECt TOP 1 from table4 t4 ORDER BY t4.date  where t4.ticketId = ticket)AS D
ON t4.ticketId = t2.ticketId
WHERE t4.ticketId =ticket

I want the ticket, NAME,STATUS, ID , desc when user supplies @inputId to proc

A: I would try to combine everything in one query. It's my guessing, because you seem to miss something:
SELECT
  t1.ticketId AS ticket,
  t2.name AS NAME,
  t3.status AS STATUS,
  t2.id AS ID,
  (SELECT TOP 1 desc FROM table4 WHERE t1.ticketId=table4.ticketId ORDER BY DESC) AS DESC
FROM table1 t1
INNER JOIN table2 t2 ON  t1.ticketId= t2.ticketId
INNER JOIN table2 t4 ON  t1.ticketId= t4.ticketId
INNER JOIN table3 t3 ON t3.name = t2.name

WHERE t1.ticketId IS NOT NULL AND t2.id = @inputId

But I am not sure where are you trying to get here:
INNER JOIN( SELECt TOP 1 from table4 t4 ORDER BY t4.date  where t4.ticketId = ticket)AS desc
ON t4.ticketId = t2.ticketId

I'm guessing you are after latest something in table4 for given ticketId... so I made my query on this assumption.

A: An inline scalar query will work
create procedure sp_proc
@inputId int
As

Select t1.ticketId AS ticket,
t2.name AS NAME,
t3.status AS STATUS,
t2.id ID,
[DESC] = (SELECT TOP(1) [DESC]
          from table4 t4
          where t4.ticketId = t1.ticketId
          ORDER BY t4.date)
from table1 t1
Inner JOIN table2 t2 ON  t1.ticketId= t2.ticketId
INNER JOIN table3 t3 on t3.name = t2.name
WHERE t1.ticketId IS NOT NULL
AND t2.id = @inputId;
GO

A: I could achieve it with single query.
create procedure sp_proc
@inputId int
As
Select t1.ticketId AS ticket,
t2.name AS NAME,
t3.status AS STATUS,
t2.id ID,
t4Description.[desc]
from table1 t1
Inner JOIN table2 t2 ON  t1.ticketId= t2.ticketId
INNER JOIN table3 t3 on t3.name = t2.name
OUTER APPLY (
              SELECT TOP 1 [desc]
              FROM table4 t4
              WHERE t4.ticketId = t1.ticketId
              ORDER BY t4.[date] DESC

        ) t4Description

WHERE
     t1.ticketId IS NOT NULL
     AND t2.id = @inputId


text:
Q: Ionic 3 native plugin of sms not working on my device I am using Ionic 3 and my device is 4.4.2 android.
Setup:
ionic cordova plugin add cordova-sms-plugin
npm install --save @ionic-native/sms@4

I have add to app.module
import { SMS } from '@ionic-native/sms';
providers: [..., SMS]
home.ts
...
import { SMS } from '@ionic-native/sms';

...
constructor(..., private sms: SMS){}

sendSMS(){
this.sms.send('0030699999999', 'sos')
}

home.html
<button ion-button block (click)="sendSMS()" margin-top color="dark">SMS</button>

I install the apk to my phone with below command:
ionic cordova run android

When I am pressing the button, my app breaks and exit, without sending a message.
I tried to remove platform android and added again, but nothing.

A: Allow from app settings on your phone

A: I had to put a send_sms permission in manifest file (android).
Check in my phone v 4.4.2.
I didn't check it in iPhone.


text:
Q: How to push a data in array in angularJS I am trying to post a data and it will return a list. But that list can't push into an array.
I tried below code:
var a=data.Data;
$scope.cont.push(a);
angular.forEach($scope.cont, function(todo) {
    $scope.datalist.push(todo);
});

But can not find the solution


text:
Q: How do I make a triangle of stars and counts the number of stars? I wrote the program to print a triangle of stars and also, the sum of the stars forms the triangle. When I make the call tringle(3), it should print as the following,
***
**
*

And, also it should count the sum as 6 and returns it. However, the code is not working as expected that I have provided following,
public static int triangular(int n) {
    int count = 0;
    count =  triangular(n, count);
    return count;
}

public static int triangular(int n, int count_){
    int count = count_;
    if(n == 0)
        return count;
if(n < 0)
    return -1;

for (int i = 0; i < n; i++) {
    System.out.print("* ");
    count = count + 1 ;
    if(i == n){
        return triangular(n-1, count);
    }
}
System.out.println();
return count;
 }

How do i improve the code ? Now, it prints
* * *
3

Please, advise.

A: You don't need more than one parameter... 3 + 2 + 1 + 0 = 6.
public static int triangular(int n){
    if(n <= 0) return 0;

    for (int i = 0; i < n; i++) {
        System.out.print("* ");
    }
    System.out.println();

    return n + triangular(n - 1);
}

A: Here's an iterative approach. Also, the number of stars can be calculated with the formula n(n+1)/2:
public static int triangular(int n) {
    for (int i = 0; i < n; i++) {
        for (int j = i; j < n; j++) {
            System.out.print("*");
        }
        System.out.println();
    }
    return n * (n + 1) / 2;
}

triangular(4):
****
***
**
*
10

A: It has an issue with the for loop and I changed the code.  It works fine now and here it is:
public static int triangular(int n) {

        int count = 0;
        count =  triangular(n, count);

        return count;
    }

    public static int triangular(int n, int count_){

        int count = count_;

        if(n == 0)
            return count;

        if(n < 0)
            return -1;

        for (int i = 0; i < n; ) {

            System.out.print("* ");

            count = count + 1 ;
            i++;

            if(i == n){

                System.out.println();

                return triangular(n-1, count);
            }
        }
        return count;
    }


text:
Q: How to improve performance of MySQL dump restore Many of us who are working on their home or pet projects and who use databases for storing structured data may encounter performance issues when trying to dump/restore data. It can annoying just to sit and wait for another dump restore operation for dozens of minutes or even for hours.
I have quite typical machine specs - 4 core i5 7300, 8 Gb RAM, quite fast M2 drive and Windows 10/MySQL 5.7.
The problem was that trying to restore ~4.5Gb file it took more than 4 hours. That was ridiculous and I wondered if mysqld process isn't using even a half of system resources - CPU/Memory/Disk I/O
Generally speaking, this post relates to some kind of summary of related issues including credits to many other posts which I put below

A: I performed a number of experiments with MySQL parameters for better dump restore operations
+--------------------------------+---------+---------+-----------------------+---------------------+
|           Parameter            | Default | Changed | Performance (minutes) | Perfomance gain (%) |
+--------------------------------+---------+---------+-----------------------+---------------------+
| All default                    | -       | -       | 259 min               | -                   |
| innodb_buffer_pool_size        | 8M      | 4G      | 32 min                | +709%               |
| innodb_buffer_pool_size        | 4G      | 6G      | 32 min                | ~0%                 |
| innodb_log_file_size           | 48M     | 1G      | 11 min                | +190%               |
| innodb_log_file_size           | 1G      | 2G      | 10 min                | +10%                |
| max_allowed_packet             | 4M      | 128M    | 10 min                | ~0%                 |
| innodb_flush_log_at_trx_commit | 1       | 0       | 9 min 25 sec          | +5%                 |
| innodb_thread_concurrency      | 9       | 0       | 9 min 27 sec          | ~0%                 |
| innodb_double_write            | -       | off     | 8 min 5 sec           | +18%                |
+--------------------------------+---------+---------+-----------------------+---------------------+

Summary (for best dump restore performance):

*

*Set innodb_buffer_pool_size to half of RAM

*Set innodb_log_file_size to 1G

*Set innodb_flush_log_at_trx_commit to 0

*Disabling innodb_double_write recommended only for fastest performance, it should be enabled on production. I also found, that changing another related parameter innodb_flush_method didn't change performance. But this can be an issue of Windows platform.

*If you have complex structure with a lot of foreign keys for example, you can try Bulk Data Loading for InnoDB Tables tricks, link is listed at bottom of page

*As you can see, I tried to increase CPU utilization by setting innodb_thread_concurrency to 0 (and also setting innodb_read_io_threads to maximum of 64) but results didn't change - it seems that mysqld process is already quite efficient for multi-core environment.

*Restoring only data (without table structure) also didn't affect performance

I also changed a number of other parameters, but those above are most relevant ones for dump restore operation so far.
It may seem obvious, but novice question can be - where I can find and set those settings?
In Windows, my.ini file is located at ProgramData/MySQL/MySQL Server <version>/my.ini. You won't find some settings there (like innodb_double_write) - it's ok, just add to the end of the file.
The best way to change settings is to use MySQL Workbench (Server > Options file > InnoDB).
I pay my credits to following posts (and a lot of similar ones), which I found very useful:
https://www.percona.com/blog/2018/02/22/restore-mysql-logical-backup-maximum-speed/
https://www.percona.com/blog/2014/01/28/10-mysql-performance-tuning-settings-after-installation/
https://dev.mysql.com/doc/refman/5.5/en/optimizing-innodb-bulk-data-loading.html
https://dba.stackexchange.com/questions/86636/when-is-it-safe-to-disable-innodb-doublewrite-buffering
https://dev.mysql.com/doc/refman/5.7/en/innodb-parameters.html


text:
Q: Postgrex how to define json library I'm just trying to use Postgrex without any kind of ecto setup, so just the example from the documentation readme.
Here is what my module looks like:
defmodule Receive do

  def start(_type, _args) do
    {:ok, pid} = Postgrex.start_link(
      hostname: "localhost",
      username: "john",
      # password: "",
      database: "property_actions",
      extensions: [{Postgrex.Extensions.JSON}]
    )
    Postgrex.query!(
      pid,
      "INSERT INTO actions (search_terms) VALUES ($1)",
      [
        %{foo: 'bar'}
      ]
    )

  end
end

when I run the code I get
** (RuntimeError) type `json` can not be handled by the types module Postgrex.DefaultTypes, it must define a `:json` library in its options to support JSON types

Is there something I'm not setting up correctly? From what I've gathered in the documentation, I shouldn't even need to have that extensions line because json is handled by default.

A: On Postgrex <= 0.13, you need to define your own types:
Postgrex.Types.define(MyApp.PostgrexTypes, [], json: Poison)

and then when starting Postgrex:
Postgrex.start_link(types: MyApp.PostgrexTypes)

On Postgrex >= 0.14 (currently master), it was made easier:
config :postgrex, :json_library, Poison


text:
Q: Reset Border style I have a image that is currently being styled with Jquery once it's clicked. I eventually hide it in Javascript. I want to reshow it, but I want it to have the border removed.
Here is HTML:

Choose your move to beat the computer!

Jquery:
$(function () {
    $("img").on("click",function() {
        $(this).siblings().css('border','0px')
        $(this).css('border', "solid 2px red");
    });
});

Here is what I was trying in Javascript:
function autobet() {
    coinBalance -= currentBet*2;
    alert(getBalance());
    document.getElementsByTagName("IMG").style.border="";
}

However when it reshows the div it has the border on it still.
Thanks for the help!

A: Your issue is that document.getElementsByTagName("IMG") returns a collection of elements, so simply applying .style.border on this collection won't work. Instead, you need to loop over this collection, and set every image within it to have no border using .style.border = 0;:
See working example (with div) below:

function removeBorder() {
  [...document.getElementsByTagName("div")].forEach(elem => {
    elem.style.border = 0;
  });
}
.box {
  height: 100px;
  width: 100px;
  background: black;
  display: inline-block;
}

.active {
  border: 3px solid red;
}

<button onclick="removeBorder()">Remove border</button>

Also note that [...document.getElementsByTagName("IMG")] is a way of converting the collection of elements into an array of elements, which thus allows us to use the .forEach method to loop over it.

A: You started with jQuery, let's continue with jQuery.
function autobet() {
    coinBalance -= currentBet*2;
    alert(getBalance());
    $("img").css("border","");
}

The problem is that getElementsByTagName() returns a collection not one element.

A: First you need to iterate over the collection of html elements you have - when using getElementsByTagName you get back an array of elements.
Second you need to give the elements a style of zero.
const divElements = document.getElementsByTagName("IMG");
for (let i=0; i < divElements.length; i++) {
  divElements[i].style.border = 0;
}

You can see the code on stackbliz -
https://stackblitz.com/edit/border-issue?file=index.js


text:
Q: Return image in header So I have this code, which im trying to return an existing picture. Though it won't display.
Chrome says server closed the connection unexpectedly, firefox says there's an error in the immage.
This is the code ;
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
            byte[] img = enc.GetBytes(response);
            Response.AddHeader("Transfer-Encoding", "Chunked");
            Response.AddHeader("Connection", "Keep-Alive");
            Response.AddHeader("Keep-Alive", "timeout=1, max=64");
            Response.BinaryWrite(img);

var content = fileStorage.readFile(src); // this is the file. Which is return in response

// edit I can't post image.

A: Have a look at HttpResponse.WriteFile. Using it probably solves it.

A: Your code is a little confused with the relationship between the response and content variables.
What is the purpose of the TransferEncoding header? Taking this out makes it work with using a simple:
var content = System.IO.File.ReadAllBytes("C:\\path\\image.gif")

and passing this in the BinaryWrite works.


text:
Q: Springboot 2.3 with Docker. I want to build image for a specific app when I have multiple springboot applications in same repository Building a springboot application version 2.3. I want to build a docker image with the cloud native build packs. I have 2 springboot applications sitting inside my repository, say App A and App B. Usually, I do mvn install, pick up the jars and start them individually. Run jar "a" for aapp a and jar "b" for app b. Now,  How do I tell the build pack on which jar I want to build my docker image on.

A: Building on a stack of other answers, you can use the advanced reactor options to target a single module in the reactor and build the image just for that module.
A command like
mvn -pl <module-name> -am spring-boot:build-image

will likely give you what you're looking for.

A: Whichever platform you're using, you should be able to point the build toward your relevant subdirectory. For instance, if you're using pack, you can use pack build -p <repo dir>/<app A dir>. Depending on which Java buildpack you're using, it should run Maven for you and set up the resulting JAR to launch when the app image is started.


text:
Q: VBA Combobox 28 error when selecting item from the list I am trying to write a specific search (that will separate search results for cities and countries) with the use of Excel's ComboBox object.
When I am using keyboard buttons, then everything is fine and search works perfectly.
However, when I try to select an item from the drop-down list with the use of mouse button, then I am getting 28-error "Out of stack space".
The debugger is looping for an unknown reason and finally stops at
Set destination_short_rng = w_search.Range("Destination_short")

line of  ComboBoxDestinations_Change subroutine provided below.
I would be very grateful for any hint on how to prevent this error from happening.
Private destination_search_rng As Range
Private destination_short_rng As Range
Private destination_search_col As New Collection

Private Sub ComboBoxDestinations_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)

    Set w_search = Sheets("4c.Travel Costs (Search)")

    Set destination_short_rng = w_search.Range("Destination_short")

    IsArrowTopDown = (KeyCode = vbKeyUp) Or (KeyCode = vbKeyDown) Or (KeyCode = vbKeyLButton)
    If KeyCode = vbKeyEscape Then UserFormSearchDest.ComboBoxDestinations.list = destination_short_rng.Value

End Sub

Private Sub InitializeDestinationSearchCollection()
    Dim num_rows As Integer
    Dim i As Integer
    num_rows = destination_short_rng.Rows.Count
    Set destination_search_col = Nothing
    For i = 1 To num_rows
        destination_search_col.Add LCase(destination_search_rng.Rows(i).Value)
    Next i
End Sub

Private Function SplitText(Text As String, separator As String) As Variant
    Dim my_array() As String
    Dim i As Integer

    my_array = Split(Text, separator)
    For i = LBound(my_array, 1) To UBound(my_array, 1)
        my_array(i) = LTrim(my_array(i))
    Next i
    SplitText = my_array
End Function

Private Function FoundDestination(destinations As Variant, entered_txt As String) As Boolean
    Dim entered_txt_len As Integer
    Dim i As Integer
    entered_txt_len = Len(entered_txt)

    FoundDestination = False

    For i = LBound(destinations, 1) To UBound(destinations, 1)
        If left(destinations(i), entered_txt_len) = entered_txt Then
            FoundDestination = True
            Exit For
        End If
    Next i
End Function

Private Function LeftDestination(searched_dest As String, entered_txt As String) As Variant
    Dim my_array(1 To 2) As Boolean
    Dim destinations() As String
    Dim cities() As String
    Dim countries() As String
    destinations = SplitText(searched_dest, ",")
    cities = SplitText(destinations(0), "/")
    countries = SplitText(destinations(1), "/")
    my_array(1) = FoundDestination(cities, entered_txt)
    my_array(2) = FoundDestination(countries, entered_txt)
    LeftDestination = my_array
End Function

Private Sub printCollection(txt As String, col As Collection, list As Variant)
    Dim i As Integer

    Debug.Print "Entered txt:", txt
    For i = 1 To Application.WorksheetFunction.Min(5, col.Count)
        Debug.Print "List item:", list(i - 1, 0)
        Debug.Print "Collection item:", col.Item(i)
    Next i
End Sub

Private Sub ComboBoxDestinations_Change()

    Dim i As Integer

    Dim txt As String
    Dim entered_txt_len As Integer
    Dim entered_txt As String
    Dim searched_dest As String
    Dim left_cities As Boolean
    Dim left_countries As Boolean

    Set w_search = Sheets("4c.Travel Costs (Search)")

    Set destination_short_rng = w_search.Range("Destination_short")

    InitializeDestinationSearchCollection

    If Not IsArrowTopDown Then
        With UserFormSearchDest.ComboBoxDestinations
            .list = destination_short_rng.Value
            entered_txt = LCase(.Text)
            If Len(entered_txt) > 0 Then

                For i = .ListCount - 1 To 0 Step -1
                    searched_dest = destination_search_col.Item(i + 1)

                    left_cities = LeftDestination(searched_dest, entered_txt)(1)
                    left_countries = LeftDestination(searched_dest, entered_txt)(2)

                    If Not (left_cities) And Not (left_countries) Then
                        .RemoveItem i
                        destination_search_col.Remove (i + 1)
                    End If
                Next i

                Dim last_left_ind As Integer
                Dim is_last_ind_found As Boolean
                is_last_ind_found = False
                For i = .ListCount - 1 To 0 Step -1

                    searched_dest = destination_search_col.Item(i + 1)

                    left_cities = LeftDestination(searched_dest, entered_txt)(1)
                    left_countries = LeftDestination(searched_dest, entered_txt)(2)

                    If left_cities And Not (is_last_ind_found) Then
                        is_last_ind_found = True
                        last_left_ind = i
                    End If

                    If left_countries And Not (left_cities) And is_last_ind_found Then
                        .AddItem pvargItem:=.list(i), pvargIndex:=last_left_ind + 1
                        .RemoveItem i
                        destination_search_col.Add Item:=searched_dest, After:=last_left_ind + 1
                        destination_search_col.Remove (i + 1)
                        last_left_ind = last_left_ind - 1
                    End If
                Next i

                If .ListCount = 0 Then
                    .AddItem "No Results"
                End If
                .DropDown
                .ListRows = Application.WorksheetFunction.Min(ListRowsMax, .ListCount)
            End If
        End With
    End If
End Sub

A: Finally, I managed to deal with the problem by putting the IsMouseDown and IsEsc variables.
Private Sub ComboBoxDestinations_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
    IsMouseDown = (Button = vbKeyLButton) Or (Button = vbKeyRButton) Or (Button = vbKeyMButton)
End Sub
Private Sub ComboBoxDestinations_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    Set w_search = Sheets("4c.Travel Costs (Search)")

    Set destination_short_rng = w_search.Range("Destination_short")
    IsMouseDown = False
    IsArrowTopDown = (KeyCode = vbKeyUp) Or (KeyCode = vbKeyDown)
    IsEsc = KeyCode = vbKeyEscape
    If IsEsc Then
        UserFormSearchDest.ComboBoxDestinations.Clear
        UserFormSearchDest.ComboBoxDestinations.list = destination_short_rng.Value
    End If
End Sub

and in the ComboBoxDestinations_Change subroutine I wrote the following logic:
If Not IsArrowTopDown And Not IsMouseDown And Not IsEsc Then
Private Sub ComboBoxDestinations_Change()
    On Error GoTo Err
    Dim i As Integer

    Dim txt As String
    Dim entered_txt_len As Integer
    Dim entered_txt As String
    Dim searched_dest As String
    Dim left_cities As Boolean
    Dim left_countries As Boolean

    Set w_search = Sheets("4c.Travel Costs (Search)")

    Set destination_short_rng = w_search.Range("Destination_short")

    InitializeDestinationSearchCollection

    If Not IsArrowTopDown And Not IsMouseDown And Not IsEsc Then
        With UserFormSearchDest.ComboBoxDestinations

However, in rare cases (e.g. when the user enters additional text and clicks backspace) the inifinite loop may happen. This is why, I wrote On Error GoTo Err statement so that the event is stopped in this case.
All in all the search is working now.

A: So as already written in the comments, you problem is that the change event routine is triggering itself recursively.
On a user form, there is no built-in mechanism to prevent this, but it's rather easy to do this by your own:
Declare a Variable (I prefer static variables as they stay local, but you can declare it also as global) and check and set it so that the routine is left immediately if it is called recursively.
Private Sub ComboBoxDestinations_Change()
    Static changeRunning As Boolean
    If changeRunning Then Exit Sub

    ... do your magic here...
    changeRunning  = False
End Sub


text:
Q: Given a list of strings, find the shortest unique substring of each string that doesn't occur in the other strings The problem statement is:

Given a list of strings, find the shortest unique substring of each string such that the substring does not occur in any of the other strings.

For example:
Input: ["cheapair", "cheapoair", "peloton", "pelican"]
Output:
"cheapair": "pa"  // every other 1-2 length substring overlaps with cheapoair
"cheapoair": "po" // "oa" would also be acceptable
"pelican": "ca"   // "li", "ic", or "an" would also be acceptable
"peloton": "t"    // this single letter doesn't occur in any other string

I think this is solved with dynamic programming, but honestly, I have no idea how to do this other than brute force: Storing all substrings for each word and checking that they don't exist in any of the other ones, which is a terrible idea.

A: Building all substrings to find those that appear in two (or more) strings. Then for each string, print a shortest substring that doesn't appear in two (or more). Maybe not the best (depends on your data and what you consider "best"), but works and is simple.
strings = ["cheapair", "cheapoair", "peloton", "pelican"]

def substrings(s):
    n = len(s)
    return {s[i:i+k]
            for k in range(1, n+1)
            for i in range(n-k+1)}

one = set()
two = set()
for s in strings:
    subs = substrings(s)
    two |= one & subs
    one |= subs

for s in strings:
    subs = substrings(s)
    uniq = subs - two
    print(s, min(uniq, key=len))

Output (Try it online!):
cheapair pa
cheapoair oa
peloton t
pelican an

Preliminary benchmark with a modified version that proceeds by length like Nick's does. Take this with some bags of salt: 1) The question has unclear issues (I asked under the question now). 2) The solutions yield all valid substrings instead of just one. 3) I modified Nick's a little to make it work here (nothing that should influence its speed). 4) It's a worst case input, where each string needs the maximum length, i.e., has no unique substring other than itself.
0.19 s  Kelly2
1.34 s  Nick
0.19 s  Kelly2
1.35 s  Nick
0.19 s  Kelly2
1.34 s  Nick