text:
Q: How can I send email from PostgreSQL trigger? I using pgsql to set a trigger, when update the table dataset(change the status to Finished)
it will automatic send a email to the email account using dataset email value and save this email in server
but i don't know how to write in trigger function to send email, and send email in server.
Thank you in advance
Pg version is 9.1, and CentOS 5.8
CREATE OR REPLACE FUNCTION sss()
RETURNS trigger AS
$BODY$begin
if(NEW.publisher== 'aaaa')
then
//send email and save to server 192.168.171.64
end if;
return NEW;
end

$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION sss()
OWNER TO postgres;
GRANT EXECUTE ON FUNCTION sss() TO postgres;

A: *

*Use a local MTA (this gives you centralized SMTP config for multiple apps)

*Have the local MTA relay to your real MTA (this gives you async support, essentially)

*If windows, use blat SMTP command line client. Make sure the path to blat is in the PATH

*You should probably do this using Apache Camel or pgAgent, and not directly in a trigger

This will work on Windows if postgres superuser. Trigger function should be SECURITY DEFINER. Similar for sendmail on Linux:
...

copy
  ( select 'my email body' )
to program
  'blat -to to@example.com -from from@example.com -subject "My Subject" -server localhost:25'
with (
  format text
);

...

~ 60 ms

A: See the excellent-as-usual depesz article, and pg-message-queue.
Sending email directly from the database may not be a great idea. What if DNS resolution is slow and everything hangs for 30 seconds then times out? What if your mail server is having a wobbly and takes 5 minutes to accept messages? You'll get database sessions hung up in your trigger until you're at max_connections and suddenly you can't do anything but wait or start manually cancelling transactions.
What I'd recommend is having your trigger NOTIFY a LISTENing helper script that remains permanently running and connected to the DB (but not in a transaction).
All your trigger has to do is INSERT a row into a queue table and send a NOTIFY. Your script gets the NOTIFY message because it has registered to LISTEN for it, examines the queue table, and does the rest.
You can write the helper program in whatever language is convenient; I usually use Python with psycopg2.
That script can send the email based on information it finds in the database. You don't have to do all the ugly text formatting in PL/PgSQL, you can substitute things into a template in a more powerful scripting language instead, and just fetch the variable data from the database when a NOTIFY comes in.
With this approach your helper can send each message and only then remove the info from the queue table. That way if there are transient problems with your mail system that causes sending to fail, you haven't lost the info and can continue to attempt to send it until you succeed.
If you really must do this in the database, see PgMail.

A: You can use plperlu to send mail.
This link shows an example of how to use it on a trigger.

A: You have the possibility to use pgMail (if you are allowed to install it):
If you follow the instructions on brandolabs.com it comes down to
pgmail('Send From ','Send To ','Subject goes here','Message body here.')

A: I agree with @Craig Ringer. You could code something in Python under 100 lines of code. I would recommend using the following Python libraries: psycopg2, smtplib. Depending on how often you would like to get notified of the changes, you could run a cronjob (depending on your working environment). That way you can aggregate multiple changes to the database into a single email rather than sending a notification every time a change takes place.

A: If you use TypeScript/Node, then use the battle-tested graphile-worker codebase to communicate from Postgres to Node. Then you can easily use your standard email logic in Node to send a email.


text:
Q: Power management failure and /usr/bin/sudo must be owned by uid 0 and have the setuid bit set A few days age I purchased a new laptop, Asus X751MD, and I installed the 64 bit Kubuntu version of 14.10. After installing some programs and restarting the computer, I got the power management failure, stating that I have to reinstall the system, which I did two times and got the same problem every time.
Also I am unable to use sudo and I get this message:
sudo: /usr/bin/sudo must be owned by uid 0 and have the setuid bit set

This laptop uses the Nvidia Geforce 610m hybrid graphics and I suspect this has something to do with the graphics, even though I installed bumblebee.
I really have no plan on installing the same system with the same results, so please help me if you can. I really don't want to return to using Windows, but if there is no other solution, I will be forced to.
Thank you in advance.
Mount results:
/dev/sda2 on / type ext4 (rw,errors=remount-ro)
proc on /proc type proc (rw,nodev,noexec,nosuid)
sysfs on /sys type sysfs (rw,nodev,noexec,nosuid)
none on /sys/fs/cgroup type tmpfs (rw,uid=0,gid=0,mode=0755,size=1024)
none on /sys/fs/fuse/connections type fusectl (rw)
none on /sys/kernel/debug type debugfs (rw)
none on /sys/kernel/security type securityfs (rw)
udev on /dev type devtmpfs (rw,mode=0755)
devpts on /dev/pts type devpts (rw,noexec,nosuid,gid=5,mode=0620)
tmpfs on /run type tmpfs (rw,noexec,nosuid,size=10%,mode=0755)
none on /run/lock type tmpfs (rw,nodev,noexec,nosuid,size=5242880)
none on /run/shm type tmpfs (rw,nosuid,nodev)
none on /run/user type tmpfs (rw,nodev,noexec,nosuid,size=104857600,mode=0755)
none on /sys/fs/pstore type pstore (rw)
/dev/sda7 on /usr type ext4 (rw)
/dev/sda8 on /usr/local type ext4 (rw)
/dev/sda6 on /home type ext4 (rw)

I reinstalled it from the DVD burned version of Kubuntu 64bit ISO. I reformatted the entire system and created new partitions.

A: The problem is that you have changed permissions of files in /usr/bin. Some of these files need setuid bit (the file is run under the account of the file's owner which is root in /usr/bin) to work properly but by setting write bit to anyone else than the owner, this would create a massive security hole (anyone could change the content and run it as root), therefore setting the write bit removes the setuid bit.
Unless you have btrfs with APT snapshotting, it is quite hard to determine what were the original permissions of the files in /usr/bin, you would basically need to reinstall all packages and it still may not set everything correctly. Therefore the easiest solution here is to reinstall the system as a whole.
If you do have btrfs with APT snapshotting (should be automatically enabled if you use btrfs for your system) and /usr or /usr/bin is not on a separate partition, it is possible to revert to an older snapshot where this change was not done yet. This can be done with the command apt-btrfs-snapshot in rescue mode (selected in GRUB):
# List all available snapshots
apt-btrfs-snapshot list

# Revert to a selected snapshot
apt-btrfs-snapshot set-default @apt-snapshot-YYYY-MM-DD_HH:mm:ss

# Reboot to load the old system
reboot

redpajama_set_name: RedPajamaStackExchange


text:
Q: JavaFX stop Label overlapping parent? in JavaFX I am trying to stop the Label from overlapping the parent. This happens when the parent is resized to a size that is lower then the label. In this circumstance I would expect the Label to start to be hidden, but it just shows over the parent's bounds a little bit.
You may use the following FXML to test this out:
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.Font?>

<AnchorPane minHeight="500.0" minWidth="500.0" prefHeight="500.0" prefWidth="558.0" style="-fx-background-color: black;" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8.0.65">
  <children>
      <AnchorPane layoutX="110.0" layoutY="102.0" prefHeight="200.0" prefWidth="200.0" style="-fx-background-color: red;" AnchorPane.bottomAnchor="15.0" AnchorPane.leftAnchor="15.0" AnchorPane.rightAnchor="15.0" AnchorPane.topAnchor="15.0">
         <children>

         </children>
      </AnchorPane>
   </children>
</AnchorPane>

Note that adding a bottom Anchor to the Label will fix this issue, but I would like to not use that. Is there any work around or fix for this? Thanks.

A: Can offer some crutch. Add to label MinHeight and MaxHeight and add to pane heightProperty listener.
Main.fxml:
<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.Font?>

<AnchorPane minHeight="500.0" minWidth="500.0" prefHeight="500.0" prefWidth="558.0" style="-fx-background-color: black;" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.Controller">
    <children>
        <AnchorPane fx:id="pane" layoutX="16.0" layoutY="15.0" style="-fx-background-color: red;" AnchorPane.bottomAnchor="15.0" AnchorPane.leftAnchor="15.0" AnchorPane.rightAnchor="15.0" AnchorPane.topAnchor="15.0">
            <children>

            </children>
        </AnchorPane>
    </children>
</AnchorPane>

Controller.java:
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;

public class Controller {

    @FXML
    Label label;
    @FXML
    AnchorPane pane;

    @FXML
    private void initialize() {

        pane.heightProperty().addListener((observableValue, oldSceneHeight, newSceneHeight) -> {
            double top_margin = 5;
            double bottom_margin = 5;
            double bound_value = label.getMaxHeight() + top_margin + bottom_margin;
            if (newSceneHeight.doubleValue() < bound_value) {
                if ((newSceneHeight.doubleValue() - top_margin - bottom_margin) >= 0) {
                    label.setPrefHeight(newSceneHeight.doubleValue() - top_margin - bottom_margin);
                }
            } else {
                label.setPrefHeight(label.getMaxHeight());
            }
        });
    }

}


text:
Q: Is it possible to bring to javascript the .net RBTree and its TreePage I've seen the .NET RbTree work and I like it, much so that I've tried to bring it to Javascript. Then I realized it uses structs array (something very hard to emulate due to javascript's functionalities doesn't allow it, at least natively). Then I saw TreePage class which allows allocate slots maps for each tree page, all of this performed by bitwise shifts to achieve indexation (RBTree.PageTable[index>>16].Slots[index&0xFFFF]) and I know if is the same performance of .net. It's the only indexable-tree I've ever seen (the far I know and I could understand).
Now my question: Is it possible to bring that tree to Javascript> (I've seen some examples but no one has indexation method). I hope to be understood, to get some answers and as I always say: Thanks in advance.
PD: Sorry for my english. :)


text:
Q: IntelliJ Tomcat Server plugin fails to auto-populate my empty external Tomcat `base` folder When I point the Tomcat and TomEE Integration plugin in IntelliJ Ultimate 2017.2 via menu item Run > Edit Configurations to a fresh download of Tomcat 8.5.16, my Vaadin 8.1 app runs successfully. Good.

But when I optionally point the configuration's Server > Application Server > Configure button > Tomcat base directory to an empty folder, I get a message:

Cant find directory 'Users/basilbourque/apache-tomcat-base-dev/conf'

➠ Must I create this conf folder?
In contrast to IntelliJ, when I point NetBeans IDE to an empty folder when running Tomcat externally, it automatically populates the empty folder with the entire hierarchy of folders and files needed to run the app.
So, okay, I create a conf folder in my otherwise empty folder. This satisfies the Edit Configurations panel. Next, I run my app by running this configuration.
Notice how Unnamed_ is prepended to my application name (timepiece), I get this message in a floating dark-red box within the IntelliJ IDE window:

Error running 'Tomcat 8.5.16'
Cannot load /Users/basilbourque/Library/Caches/IntelliJIdea2017.2/Unnamed_timepiece/conf/server.xml: /Users/basilbourque/Library/Caches/IntelliJIdea2017.2/tomcat/Unnamed_timepiece/conf/server.xml (No such file or directory) (5 minutes ago)

➠ Must I create a server.xml?
Such a requirement confuses me given that as I said above, NetBeans simply populates the external Tomcat "base" empty folder as needed entirely and automatically.
I am also curious why the message repeats the same path with a colon in the middle, though that is a minor issue.

A: This directory is used to have the configuration that is different from the default Tomcat conf in the root of the server installation.

*

*Copy TOMCAT_HOME/conf into CATALINA_BASE/conf.

*Select this new CATALINA_BASE in the IntelliJ Run > Edit Configurations dialog.

This way you can have the same physical installation of the server, but run multiple server instances with different configurations. IntelliJ IDEA expects the pre-configured CATALINA_BASE from you, it will not populate it automatically.


text:
Q: HttpLoggingInterceptor not logging with retrofit 2 Im trying to log all the requests (with a network interceptor) using refrofit2, kotlin and logging-interceptor:

*

*retrofit: "2.0.2"

*okhttp3 : "3.2.0"

*com.squareup.okhttp3:logging-interceptor 3.2.0

like:
val interceptor = HttpLoggingInterceptor()
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

    val okHttpClient = OkHttpClient.Builder()
        .addNetworkInterceptor(interceptor) // same for .addInterceptor(...)
        .connectTimeout(30, TimeUnit.SECONDS) //Backend is really slow
        .writeTimeout(30, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS)
        .build()

    sRestAdapter = Retrofit.Builder()
        .client(okHttpClient)
        .baseUrl(if (host.endsWith("/")) host else "$host/")
        .addConverterFactory(GsonConverterFactory.create(gson()))
        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
        .build()

It just print:
D/OkHttp: --> GET url...
D/OkHttp: --> END GET

What is happening?
--------------- EDIT --------
Errors doing requests on Main Thread are not showing by the logger, so be careful.

A: private val interceptor = run {
    val httpLoggingInterceptor = HttpLoggingInterceptor()
    httpLoggingInterceptor.apply {
        httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
    }
}

private val okHttpClient = OkHttpClient.Builder()
    .addNetworkInterceptor(interceptor) // same for .addInterceptor(...)
    .connectTimeout(30, TimeUnit.SECONDS) //Backend is really slow
    .writeTimeout(30, TimeUnit.SECONDS)
    .readTimeout(30, TimeUnit.SECONDS)
    .build()

A: Instead of
val okHttpClient = OkHttpClient.Builder()
    .addNetworkInterceptor(interceptor)
    ...

you should have something like:
val okHttpClient = OkHttpClient.Builder()
    .addInterceptor(interceptor)
    ...

as the addNetworkInterceptor() plays with interceptors that observe a single network request and response, while addInterceptor() adds interceptor that observes the full span of each call: from the connection is established (if any) until after the response source is selected (either the origin server, cache, or both).
EDIT

Errors doing requests on Main Thread are not showing by the logger, so be careful

Doing networking on main thread is not an "ordinary" error. It will result in your app being killed by the system with NetworkOnMainThreadException and this will happen before interceptor would be given any chance to run.


text:
Q: Flutter Text Field: How to add Icon inside the border
I would like to add the icon in the search bar. Here is my code so far:
new TextField(
     decoration: new InputDecoration(
     icon: new Icon(Icons.search)
     labelText: "Describe Your Issue...",
     enabledBorder: const OutlineInputBorder(
     borderRadius: BorderRadius.all(Radius.circular(20.0)),
     borderSide: const BorderSide(
       color: Colors.grey,
      ),
    ),
    focusedBorder: OutlineInputBorder(
      borderRadius: BorderRadius.all(Radius.circular(10.0)),
      borderSide: BorderSide(color: Colors.blue),
    ),
   ),
  ),

This is the result of the code above (this is not what i want):

A: use prefixicon
return TextFormField(
  decoration: InputDecoration(
    hintText: hint,
    labelText: label,
    prefixIcon: Icon(Icons.person),
    contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 10.0),
  ),
);

A: TextField(
      decoration: InputDecoration(
        filled: true,
        fillColor: Color(0xFFFFFFFF),
        prefixIcon: Icon(Icons.search, color: Colors.pink),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.all(
            Radius.circular(30),
          ),
        ),
        hintText: ' Search',
      ),
    ),

A: You can use the InputDecoration argument prefixIcon, or suffixIcon.
prefixIcon will show before the text inside your TextField.
TextField(
  decoration: InputDecoration(
    prefixIcon: Icon(Icons.done),
  ),
);

prefixIcon showcase
OR
suffixIcon will show after the text inside your TextField.
TextField(
  decoration: InputDecoration(
    suffixIcon: Icon(Icons.done),
  ),
);

suffixIcon showcase
ATTN: Code above does not include the border styling that is shown on the screenshots :)

A: You can try this:
Container(
  decoration: BoxDecoration(
    border: Border.all(
      color: Colors.grey.withOpacity(0.5),
      width: 1.0,
    ),
    borderRadius: BorderRadius.circular(4.0),
  ),
  margin: EdgeInsets.all(12),
  child: Row(
    children: <Widget>[
      Padding(
        padding: EdgeInsets.only(left: 8),
        child: Icon(
          Icons.search,
          color: Colors.grey,
          size: 20,
        ),
      ),
      new Expanded(
        child: TextField(
          keyboardType: TextInputType.text,
          decoration: InputDecoration(
            border: InputBorder.none,
            hintText: "Search by Name",
            hintStyle: TextStyle(color: Colors.grey),
            contentPadding:
                EdgeInsets.symmetric(vertical: 8, horizontal: 8),
            isDense: true,
          ),
          style: TextStyle(
            fontSize: 14.0,
            color: Colors.black,
          ),
        ),
      )
    ],
  ),
)

It will be displayed as:

A: Use the prefixIcon in Just adjust in Boarder Radius
import 'package:flutter/material.dart';

class TextFieldShow extends StatelessWidget {
  TextEditingController _controller = TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: new Text("Tab demo"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: TextField(
            style: TextStyle(
              fontSize: 25.0,
              color: Colors.blueAccent,
            ),
            decoration: InputDecoration(
                contentPadding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
                prefixIcon: Icon(Icons.people),
                hintText: "Enter Your Name",
                border: OutlineInputBorder(
                    borderSide: BorderSide(color: Colors.blueAccent, width: 32.0),
                    borderRadius: BorderRadius.circular(25.0)),
                focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: Colors.white, width: 32.0),
                    borderRadius: BorderRadius.circular(25.0)))),
      ),
    );
  }
}

A: If you need to ad an icon in the Textfield use the arguments prefixIcon and suffixIcon inside it, like
TextField(
  decoration: InputDecoration(
    prefixIcon: Icon(Icons.mail),
    suffixIcon: Icon(Icons.search),
  ),
);

A: Edited Answer
Updating answer as my original answer doesn't actually cover the original context of the question.
You can use the prefixIcon in the TextField or in the TextFormField to get some widget as a leading in your TextField.
Example
    TextField(
//    ...,other fields
      decoration: InputDecoration(
        prefixIcon: prefixIcon??Icon(Icons.done),
      ),
    ),

PS: Do not get confuse between prefixIcon and prefix as this two
  are different things.
  https://api.flutter.dev/flutter/material/InputDecoration/prefix.html

Also if you want to achieve something like floating app bar then you can refer to my original answer.
Original answer
You can use my Flutter package to implement Floating AppBar in your application.
You need to add below package in your pub.
rounded_floating_app_bar: ^0.1.0
run $ flutter packages get from the command line.
Now in your Dart code, you can use:
import 'package:rounded_floating_app_bar/rounded_floating_app_bar.dart';
...
NestedScrollView(
  headerSliverBuilder: (context, isInnerBoxScroll) {
    return [
      RoundedFloatingAppBar(
        floating: true,
        snap: true,
        title: TextField(
          decoration: InputDecoration(
            prefixIcon: Icon(Icons.search),
            border: InputBorder.none,
          ),
        ),
      ),
    ];
  },
  body: Container(),
),

Output:

A: Try this way (using prefixIcon), just adjust the border radius
TextField(
          style: TextStyle(fontSize: 25.0),
          decoration: InputDecoration(
            contentPadding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
            prefixIcon: Icon(Icons.search),
            hintText: "Describe your issue",
            border: OutlineInputBorder(
                    borderSide: BorderSide(color: Colors.red[300], width: 32.0),
                    borderRadius: BorderRadius.circular(25.0)
              ),
            focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: Colors.red[300], width: 32.0),
                    borderRadius: BorderRadius.circular(25.0)))

Hope this help.


text:
Q: Comparar resultado consulta SQL Laravel con Int estoy programando en Laravel 5.5 y necesito comparar una consulta con un entero para realizar una verificación. El código es el siguiente:
$sum_=DB::table('eventos_tienen_trabajadores as ett')
   ->where('ett.id_trabajador', '=', $id)
   ->where('ett.estado', '=', '1')
   ->select(DB::raw('sum(monto) as sum'))
   ->get();

   if($sum_ == 0){...

Desde luego que no es posible compararlo por lo que quisiera saber como puedo hacer esto de una manera eficiente.

A: Debe tener en cuenta que al realizar un select ->select(DB::raw('sum(monto) as sum')) le retornará una colección. por lo cuál no podrá acceder hacer la validación  if($sum_ == 0) , sí solo participará una sola tabla podría realizar de una forma más legible utilizando aggregates y retorne un valor directamente.
$sum= DB::table('eventos_tienen_trabajadores ')
        ->where('id_trabajador', '=', $id)
        ->where('estado', '=', '1')
        ->sum('monto');

if($sum==0) { ... }

Como recomendación, debe tener cuidado al utilizar raw-expressions
  porque puede dejar una puerta abierta para ataques de Inyección SQL


text:
Q: oracle sql monthly sum of values I have a table that records random daily production data two oil fields:
field           Date              Production
fld1         02/01/2013              100
fld2         02/05/2013               50
fld1         02/03/2013               70
fld2         02/06/2013               30
...
fld1         11/31/2014               80
fld2         11/29/2014               70

I want to write a sql to generate a report of monthly production for each field:
fld1         02/2013            xxxx
fld1         03/2013            xxxx
....
fld2         02/2013            xxxx
fld2         03/2013            xxxx

Can it be done in a single sql? I am relatively new to Oracle analytics.

A: Try this:
select field, to_char(prod_date,'MM/YYYY') mon, sum(production) total_prod
from data
group by field,  to_char(prod_date,'MM/YYYY')
order by field, to_char(prod_date,'MM/YYYY')

Here is the SqlFiddle


text:
Q: A numerical coincidence with continued fractions My brother built a garage that measures 45 feet by 30 feet.  To make sure the right angles were accurate, he measured the two diagonals of the rectangle to see that they were equal.  In  inches,
\begin{align}
& \sqrt{540^2+360^2} \approx 648.999229548\text{ inches} \\[6pt]
= {} & 54\text{ feet}+1\text{ inch} - \text{less than $0.001$ inches}.
\end{align}
It's a bit odd to come within a thousandth of an inch when rounding to the nearest inch, but there's more:
$$
\sqrt{540^2+360^2} = 649 - \cfrac{1}{1298+\cfrac{1}{24073+\cdots}}.
$$
One part in twenty-four thousand??
Did I just happen to be there when someone rolled boxcars two dozen times in a row, or is there more to be said?
(Maybe I should add that $540^2+360^2 = 649^2-1$.)
PS:
$$
\sqrt{540^2+360^2} = 648 + \cfrac{1}{1+\cfrac{1}{1297+\cfrac{1}{25700+\cdots}}} \\
\text{(This part is mistaken; see below.)}
$$
Later edit: A calculator gave me the results above repeatedly; later another calculator disagreed, just as persistently, and I figured out what the truth is.

A: Since $540^2+360^2+1^2=649^2$, we have $\sqrt{540^2+360^2} = \sqrt{649^2-1}$, and notice that since $2\cdot649=1298$, we get that
$$-649+\sqrt{649^2-1}=\frac{-1298+\sqrt{1298^2-4}}{2}\tag{1}$$
is a solution to
$$
x^2+1298x+1=0.
$$
Rearrange the quadratic equation:
$$
x = \frac{-1}{1298+x}
$$
and then substituting the expression on the right for $x$ within that very expression gives us
$$
x=\cfrac{-1}{1298-\cfrac{1}{1298-\cfrac{1}{1298-\cfrac{1}{1298-\cdots\cdots\cdots}}}}
$$
and from $(1)$ we have
$$
\sqrt{649^2-1} = 649+x.
$$
That's ONE WAY OF LOOKING AT IT, and at one level it explains it and at another it doesn't.  But it proves that this expansion is right.

A: More generally, consider $\sqrt{n^2 - 1}$. The square root of $(n^2 - 1)$ should be just slightly less than the square root of $n^2$ (which is $n$), so letting $x = n - \sqrt{n^2 - 1}$, we have $(n-x)^2 = n^2 - 1$ and therefore $2nx - x^2 = 1$, or the distance from the square root to the integer $n$ is
$$x = \dfrac{1}{2n - x}
= \cfrac{1}{2n - \cfrac{1}{2n - x}}
= \cfrac{1}{2n - \cfrac{1}{2n - \cfrac{1}{2n - \cfrac{1}{\dots}}}}
$$
Anyway we don't have to go that far; just the fact that $x = \frac{1}{2n + x} \le \frac{1}{2n-1}$ suffices to show that $x$ must be really small. To come within a thousandth of an inch when rounding to the nearest inch isn't surprising considering this.
Similar to continued fractions, we can also use the binomial theorem:
$$\begin{align}
\sqrt{n^2 - 1}
&= n\sqrt{1 - 1/n^2} = n(1 - 1/n^2)^{1/2} \\
&= n\left(1 - \frac{1}{2n^2} - \frac{1}{8n^4} - \frac{1}{16n^6} - \frac{5}{128n^8} - \dots \right)
\end{align}$$
and so
$$x = n - \sqrt{n^2 - 1} = \frac{1}{2n} + \frac{1}{8n^3} + O\left(\frac{1}{n^6}\right)$$
to see that $x$, the offset from an integer, is itself very close to $\frac{1}{2n}$, which is probably related to what the first calculator (incorrectly) gave in the first case.


text:
Q: org.apache.camel.RuntimeCamelException: com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions I am trying to build a quarkus service using JSON input and Camel routes. I am using beans to capture the JSON data and convert it into Java objects for further processing. For the sake of testing, i am trying to return the input which my quarkus service receives via HTTP client back to the calling program. As soon i try to process a HTTP request, i am getting an error.
Below is the JSON input my quarkus service recieves:
{
  "requestHeader": {
    "inputTransactionId": "ABC",
    "partnerId": "1",
    "partnerName": "ABC",
    "integrationID": "123",
    "integrationName": "TESTING",
    "applicationID": "TEST",
    "applicationName": "SOMETHING",
    "metadata":[{
        "A":"1",
        "B":"2"
    }]
     },
  "city": "",
  "state": "AC",
  "zipcode": "64035"
}

Below is the ZipCodeRequest Bean definition
import io.swagger.v3.oas.annotations.media.Schema;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import com.fasterxml.jackson.annotation.JsonCreator;

public class USZipcodeRequest   {

  @Schema(description = "")
  private RequestHeader requestHeader = null;

  @Schema(description = "The city name")
  private String city = "";

  @Schema(description = "State name or two-letter abbreviation")
  private String state = "";

  @Schema(description = "The ZIP Code. See the paragraphs below this table for a few relevant details.")
  private String zipcode = "";

  @JsonProperty("requestHeader")
  public RequestHeader getRequestHeader() {
    return requestHeader;
  }

  public void setRequestHeader(RequestHeader requestHeader) {
    this.requestHeader = requestHeader;
  }

  public USZipcodeRequest requestHeader(RequestHeader requestHeader) {
    this.requestHeader = requestHeader;
    return this;
  }

 @JsonProperty("city")
  public String getCity() {
    return city;
  }

  public void setCity(String city) {
    this.city = city;
  }

  public USZipcodeRequest city(String city) {
    this.city = city;
    return this;
  }

 @JsonProperty("state")
  public String getState() {
    return state;
  }

  public void setState(String state) {
    this.state = state;
  }

  public USZipcodeRequest state(String state) {
    this.state = state;
    return this;
  }

   @JsonProperty("zipcode")
  public String getZipcode() {
    return zipcode;
  }

  public void setZipcode(String zipcode) {
    this.zipcode = zipcode;
  }

  public USZipcodeRequest zipcode(String zipcode) {
    this.zipcode = zipcode;
    return this;
  }
}

Below is the RequestHeader bean definition (Request Header from the input) which is causing the error
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import javax.enterprise.context.ApplicationScoped;

import com.fasterxml.jackson.annotation.JsonProperty;

import io.quarkus.runtime.annotations.IgnoreProperty;
import io.swagger.v3.oas.annotations.media.Schema;

@ApplicationScoped

@Schema(description="base header fields for all requests")
public class RequestHeader   {

  @Schema(required = true, description = "An identifier passed into the API call to identify the transaction within the calling application; this field will be returned with the output.")

  private String inputTransactionId = null;

  @Schema(required = true, description = "Trading parter Id as in the intgration registry.")

  private String partnerId = null;

  @Schema(required = true, description = "Trading parter name as in the intgration registry.")

  private String partnerName = null;

  @Schema(required = true, description = "Integration Id as in the intgration registry.")

  private String integrationID = null;

  @Schema(required = true, description = "Integration name as in the intgration registry.")

  private String integrationName = null;

  @Schema(required = true, description = "Application Id as in the intgration registry.")

  private String applicationID = null;

  @Schema(required = true, description = "Application Id as in the intgration registry.")

  private String applicationName = null;

  @Schema(description = "Contains addtion flex metadata.")

  //private List<Metadata> metadata = null;
  private List<Map<String, String>> metadata = new ArrayList<Map<String, String>>();

  @JsonProperty("inputTransactionId")
  public String getInputTransactionId() {
    return inputTransactionId;
  }

  public void setInputTransactionId(String inputTransactionId) {
    this.inputTransactionId = inputTransactionId;
  }

  public RequestHeader inputTransactionId(String inputTransactionId) {
    this.inputTransactionId = inputTransactionId;
    return this;
  }

  @JsonProperty("partnerId")
  public String getPartnerId() {
    return partnerId;
  }

  public void setPartnerId(String partnerId) {
    this.partnerId = partnerId;
  }

  public RequestHeader partnerId(String partnerId) {
    this.partnerId = partnerId;
    return this;
  }

   @JsonProperty("partnerName")
  public String getPartnerName() {
    return partnerName;
  }

  public void setPartnerName(String partnerName) {
    this.partnerName = partnerName;
  }

  public RequestHeader partnerName(String partnerName) {
    this.partnerName = partnerName;
    return this;
  }

  @JsonProperty("integrationID")
  public String getIntegrationID() {
    return integrationID;
  }

  public void setIntegrationID(String integrationID) {
    this.integrationID = integrationID;
  }

  public RequestHeader integrationID(String integrationID) {
    this.integrationID = integrationID;
    return this;
  }

  @JsonProperty("integrationName")
  public String getIntegrationName() {
    return integrationName;
  }

  public void setIntegrationName(String integrationName) {
    this.integrationName = integrationName;
  }

  public RequestHeader integrationName(String integrationName) {
    this.integrationName = integrationName;
    return this;
  }

  @JsonProperty("applicationID")
  public String getApplicationID() {
    return applicationID;
  }

  public void setApplicationID(String applicationID) {
    this.applicationID = applicationID;
  }

  public RequestHeader applicationID(String applicationID) {
    this.applicationID = applicationID;
    return this;
  }

  @JsonProperty("applicationName")
  public String getApplicationName() {
    return applicationName;
  }

  public void setApplicationName(String applicationName) {
    this.applicationName = applicationName;
  }

  public RequestHeader applicationName(String applicationName) {
    this.applicationName = applicationName;
    return this;
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class RequestHeader {\n");

    sb.append("    inputTransactionId: ").append(toIndentedString(inputTransactionId)).append("\n");
    sb.append("    partnerId: ").append(toIndentedString(partnerId)).append("\n");
    sb.append("    partnerName: ").append(toIndentedString(partnerName)).append("\n");
    sb.append("    integrationID: ").append(toIndentedString(integrationID)).append("\n");
    sb.append("    integrationName: ").append(toIndentedString(integrationName)).append("\n");
    sb.append("    applicationID: ").append(toIndentedString(applicationID)).append("\n");
    sb.append("    applicationName: ").append(toIndentedString(applicationName)).append("\n");
 //   sb.append("    metadata: ").append(toIndentedString(metadata)).append("\n");
    sb.append("}");
    return sb.toString();
  }

 public List<Map<String, String>> getMetadata() {
  return metadata;
}

public void setMetadata(List<Map<String, String>> metadata) {
  this.metadata = metadata;
}
}

Whenever i try to compile my code, i get the below error :
Failed to start application (with profile dev): com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
java.util.Map is an interface, and JAXB can't handle interfaces.
        this problem is related to the following location:
                at java.util.Map
                at public java.util.List com.company.beans.asv.RequestHeader.getMetadata()
                at com.company.beans.asv.RequestHeader
                at public com.company.beans.asv.RequestHeader com.company.beans.asv.USZipcodeRequest.getRequestHeader()
                at com.company.beans.asv.USZipcodeRequest

        at com.sun.xml.bind.v2.runtime.IllegalAnnotationsException$Builder.check(IllegalAnnotationsException.java:76)
        at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getTypeInfoSet(JAXBContextImpl.java:441)
        at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:273)
        at com.sun.xml.bind.v2.runtime.JAXBContextImpl.<init>(JAXBContextImpl.java:109)
        at com.sun.xml.bind.v2.runtime.JAXBContextImpl$JAXBContextBuilder.build(JAXBContextImpl.java:1126)
        at com.sun.xml.bind.v2.ContextFactory.createContext(ContextFactory.java:135)
        at com.sun.xml.bind.v2.JAXBContextFactory.createContext(JAXBContextFactory.java:35)
        at javax.xml.bind.ContextFinder.find(ContextFinder.java:393)
        at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:691)
        at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:632)
        at org.apache.camel.converter.jaxb.JaxbDataFormat.createContext(JaxbDataFormat.java:548)
        at org.apache.camel.converter.jaxb.JaxbDataFormat.doStart(JaxbDataFormat.java:516)
        at org.apache.camel.support.service.BaseService.start(BaseService.java:119)
        at org.apache.camel.support.service.ServiceHelper.startService(ServiceHelper.java:113)
        at org.apache.camel.impl.engine.AbstractCamelContext.internalAddService(AbstractCamelContext.java:1568)
        at org.apache.camel.impl.engine.AbstractCamelContext.addService(AbstractCamelContext.java:1489)
        at org.apache.camel.support.processor.MarshalProcessor.doStart(MarshalProcessor.java:122)
        at org.apache.camel.support.service.BaseService.start(BaseService.java:119)
        at org.apache.camel.support.service.ServiceHelper.startService(ServiceHelper.java:113)
        at org.apache.camel.impl.engine.DeferServiceStartupListener.doStart(DeferServiceStartupListener.java:63)
        at org.apache.camel.impl.engine.DeferServiceStartupListener.onCamelContextStarted(DeferServiceStartupListener.java:54)
        at org.apache.camel.impl.engine.InternalRouteStartupManager.safelyStartRouteServices(InternalRouteStartupManager.java:196)
        at org.apache.camel.impl.engine.InternalRouteStartupManager.doStartOrResumeRoutes(InternalRouteStartupManager.java:147)
        at org.apache.camel.impl.engine.AbstractCamelContext.doStartCamel(AbstractCamelContext.java:3344)
        at org.apache.camel.impl.engine.AbstractCamelContext.doStartContext(AbstractCamelContext.java:3023)
        at org.apache.camel.impl.engine.AbstractCamelContext.doStart(AbstractCamelContext.java:2978)
        at org.apache.camel.support.service.BaseService.start(BaseService.java:119)
        at org.apache.camel.impl.engine.AbstractCamelContext.start(AbstractCamelContext.java:2639)
        at org.apache.camel.impl.DefaultCamelContext.start(DefaultCamelContext.java:255)
        at org.apache.camel.quarkus.main.CamelMain.doStart(CamelMain.java:94)
        at org.apache.camel.support.service.BaseService.start(BaseService.java:119)
        at org.apache.camel.quarkus.main.CamelMain.startEngine(CamelMain.java:140)
        at org.apache.camel.quarkus.main.CamelMainRuntime.start(CamelMainRuntime.java:49)
        at org.apache.camel.quarkus.core.CamelBootstrapRecorder.start(CamelBootstrapRecorder.java:45)
        at io.quarkus.deployment.steps.CamelBootstrapProcessor$boot173480958.deploy_0(Unknown Source)
        at io.quarkus.deployment.steps.CamelBootstrapProcessor$boot173480958.deploy(Unknown Source)
        at io.quarkus.runner.ApplicationImpl.doStart(Unknown Source)
        at io.quarkus.runtime.Application.start(Application.java:101)
        at io.quarkus.runtime.ApplicationLifecycleManager.run(ApplicationLifecycleManager.java:103)
        at io.quarkus.runtime.Quarkus.run(Quarkus.java:67)
        at io.quarkus.runtime.Quarkus.run(Quarkus.java:41)
        at io.quarkus.runtime.Quarkus.run(Quarkus.java:120)
        at io.quarkus.runner.GeneratedMain.main(Unknown Source)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at io.quarkus.runner.bootstrap.StartupActionImpl$1.run(StartupActionImpl.java:103)
        at java.base/java.lang.Thread.run(Thread.java:829)

2022-06-19 13:04:49,241 INFO  [io.qua.dep.dev.IsolatedDevModeMain] (main) Attempting to start live reload endpoint to recover from previous Quarkus startup failure
2022-06-19 13:09:40,358 INFO  [io.qua.dep.dev.RuntimeUpdatesProcessor] (Timer-0) Restarting quarkus due to changes in AddressValidationRoute.class.
2022-06-19 13:09:40,358 INFO  [io.qua.dep.dev.RuntimeUpdatesProcessor] (Timer-0) Restarting quarkus due to changes in AddressValidationRoute.class.
__  ____  __  _____   ___  __ ____  ______
 --/ __ \/ / / / _ | / _ \/ //_/ / / / __/
 -/ /_/ / /_/ / __ |/ , _/ ,< / /_/ /\ \
--\___\_\____/_/ |_/_/|_/_/|_|\____/___/
2022-06-19 13:09:41,282 INFO  [org.apa.cam.qua.cor.CamelBootstrapRecorder] (Quarkus Main Thread) Bootstrap runtime: org.apache.camel.quarkus.main.CamelMainRuntime

2022-06-19 13:09:41,285 INFO  [org.apa.cam.mai.MainSupport] (Quarkus Main Thread) Apache Camel (Main) 3.16.0 is starting
2022-06-19 13:09:41,360 ERROR [org.apa.cam.qua.mai.CamelMainRuntime] (Quarkus Main Thread) Failed to start application: org.apache.camel.FailedToCreateRouteException: Failed to create route us-zip-code-route at: >>> From[direct:us-zip-code] <<< in route: Route(us-zip-code-route)[From[direct:us-zip-code] -> []] because of Route us-zip-code-route has no output processors. You need to add outputs to the route such as to("log:foo").
        at org.apache.camel.reifier.RouteReifier.doCreateRoute(RouteReifier.java:222)
        at org.apache.camel.reifier.RouteReifier.createRoute(RouteReifier.java:74)
        at org.apache.camel.impl.DefaultModelReifierFactory.createRoute(DefaultModelReifierFactory.java:49)
        at org.apache.camel.impl.DefaultCamelContext.startRouteDefinitions(DefaultCamelContext.java:887)
        at org.apache.camel.impl.DefaultCamelContext.startRouteDefinitions(DefaultCamelContext.java:775)
        at org.apache.camel.impl.engine.AbstractCamelContext.doInit(AbstractCamelContext.java:2937)
        at org.apache.camel.quarkus.core.FastCamelContext.doInit(FastCamelContext.java:172)
        at org.apache.camel.support.service.BaseService.init(BaseService.java:83)
        at org.apache.camel.impl.engine.AbstractCamelContext.init(AbstractCamelContext.java:2620)
        at org.apache.camel.support.service.BaseService.start(BaseService.java:111)
        at org.apache.camel.impl.engine.AbstractCamelContext.start(AbstractCamelContext.java:2639)
        at org.apache.camel.impl.DefaultCamelContext.start(DefaultCamelContext.java:255)
        at org.apache.camel.quarkus.main.CamelMain.doStart(CamelMain.java:94)
        at org.apache.camel.support.service.BaseService.start(BaseService.java:119)
        at org.apache.camel.quarkus.main.CamelMain.startEngine(CamelMain.java:140)
        at org.apache.camel.quarkus.main.CamelMainRuntime.start(CamelMainRuntime.java:49)
        at org.apache.camel.quarkus.core.CamelBootstrapRecorder.start(CamelBootstrapRecorder.java:45)
        at io.quarkus.deployment.steps.CamelBootstrapProcessor$boot173480958.deploy_0(Unknown Source)
        at io.quarkus.deployment.steps.CamelBootstrapProcessor$boot173480958.deploy(Unknown Source)
        at io.quarkus.runner.ApplicationImpl.doStart(Unknown Source)
        at io.quarkus.runtime.Application.start(Application.java:101)
        at io.quarkus.runtime.ApplicationLifecycleManager.run(ApplicationLifecycleManager.java:103)
        at io.quarkus.runtime.Quarkus.run(Quarkus.java:67)
        at io.quarkus.runtime.Quarkus.run(Quarkus.java:41)
        at io.quarkus.runtime.Quarkus.run(Quarkus.java:120)
        at io.quarkus.runner.GeneratedMain.main(Unknown Source)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at io.quarkus.runner.bootstrap.StartupActionImpl$1.run(StartupActionImpl.java:103)
        at java.base/java.lang.Thread.run(Thread.java:829)
Caused by: java.lang.IllegalArgumentException: Route us-zip-code-route has no output processors. You need to add outputs to the route such as to("log:foo").
        at org.apache.camel.reifier.RouteReifier.doCreateRoute(RouteReifier.java:220)


text:
Q: On the equality of two generating functions related to plane partitions I'd like to prove
$$\prod_{(i,j,k)\in\mathcal{B}(r,s,t)}\frac{1-q^{i+j+k-1}}{1-q^{i+j+k-2}}=\prod_{i=1}^r\prod_{j=1}^s\frac{1-q^{i+j+t-1}}{1-q^{i+j-1}},$$
where
$$\mathcal{B}(r,s,t)=\{(i,j,k):1\leq i\leq r,1\leq j\leq s,1\leq k\leq t\}.$$
I'm guessing that we could find a bijection between products of terms from the left-hand side and terms from the right-hand side, but how I am not sure how. Of course there might be something easy/obvious that I am missing. Any help or general hints on how to approach problems like this would be appreciated!

A: The left hand side is the same as
$$\prod_{i=1}^r\prod_{j=1}^s\prod_{k=1}^t\frac{1-q^{i+j+k-1}}{1-q^{i+j+k-2}}$$
Now just consider
$$\prod_{k=1}^t\frac{1-q^{i+j+k-1}}{1-q^{i+j+k-2}}=\frac{1-q^{i+j+t-1}}{1-q^{i+j+1-2}}$$
because a lot of the factors cancel each other out.


text:
Q: how to sync cookies android in webview and chrome i have search for this but not found answer in stackoverflow untill now.
My project is create android webview app show mobile version of website.
i know there are no way website can detect the app installed on device or not while running in chrome browser for security.
So I change the useragent of the android app with addtional App's name .. then every time user use the app, website will detect web is running in webview then write cookes " Appname" in device.
from there if user using chrome to browse website will find that cookie, if not found web will show some link help user install the app.
The problems is sysn cookies between my app and chrome look like not work.
following is my activity.java
Thanks for any help !
public class XaLuanActivity extends Activity{
    private static final String tag=XaLuanActivity.class.getCanonicalName();
    private static final int CHIASE_MENU=1;
    private static final int THOAT_MENU=2;
    private static final int TAILAI_MENU=3;
    private static final int TROGIUP_MENU=4;
    private static final int DANHGIA_MENU=5;

    private String mainUrl="http://www.xaluan.com/m.php";
    ProgressBar mProgressBar;
    WebView wbvContent;
    @SuppressWarnings("deprecation")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        CookieSyncManager.createInstance(this);
        CookieSyncManager.getInstance().startSync();
        CookieManager.getInstance().setAcceptCookie(true);
        setContentView(R.layout.xaluan);
        wbvContent=(WebView) findViewById(R.id.wbvContent);
        //wbvContent.setBackgroundColor(Color.parseColor("#FFFFFF"));
        mProgressBar=(ProgressBar)findViewById(R.id.progressBar);
        wbvContent.getSettings().setJavaScriptEnabled(true);
        wbvContent.setInitialScale(1);
        wbvContent.getSettings().setLoadWithOverviewMode(true);
        wbvContent.getSettings().setUseWideViewPort(true);
        wbvContent.getSettings().setSupportZoom(true);
        wbvContent.getSettings().setBuiltInZoomControls(true);

        wbvContent.setDownloadListener(new DownloadListener() {
            public void onDownloadStart(String url, String userAgent,
                    String contentDisposition, String mimetype,
                    long contentLength) {
              Intent i = new Intent(Intent.ACTION_VIEW);
              i.setData(Uri.parse(url));
              startActivity(i);
            }
        });
        wbvContent.getSettings().setUserAgentString(
                wbvContent.getSettings().getUserAgentString()
                + " "
                + getString(R.string.user_agent_suffix)
        );   // detect useragent and add XLAndroidApp suffix name to the end

        HelloWebViewClient wbvClient=new HelloWebViewClient();
        wbvContent.setWebViewClient(wbvClient);

        if(!isConnectedNetwork(this)) {
            new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_dialog_alert)
            .setTitle("Thông báo")
            .setMessage("Không có kết nối mạng, vui lòng kết nối mạng để sử dụng")
            .setPositiveButton("Thử lại", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    XaLuanActivity.this.finish();
                    startActivity(new Intent(XaLuanActivity.this, XaLuanActivity.class));
                }
            })
            .setNegativeButton("Thoát", new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    XaLuanActivity.this.finish();
                }
            })
            .show();
        }else {
             wbvContent.loadUrl(mainUrl);
             wbvContent.setWebChromeClient(new WebChromeClient() {
                 public void onProgressChanged(WebView view, int progress)  {
                    if(progress < 100 && mProgressBar.getVisibility() == ProgressBar.GONE){
                       mProgressBar.setVisibility(ProgressBar.VISIBLE);
                    }
                    mProgressBar.setProgress(progress);
                    if(progress == 100) {
                       mProgressBar.setVisibility(ProgressBar.GONE);
                    }
                 }
             });
        }
        isFirstTime();
    }
    public void isFirstTime() {// check if the first time
        try{
            SharedPreferences mPreference=PreferenceManager.getDefaultSharedPreferences(this);
             boolean firstTime=mPreference.getBoolean("firstTime", true);
             if(firstTime) {
                ShortcutIconResource icon = Intent.ShortcutIconResource.fromContext(this, R.drawable.ic_launcher);
                Intent intent = new Intent();
                Intent launchIntent = new Intent(this, XaLuanActivity.class);

                intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launchIntent);
                intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launchIntent);
                intent.putExtra("android.intent.extra.shortcut.NAME", "Xã Luận");
                intent.putExtra("android.intent.extra.shortcut.ICON_RESOURCE", icon); //can also be ignored too
                intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
                sendBroadcast(intent);
                SharedPreferences.Editor edit=mPreference.edit();
                edit.putBoolean("firstTime", false);
                edit.commit();
             }
        }catch (Exception e) {
            Log.e(tag+".isFirstTime", e.toString());
        }
    }

    private static class HelloWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            if (url != null && (url.startsWith("market://")  || url.indexOf("play.google.com/store/apps/details")!=-1) ) {
                view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                //return true;
            }
            else if(url.endsWith(".apk") || url.indexOf("adsxaluan.apk.vn/download/")!=-1 )
            {
                view.getContext().startActivity( new Intent(Intent.ACTION_VIEW).setData(Uri.parse(url)) );
            }
            else {
                view.loadUrl(url);
                //return false;
            }
            return true;
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, CHIASE_MENU, 0, "Chia Sẻ").setIcon(R.drawable.share);
        menu.add(0, TAILAI_MENU, 0, "Tải Lại").setIcon(R.drawable.refresh);
        menu.add(0, DANHGIA_MENU, 0, "Đánh Giá").setIcon(R.drawable.rate);
        menu.add(0, TROGIUP_MENU, 0, "Trợ Giúp").setIcon(R.drawable.about);
        menu.add(0, THOAT_MENU, 0, "Thoát").setIcon(R.drawable.exit);
        return super.onCreateOptionsMenu(menu);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case CHIASE_MENU: // chia se
            Intent sharingIntent = new Intent(Intent.ACTION_SEND);
            sharingIntent.setType("text/plain");
            sharingIntent.putExtra(Intent.EXTRA_SUBJECT, wbvContent.getTitle());
            sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, wbvContent.getUrl());
            startActivity(Intent.createChooser(sharingIntent,"Chia sẻ"));
            break;
        case THOAT_MENU: // chia se
            System.exit(0);
            break;
        case TAILAI_MENU: // chia se
            wbvContent.reload();
            break;
        case TROGIUP_MENU: // chia se
            Intent intent1=new Intent(this, About.class);
            startActivity(intent1);
            break;
        case DANHGIA_MENU:
            String url="market://details?id="+getApplicationContext().getPackageName();
            Intent intent2 = new Intent(Intent.ACTION_VIEW,Uri.parse(url));
            startActivity(intent2);
            break;
        default:
            break;
        }
        return super.onOptionsItemSelected(item);
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(wbvContent.canGoBack()) {
                wbvContent.goBack();
                return false;
            }else {
                new AlertDialog.Builder(this)
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setTitle("Thoát")
                .setMessage("Bạn có muốn thoát khỏi ứng dụng không")
                .setPositiveButton("Có", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        XaLuanActivity.this.finish();
                    }
                })
                .setNegativeButton("Không", null)
                .show();
            }
        }
        return super.onKeyDown(keyCode, event);
    }
    public static boolean isConnectedNetwork(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null;
    }
}

A: Sorry, but what you want to do is not possible. The cookie jar for your app and Chrome are completely separate and inaccessible to each other for security and privacy reasons.


text:
Q: Not getting reputation gains I am not getting reputation gain for the last couple answer I posted, though it has two upvotes.  I am nowhere near any rep caps.  This particular question is listed as a community wiki but I didn't make it such and if it is, it shouldn't be. What gives?
https://stackoverflow.com/a/21998720/1085699

A: The answer seems to have been marked CW at the moment it was created (judging from the timestamps of both events).
This was probably done by mistake.
I have removed the CW from the answer, so any votes coming in from now on will be credited to you.
When posting new answer or editing one of your existing answers, beware the checkbox:


text:
Q: Perfomance issue with canvas in Firefox I need to do some animated transformations with images using canvas.
Simple demonstration is in my fiddle, it's just a canvas, filled with pattern and rotated using requestAnimationFrame.
It works perfect in Chrome, but in Firefox it slows down, for what seems a rather simple task. It has 6-8 fps in FF instead of 50-60 in Chrome.
Firefox 38.0.5, Mac OS X 10.10
Demonstration: http://jsfiddle.net/jyoggnjr/
context.fillStyle = context.createPattern(image, 'repeat');
update = function() {
  var date, offsetRotation;
  date = new Date();
  offsetRotation = ((Math.round(date / 10)) % 1000) / 1000 * (Math.PI * 2) - Math.PI;
  context.save();
  context.translate(radius, radius);
  context.beginPath();
  context.arc(0, 0, radius * 2, Math.PI, -Math.PI);
  context.closePath();
  context.rotate(offsetRotation);
  context.fill();
  context.restore();
  requestAnimationFrame(update);
}

Any help is appreciated.


text:
Q: How to get Visual Studio Output Window content via EnvDTE (Non Package) I'm writing an out of process console program that automate Visual Studio (2012).
i need to get the content of the output pane either read it at once or preferably register to a notification on each line added to the output window.
I've seen some examples that only apply when writing a package, but they won't apply when doing so for an out of process program.
the big problem at the moment is that i can't get the output window service via GetService of a Service Provider. it always returns null.
I'm not sure i can get it if i'm not writing a package.

A: This seems to work for me
public string GetOutput()
{
    const string buildOutputPaneGuid = "{1BD8A850-02D1-11D1-BEE7-00A0C913D1F8}";
    const string vsWindowKindOutput = "{34E76E81-EE4A-11D0-AE2E-00A0C90FFFC3}";
    var outputWindow = dte.Windows.Item(/*EnvDTE.Constants.*/vsWindowKindOutput);
    var outputWindowDynamic = outputWindow.Object;

    foreach(OutputWindowPane pane in outputWindowDynamic.OutputWindowPanes)
    {
        if (pane.Guid == buildOutputPaneGuid)
        {
            try
            {
                pane.Activate();
                var sel = pane.TextDocument.Selection;
                sel.StartOfDocument(false);
                sel.EndOfDocument(true);
                return sel.Text;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
    }

    return null;
}


text:
Q: How can I stretch a div within a table within a div to the remainder of the page's height? Having been working on a website that uses a single page layout with buttons that actively alter the content in a single div, I have become stuck on how to fix one formatting issue that I have. Namely, I would like to be able to stretch the content in div id="CTR1" in the bottom most table to the bottom of the page, leaving only space for the footer, thus sticking it to the bottom as well. I have approached this problem with various tricks such as Ryan Fait's sticky footer, but all to no avail. I have commented the code such that it is easier to read.
"How can I stretch the div "CTR1" to the bottom of the page leaving space only for the 25px footer?"
I am working with some code that I have laid out in the following format:
Original Code at: jsfiddle


text: Q: Forge viewer properties won't reflect the updated info I just realized that sometimes Forge viewer OOTB Properties button won't reflect the updated info, any clue why it happens and how to fix it? thanks


text:
Q: \refstepcounter does not print the counter So I am trying to automate a counter using new counter and \refstepcounter. However I would like to print the number of the counter and the code below does not seem to word. Any idea why?
\newcounter{taskcounter}
\stepcounter{taskcounter}
\refstepcounter{taskcounter}

A: In order to display the value of a counter <X> within your document, use \the<X>. For you specific example,
\thetaskcounter

This defaults to \arabic{<x>}, but can be changed.
\refstepcounter has nothing to do with the representation of the counter; it steps the counter (like \stepcounter) but also updates the components needed for referencing (via \label-\ref).
Related reference: The \the command


text:
Q: R get the means for all columns in a data frame while ignoring zeroes I have a dataframe with columns of simulation data.
I want the means of each column.
The issue is some columns have a bunch of zeroes on the bottom and these need to be ignored.
I can ignore the zeroes and look at one column with
mean(which(df$colname >0))

But I want a vector of every column's mean, gotten with sapply.
Is there a clean way to ignore the zeroes and get these values within a sapply function?
Or do I have to write a custom function and call that in the sapply?

A: You can use :
sapply(df, function(x) mean(x[x != 0], na.rm = TRUE))

Or using dplyr :
library(dplyr)
df %>% summarise_all(~mean(.[. != 0], na.rm = TRUE))

A better/efficient approach would be to set all 0 values to NA and use colMeans
df[df == 0] <- NA
colMeans(df, na.rm = TRUE)

A: We can use an one-liner in base R
colMeans(replace(df, !df, NA), na.rm = TRUE)

Or with dplyr
library(dplyr)
df %>%
   summarise(across(everything(), ~ mean(na_if(., 0), na.rm = TRUE))


text:
Q: Last array element in a row and first element in the next row having the same pointer I was working on a college assignment that required me to get a mathematical equation related to array pointers, I wrote the following code to display the pointers of all elements:

It was all smooth until I decided to convert the addresses to decimal to make my calculations easier, I used the following line of code:
size_t D = reinterpret_cast<size_t>(&X);

Once I did, somehow the last element in a row and first element in the next row returned the same address:

Even after I removed that line and restored my code to it's previous state, the specified elements still return the same address. I thought it might be a weird Visual Studio behavior and I tried restarting it, but the issue wasn't fixed. I'm wondering how this happened and how it can be fixed, it doesn't make sense.

A: The size of your array was changed to Arr[5][4].  It won't return an error or warning as, they are all valid pointers to the 'one past the end' element of an array.


text:
Q: Unique unital $R$-algebra homomorphism $\varphi: R[x] \to A$ where $\varphi(x) = \alpha$ holds.
In general, if $A$ is a unital algebra over a commutative unital ring $R$ and $\alpha\in A$ is an element, then there is a unique unital $R$-algebra homomorphism $\varphi : R[x] \to A$ such that $\varphi(x) = \alpha$ holds.

Why is this true?

A: Define the map $\varphi : R[x] \to A$ via $\varphi (x) = \alpha$. We want this map to be an $R$-algebra homomorphism, so we have to force the following conditions on $\varphi$: $\varphi(x \cdot x) = \varphi(x) \cdot \varphi(x)$ and $\varphi(r x) = r \varphi(x)$.
Incidentally, this already defines $\varphi$ for each element of $R[x]$, as each element in $R[x]$ is a linear combination of monomials in $x$ with coefficients in $R$. This is just a restatement of the fact that $R[x]$ is generated by $x$ as an $R$-algebra. Since it has only $1$ generator, we (can) only have to specify $1$ element as the rest is defined via the unitality of the homomorphism, and the homomorphism attribute $\varphi(r x) = r \varphi(x)$.
But once the image of $x$ is specified, the homomorphism is uniquely determined, as discussed above.


text:
Q: Snap pour points not recognizing sample sites as valid points when using ArcPy? I am trying to go from a CSV of sample sites and a DEM to creating watersheds. I can process the DEM fine to stream networks and can import the points (first to event layer, then convert them to a feature class. The problem arises when I try to snap pour points (my sample sites) on to my flow accumulation raster to create the watersheds, the same error of "Sample_Sites do not exist" keeps popping up even though I can go to ArcMap and open them.
Any ideas on how to get around this problem?


text:
Q: WPF - exe is crashing on close Our WPF application is crashing on closing it (using cross button) with below error details. Is this related to any unmanaged code not being handled properly?
We are using .Net 4.0 framework and Windows 7 machine to install and run it.
The business class of the solution is having one web service reference to external .asmx path. Not sure if this can be an issue. I also checked the custom log trace file and application event log, but nothing is found there.
Problem signature:
  Problem Event Name:   APPCRASH
  Application Name: MoneyDesk.exe
  Application Version:  1.0.12.16
  Application Timestamp: 57023aab
  Fault Module Name:    KERNELBASE.dll
  Fault Module Version: 6.1.7601.19135
  Fault Module Timestamp:   56a1c9ac
  Exception Code:   c0020001
  Exception Offset: 000000000000965d
  OS Version:   6.1.7601.2.1.0.256.48
  Locale ID:    2057
  Additional Information 1: 97cc
  Additional Information 2: 97cc899a944cd5ead2ae7642164506a1
  Additional Information 3: 2288
  Additional Information 4: 22884be20c5137a5026bc4f0e8b43aa2


text:
Q: How to change YAML value from Controller in Symfony I want to change a value of my config.yml
I need to change it from my DefaultController.php but I don't know if this is possible (and if it's possible how to do it).
The YAML file
 google:
    enabled: true          # If Google Authenticator should be enabled, default false
    server_name: Zioo      # Server name used in QR code
    issuer: Zioo           # Issuer name used in QR code
    template: ZPAdminBundle:Authentication:form.html.twig   # Template used to render the authentication form

I need to change "enabled" to false from the defaultcontroller when A user doesn't want to use this option.

A: Got a fix!
In user I made an IsActivated value for the GoogleAuth
 /**
 * @return mixed
 */
public function getGoogleAuthenticatorIsActivated()
{
    return $this->googleAuthenticatorIsActivated;
}

/**
 * @param mixed $googleAuthenticatorIsActivated
 */
public function setGoogleAuthenticatorIsActivated($googleAuthenticatorIsActivated)
{
    $this->googleAuthenticatorIsActivated = $googleAuthenticatorIsActivated;
}

And then I checked if it is activated. If not it returns NULL. The bundle automaticly disables google auth if "getGoogleAuthenticatorSecret" returns NULL
    public function getGoogleAuthenticatorSecret()
    {

    if($this->getGoogleAuthenticatorIsActivated() == true){
        return $this->googleAuthenticatorSecret;
    }

    return NULL;
    }


text:
Q: Can the NSG be applied to the Subnet AFTER the Azure SQL Managed Instance is deployed into the subnet? Can the NSG be applied to the Subnet AFTER the SQL MI is deployed into the subnet?
https://learn.microsoft.com/en-us/azure/sql-database/sql-database-managed-instance-vnet-configuration
We are getting the following error when saving:
"Failed to save subnet 'managed-sql-dev-corp'. Error: 'Found conflicts with NetworkIntentPolicy. Details: Subnet or Virtual Network cannot have resources or properties which conflict with network intent policy."
Is the "Network Intent Policy" created by Azure Service or one of my own policies?

A: Once Managed Instance is deployed in the valid network/subnet, it will enforce some "Intent Policies" that prevent you from making some configurations that can invalidate the subnet.
As an example, Managed Instance can be deployed only in the subnet that don't contains other VMs. Once you deploy Managed Instance, it will setup intent rule that don't allow you to create VMs in this subnet and make the subnet invalid after deployment. Without these rules, you would be able to block access to Managed Instance. It cannot block everything, but this Intent Policy is the first-line of defense that Managed Instance uses to prevent someone to reconfigure the subnet.
Below is an example of the outbound rules that could be used in NSG.

*

*Rule allow_management_inbound allows management traffic to reach the
instance.

*Rule allow_misubnet_inbound allows communication between
the virtual machines that form Managed Instance cluster.

*Rule allow_health_probe allows health check from the virtual machines
host. Without it service fabric will think that nodes are unhealthy
and block the access.

*Rule allow_tds_inbound is optional but without it yon can't access the Managed Instance. It is advised to narrow its IP range as much as possible.

Priority numbers need not to be as depicted, but top 3 rules have to be of higher priority than any Deny rules.
To be compliant with Managed Instance Network Intent Policy, NSG must have rules that are numbered on picture as 100 and 200 on the top of the list.

*

*Rule allow_management_outbound allows management traffic to reach the services managed instance depends upon.

*Rule allow_misubnet_outbound allows communication between the virtual machines that form Managed Instance cluster.

Priority numbers need not to be as depicted, but top 2 rules have to be of higher priority than any Deny rules.
Managed Instance additional features may require additional ports to be open. This would be defined in the specific feature documentation.


text:
Q: Emulating private methods with closures vs public methods in objects As MDN states closures are used to emulate private methods for the module pattern:
var counter = (function () {
    var privateCounter = 0;

    function changeBy(val) {
        privateCounter += val;
    }

    return {
        increment: function () {
            changeBy(1);
        },
        decrement: function() {
            changeBy(-1);
        }
    };
}());

However, instead of using the module pattern we can also create a class instead. What is the advantage of creating a class over using the module pattern?
function Counter() {
    var privateCounter = 0;

    function changeBy(val) {
        privateCounter += val;
    }

    this.increment = function() {
        changeBy(1);
    };

    this.decrement = function() {
        changeBy(-1);
    };
}

var counter = new Counter();

A:
What is the advantage of creating a class over using the module pattern?

The advantage of creating a class over using the module pattern is that you can create several instances of a class:
var counter1 = new Counter;
var counter2 = new Counter;

Each instance will have its own set of private variables.
On the other hand, when you use the module pattern, you are only creating a single object (often called a singleton, namespace or module). Again, it has it's own set of private variables.
Both the module pattern and the class have their own uses. The module pattern is useful for creating modules, manager objects (of which only one instance must exist), etc.
The class pattern is useful for creating new data structures of the same type. For example, a linked list data structure would be modeled as a class and not as a singleton or a module.


text:
Q: java String.format - how to put a space between two characters I am searching for a way to use a formatter to put a space between two characters.  i thought it would be easy with a string formatter.
here is what i am trying to accomplish:
given: "AB" it will produce "A B"
Here is what i have tried so far:
"AB".format("%#s")

but this keep returning "AB" i want "A B". i thought the number sign could be used for space.
i also tried this:
"26".format("%#d") but its still prints "26"

is there anyway to do this with string.formatter.

A: I could not find way to do this using String#format.  But here is a way to accomplish this using regex replacement:
String input = "AB";
String output = input.replaceAll("(?<=[A-Z])(?=[A-Z])", " ");
System.out.println(output);

The regex pattern (?<=[A-Z])(?=[A-Z]) will match every position in between two capital letters, and interpolate a space at that point.  The above script prints:
A B

A: It is kind of possible with the string formatter although not directly with a pattern.
jshell> String.format("%1$c %2$c", "AB".chars().boxed().toArray())
$10 ==> "A B"

We need to turn the string into an object array so it can be passed in as varargs and the formatter pattern can extract characters based on index (1$ and 2$) and format them as characters (c).
A much simpler regex solution is the following which scales to any number of characters:
jshell> "ABC^&*123".replaceAll(".", "$0 ").trim()
$3 ==> "A B C ^ & * 1 2 3"

All single characters are replaced with them-self ($0) followed by a space. Then the last extra space is removed with the trim() call.


text:
Q: Creating an application that uses Expansion Files without publisher account I'm just starting to develop for Android and I don't have license of Google Play developer. For my application I have to use APK Expansion Files.
I tried to apply code of downloader_sample that contained at play_apk_expansion, but get InvalidKeySpecException thrown by this method
private static PublicKey generatePublicKey(String encodedPublicKey) {
    try {
        byte[] decodedKey = Base64.decode(encodedPublicKey);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
        return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
    } catch (NoSuchAlgorithmException e) {
        // This won't happen in an Android-compatible environment.
        throw new RuntimeException(e);
    } catch (Base64DecoderException e) {
        Log.e(TAG, "Could not decode from Base64.");
        throw new IllegalArgumentException(e);
    } catch (InvalidKeySpecException e) {
        Log.e(TAG, "Invalid key specification.");
        throw new IllegalArgumentException(e);
    }
}

Also I have
public class SampleDownloaderService extends DownloaderService {
// You must use the public key belonging to your publisher account
public static final String BASE64_PUBLIC_KEY = "MyLVLKey";
// You should also modify this salt
public static final byte[] SALT = new byte[] { 1, 42, -12, -1, 54, 98,
        -100, -12, 43, 2, -8, -4, 9, 5, -106, -107, -33, 45, -1, 84
};

How can I to test my application without real publisher account?

A: The sample code for the APK Expansion project has a specific check for the file being in place before calling the downloader functions.  Make sure that your file is in place on the SD card and access it directly.
To use the built-in downloader as-is, you will need a publisher account, because the files are hosted on Google Play.  With minor changes, you can use the downloader to download from wherever you would like, such as a local server.


text:
Q: Ruby get backtrace without an exception I have a Ruby on Rails application where a validation is failing for one of my models. There are different entry points into the code base for where this validation could fail. I'm interested in figuring out where it's coming from. Since it is a simple validation method, there aren't any exceptions involved, I just return false from the method and the save fails.
Is it currently possible to also log the backtrace to figure out what service/route this validation originated from so I can see what caused the state to change for this object in order for it to fail validation?

A: You could try caller():
def foo2
  puts caller
end
def foo
  foo2   #line5
end
foo     #line 7

Result:
test.rb:5:in `foo'
test.rb:7:in `<main>'

A: I'm not sure of a clever way to do it, but this will get the job done. You could wrap it in a nice little function even. I'm not sure if throwing exceptions and rescuing them will impact performance, but you probably wouldn't want to do something like this in production.
begin
  throw
rescue
  puts $!.backtrace
end


text:
Q: Understanding the result of modulo operator: %% I'm trying to understand how the %% operator works in R:
10 %% 10  # 0
20 %% 10  # 0

I'm not sure about these two results:
10 %% 20  # 10
2 %% 8  # 2

Can you help me understand the last two results? I'm a little confused.

A: I'll offer another explanation. Take this problem:
20 %% 10 = 0

Instead of evaluating the modulo, start with simple divison:
20 / 10 = 2

As you know, the answer "2" means that it takes two sets of 10 to get 20. Note that we can also write the answer this way with the decimal, 2.0.
The decimal is important. When the decimal is .0, we have no remainder. We have complete sets. If division yields a 0 decimal, then the modulo evaluates to zero.
Now consider this:
11/3 = 3.667

That tail part, the 0.667, is the portion of a set of 3 that remains after we form all full sets of 3 that we can. On the left side of the decimal, we show:
#Splitting the answer into its components - 3 full sets, 0.667 partial sets
3.0 + 0.667 = 3.667

So if we want to know the actual remaining quantity, we can multiply 0.667 by the divisor, 3:
0.667 * 3 = 2

This is the remainder. It is the quantity that remains after all full sets of 3 are formed. It's the same result we get using modulo:
11 %% 3 = 2

The same applies here. Given this problem,
10 %% 20 = 10

we can divide normally and get:
10 / 20 = 0.5

Reading this out, we have 0 full groups of 20 (left side); we only have half a set, 0.5, of 20.
0.5 * 20 = 10

This is equivalent to:
10 %% 20 = 10

10 is thus the remainder. It's the gap between the 10 we have and the 10 we need to get to 20.

A: I was also very confused, but if you understand that the result of the %% operator is the REMAINDER of a division, it is very easy.
Eg. 75%%4 = 3
and I noticed if the dividend is lower than the divisor, then R returns the same dividend value.
Eg.
4%%75 = 4
10 %% 20  = 10
2 %% 8  = 2

A: Nothing wrong:
10 = 1 * 10 + 0
20 = 2 * 10 + 0
10 = 0 * 20 + 10
2  = 0 * 8  + 2

The modulo is the number after +.

In general, for two numbers a and b, there is
a = floor(a / b) * b + (a %% b)

Let's write a toy function:
foo <- function(a,b) c(quotient = floor(a / b), modulo = a %% b)

foo(10, 10)
#quotient   modulo
#   1        0

foo(20, 10)
#quotient   modulo
#   2        0

foo(10, 20)
#quotient   modulo
#   0       10

foo(2, 8)
#quotient   modulo
#   0        2

Update: Instead of using floor(a / b) to get quotient, we can also use a %/% b.

A: Trying to understand some results in R with x modulo y I found this page. Then trying to explain to myself some "quirky" results I wrote this R script below. I had read that the remainder or result of modulo operator is supposed to be always positive, but this is not the case in R, and the definition and example provide here explain the logic that seems to be used. Definition x mod y = x - ( |_x/y_| * y) where |_x/y_| = floor(x/y) seems to always be true in R, or in a more standard way, the definition of the remainder r of the operation q = x / y is x = k*q + r, where k and r both are integers.
Basically in R with x = 2 and y = - 5, x mod y = -3; or using definition x = k*q + r we have r = x - k*q = -3.
Still, this is kind of quirky in a mathematical sense because "integer part product" (k*q) actually exceeds the dividend (x), thus defining the remainder (r) as a negative integer...
x <- 2
y <- -5
q <- x/y
k <- floor(2/-5)
kq <- floor(2/-5) * -5
r <- 2 - (floor(2/-5) * -5)
x %% y

A: Syntax
remainder <- dividend %% divisor

Details
The only thing that were missing from the documentations were the details on which side is the dividend and which side is the divisor. Wikipedia describes the two terms as:

What is being divided is called the dividend, which is divided by the divisor, and the result is called the quotient. In the example, 20 is the dividend, 5 is the divisor, and 4 is the quotient.

However, in comparison with the division operation, the modulo operation is not returning the quotient. Instead, it is returning the remainder.
Examples
To easily understand the modulo operation, ideally the dividend > divisor.
12 %% 11
# quotient is 1.090909
# remainder is 1

12 %% 10
# quotient is 1.2
# remainder is 2

12 %% 9
# quotient is 1.333333
# remainder is 3

12 %% 8
# quotient is 1.5
# remainder is 4

12 %% 7
# quotient is 1.714286
# remainder is 5

12 %% 6
# quotient is 2
# remainder is 0
# 12 is divisible by 6

12 %% 5
# quotient is 2.4
# remainder is 2

12 %% 4
# quotient is 3
# remainder is 0
# 12 is divisible by 4

12 %% 3
# quotient is 4
# remainder is 0
# 12 is divisible by 3

12 %% 2
# quotient is 6
# remainder is 0
# 12 is divisible by 2

12 %% 1
# quotient is 12
# remainder is 0
# any whole number is divisible by 1


text:
Q: React: Splash screen/container
Currently I have a page with a container set up as above, with a small game running inside it and a bar which keeps the score/time taken to complete a task within a game.
I am wanting to build a sort of splash screen that displays initially when you start the game, and maybe allows you to change a few options such as whether to use Addition/Subtraction etc.
I am quite new to React so I'm not sure I fully understand how everything works with rendering but how would I build this so that the container does not render again but can change between the splash and the game itself. My code in the render part so far is:
 render() {
    return (

            Score:  {this.state.score}

              <Timer onRef={ref => (this.timer = ref)} />

              1 + 1 = 2

              2 + 1 = 3

            What is {this.state.numbers.x} + {this.state.numbers.y}?

                <form className="main-form" onSubmit={this.handleSubmit}>

                    Answer:
                    <input className="input-field" type="text" value={this.state.value} onChange={this.handleChange} />

                  <button className="btn-submit" type="submit">Submit</button>
                </form>

    );
  }
};

I was thinking of having the two views in separate files but that means moving out a lot of dependent functions which just seems like it would create a big mess.
EDIT: Also, should I be using refs to manipulate state etc from the parent class?

A: The most readable way would be to create a component for the Splashscreen, like this. Notice that I'm setting the style for the component in its own function to prevent unnecessary re-renders.
export default class SplashScreen extends React.Component {
    renderSplash() {
        let splashStyle = {
            height: "100vh",
            width: "100vw",
            display: "flex",
            justifyContent: "center",
            alignItems: "center"
        }
        return(

SPLASH SCREEN

        )
    }

    render() {
        return this.renderSplash()
    }
}

Then in your parent component you need to set a state for handling the logic. Suppose your class is App then it should look something like this:
export default class App extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
          showSplash: true //this is the initial state
        }
    }

    renderApp() {
        return (
            {*/ Your code here /*}
        )
    }

    render() {
        {this.state.showSplash ? <SplashScreen /> : this.renderApp()}
    }
}

Notice that I'm dividing everything in functions. It makes it easy to switch between states/components in cases like this.
I don't know how you want to show the splash, if you want it deactivated once data is loaded or some timer function, but I'll update this answer with a few tips if you'd like.

A: If you plan to expand the application in the future and add more pages/screens you might consider using react-router which takes a bit to set up but after that makes switching screens much easier.
There are quite a lot of tutorials and examples involving react-router here:
https://reacttraining.com/react-router/


text:
Q: How does the login authentication work in Vaadin Bakery App I am trying to learn vaadin JAVA framework. I am looking at the code of Bakery App. In LoginView.java there is call to setAction('login') that takes care of the successfull authentication. I want to know where in the code this is taking place. I just want to add a new username and password to the exisitng code. How to do that?

A: The Bakery app uses Spring Security to handle login logic. Spring Security is configured in class SecurityConfiguration. The users are loaded/saved within UserRepository which extends JpaRepository which is part of the Spring Data JPA framework. This repository saves entities inside Bakery app in memory by default which is mentioned in the README.md:

*Optionally you might want to avoid the data generator to be run on each single reload, therefore, make H2 database store entities in
  file-system instead of in memory by adding the following lines to the
  src/main/resources/application.properties

spring.datasource.url=jdbc:h2:file:~/bakery-test-data
spring.jpa.hibernate.ddl-auto=update

The place where those users are created and saved into memory is in DataGenerator Line 77  - 81:
    User baker = createBaker(userRepository, passwordEncoder);
    User barista = createBarista(userRepository, passwordEncoder);
    createAdmin(userRepository, passwordEncoder);
    // A set of products without constrains that can be deleted
    createDeletableUsers(userRepository, passwordEncoder);

This would be the place where you could add additional users.


text:
Q: Can't figure out how to create exchange rate tables These are two commands I try to execute to create a pair or tables related to exchange rates.
CREATE TABLE IF NOT EXISTS Currencies(
      numeric_code integer NOT NULL PRIMARY KEY,
      code text NOT NULL UNIQUE

CREATE TABLE IF NOT EXISTS ExchangeRates(
      id integer NOT NULL PRIMARY KEY AUTOINCREMENT,
      numeric_code integer NOT NULL,
      exchange_rate real NO NULL,
      date_from date NOT NULL,
      FOREIGN KEY (numeric_code) REFERENCES Currencies(numeric_code)

I get the error: SQLITE_ERROR: incomplete input errno: 1, code: 'SQLITE_ERROR'
What is wrong? I am not good at SQL queries.


text:
Q: Wrap hint text on SearchView Android I need to wrap the hint text that is written inside the SearchView. How can I achieve this?
With the next code the text is shown like this: "This is a very lo..."
Here is my SearchView:
<SearchView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/sv"
        android:queryHint="This is a very long searchview hint"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true" />

Edit
I was able to do this programmatically:
int id = mSvBusqueda.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
EditText editText = (EditText) mSvBusqueda.findViewById(id);
editText.setSingleLine(false);

But I cant make the searchview container to wrap the edit text (see picture)

A: Add:
android:lines="1"

And now to disable "Enter":
EDIT_TEXT.setOnKeyListener(new OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event)
        {
            if (keyCode == KeyEvent.KEYCODE_ENTER)
            {
                return true;
            }
            return false;
        }
    });

How to word wrap the hint of a single line AutoCompleteTextView?

A: Try using android:ellipsize="end"


text:
Q: why "true || undefined ? undefined : false;" returns "undefinied"? I wrote this expression in chrome console:
true || undefined ? undefined : false;

and it returned:
undefined

How come?

A: The condition (true || undefined) is true, hence, the ternary operator will take undefined as the result:

const condition = true || undefined;
console.log("condition:", condition);

console.log("result:", condition ? undefined : false);

If your goal is to split by the ||:

const result = true || (undefined ? undefined : false);

console.log("result:", result);

A: || is higher precedence than ?:, making the expression equivalent to (true || undefined) ? undefined : false;. Thus, it evaluates true || undefined first, which evaluates to true, then chooses the truthy side of the :, undefined.

A: the expression is equivalent to:
if (true) {
  return undefined;
} else if (undefined) {
  return undefined;
} else {
  return false;
}

so it's return the first undefined.

A: You want to use something like this:
function IsSomething(bool){
    return bool || bool === undefined;
}

The problem with "true || undefined" is that the answer to this is undefined, which is why you are seeing undefined returned.

A: true or <literally any other value>

...is always true.
"Or" statements return the first true item they encounter, if one is present. "And" statements return the last true item if present.


text:
Q: Spring CXF configuration without xml I want to create a RESTfull web service using Spring + CXF without XML bean configuration. How can I convert the below XML based configuration into Java ?
applicationBean.xml
<jaxrs:server id="employeeService" address="/employeeservices">
    <jaxrs:providers>
        <bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />
    </jaxrs:providers>
    <jaxrs:serviceBeans>
        <ref bean="cxfServiceImpl" />
    </jaxrs:serviceBeans>
    <jaxrs:extensionMappings>
        <entry key="xml" value="application/xml" />
        <entry key="json" value="application/json" />
    </jaxrs:extensionMappings>
</jaxrs:server>

Spring CXF configuration
@Configuration
public class AppConfig {
  //Code for CXF need to be here
}

A: if you are using spring-boot, here is the simplest way.
@Import(SpringComponentScanServer.class)
@Configuration
public class KpCxfConfiguration {

    @Bean
    public ServletRegistrationBean servletRegistrationBean(ApplicationContext context) {
        return new ServletRegistrationBean(new CXFServlet(), "/api/*");
    }

}

Note: your service classes needs to be annotated with @Path annotation
And if you are using non-spring boot application you can define servlet mapping in web.xml


text:
Q: Calculating sum of several records with different ID When reaching last record, adding items "B" with same name "Y" (order by Y) I have:
  Do While Y < Z
      total=0
  Do While X=Y
     Total = A + B (item to sum)
     MoveNext
  Loop
    MovePrevious
    DoCmd.RunSQL
   MoveNext
  Loop
  Close

it says no record found, it stops and does not record the value A (sum) on last record "Y". What am I missing?
Thank you.


text:
Q: Not able to find location field for this particular site "http://www.macys.com/" I have the following site : "http://www.macys.com/" for which there is redirection.
This is code snippet:
String location = "http://www.macys.com/";
do {
    HttpURLConnection conn = null;
    try {
        url = location;
        conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestMethod("GET");
        /**
         * Setting the Browser properties
         */
        conn.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76 Safari/537.36");
        conn.setConnectTimeout(2000);
        conn.setInstanceFollowRedirects(false);
        conn.setReadTimeout(10000);
        conn.connect();
    } catch (Exception e) {
        logger.error("Exception : {}", e.getMessage());
    }

    responseCode = connection.getResponseCode();

    if ((responseCode > 300 && responseCode < 310)) {
        location = connection.getHeaderField("Location");
        if (location == null)
            break;
    }
} while (responseCode > 300 && responseCode < 310);

After first iteration, response code is 302, but no location field is found.
What am I doing wrong here?

A: If you look at the response body, you can see that the site is denying your request.
Access Denied: You don't have permission to access the requested URL on this server.
The site won't send you a Location header despite showing response code of 302 when they deny you access.


text:
Q: Пригласительная ссылка в приватный канал создается уже просроченная (aiogram) Создавала ссылку на chat с помощью
link = await bot.create_chat_invite_link(TEST_ID, member_limit=1)

Все работало, пригласительная ссылка на одного человека создавалась.
Сейчас решила поменять TEST_ID с ID чата на ID приватного канала, ссылка создается, но при нажатии на нее появляется "срок действия ссылки истек", несмотря на то, что по ней никто не переходил
Также пробовала:
link = await bot.export_chat_invite_link(TEST_ID_CHENNEL)

но та же история
Может нужно установить какие-то настройки в самом канале?
Подскажите пожалуйста и заранее спасибо!

A: Решила свой вопрос, может кому будет полезно:
Проблема заключалась в том, что я тестировала возможность по времени удалять пользователей и приглашать по ссылке обратно
Добавила пользователя, удалила, обратно не смогла пригласить, поскольку при удалении из канала пользователь автоматически добавляется в черный список канала, чтобы пригласить его повторно, нужно:
await bot.kick_chat_member(TEST_ID_CHENNEL, user_id)
await bot.unban_chat_member(TEST_ID_CHENNEL, user_id)


text:
Q: How to search an array for matching property from another array? I have a products array that looks like this:
const products =
[
    { product: 'prod_aaa', name: 'Starter' },
    { product: 'prod_bbb', name: 'Growth' },
    { product: 'prod_ccc', name: 'Elite' },
];

And a subscriptions array that looks something like this:
const subscriptions =
[
    {
        "status":"active",
        "product": "prod_aaa",
        "quantity": 1,
    },
    {
        "status":"active",
        "product": "prod_2342352345",
        "quantity": 1,
    }
];

Now I want to check the subscriptions array to find the first occurance of a matching product from the products array, and output the name of the product  it finds (Starter/Growth/Elite).
I imagine it needs something like subscriptions.filter(). But I don't know how to make it give me the name of the product it finds.
I cannot change the subscriptions input, but I can change the plans input if needed.
What is the best way to do this?
P.S. My code is written in TypeScript

A: You mentioned filter(), but it should only be used when you are looking to use the array returned by it. Since you are only looking for the name, you would be better served with a for loop.

const products = [{
    product: 'prod_aaa',
    name: 'Starter'
  },
  {
    product: 'prod_bbb',
    name: 'Growth'
  },
  {
    product: 'prod_ccc',
    name: 'Elite'
  },
];

const subscriptions = [{
    "status": "active",
    "product": "prod_aaa",
    "quantity": 1,
  },
  {
    "status": "active",
    "product": "prod_2342352345",
    "quantity": 1,
  }
];

function find() {
  for (const product of products) {
    for (const subs of subscriptions) {
      if (product.product === subs.product) {
        return product.name;
      }
    }
  }
}

console.log(find())

Edit: If you are absolutely looking for something with filter(). Here is what will help:

const products = [{
    product: 'prod_aaa',
    name: 'Starter'
  },
  {
    product: 'prod_bbb',
    name: 'Growth'
  },
  {
    product: 'prod_ccc',
    name: 'Elite'
  },
];

const subscriptions = [{
    "status": "active",
    "product": "prod_aaa",
    "quantity": 1,
  },
  {
    "status": "active",
    "product": "prod_2342352345",
    "quantity": 1,
  }
];

let result = products.filter(prod => {
  return subscriptions.some(sub => prod.product === sub.product)
})[0].name;

console.log(result)

A: As opposed to Avneesh's approach I have traversed through the subscriptions array first.
// find a first subscription for which product is found in the products array.

let requiredSub = subscriptions.find(sub => products.some(p => p.product === sub.product))

let requiredProduct = requiredSub.product

Javascript Array.some method mdn reference -
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some


text:
Q: API to get instance type of softlayer node I am trying to write some scripts that could perform a switch statement depending on the type of instances the node is; VM or baremetal.
Is there a way to reliably tell what type of an instance the machine is from within the environment?
My first thinking was the existence of a bond0 interface, but this could potentially be problematic if someone orders a VM with a weird networking config. If there is an easy API call to check the instance type?

A: you could use this service:
http://sldn.softlayer.com/reference/services/SoftLayer_Resource_Metadata
This service is desing to identify the device. the service must run whithin the machine and you do not need specify your username or API key.
So you can run the method to get the id of the machine e.g.
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET https://api.service.softlayer.com/rest/v3/SoftLayer_Resource_Metadata/getId

Once you get the ID of the device you can see if this ID belongs to a bare metal server or VSI, for that you can use the getObject methods.
http://sldn.softlayer.com/reference/services/SoftLayer_Hardware_Server/getObject
http://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest/getObject
For example if your ID belongs to VSI and you call the SoftLayer_Hardware_Server::getObject method you will get an error like that ID does not exist, and when you call the SoftLayer_Virtual_Guest::getObject method you will able to get information about the machine.
Also you could list all the bare metal and VSI servers in your account, an verify if your ID belongs to bare metal or VSI, you can use these methods:
http://sldn.softlayer.com/reference/services/SoftLayer_Account/getVirtualGuests
http://sldn.softlayer.com/reference/services/SoftLayer_Account/getHardware
Regards