text:
Q: Client still can ssh login without password on server after generating new keys First I generated keys on client (Ubuntu 18.04)
$ ssh-keygen -t rsa -f .ssh/id_rsa

then I copied it to server (Ubuntu Server 18.04)
$ ssh-copy-id 192.168.1.58

Now I can see the key in .ssh/authirized_keys on server and I can login without a password.
Then I generated new keys on client and previous keys were overwritten. But I can still login to server without a password. I was expecting since the keys have been changed, server wouldn't verify me. What am I missing?
Edit:
I even removed keys
$ rm .ssh/id*
$ ls .ssh/
known_hosts

I can still login
$ ssh 192.168.1.58
Welcome to Ubuntu 18.04.4 LTS (GNU/Linux 4.15.0-91-generic x86_64)

* Documentation:  https://help.ubuntu.com
* Management:     https://landscape.canonical.com
* Support:        https://ubuntu.com/advantage

System information as of Mon Mar 23 08:51:34 UTC 2020

System load:  0.0                Processes:              106
Usage of /:   42.8% of 12.31GB   Users logged in:        1
Memory usage: 6%                 IP address for enp0s3:  192.168.1.58
Swap usage:   0%                 IP address for docker0: 172.17.0.1

0 packages can be updated.
0 updates are security updates.

Last login: Mon Mar 23 08:46:19 2020 from 192.168.1.59

$ cat .ssh/authorized_keys
ssh-rsa AAAAB3NzaC1[...]nr6eR33QK1BYeNT0BjyhRztd me@ubnutu-vm
$ w
08:53:57 up  2:10,  2 users,  load average: 0.06, 0.02, 0.00
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
me       tty1     -                07:12   21.00s  0.35s  0.32s -bash
me       pts/0    192.168.1.59     08:51    1.00s  0.06s  0.00s w

Edit 2:
This is from ssh -v:
...
debug1: Authentications that can continue: publickey,password
debug1: Next authentication method: publickey
debug1: Offering public key: RSA SHA256:Db+pAR0Bc2kmZ9jju9zttSZDwfbEl4TM82AV7KSZ3DM /home/me/.ssh/id_rsa
debug1: Server accepts key: pkalg rsa-sha2-512 blen 279
debug1: Authentication succeeded (publickey).
Authenticated to 192.168.1.58 ([192.168.1.58]:22).
...

Although there is no id_rsa file in /home/me/.ssh/ folder. So I thought that maybe some sort of cache is involved and after a reboot on client now I have to enter the password.
This is ssh -v after reboot:
...
debug1: Authentications that can continue: publickey,password
debug1: Next authentication method: publickey
debug1: Trying private key: /home/me/.ssh/id_rsa
debug1: Trying private key: /home/me/.ssh/id_dsa
debug1: Trying private key: /home/me/.ssh/id_ecdsa
debug1: Trying private key: /home/me/.ssh/id_ed25519
debug1: Next authentication method: password
me@192.168.1.58's password:

So a reboot was needed.

A: Following @fra-san's advise I dug a little deeper and This is what I got:
This is from https://www.ssh.com/ssh/agent

By default, the agent uses SSH keys stored in the .ssh directory under
the user's home directory. The ssh-add command is used for adding
identities to the agent. In the simplest form, just run if without
argument to add the default files ~/.ssh/id_rsa, .ssh/id_dsa,
~/.ssh/id_ecdsa, ~/.ssh/id_ed25519, and ~/.ssh/identity. Otherwise,
give it the name of the private key file to add as an argument.
The following command will list private keys currently accessible to the agent:
ssh-add -l

After connecting to the server the ssh-add -l shows this:
$ ssh-add -l
2048 SHA256:rzgw39XLAT0NHof4RBXFU/ahKhFWlH8FqMgNxBX2SAE /home/me/.ssh/id_rsa (RSA)

If the id_* keys in the .ssh/ folder change or be deleted the ssh-add -l still shows the same output and it will be used for future connections (at least in my case).
At that point a reboot or one of the following commands will remove the cached key:
$ ssh-add -d /home/me/.ssh/id_rsa
Identity removed: /home/me/.ssh/id_rsa (me@ubnutu-vm)

or
$ ssh-add -D
All identities removed.

Now password prompt will be shown for new connections.
Update:
This is from https://man.openbsd.org/ssh_config.5#AddKeysToAgent:

AddKeysToAgent
Specifies whether keys should be automatically added to a running
ssh-agent(1). If this option is set to yes and a key is loaded from a
file, the key and its passphrase are added to the agent with the
default lifetime, as if by ssh-add(1). If this option is set to ask,
ssh(1) will require confirmation using the SSH_ASKPASS program before
adding a key (see ssh-add(1) for details). If this option is set to
confirm, each use of the key must be confirmed, as if the -c option
was specified to ssh-add(1). If this option is set to no, no keys are
added to the agent. The argument must be yes, confirm, ask, or no (the
default).


text:
Q: Showing the group of polynomial modulo 3 is isomorphic to $\mathbb{Z}_{3} \oplus \mathbb{Z}_{3} \oplus \mathbb{Z}_{3} $ Let $G=\left \{ ax^{2}+bx+c \mid a,b,c \in \mathbb{Z}_{3} \right \}$, Add elements of G as you would polynomials with integer coefficients, except use addition modulo 3.
Prove that G is Isomorphic to $\mathbb{Z}_{3} \oplus \mathbb{Z}_{3} \oplus \mathbb{Z}_{3}$
Suppose $g_{1}=a_{1}x^{2}+b_{1}x+c_{1} , g_{2}=a_{2}x^{2}+b_{2}x+c_{2}$
Define:
$\phi: G \rightarrow  \mathbb{Z}_{3} \oplus \mathbb{Z}_{3} \oplus \mathbb{Z}_{3}$
$g \mapsto \left ( a,b,c \right )
$
Now,
$\phi\left ( g_{1}+g_{2} \right )=\phi\left (  \left ( a_{1}+a_{2} \right )x^{2}+\left ( b_{1}+b_{2} \right )x+\left ( c_{1}+c_{2} \right )      \right )
=\left ( a_{1}+a_{2},b_{1}+b_{2},c_{1}+c_{2} \right )
=\left ( a_{1},b_{1},c_{1} \right )+\left ( a_{2},b_{2},c_{2} \right )
=\phi\left ( g_{1} \right )+\phi\left ( g_{2} \right )$
Is my attempt in the right direction?
Thanks in advance.

A: Yes, that is already a canonical isomorphism and I don't think much else interesting about it. Using the addition operator then
$$\phi(ax^2 + bx + c) + \phi(dx^2 + ex + f) = (a, b, c) + (d, e, f) = (a + d, b + e, c + f) \text{ mod } 3 = \phi((a+d)x^2 + (b + e)x + (c + f))$$
It is evidently onto and one-to-one, you are done.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Autofill an Integrated Windows Authentication I'm making an application with C#, this application will automatically navigate to a SharePoint site and gather some information. I have basic User Rights to the site (Meaning I'm not at a Site Admin), the SP site uses Integrated Windows Authentication which looks like this,
How can I get the C# application to autofill the needed credentials when the WebBrowser control navigates to the site?
This is a very basic break-down,
- Application Opens
- 'Navigate' Button is clicked
- WebBrowser1 Control Navigates to the SP Site and autofills the supplied credentials (Within the code).

A: This is the code I'm using to complete this operation,
WebClient client = new WebClient();
        CredentialCache cc = new CredentialCache();
        cc.Add(new Uri("http://spSite"), "NTLM", new NetworkCredential(username, password, domain));
        client.Credentials = cc;


text:
Q: jquery how to toggle this specific animation? So I want to toggle this animation in jQuery but I found it very hard to find a way.
$( "#console" ).animate({height: "20px"});

A: You can set height of element in variable and use it to animate. Also you need to save toggle state to having animation without bug.

var firstHeight = $("div").height();
$("div").click(function(){
    $(this).stop();
    if (!$(this).data("animateToggle"))
        $("div").data("animateToggle", 1).animate({height: "200px"});
    else
        $("div").removeData("animateToggle").animate({height: firstHeight});
});
div {
    width: 100px;
    height: 100px;
    background: green;
}


text:
Q: GAMLSS ERROR : NA's in the working vector or weights for parameter mu I am getting the following error ERROR : NA's in the working vector or weights for parameter mu
for the gamlss function: fit <- gamlss::gamlss(x ~ y, sigma.formula = ~ y, data = d, family = GA)
where d is a dataframe containing x and y
x = 17.83961 29.73269 14.15842 15.00793 35.53764 13.53545 17.13169 35.67923 14.68229 10.59050 13.73367 26.58952 21.33674 28.60002 36.24556 22.00219 30.2990326.50457 28.17526 41.05943 19.22714 37.09507 24.32417 21.29427 23.72952 23.72952 18.37763
y =  0.037059 0.037059 0.037059 0.037059 0.037059 0.037059 0.037059 0.037059 0.037059 0.037059 0.037059 0.037059 0.037059 0.037059 0.037059 0.037059 0.037059 0.037059 0.037059 0.037059 0.037059 0.037059 0.037059 0.037059 0.079820 0.079820 0.131133

what is the cause of this error?

A: Maybe it is related to the data. If you swap x and y, a model will come out:
fit <- gamlss(y ~ x, sigma.formula = ~ x, data = d, family = GA)


text:
Q: Using Snowflake & Apache Airflow, how can I change DATABASE or SCHEMA for a connection using SqlSensor? I'm new to Snowflake (and using it in Apache Airflow).  I'm attempting to use the SqlSensor with it.
I've found that the Snowflake driver doesn't allow multi-statement SQL.  The SnowflakeOperator appears to have worked around this by splitting on ; and executing the statements one at a time.
Snowflake is a valid connection type for SqlOperator.  But, I haven't noticed an SqlSensor specifically for Snowflake.  The SqlOperator doesn't split commands the way the SnowflakeOperator does. Therefore it seems like each query to use for sensing must be established on the right database and schema from the get go, i.e. no USE DATABASE type commands - otherwise it is multi-statement and the sensor fails.
Do I need to establish a separate airflow connection for each Schema and Database I might choose to sense?  Or is there another way to specify the DATABASE, SCHEMA, etc at runtime using the SqlSensor?

A: SqlSensor is designed to accept single query.
I assume that you are trying to run queries like:
USE DATABASE my_database;
USE SCHEMA my_schema;
SELECT ...

Which doesn't work. For the moment there is no out of the box solution. A PR is in progress to handle it by exposing the underlying hooks of SqlSensor allowing to pass parameters.
However you can still solve your problem with one of the following:

*

*Define another Snowflake connection that you will not need to change its properties in the query thus you will run only a single SELECT statement.

*create a custom SnowflakeSensor.

I didn't test it but the general idea is something like
from airflow.sensors.sql import SqlSensor
from airflow.providers.snowflake.hooks.snowflake import SnowflakeHook

class SnowflakeSensor(SqlSensor):
    def __init__(
        self, **kwargs
    ):
        self.account = kwargs.pop("account", None)
        self.warehouse = kwargs.pop("warehouse", None)
        self.database = kwargs.pop("database", None)
        self.region = kwargs.pop("region", None)
        self.role = kwargs.pop("role", None)
        self.schema = kwargs.pop("schema", None)
        self.authenticator = kwargs.pop("authenticator", None)
        self.session_parameters = kwargs.pop("session_parameters", None)
        super().__init__(**kwargs)

    def _get_hook(self):
        return SnowflakeHook(
            snowflake_conn_id=self.conn_id,
            warehouse=self.warehouse,
            database=self.database,
            role=self.role,
            schema=self.schema,
            authenticator=self.authenticator,
            session_parameters=self.session_parameters,
        )

What this code does is everything that SqlSensor does with the difference that it accept also Snowflake specific parameters by overwriting the _get_hook function.


text:
Q: OpenLayers 2: WFS layer not being portrayed in map canvas I have a "rich" application (OL 2.13 + GeoExt 1) where some layers
must be styled dynamically according to user input. I am able to add a
vector layer using WFS and then apply a style rule. Recently, some
users started complaining the feature is not working. Eventually I
found out some WFS layers are not being portrayed in the map canvas by
OL.
Below is a minimum example with a simple map and one of the
problematic layers. After loading all objects the debugger shows a
vector layer within the map object; this vector layer is reported as
visible and with the drawn property set to true. In the features array
there are 8 objects as expected, but there is nothing visible in the
map. There are no errors reported in the console.
I am able to display this same layer through WFS in QGIS and access
all its attributes without trouble.
What is going wrong here?

 <link rel="stylesheet" type="text/css" href="http://localhost/spatiallib/OpenLayers-2.13.1/theme/default/style.css">

     <input type=button value="Click for debugger" onclick="debugger;"></input>

A: Your problem may come from using WFS 1.1.0 with a coordinate system that has a northing-easting axis order. You can try these solutions:

*

*Use WFS 1.0.0 version. You can test that 1.1.0 sends coordinates as northing-easting

http://maps.iguess.tudor.lu/cgi-bin/mapserv?map=/srv/mapserv/MapFiles/LB_localOWS_test.map&service=WFS&version=1.1.0&request=getfeature&typename=LB_sliders_test&maxfeatures=100
<gml:posList srsDimension="2">5417870.977814 3514129.458722

while WFS 1.0.0 sends them as easting-northing
http://maps.iguess.tudor.lu/cgi-bin/mapserv?map=/srv/mapserv/MapFiles/LB_localOWS_test.map&service=WFS&version=1.0.0&request=getfeature&typename=LB_sliders_test&maxfeatures=100
<gml:coordinates>3514129.458722,5417870.977814

*Actually OpenLayers WFS protocol should be clever enough and flip axis automatically when needed but that may not be the case. You should be able to give a hint for OpenLayers with format option "xy" as in a rather similar case in OpenLayers WFS flip coordinates

formatOptions: {
       xy: false
}


text:
Q: How to read pdf file on webView From my Local device I have two type read
first :Pdf Read from url OnWebView :Its working
second:Pdf Read from local path OnWebView: dosent working

(/data/data/com.akfix.navigationdrawer/files/550192f3a1583.pdf)

Second chart isnt working.And i havent any error log.what am i do,
My Pdf reader class here;
public class PdfReader extends Activity {
String pdf;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_pdf_reader);
    WebView webview = (WebView) findViewById(R.id.webView3);
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        pdf = extras.getString("pdfUrl");
        if (extras.getString("catalogPdfUrl") != null) {
            String pdfPath = extras.getString("catalogPdfUrl");

            Uri path = Uri.parse(pdfPath);
            viewPdf(path);

        } else {
            webview.getSettings().setJavaScriptEnabled(true);

            pdf.replaceAll("\"", "");
            webview.loadUrl("http://docs.google.com/gview?embedded=true&url=" + pdf);
        }
    }

}

private void viewPdf(Uri file) {
    Intent intent;
    intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(file, "application/pdf");
    try {
        startActivity(intent);
    } catch (ActivityNotFoundException e) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("No Application Found");
        builder.setMessage("Download one from Android Market?");
        builder.setPositiveButton("Yes, Please",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent marketIntent = new Intent(Intent.ACTION_VIEW);
                        marketIntent
                                .setData(Uri
                                        .parse("market://details?id=com.adobe.reader"));
                        startActivity(marketIntent);
                    }
                });
        builder.setNegativeButton("No, Thanks", null);
        builder.create().show();
    }
}

}
Help me please.

A: since it's local, why you need to display it in a webview?
i've used this library inside my app, it's simply amazing
Load a PDF file
pdfView.fromAsset(pdfName)
.pages(0, 2, 1, 3, 3, 3)
.defaultPage(1)
.showMinimap(false)
.enableSwipe(true)
.onDraw(onDrawListener)
.onLoad(onLoadCompleteListener)
.onPageChange(onPageChangeListener)
.load();


text:
Q: Why is $stateChangeStart triggering multiple times? I am trying to use $stateChangeStart with ui router in a controller. It seems like everytime it's fired, the callback fires +1 times more than the last time.
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){
    console.log('$stateChangeStart');
});

For example, on first change start console.log will be fired once. second time console.log will be fired twice, etc etc.
I know using event.preventDefault() will stop this behavior, but it'll also stop all behaviors and that's not a realistic solution to me.
I do have a solution although I feel like there might be a more intelligent way to handle this:
var stateChangeStarted = false;
$rootScope.$on('$stateChangeStart', function(event){
    if(!stateChangeStarted) {
        stateChangeStarted = true;
        console.log('$stateChangeStart');
    }
});

Does anyone have any idea why this is happening and what else I can do to prevent this?

A: Clear out the listeners for stateChangeStart at the beginning of your controller.
$rootScope.$$listeners.$stateChangeStart = [];

A: Your controller is instantiated by ui-router every time you enter the state it is associated with. Therefore, your $rootScope.$on call will be adding a new listener to the $stateChangeStart event each time you enter that state.
If you only need to handle the event once per controller instance, you can save the deregister function that $rootScope.$on returns and execute it from within the listener callback.
var deregisterStateChangeStart = $rootScope.$on('$stateChangeStart', function (event) {
    // Do something here.

    deregisterStateChangeStart();
});


text:
Q: Коммуникация процессов в Java Как на Java я могу из одного процесса отправить сообщение другому. В С++ я знаю, что можно использовать: file mapping, pipes, mailslots, sockets. К примеру идея использования какого-нибудь текстового файла и запись в него, чтобы другой процесс прочитал из него мне не очень понравилась. Есть какое-то простое решение, как в С++? В Java я новичок, хочу сделать подобие системы телефонной связи. Телефон 1 передает сообщение АТС, которая передает это Телефону 2.

A: Мой вопрос решил этот class RandomAccessFile.


text:
Q: ButeBuf release strategy when channel already closed before external callback calls fireUserEventTriggered Good day everyone!
I'm working in scenario where channelRead processing does not consume msg in an ordinary case - msg is passed to external processing(in different thread pool) with callback, and then returns to netty channel pipeline via fireUserEventTriggered. And got problem with msg release.
Tried to visualize the idea(code illustration at the bottom of question):
Netty                                                                              SomeExternalProcessingInSeparateThreadPool

.                                                                                .
onRead(ChannelHandlerContext ctx, Object msg){                                                      .
|                                                                                .
|                                                                                .
| > +------------------------------------------------------+ ------------------------------------ > someProcessingWithCallback{
|   | schedules processing to external logic,              |                                        |
|   | along with callback to                               |                                        | processing here does not modify msg!
|   | ctx.channel().pipeline().fireUserEventTriggered(...) |                                        |
|   | with msg reference                                   |                                        |
|   +------------------------------------------------------+                                        |
|                                                                                |
}   - !no release/consume at the end!                                                               |
.                                                                                |
.                                  <  PROBLEM ZONE  >                                               |
.                                                                                |
userEventTriggered(){ < -------------- +------------------------------------------------------+ - < |
|                                      | calling block with                                   |     |
|                                      | ctx.channel().pipeline().fireUserEventTriggered(...) |     |
|                                      +------------------------------------------------------+     }
|
| some processing here with msg.release or writeAndFlush to channel
|
}

And there is a problem - if channel is closed/unregistered before the callback code will call fireUserEventTriggered, then userEventTriggered never called and seems msg leaks.
I tried to solve this in ad-hoc manner for testing purpose:

*

*at onRead - put msg to ctx.channel().attr(ATTR_KEY_MSG).set(...)

*in handlers of onInactive check if there is data in attributes and release it if any.

But this led(not sure if connected) to some unexpected behavior and it just looks strange. So I googled, but failed to find the decision and came for SO advice.
The question is am I doing link with external processing in a correct way and what is the goto design to avoid msg leak in such scenarios?
PS Code illustration (real code is more complex, so the idea):
public class MyInboundHandler extends ChannelInboundHandlerAdapter {
    <...>
    public static final AttributeKey<MyMsg> ATTR_KEY_MSG = AttributeKey.valueOf("msg");
    <...>
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        final MyMsg myMsg = (MyMsg) msg;
        ctx.channel().attr(ATTR_KEY_MSG).set(myMsg);
        try{
            <...>
            someService.process(
                ...args...,
                () -> {
                    ctx.channel().pipeline()
                        .fireUserEventTriggered(
                            new MyCallbackEvent(....,myMsg,...)
                        );
                }
            );

            <...>//no myMysg release till method exist
        } catch(Exception ex) {
           // release msg here
        }
        <...>
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        <...>
        if (evt instanceof MyCallbackEvent) {
            <...>
            //process event and release explicitly or write it to channel
        } else {
            super.userEventTriggered(ctx, evt);
        }
        <...>
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        if (ch.hasAttr(ATTR_KEY_MSG)) {
            final MyMsg msg = ch.attr(ATTR_KEY_MSG).get();
            <...>
            //release it
        }
    }
    <...>
}

Thanks in advance.


text:
Q: How to Split this String and store in HashMap String str = "id1;;name1 || id2;;name2 || id3;;name3||";
into id1 name1 ...and then store it in hashmap as id1 - key , name1- value
                           id2 - key , name2 - value
                           ......

A: One way to reach your goal is to use a StringTokenizer.
Code example:
public static void main(String[] args) {
    String input = "id1;;name1 || id2;;name2 || id3;;name3||";
    Map<String, String> map = new HashMap<>();
    // You have to split two times
    for (String outer : splitBy(input, " || ")) {
        List<String> inner = splitBy(outer, ";;"); // for example: outer="id1;;name1"
        // Make sure, you have two inner input-elements
        if (inner.size() == 2) {
            String key = inner.get(0); // First element of List = Key
            String value = inner.get(1); // Second element of List = Value
            map.put(key, value);
        }
    }
}

private static List<String> splitBy(String toSplit, String delimiter) {
    List<String> tokens = new ArrayList<>();
    StringTokenizer tokenizer = new StringTokenizer(toSplit, delimiter);
    while (tokenizer.hasMoreTokens()) {
        tokens.add(tokenizer.nextToken());
    }
    return tokens;
}

Also take a look at this: Scanner vs. StringTokenizer vs. String.Split

A: for this particular case you should do something like this:
    Map<String, String> yourHashMap = new HashMap<String, String>();
    String input = "id1;;name1 || id2;;name2 || id3;;name3||";
    // "\" is special character so it need an escape
    String[] yourStrings = input.split("\\|\\|");
    String[] hashObject = new String[2];
    for (int i = 0; i <= yourStrings.length - 1; i++) {
        //fist you have to remove the whitespaces
        yourStrings[i] = yourStrings[i].replaceAll("\\s+", "");
        hashObject = yourStrings[i].split(";;");
        yourHashMap.put(hashObject[0], hashObject[1]);
    }

Your input string have a strange format, I recommend you to change it.


text:
Q: ProgressDialog gets dismissed when button is pressed I have a "please wait" ProgressDialog that includes a button, the problem is that when the button is clicked the dialog is dismissed (it disappears), how can I make the dialog stay on the screen?
    // Please wait dialog
private void showWaitDialog() {
    prgDialg = new ProgressDialog(context);
    prgDialg.setTitle("Working...");
    prgDialg.setMessage("Please wait.");
    prgDialg.setCancelable(false);
    prgDialg.setButton("Do something", myListener);
    prgDialg.show();
}

// Click listener
public OnClickListener myListener = new OnClickListener(){

    @Override
    public void onClick(DialogInterface dialog, int which) {
        textViev1.setText("xxx");
    }

A: Try this
prgDialg.setButton("Do something", new DialogInterface.OnClickListener()
    {
        public void onClick(DialogInterface dialog, int which)
        {
            // Use either finish() or return() to either close the activity or just the dialog
            return;
        }
    });

A:

prgDialg.setButton("Do something", myListener);
    the above method setButton(CharSequence text, DialogInterface.OnClickListener listener) is deprecated.

you can use
private void showWaitDialog() {
    prgDialg = new ProgressDialog(this);
    prgDialg.setTitle("Working...");
    prgDialg.setMessage("Please wait.");
    prgDialg.setCancelable(false);
    prgDialg.setButton(DialogInterface.BUTTON_NEUTRAL, "Do something", this);
    prgDialg.show();
}

@Override
public void cancel() {

}

@Override
public void dismiss() {

}

A: private void showWaitDialog() {
    prgDialg = new ProgressDialog(context);
    prgDialg.setTitle("Working...");
    prgDialg.setMessage("Please wait.");
    prgDialg.setCancelable(false);
    prgDialg.setNeutralButton("Do Something", new View.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {
                textViev1.setText("xxx");
    }
    });
    prgDialg.show();
}


text:
Q: Front end label configuration in spring I would like to have a external property (which has label name & value pairs) for each jsp pages in my web application.
I've done in this way like simply reading property file in a Map and placing in jsp using expression language.
Is there any other methodology to handle these in Java/Spring?

A: You can have these as message properties
http://www.mkyong.com/spring-mvc/spring-mvc-internationalization-example/
This also explains this in detail - http://www.journaldev.com/2610/spring-mvc-internationalization-i18n-and-localization-l10n-example
If you need these to be by locale, you can use localechangeInterceptor also.
You can PropertyPlaceholderConfigurer for  external properties (eg the systemPropertiesMode property)
http://www.summa-tech.com/blog/2009/04/20/6-tips-for-managing-property-files-with-spring
There are also more ways to do this like http://howtodoinjava.com/2015/01/27/how-to-load-external-resources-files-into-spring-context/
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename">
        <value>locale\customer\messages</value>
    </property>
</bean>

spring mvc and ReloadableResourceBundleMessageSource

A: Yes there is another way to show the labels in spring and this one is the best practice code.
enter link description here This will explain you how to use <spring:message code="label.viewUser" />  in your project.


text:
Q: Random timer between two numbers I'm currently trying to learn C#.
So i have created an project where i want to generate a random number between 1 Hour for example: A random number from 20-21 PM so like 20.23.
Its working but i need to compare it so when they are equal a pop up is coming but the milliseconds are in my way i need to remove them .
Any idea how i can solve this problem ?
So there is what i got so far:
namespace Timer
{
public partial class Form1 : Form
{

    private static readonly Random rnd = new Random();
    private static int minimum = 20;
    private static int maximum = 21;
    private static double x = rnd.NextDouble() * (maximum - minimum) + minimum;
    private static TimeSpan timeSpan = TimeSpan.FromHours(x);
    public static TimeSpan timeNow = DateTime.Now.TimeOfDay;
    public static TimeSpan diffTime = timeSpan - timeNow;

    public Form1()
    {
        InitializeComponent();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {

        if (diffTime != timeNow)
        {
            diffTime = timeSpan - timeNow;
            timeNow = DateTime.Now.TimeOfDay;
            LblTimeLeft.Text = diffTime.ToString();
            LblTime.Text = timeNow.ToString();
        }
        else
        {
            MessageBox.Show("EQUAL!");

        }
    }
  }
}

I hope you can help me.
Thanks !

A: You can do
var timeSpanSeconds = Math.Floor(TimeSpan.FromHours(x).TotalSeconds);
var nowSeconds = Math.Floor(DateTime.Now.TimeOfDay.TotalSeconds);
var diffSeconds = timeSpanSeconds - nowSeconds;

and then
if (diffSeconds != 0 )

or use this answer to round the timespans.


text:
Q: Axios vs jQuery.ajax() Изучаю Vue.js и потребовался асинхронный запрос на сервер... До этого пользовался всегда Ajax'ом от jQuery, но недавно наткнулся на Axios. Нигде нет плюсов и минусов этих библиотек и прошу вашего совета: что лучше в совокупности с Vue.js? Где больше/меньше нагрузки на сервер при постоянных запросах и тд

A: axios - это универсальная библиотека и может использоваться и с node.js и в браузере. axios - реализует правильный современный Promise API. axios поддерживает ES6 и легко интегрируется с Vuе на этапе разработки. axios - легко расширять для конкретного приложения, создавая свой собственный экземпляр.
Используйте axios с vue везде, где это возможно, особенно в отдельных приложениях на Vue/Vuex. Это будет еще один удобный инструмент в вашем арсенале.


text:
Q: Convert comma's into periods js So I'm trying to make a calculation but it obviously wont calculate with ',' in the numbers. I want to change these vars and make the ',' into '.' using javascript
oldSum.value = '48,35'
newSum.innerHTML = '€43,40'
            var oldSumPre = oldSum.value;
            var oldStripped = oldSumPre.replace(/,/g, ".");

            var newSumPre = newSum.innerHTML;
            var newStripped = newSumPre.replace(/,/g, ".");
            bedrag.innerHTML =  oldStripped - newStripped;

Is what Im doing right now.. but it changes bedrag.innerHTML into NaN

A: Suppose your variable is vNum. You need to replace all commas with '.' using this
vNum = vNum.replace(",", ".");

A: var str = "R,e,p,l,a,c,e";
var res = str.replace(/,/g, ".");

alert (res);

A: In general you could use a localization / internationalization library, which will solve some other tasks you are likely to run into as well.
For example this one:
https://github.com/jquery/globalize/blob/master/doc/api/number/parse-number.md
Snippet:
Globalize.locale( "es" );
Globalize.parseDate( "3,14" ); // 3.14


text:
Q: How to invoke previous POSIX signal handler? Note that this question is not duplicate of executing default signal handler. That question only asks for how to call default handler. While I want to call default handler while keeping my own for future signals. Apparently this must be done in a significantly different way since solutions provided in that other question don't work as explained below. Futhermore both most thumbed-up answers are plain wrong which I pointed out in comments there. (This: https://stackoverflow.com/a/6015916/422489 and this: https://stackoverflow.com/a/13290134/422489.)
Similar case with question Explicitly invoke SIG_DFL/SIG_IGN handlers on Linux.

Is it possible for a signal handler to somehow invoke previous handler without permanently resetting the handler?
Let us assume that I have some global variables:
struct sigaction new_action, old_action;

Then somewhere in my code I do something like this:
sigemptyset(&new_action.sa_mask);
new_action.sa_flags = 0;
new_action.sa_handler = &my_handler;
sigaction(SIGINT, &new_action, &old_action);

Now how would I implement my_handler so that it does its own staff and calls whatever was the previous handler (as saved in old_action)?
If we would assume just programmer provided handlers then we could do simply this:
void my_handler(int sig) {
    /* own staff */
    (*old_action)(sig);
    /* own staff */
}

(Possibly slightly more complex if SA_SIGINFO was taken int accont.) But this will obviously fail with SIG_IGN and SIG_DFL handlers as those are not actual function pointers but some "magic special values".
SIG_IGN could be dealt with by just doing… nothing. But that still leaves SIG_DFL. And also I would hesitate to do some if checks for special values as they will not work on systems that introduce their own custom special values that I don't know about (or future standards that will add new special values).
(And yes, I do know that SIG_DFL often just closes the process. But still this remains an interesting issue.)
Now it seems that I could switch handlers and use raise to reissue the signal. A simple approach like this:
void my_handler(int sig) {
    /* own staff */
    sigaction(sig, &old_action, NULL);
    raise(sig);
    sigaction(sig, &new_action, NULL);
    /* own staff */
}

But it will not work as expected. While a handler is executing its own signal gets blocked. Which means that raise will not deliver the signal but instead will just leave it until the signal will be unblocked again. Then we will change the handler back and upon exiting the handler the signal raised made will be delivered to current handler which is again my_handler. (I did simple tests and this seems to lead to obvious infinite recursion.)
There is a simple "workaround":
void my_handler(int sig) {
    /* own staff */
    sigaction(sig, &old_action, NULL);
    raise(sig);
}

But it doesn't work as well. Now the signal will be delivered to previous handler but we will not reset back to my_handler and there is no clear place in which we could do that.
I considered using the "infinite recursion" approach but explicitly unblock the signal after changing to old handler. Yet it seems unsafe. Can I be sure that raise will indeed deliver the signal? Or some other signal will get delivered instead and problem returns? Also it seems that I would no longer be sure if the signal was not raised by someone else somewhere else and I will end up with two deliveries to old handler.
Is there any way to safely invoke previous handler?


text:
Q: Performance tuning and optimization of XML::Twig in Perl Following is the code I have scribbled in order to filter my 3 to 5 GB XML file based on four conditions:
Following are the conditions:
1) All sub-stocks should be filtered.
2) Stocks having certain origin should persist. Else all should be filtered.
3) Inside the stock trade, there is an <event> tag which subsequently has a <subevent> tag. For the <event> tag attribute 'code' should have value 'abc' and the <subevent> tag should have certain values for their attributes as can be seen in code.
4) Only the highest version (attribute of stock) for a given ref (another attribute of stock) should be persisted with. The rest should all be deleted (This one is the most complicated condition)
My code is:
use strict;
use warnings;
use XML::Twig;

open( my $out, '>:utf8', 'out.xml') or die "cannot create output file  out.xml: $!";
my $twig = new XML::Twig(
    twig_roots => {  '/STOCKEXT/STOCK/STOCK'=> sub { $_->delete() },
                     '/STOCKEXT/STOCK[@origin != "ASIA"]' => sub  { $_->delete; },
                     '/STOCKEXT/STOCK' => \&trade_handler
                  },
    att_accessors => [ qw/ ref version / ],
    pretty_print  => 'indented',
);

my %max_version;
$twig->parsefile('1513.xml');
for my $stock ($twig->root->children('STOCK'))
{
   my ($ref, $version) = ($trade->ref, $trade->version);

   if ($version  eq  $max_version{$ref} &&
   grep {grep {$_->att('code') eq 'abc' and $_->att('narrative') eq 'def'}
   $_->children('subevent')} $trade->children('event[@eventtype="ghi"]'))

   {
        $trade->flush($out);
   }

   else
   {
    $trade->purge;

   }
}

sub trade_handler
{
  my ($twig, $trade) = @_;
  {
    my ($ref, $version) = ($trade->ref, $trade->version);

    unless (exists $max_version{$ref} and $max_version{$ref} >= $version)
    {
      $max_version{$ref} = $version;
    }
}

 1;
}

Sample XML
<STOCKEXT>
  <STOCK origin = "ASIA" ref="12" version="1" >(Filtered out, lower version ref)
    <event eventtype="ghi">
      <subevent code = "abc" narattive = "def" />
    </event>
  </STOCK>
  <STOCK origin = "ASIA" ref="12" version="2" >(highest version=2  for ref=12)
    <event eventtype="ghi">
      <subevent code = "abc" narattive = "def" />
    </event>
  </STOCK>
  <STOCK origin = "ASI" ref="13" version="1" >(Fileterd out "ASI" val wrong)
    <event eventtype="ghi">
      <subevent code = "abc" narattive = "def" />
    </event>
  </STOCK>

Code is working absolutely fine and providing requisite output. But it's consuming a hell of a lot of memory, even though I have tried to implement "FLUSH" & "PURGE". Can anybody please help with some optimization tips.

A: If you're worried about the memory footprint, you really want to be using flush/purge in a twig handler.
That way it's called as the file is being parsed.
Your calls to purge are being made after your parsefile, which means - it has to load and parse the whole thing first.
You might be able to build part of that into your trade_handler - e.g. you test for a max version, and then compare it in your iteration loop later. So you could probably test that condition during the handler:
if ( $max_version{$ref} > $version ) { $trade -> purge; }

But bear in mind if you did this, you'd need to rethink your post-parse foreach loop, because you'd be discarding as you went.
I'm not entirely sure what your grep is for though. You could possibly also implement that logic in your trade_handler too, but I can't say for sure. (e.g. negative test, purge if this element isn't required).
I think - pretty fundamentally - you should be able to use a handler for your 'for' loop, and process and purge as you go. I can't tell for sure - you might need a two-pass approach, because of needing to look ahead for version numbers.
Edit: This doesn't quite do what you want, but hopefully illustrates what I'd be suggesting:
#!/usr/bin/perl

use strict;
use warnings;
use XML::Twig;

open( my $out, '>:utf8', 'out.xml' )
    or die "cannot create output file  out.xml: $!";
my $twig = new XML::Twig(
    twig_roots => {
        '/STOCKEXT/STOCK/STOCK'              => sub { $_->delete() },
        '/STOCKEXT/STOCK[@origin != "ASIA"]' => sub { $_->delete; },
        '/STOCKEXT/STOCK' => \&trade_handler
    },
    att_accessors => [qw/ ref version /],
    pretty_print  => 'indented',
);

my %max_version;
my %best_version_of;

local $/;
$twig->parse(<DATA>);

foreach my $ref ( keys %best_version_of ) {
  $best_version_of{$ref} -> print;
}
#$twig->parsefile('1513.xml');

sub trade_handler {
    my ( $twig, $trade ) = @_;
    my ( $ref, $version ) = ( $trade->ref, $trade->version );

    if ( not exists $max_version{$ref}
        or $max_version{$ref} < $version )
    {
        ###something here that replicates your grep test, as I'm not sure I've got it right.
        $max_version{$ref}     = $version;
        $best_version_of{$ref} = $trade;
    }
  $trade -> purge;
}

__DATA__

<STOCKEXT>
  <STOCK origin = "ASIA" ref="12" version="1" >
    <event eventtype="ghi">
      <subevent code = "abc" narattive = "def" />
    </event>
  </STOCK>
  <STOCK origin = "ASIA" ref="12" version="2" >
    <event eventtype="ghi">
      <subevent code = "abc" narattive = "def" />
    </event>
  </STOCK>
  <STOCK origin = "ASI" ref="13" version="1" >
    <event eventtype="ghi">
      <subevent code = "abc" narattive = "def" />
    </event>
  </STOCK>
</STOCKEXT>

As said, this doesn't quite do what you want - it'll 'save memory' only as long as you're able to discard a lot of the XML by purging it as you go along... but because you don't know which version is the highest until you get to the end, a memory footprint is inevitable, because you'll never entirely know what you can safely discard until you get there.
So perhaps you need a two-pass approach, where you parse first to extract 'highest version numbers' - much like you're doing, but purging as you go... and then start over once you know them, because then you know what you can purge or flush as you're going.
The reason you're having this problem is that you can't know if you've got the latest version until you hit the end of the file.
So you might need to do something like this instead?
#!/usr/bin/perl

use strict;
use warnings;
use XML::Twig;

open( my $out, '>:utf8', 'out.xml' )
    or die "cannot create output file  out.xml: $!";

my $first_pass = new XML::Twig(
    twig_roots => {
        '/STOCKEXT/STOCK/STOCK'              => sub { $_->delete() },
        '/STOCKEXT/STOCK[@origin != "ASIA"]' => sub { $_->delete; },
        '/STOCKEXT/STOCK' => \&extract_highest_version,
    },
    att_accessors => [qw/ ref version /],
    pretty_print  => 'indented',
);

my $main_parse = new XML::Twig(
    twig_roots => {
        '/STOCKEXT/STOCK/STOCK'              => sub { $_->delete() },
        '/STOCKEXT/STOCK[@origin != "ASIA"]' => sub { $_->delete; },
        '/STOCKEXT/STOCK' => \&trade_handler
    },
    att_accessors => [qw/ ref version /],
    pretty_print  => 'indented',
);

my %max_version_of;

$first_pass->parsefile('1513.xml');
$main_parse->parsefile('1513.xml');

sub extract_highest_version {
    my ( $twig, $trade ) = @_;
    my ( $ref, $version ) = ( $trade->ref, $trade->version );

    if ( not exists $max_version_of{$ref}
        or $max_version_of{$ref} < $version )
    {
        $max_version_of{$ref} = $version;
    }
    $trade->purge;
}

sub trade_handler {
    my ( $twig, $trade ) = @_;
    my ( $ref, $version ) = ( $trade->ref, $trade->version );
    if ( $version >= $max_version_of{$ref}
        and ( $trade->first_child('event')->att('eventtype')                           eq 'ghi' )
        and ( $trade->first_child('event')->first_child('subevent')->att('code')       eq 'abc' )
        and ( $trade->first_child('event')->first_child('subevent') ->att('narattive') eq 'def' )
        )
    {
        $trade->flush;
    }
    else {
        $trade->purge;
    }
}

Can probably be a bit tidier, but the point is - you run through it once - and purge as you go, so you only have a single <STOCK> in memory at a given time. Then you have a relationship between 'ref' and 'highest version.
So then you parse a second time, and because you know what the highest version is, you can purge/flush as you go - you don't have to read the future.
Now as noted in the comments - your first approach reads the whole file into memory, because it needs to know the 'highest version'. It's single pass though, which makes it faster.
The other approach is two pass - reading the file twice. Slower, but not retaining very much in memory at all.
A halfway house might be:
#!/usr/bin/perl

use strict;
use warnings;
use XML::Twig;

open( my $out, '>:utf8', 'out.xml' )
    or die "cannot create output file  out.xml: $!";
my $twig = new XML::Twig(
    twig_roots => {
        '/STOCKEXT/STOCK/STOCK'              => sub { $_->delete() },
        '/STOCKEXT/STOCK[@origin != "ASIA"]' => sub { $_->delete; },
        '/STOCKEXT/STOCK' => \&trade_handler
    },
    att_accessors => [qw/ ref version /],
    pretty_print  => 'indented',
);

my %max_version_of;
my %best_version_of;

$twig->parsefile('1513.xml');

print {$out} "<STOCKEXT>\n";
foreach my $ref ( keys %best_version_of ) {
    foreach my $trade ( @{ $best_version_of{$ref} } ) {
        $trade->print($out);
    }
}
print {$out} "</STOCKEXT>\n";

sub trade_handler {
    my ( $twig, $trade ) = @_;
    my ( $ref, $version ) = ( $trade->ref, $trade->version );

    if ((   not defined $max_version_of{$ref}
            or $version >= $max_version_of{$ref}
        )
        and ( $trade->first_child('event')->att('eventtype') eq 'ghi' )
        and
        ( $trade->first_child('event')->first_child('subevent')->att('code')
            eq 'abc' )
        and ( $trade->first_child('event')->first_child('subevent')
            ->att('narattive') eq 'def' )
        )
    {
        if ( not defined $max_version_of{$ref}
            or $version >= $max_version_of{$ref} )
        {
           #this version is higher, so anything lower is redundant - remove it
            @{ $best_version_of{$ref} } = ();
        }
        push( @{ $best_version_of{$ref} }, $trade );
        $max_version_of{$ref} = $version;
    }
    $trade->purge;
    #can omit this, it'll just print how 'big' the hash is getting.
    print "Hash size: ". %best_version_of."\n";
}

What this does is still purge as it goes, but slowly fills up %best_version_of. It might still have a big memory footprint though - it depends rather a lot on the ratio of 'keep' vs. 'discard'.
I'm afraid there's just no optimal solution - to figure out which version is 'newest' you have to run through the file twice, and either you do that at expense of memory consumption, or you do so at the expense of disk IO.
(And I think I have to offer a caveat - this won't produce 'valid' XML, because the root node <STOCKEXT> will be discarded. Putting that at the start of $out and </STOCKEXT> at the end will solve that though).


text:
Q: Why is JGroups on Android using IPv6 to connect? From an Android device, I'm attempting to set up a tunnel to a Gossip router on the local network. I'm using this as the config:
<config xmlns="urn:org:jgroups"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="urn:org:jgroups http://www.jgroups.org/schema/JGroups-3.4.xsd">
    <TUNNEL gossip_router_hosts="${jgroups.tunnel.gossip_router_hosts:10.20.30.152[12001]}"/>
</config>

With code like this:
channel = JChannel(context.getAssets().open("jgroups.xml"))
channel.setReceiver(this)
channel.connect("MyGroup")

However, the app is attempting to connect via IPv6 by default, which doesn't appear to be working:
20096:connect(41, {sa_family=AF_INET6, sin6_port=htons(12001), inet_pton(AF_INET6, "::ffff:10.20.30.152", &sin6_addr), sin6_flowinfo=htonl(0), sin6_scope_id=0}, 28) = -1 ENETUNREACH (Network is unreachable)

This occurs even when I remove any IPv6 addresses from the network interface. I understand that there is a JVM flag for favoring IPv4, but I believe this is not applicable to Android. Setting options via adb isn't going to be a good solution either.
Is there another way to force JGroups to use IPv4 for connecting? Or is there some other route to a fix?
I've tested this on Android 8.0 and see the behavior with JGroups versions 4.1.6 and 3.6.19.

A: This is a weird config! Are you sure, you want to have a protocol stack with only TUNNEL in it?
If so, then I guess gossip_router_hosts needs to point to an IPv6 address.


text:
Q: For $\triangle ABC$, show that $ac\cos B+ab\cos C-bc\cos A-a^2 \le \frac{c^2}{8\cos^2(90^\circ-C)}$
Triangle $\triangle ABC$ has sides $a$, $b$, and $c$, and circumradius $R$. Prove that
$$ac \cos B + ab \cos C - bc \cos A - a^2 \le \frac{c^2}{8\cos^2(90^\circ - C)}$$
When does equality occur?

I came across this question in a different forum and I thought it was interesting. I made a bit of progress but not much: I changed $R^2$ to the fraction in the inequality. I think that there is probably another use of Law of Sines or Law of Cosines but I can't find one.
Edit: A lot of people have questions about if the problem is right; here is the original problem:
Triangle $\triangle ABC$ has sides $a$, $b$, and $c$, and circumradius $R$. Prove that
$b^2 + c^2 - a^2 \ge -R^2$
When does equality occur?

A: Id est, by the law of cosines we need to prove that:
$$\frac{a^2+c^2-b^2}{2}+\frac{a^2+b^2-c^2}{2}-\frac{b^2+c^2-a^2}{2}-a^2\leq\frac{c^2}{8\left(\frac{2S}{ab}\right)^2},$$
where $S=\frac{1}{4}\sqrt{\sum\limits_{cyc}(2a^2b^2-a^4)}$.
Thus, we need to prove that
$$b^2+c^2-a^2+\frac{a^2b^2c^2}{\sum\limits_{cyc}(2a^2b^2-a^4)}\geq0.$$
Now, let $a=y+z$, $b=x+z$ and $c=x+y$.
Thus, $x$, $y$ and $z$ are positives and we need to prove that:
$$2(x^2+xy+xz-yz)+\frac{\prod\limits_{cyc}(x+y)^2}{16xyz(x+y+z)}$$ or
$$(y^2+34yz+z^2)x^4+2(y^3+35yz+35y^2z^2+z^4)x^3+$$
$$+(y^4+38y^3z+42y^2z^2+38yz^3+z^4)x^2+$$
$$+2yz(y^3-13y^2z-13yz^2+z^3)x+y^2z^2(y+z)^2\geq0.$$
Now, let $x^4=t\cdot\frac{y^2z^2(y^2+10yz+z^2)}{12}.$
Thus, since $$y^2+34yz+z^2\geq36\sqrt[3]{\frac{y^2z^2(y^2+10yz+z^2)}{12}},$$
$$2(y^3+35y^2z+35yz^2+z^3)\geq144\sqrt{\frac{y^2z^2(y^2+10yz+z^2)}{12}},$$
$$y^4+38y^3z+42y^2z^2+38yz^3+z^4\geq120\sqrt[3]{\left(\frac{y^2z^2(y^2+10yz+z^2)}{12}\right)^2},$$
$$2yz(y^3-13y^2z-13yz^2+z^3)\geq-48\sqrt[6]{\left(\frac{y^2z^2(y^2+10yz+z^2)}{12}\right)^5}$$ and $$y^2z^2(y+z)^2\geq4\cdot\frac{y^2z^2(y^2+10yz+z^2)}{12},$$
it's enough to prove that:
$$36t^4+144t^3+120t^2-48t+4\geq0$$ or
$$(3t^2+6t-1)^2\geq0$$ and we are done!
The equality occurs for $t=\frac{2}{\sqrt3}-1$ and, for example, for $y=z=1$, which gives $x=\frac{2}{\sqrt3}-1$ and we got a triangle with measured angles $30^{\circ}$, $30^{\circ}$ and $120^{\circ}.$

A: Answer to the second question (equality).

Triangle $ABC$ has sides $a$, $b$, and $c$, corresponding angles
$\alpha,\beta,\gamma$,  semiperimeter $\rho$, inradius $r$ and
circumradius $R$.  Prove that
\begin{align} R^2-a^2+b^2+c^2\ge0\tag{1}\label{1}. \end{align}
When does equality occur?

By dividing \eqref{1} by $R^2$, we have
\begin{align}
1-4\sin^2\alpha+4\sin^2\beta+4\sin^2\gamma&\ge0
\tag{2}\label{2}
.
\end{align}
It's easy to verify that \eqref{2} becomes an equality
for $\alpha=120^\circ,\beta=\gamma=30^\circ$.
In other words,
\eqref{1} becomes an equality
for an isosceles triangle with $\alpha=120^\circ$.


text:
Q: Django App to open github issues on server 500 I am working on a Django project and, so far, we are receiving e-mails when a Server Error 500 happens in our backend. However, as we are a team of developers, we would like to open Github Issues instead of sending these e-mails. We have our project on Github of course.
I have been searching for an existing Django App that we could reuse but unfortunately I did not find any integrating such functionality.
Does anyone know if there is such Django application? The idea seems pretty simple and I am surprised i could not find any application available for this purpose.
Moreover, a search on django packages does not show many results...
Thanks in advance


text:
Q: Rust program works on dev build but segfaults on release build I've written a wrapper for a camera library in Rust that commands and operates a 16-bit camera, and also saves an image to file, using bindgen. Once I command an exposure to start (basically telling the camera to take an image), I can grab the image using a function of the form:
pub fn GetQHYCCDSingleFrame(
handle: *mut qhyccd_handle,
w: *mut u32,
...,
imgdata: *mut u16,) -> u32 //(u32 is a retval)

In C++, this function was:
uint32_t STDCALL GetQHYCCDSingleFrame(qhyccd_handle: *handle, ..., uint8_t *imgdata)

In C++, I can pass in a buffer of the form imgdata = new unsigned char[length_buffer] and the function would fill the buffer with image data from the camera.
In Rust, similarly, I can pass in a mut_ptr of a buffer in the form of a Vec: let mut buffer: Vec<u16> = vec![0u16; length_buffer].
Currently, the way I have structured the code is that there is a main struct, with settings such as the width and height of image, the camera handle, and others, including the image buffer. The struct has been initialized as a mut as:
let mut main_settings = MainSettings {
width: 9600,
...,
buffer: vec![0u16; length_buffer],
}

And when passing it to the GetQHYCCDSingleFrame function, I pass it accordingly:
let retval = unsafe { GetQHYCCDSingleFrame(main_settings.cam_handle, ..., main_settings.image_buffer.as_mut_ptr()) };

This code works perfectly when I build the program with cargo build or cargo build --release and run using cargo run or cargo run --release. The program starts the exposure, waits until the exposure is done, and then "gets" the frame and populates the buffer with image data correctly.
However, initially when I was writing the program, I had mistakenly declared the GetQHYCCDSingleFrame function as:
pub fn GetQHYCCDSingleFrame(
handle: *mut qhyccd_handle,
w: *mut u32,
...,
imgdata: &mut [u16],) -> u32 //(u32 is a retval)

(Note the change in imgdata type from *mut u16 to &mut [u16]).
When I passed in the same previous buffer as a slice and not a pointer:
let retval = unsafe { GetQHYCCDSingleFrame(main_settings.cam_handle, ..., &mut main_settings.image_buffer) };

the program worked perfectly when I built it with cargo build and ran using cargo run (dev build with 0 optimizations). The function and call worked, and the image buffer populated. However, the program segfaulted at GetQHYCCDSingleFrame when I built it using cargo build --release or ran it using cargo run --release  (release build with opt-level = 3).
Using rust-gdb, the segfault error was:
Thread 1 "qsc" received signal SIGSEGV, Segmentation fault.
_memmove_sse2_unaligned_erms()
at ../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:538
538
../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S: No such file or directory.

I haven't had much experience with Rust optimizations, and don't quite get what optimizations Rust is doing to cause the program to segfault when it runs perfectly with no optimizations. I do understand the correct thing to do is to send in a mut_ptr as I do now, and everything works, but looking back, I would like to understand why the previous erroneous program worked but only in dev build and not release build? Is there a possibility it might be understanding the context in the C++ code the requirement there? Or is it something else going on?
If any more information might help understand, I'd be more than happy to provide that as well. Thanks!

A: Your FFI-function signature is invalid because you use invalid ABI:
pub fn GetQHYCCDSingleFrame(
handle: *mut qhyccd_handle,
w: *mut u32,
...,
imgdata: *mut u16,) -> u32 //(u32 is a retval)

You should read about FFI first.
https://doc.rust-lang.org/nomicon/ffi.html
https://doc.rust-lang.org/reference/items/external-blocks.html
By default, Rust uses "C" ABI for external functions but you function should use stdcall ABI (assuming by your C++ code). You can read more about this.
E.g.
extern "stdcall" {
 pub fn GetQHYCCDSingleFrame(
   handle: *mut qhyccd_handle,
   w: *mut u32,
   ...,
   imgdata: *mut u16,) -> u32;
}


text:
Q: Unfamiliar output of FullSimplify I got the following output of FullSimplify, when expecting to get "0".

I found no explanation of this output here.
 Could you please explain, what it means? That my expression equals zero when the condition $m^4 \Omega ^2 \sin ^2(\theta )+2 m r<r^2$ holds and that big fraction otherwise? Or maybe something else?

A:
my expression equals zero when the condition m4Ω2sin2(θ)+2mr<r2 holds and that big fraction otherwise?

Your assumption is correct. What you see is the typeset OutputForm of Piecewise.
Normally you can simply highlight an expression or a keyword, hit F1 and see the documentation page for it, but in this case it doesn't seem to work, so it's understandably unclear.
What you can do, however, is to run FullForm@% after you get a result like that. The output will be something like
Piecewise[ (* stuff *) ]

then you can realize that you need to look up Piecewise.


text:
Q: inner product and hermitian scalar product suppose $\underline x,\underline y\in\mathbb C^{n\times 1}$ then because the two vectors are in complex vector field, the definition of their inner product will be:
$$\langle\underline x,\underline y\rangle=\sum_{i=1}^n x_iy_i^*\qquad\text{* represents conjugate}$$
then it seems that the definition for hermitian scalar product of these two vectors is the same
$$\langle\underline x|\underline y\rangle=\underline x^T.\underline y^*=\sum_{i=1}^n x_iy_i^*\qquad\text{T represents transpose}$$
Are inner product and hermitian scalar product the same concept in vector spaces defined on complex numbers field?

A: A scalar product is just another name for inner product. Let V be a complex vector space. A Hermitian inner
product on V is any function
$$\langle ,  \rangle : V × V \rightarrow \mathbb{C},$$
that satisfies these axioms:

*

*$$\langle u, v \rangle  = \langle v, u \rangle $$

*$$\langle u + v, w \rangle  = \langle u, w \rangle  + \langle v, w \rangle  \text{ and}$$
$$\langle u, v + w \rangle  = \langle u, v \rangle  + \langle u, w \rangle $$

*$$\langle cu, v \rangle  = \overline{c} \langle u, v \rangle  \text{ and}$$
$$\langle u, cv \rangle  = c\langle u, v \rangle .$$

*$\langle u, u \rangle $ is a non-negative real number and $\langle u, u \rangle  = 0$ if and only if $\langle u = 0 \rangle $.
What you've defined is just an example of a Hermitian inner product.


text:
Q: After using where condition how to get single column values without repeated values in a table in laravel 5.4 I'm using Laravel 5.4. I have three tables like below.
users table
id          name         username

1           krish        krish@gmail.com

2           kaviz        kaviz@gmail.com

roles table
id      role      sub_role

1       admin     default

2       support   default

3       Hr        default

3       admin     admin_1

roles_users
id    user id  role id

1     1        1

2     1        2

3     1        3

3     2        2

My Controller
$users=Rolesusers::all();
foreach($users as $user)
{
    $user_names[]=User::where('id', '=', $user->user_id)->groupby('name')->select('name')->get();
}
return $user_name;

My result
[
  {
    "name": "krish"
  }
  {
    "name": "krish"
  }
  {
    "name": "krish"
  }
  {
    "name": "kaviz"
  }
]

but I need a result without repeated values, like this:
[
  {
    "name": "krish"
  }
  {
    "name": "kaviz"
  }
]

A: I think your query is running for each $users value that's why it store value for each query you should change your logic or at the end you use array_unique() function in php hope this will help you

A: The where clause returns a collection, so you can utilize the unique() method on collections.
In your case
  foreach($users as $user)
  {
      $user_names = User::where('id', '=', $user->user_id)->groupby('name')->select('name')->get();

  }

  $user_names->unique('name');

  dd($user_names);

Or, Using arrays
  foreach($users as $user)
  {
      $user_names[] = User::where('id', '=', $user->user_id)->groupby('name')->select('name')->get();

  }
 $user_names = array_unique($user_names);
 print_r($user_names);

see array_unique or eloquent collection unique()

A: I think you should do your 'groupBy' in your Rolesusers. Please try the below to answer your query,
    $users = Rolesusers::select('user_id')->groupBy('user_id')->toArray();
    $user_names = User::select('name')->whereIn('id', $users)->get();
    return $user_name;

Please note that in your code, the query runs in a loop which should be never done. Please do not run a query inside a loop.


text:
Q: Clarification of text from the book "Elements of statistical learning" Matrices are represented by bold uppercase letters; for example, a set of N input p-vectors $x_i$, $i = 1, \dots ,N$ would be represented by the $N×p$ matrix $X$. In general, vectors will not be bold, except when they have N
components; this convention distinguishes a p-vector of inputs $x_i$ for the  $i^{th}$ observation from the N-vector $\textbf{x}_j$ consisting of all the observations on variable $X_j$. Since all vectors are assumed to be column vectors, the $i^{th}$ row of $X$ is $x^T_i$, the vector transpose of $x_i$.
The above text is taken from chapter 2 page 10, I understand the first sentence, data is represented in a matrix where there are p variables and N observations. What I don't understand is this bit:

this convention distinguishes a p-vector of inputs $x_i$ for the  $i^{th}$ observation from the N-vector $\textbf{x}_j$ consisting of all the observations on variable $X_j$

Can someone please clarify this?

A: Let's start with the understanding of what $X \in R^{\text{N x p}}$ is:
It is a matrix with dimension $\text{N x p}$, which means that $X$ has $N$ rows and $p$ columns.
Now what is $N$ ?  - The number of observations.
So what is $p$ ? - The number of variables or features.
Further, recall that each of the N rows corresponds to a singe observation, giving the p variables/features used in a learning algorithm. Therefore, the i-th row vector stores all values of features  for individual i and is of dimension $R^\text{1 x p}$
The j-th column-vector therefore corresponds to the vaues of variable j for each of the $N$ observations and is of dimension $R^\text{N x 1}$
With the last sentence they literally say: column-vectors are denoted in bold, row-vectors not.


text:
Q: AWS lambda function to restart one of the ECS cluster service We are deploying multiple service in ECS cluster with fargate, On the front end we are using nginx service. On the backend some services are getting deployed frequently. Once any of the backend service deployed we manually need to update nginx service forcefully. Do we have any approach to update only nginx service forcefully when any of the new service deployed successfully?
How we can achieve this ? using lambda or cloudwatch....
Any help is appreciated, Thanks in advance

A: When the backend Services are updated you can use cloud watch to trigger a lambda. This lambda can use the AWS SDK to to restart the Nginx container service/task. You could also version your Nginx container along with all your backend services so that that the a new Nginx image is push up when your backend changes and the task definition is changed contains the new image. Providing your using AWS ECS Service it can update it self.
See here for more information: https://docs.aws.amazon.com/AmazonECS/latest/developerguide/update-service.html


text:
Q: Proof check regarding complete space with seminorm I just came across a simple Functional Analysis exercise which I just dont know if I correctly solved. The problem states:
Consider the space $C(\mathbb{R}):=\{f: \mathbb{R} \longrightarrow \mathbb{C}; f$ continuous$\}$ equipped with the seminorm:
$$
p_{j}(f)=\sup \{|f(x)| ;|x| \leq j\}, \quad j \in \mathbb{N}
$$
Prove that:
1. Let $f_{n} \in C(\mathbb{R}), n \in \mathbb{N}$, be defined by $f_{n}(x)=x-n+|x-n|, x \in \mathbb{R}$. Show that $\lim _{n \rightarrow \infty} f_{n}=0$.
2. Show that $C(\mathbb{R})$ is a complete metric space.
Regarding Completeness
Let $\left(f_{n}\right)_{n}$ be a Cauchy sequence in $C(\mathbb{R})$. Now, noting that:
$$
H=\left\{\left|f_{n}(x)-f_{m}(x)\right| ;|x| \leqslant j\right\} \subseteq G \doteq\left\{\left|f_{n}(x)-f_{m}(x)\right|x \in \mathbb{R}\right\}
$$
We conclude that $\sup H \leq \sup G$. Noting that $\sup G$ is precisely the $\sup$ norm, means we have:
$$
0 \leq p_{j}\left(f_{n}-f_{m}\right) \leqslant\left\|f_{n}-f_{m}\right\|_{\infty}
$$
Since $C(\mathbb{R})$ is complete with respect to the sup norm, we have that our initial Cauchy sequence $\left(f_{n}\right)_{n}$ converges to a function $f$, which should be continuous as well, with respect to the $\sup$ norm. This implies that there exists $n_{0}$ such that for $n, m > n_{0}$, we have that $\left\|f_{n}-f_{m}\right\|_{\infty} < \epsilon$, which implies:
$$
0 \leq p_{j}\left(f_{n}-f_{m}\right) \leqslant\left\|f_{n}-f_{m}\right\|_{\infty} < \epsilon
$$
Consequently, $p_{j}\left(f_{n}-f_{m}\right)$ is a Cauchy sequence which converges to $f$ the same continuous function, turning our initial space equipped with the seminorm $p_{j}$ complete.
Regarding the limit $\lim _{n \rightarrow \infty} f_{n}=0$:
We want to show that, given $\epsilon > 0$, there exists $n_{0}$ such that for $n > n_{0} \implies p_{j}(f_{n}, 0) < \epsilon$. Since $\mathbb{N}$ is unbounded, there exists $N$ such that for every $n > N$, the difference $|x-n| = n-x$. This implies that:
$$
\begin{aligned}
p_{j}(f_{n}, 0) & \doteq \sup \{|x-n+|x-n|| ;|x| \leqslant j\}=\\
&=\sup \{|0| ;|x| \leqslant j \mid=0<\varepsilon
\end{aligned}
$$
which proves that $\lim _{n \rightarrow \infty} f_{n}=0$ with respect to the seminorm $p_{j}$.
Questions:

*

*Are the arguments ok for each of the questions? If no, what is missing? Is it well written?

Thanks in advance, Lucas


text:
Q: Why does my angular resource ignore the action-specific url? I have the following angular code:
var app = angular.module('app', ['ngResource']);

app.factory('Post', function ($resource) {
    return $resource('/post', {}, {
        query: { method: 'GET', url: '/post/get/:id', params: { id: '@id' } },
        save: { method: 'POST', url: '/post/addorupdate/:id', params: { id: '@id' } },
        delete: { method: 'POST', url: '/post/delete/:id', params: { id: '@id' } }
    });
});

app.controller('appController', function ($scope, Post) {
    $scope.createPost = function () {
        var post = new Post({
            title: "Test post",
            body: "Test body.<br/ >Yay!"
        });
        post.$save();
    };
});

The markup looks like this:
<body data-ng-app="app">
    <div data-ng-controller="appController">
        <button ng-click="createPost()">Create Post</button>
    </div>
</body>

When I click the button it tries to do a POST to the server, but to the original URL and not the action-specific URL. The URL from the request looks like this:
http://localhost:8080/post?id=undefined

Any idea why it's trying to POST to just /post? Also, any idea why id=undefined? In other examples it seems like ?id=blah just isn't included in the request if the ID isn't specified. Thank you in advance.

A: This is a bug in the current version (1.0.8) of AngularJS as of this writing. ngResource is ignoring the url property on action overrides. It was fixed in version 1.1.4 and the fix is present in the latest release candidate (1.2.0).


text:
Q: Customizing Ubuntu to look like mac You should see my setup first.
I customized Gnome to look like mac

I even changed the name to macOS catalina but I don't know how to change the
Host> HP Slim Desktop 290-p0xxx

and that tiny ubuntu icon in Command prompt.I want to change that icon to "apple" icon.I am using "oh my zsh" with powerlevel10k.
Can anyone help me here?

A: To replace the Ubuntu logo with Apple logo in Powerlevel10k prompt you need to add the following parameter to ~/.p10k.zsh:
typeset -g POWERLEVEL9K_LINUX_UBUNTU_ICON='\uF179'


text:
Q: Is there any way to get user input within a loop without pausing the loop to ask for it? I have a while loop that displays the the current time in two different formats, then clears the screen, adds a second and then redisplays the time again.
I would like for this loop to continue until the user hits a key, and then it goes into a separate loop that asks for user input.  If I use cin it pauses the entire loop waiting for the user input.  Is there a way to avoid pausing the loop to get user input?

A: spawn 2 threads ... Keep the loop running in first thread. Make the second thread wait for user input. Once the second thread returns exit first thread and continue with second loop on second thread ..


text:
Q: How do I get embed codes from vshare.io responsive? How do I get this iframe code responsive?

Any other iframe code from other video hosters are working responsively on my wordpress site.
Width and height are set in the source link, I guess this is the problem.
Do you have any hint how solve this?


text:
Q: why this graphql is showing TypeError: (...) is undefined Hi I am trying to show featured post on blog with graphql, why it's not working?
I want to show first post with different style - like featured and rest like a post list so I try to create 2 diffrent graphql but I am stuck with it.
export default function Featured() {
  return (
    <StaticQuery
      query={graphql`
              query HeadingQuery {
                allMarkdownRemark {
                  edges {
                    node {
                      frontmatter {
                        title
                      }
                    }
                  }
                }
              }

      `}
      render={data=> (

{data.allMarkdownRemark.edges.node.frontmatter.title}

      )}
    />
  )
}

there is TypeError: (...) is undefined

A: Is your query working in the GraphQL playground (localhost:8000/___graphql)?
In addition, your render method has an error. edges, is an array, so you should loop through them to show your content or enter position by position specifically:

{data.allMarkdownRemark.edges[0].node.frontmatter.title}


text:
Q: C#: Compare two list values having time in string format and extract only which is larger value I have two lists which has time in string format. I need to compare these two and extract the larger values in to another list.
List 1
"00:00"
"00:15"
"00:30"
"00:45"
....
"23:45"

List 2
"00:15"
"15:30"
"15:45"

now List 3 should contain all the values from list 1 which are larger than each value when compared to List 2.

A: if I'm correct you want to compare each element witch are at the same position.
I whould go with:
        List<string> times1 = new List<string>(new string[] { "00:15", "01:01" });
        List<string> times2 = new List<string>(new string[] { "00:16", "01:00" });
        List<string> result = new List<string>();
        for (int i = 0; i < times1.Count; i++)
            {
            if (int.Parse(times1[i].Substring(0, 2)) > int.Parse(times2[i].Substring(0, 2))) //check hours
                {
                result.Add(times1[i]);
                }
            else
                {
                if (int.Parse(times1[i].Substring(0, 2)) < int.Parse(times2[i].Substring(0, 2)))
                    {
                    result.Add(times2[i]);
                    }
                else  //check minuts
                    {
                    if (int.Parse(times1[i].Substring(3, 2)) > int.Parse(times2[i].Substring(3, 2)))
                        {
                        result.Add(times1[i]);
                        }
                    else
                        {
                        if (int.Parse(times1[i].Substring(3, 2)) <= int.Parse(times2[i].Substring(3, 2)))
                            {
                            result.Add(times2[i]);
                            }
                        }
                    }
                }
            }

Comparing hour first and minuts if necesary because it's only time.
If strings were date/time I whould DateTime vars to make conversion.

A: I think this is what you want
 var List3 = List1.Where(c => {Array.TrueForAll(List2.ToArray(), value => {
                                  c > value }}
                               );


text:
Q: Using RDA in R with just one dataset This is possibly a stupid question, but I was told to do a Redundancy Analysis in R (using the package Vegan) to test the differences between different groups in my data. However I only have one dataset (roughly comparable to the Iris dataset (https://en.wikipedia.org/wiki/Iris_flower_data_set)), and everything I have found on RDA seems to need two matching sets. Did I mishear or misunderstand, or is there something else going on here?

A: As far as the underlying statistics are concerned, you have two data matrices;

*

*the four morphological variables in the iris data set

*a single categorical predictor variable or constraint
In vegan using rda() for this and the iris example data you'd do:
library("vegan")
iris.d <- iris[, 1:4]
ord <- rda(iris.d ~ Species, data = iris)
ord

set.seed(1)
anova(ord)

The permutation test, tests for differences between species.
> anova(ord)
Permutation test for rda under reduced model
Permutation: free
Number of permutations: 999

Model: rda(formula = iris.d ~ Species, data = iris)
          Df Variance      F Pr(>F)
Model      2   3.9736 487.33  0.001 ***
Residual 147   0.5993
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

You might also look at adonis(), which should do the same thing here as RDA but from a different view point:
> adonis(iris.d ~ Species, data = iris)

Call:
adonis(formula = iris.d ~ Species, data = iris)

Permutation: free
Number of permutations: 999

Terms added sequentially (first to last)

           Df SumsOfSqs MeanSqs F.Model      R2 Pr(>F)
Species     2   2.31730 1.15865  532.74 0.87876  0.001 ***
Residuals 147   0.31971 0.00217         0.12124
Total     149   2.63701                 1.00000
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

(For some reason that is a lot slower...)
Also see betadisper() as you might detect a difference in means (centroids) using these methods where that may be due at least in part to differences in variance (dispersion).


text:
Q: You have a usable connection already I downloaded and installed visual studio 2017 community edition and i installed mysql community 8.0.15. In visual studio 2017 data connections work fine for mysql i can store data through visual studio. But when i create data source after selecting the table it shows some updating commands could not be generated automatically database returned following error : you have a usable connection. Then it shows another error could not retrieve schema from table . I had tried other steps by downgrading connector and mysql for visual studio but it does not work.
This is the first error:

This is the second error after clicking ok:

A: Me too. To confirm, with Visual Studio 2017 vb.net I finally got it to connect to a remote MySql database without errors using the slightly newer MYSQL for Visual Studio 1.2.8 and that same older connector vs 6.9.8. (I also had it working well with the free dotConnect for MySQL 8.12 Express). Tables load successfully into a Datagridview, zero issues. Well one proviso. I can only add one table on adding a datasource to a Datagridview. However you can add more tables in Design View later on.
Hope that helps someone else.


text:
Q: CSS automatically fitting multiple divs to span to the size of a page? so I need multiple lined divs to span across my page and then do the same thing when another div is added. But I'm not sure how I can achieve this. an example of this is:
[ div 1][ div 2][ div 3][ div 4][ div 5]
And then when another div is added it won't stack below, but decrease the size of the divs to fit into the space.

A: You should use display: table-cell.
See: http://jsfiddle.net/2X73J/
The browser support is excellent: http://caniuse.com/css-table

div 1

    ..

.multiContainer {
    width: 100%;
    display: table;
    background: #ccc
}
.multiContainer > div {
    display: table-cell;
    border: 1px dashed #f0f
}

A: try this
.Someclass div{
    border:1px solid #000;
    height:20px;
    width:100px;
    display:inline-block;
    margin:0;
    }

div 1

div 2

div 3

div 4


text:
Q: My exception handing is not working When a user enters a string the program breaks and my exception handling is not picking up this problem. What am I doing wrong ?
int number;

Console.WriteLine("Please enter your age");

number = Convert.ToInt32(Console.ReadLine());

try
{
    if (number >= 18)
     Console.WriteLine("You are old enough to enter");
    else if (number < 18)
     Console.WriteLine("You are not old enough to enter");
}
catch
{
    Console.WriteLine("Only enter a number");
}

Console.ReadLine();

A: You have to put
number = Convert.ToInt32(Console.ReadLine());

inside Try/Catch too. You are reading a string and trying to convert it to int. When it's not possible Convert.ToInt32 will throw an exception.
    try
    {
        number = Convert.ToInt32(Console.ReadLine());

        if (number >= 18)
            Console.WriteLine("You are old enough to enter");
        else if (number < 18)
            Console.WriteLine("You are not old enough to enter");
    }
    catch
    {
        Console.WriteLine("Only enter a number");
    }

    Console.ReadLine();

Also, would recommend you using int.TryParse(). In that case, you can check the result without catching an exception.

A: You must edit your code to place try .. catch on a right place, you placed this line:
number = Convert.ToInt32(Console.ReadLine());
out of try .. catch block and that's reason why your exception is not handled, check the code below:
{
      try
      {
        int number;

        Console.WriteLine("Please enter your age");
        number = Convert.ToInt32(Console.ReadLine());
        if (number >= 18)
        {
          Console.WriteLine("You are old enough to enter");
        }
        else if(number < 18)
        {
          Console.WriteLine("You are not old enough to enter");
        }
        catch
        {
            Console.WriteLine("Only enter a number");

        }

        Console.ReadLine();
}

More about try..catch HERE.

A: number = Convert.ToInt32(Console.ReadLine());

Add this in the try block


text:
Q: Invalid facebook key hash when app is published on playstore I recently published my app on playstore i thought everything is fine suddenly a pop up error message showed up when trying to sign in with facebook:
Invalid key hash : the key hash ### doesn t match any stored keys hashes..
But when releasing the app on my phone or emulator it works fine.
What i did is getting the hash key in two methods:
1- Using code
try {
    PackageInfo info = getPackageManager().getPackageInfo(
                "com.example.packagename",
                PackageManager.GET_SIGNATURES);
    for (Signature signature : info.signatures) {
        MessageDigest md = MessageDigest.getInstance("SHA");
        md.update(signature.toByteArray());
        Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
    }
} catch (NameNotFoundException e) {

} catch (NoSuchAlgorithmException e) {

}

2- Using command prompt
keytool -exportcert -alias alahedclubsuperfinal -keystore "ahedclubsuperfinal.jks" | "C:\GnuWin32\bin\openssl" sha1 -bnary | "C:\GnuWin32\bin\openssl" base64

In both ways i am getting same hash key and i set it on facebook dev account.
But what i am still getting this error when app is published on playstore?


text:
Q: MYSQL - Error Code: 1242 subquery returns more than 1 rows The query is trying to return all the roles from lprovider table for a given provider if his role is not ExternalHealthCoach. If his role is ExternalHealthCoach then return ExternalHealthCoach as provider's role.
select
 role
from lprovider
where provider_id = 63 and
role in (select case when role = 'ExternalHealthCoach' then role
                else (select distinct role from lprovider) end from lprovider);

Sample records in Lprovider table:
role_column
ExternalHealthCoach
InternalHealthCoach
Doctor
FrontDesk
Admin
Co-ordinator
If the provider_id = X and if he is not ExternalHealthCoach then I want to return all the roles not a just only doctor.
Ex:
If provider_id = 63 and his role = doctor then the query should return all the roles in the lprovider table. i.e.
ExternalHealthCoach, InternalHealthCoach, Doctor, FrontDesk, Admin, Co-ordinator
But getting an error while executing.
Error Code: 1242 subquery returns more than 1 rows
Thanks in advance.

A: A case *expression` returns one value, not a list of values.
I think the logic you want is:
select l.role
from lprovider l
where l.provider_id = 63 and
      (l.role = 'Rejuvalyte-ExternalHealthCoach' or
       l.role in (select l2.role from lprovider l2)
      );

Note that select distinct is not needed when using in with a subquery.
This logic is still a bit confusing.  I don't think the in part of the condition does anything.  You can just remove it.


text:
Q: kubernetes cluster initilization issue I am trying to create a Kubernetes cluster using kubeadm in ubuntu 18.04
by following the link but getting errors while using initializing the cluster as below:
kubeadm init --apiserver-advertise-address=192.168.x.x --pod-network-cidr=192.168.0.0/16
This can take up to 4m0s
[kubelet-check] Initial timeout of 40s passed.`

Unfortunately, an error has occurred:
`timed out waiting for the condition`

This error is likely caused by:
- The kubelet is not running
- The kubelet is unhealthy due to a misconfiguration of the node in some way (required cgroups disabled)

If you are on a systemd-powered system, you can try to troubleshoot the error wi th the following commands:
- 'systemctl status kubelet'
- 'journalctl -xeu kubelet'
Additionally, a control plane component may have crashed or exited when started by the container runtime.
To troubleshoot, list all containers using your preferred container runtimes CLI , e.g. docker.
Here is one example how you may list all Kubernetes containers running in docker :
- 'docker ps -a | grep kube | grep -v pause'
Once you have found the failing container, you can inspect its logs with :
- 'docker logs CONTAINERID'
error execution phase wait-control-plane: couldn't initialize a Kubernetes cluster
To see the stack trace of this error execute with --v=5 or higher

I looked the error, in google and got a link below https://github.com/kubernetes/kubernetes/issues/83225
but this did not solve my problem either.
Please help with this.
Thank you in advance.
I have the images downloaded as below.
k8s.gcr.io/kube-proxy                v1.20.2           43154ddb57a8   12 days ago     118MB
k8s.gcr.io/kube-controller-manager   v1.20.2           a27166429d98   12 days ago     116MB
k8s.gcr.io/kube-apiserver            v1.20.2           a8c2fdb8bf76   12 days ago     122MB
k8s.gcr.io/kube-scheduler            v1.20.2           ed2c44fbdd78   12 days ago     46.4MB
k8s.gcr.io/etcd                      3.4.13-0          0369cf4303ff   5 months ago    253MB
k8s.gcr.io/coredns                   1.7.0             bfe3a36ebd25   7 months ago    45.2MB
k8s.gcr.io/pause                     3.2               80d28bedfe5d   11 months ago   683kB


text:
Q: SuiteCRM v7.10.29 Custom API v4.1 I am creating a custom API for SuiteCRM. When I attempt to run the new API from {CRM Home}/custom/service/v4_1_custom I receive an 'HTTP ERROR 500'. There are not errors in the error_log file or the SuiteCRM.log file.
I have followed the method in the following two url's
https://fayebsg.com/2013/05/extending-the-sugarcrm-api-updating-dropdowns/
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_10.0/Integration/Web_Services/Legacy_API/Extending_Web_Services/
registry.php

<?php

require_once('service/v4_1/registry.php');
class registry_v4_1_custom extends registry_v4_1
{
    protected function registerFunction()
    {

        parent::registerFunction();
        $this->serviceClass->registerFunction('test', array(), array());

    }
}

SugarWebServicesImplv4_1_custom.php

<?php

if(!defined('sugarEntry'))define('sugarEntry', true);

require_once('service/v4_1/SugarWebServiceImplv4_1.php');

class SugarWebServiceImplv4_1_custom extends SugarWebServiceImplv4_1
{
    /**
     * @return string
     */
    public function test()
    {

        LoggerManager::getLogger()->warn('SugerWebServiceImplv4_1_custom test()');

        return ("Test Worked");
    }   // test
}   // SugarWebServiceImplv4_1_custom

A: I found the answer to this issue.
In the file {SuiteCRM}/include/entryPoint.php there are many files that are included thru require_once. In this list of require_once files, there were 4 files that were set as require not require_once. These were classes and therefore could not be included a second time. I changed these to require_once and the HTTP Error 500 went away and the custom APIs started working.


text:
Q: Why trace is more natural than (preferred to) determinant for smooth map $f:M\to N$? Cross-post from MSE.
For a continuous map $f:(M,g)\to (N,h)$, between Riemannian manifolds $(M,g)$ and $(N,h)$ we can pullback $h$ by $f$. Most experts take the trace from this new tensor and work with it, i.e. $\operatorname{tr}_g(f^*h)$ which I think is equal to $\lvert df\rvert^2$. I think there is a simple reason from Linear Algebra that perhaps I missed it that

Question: why they use trace (e.g. see this, this and this posts) and not determinant or any other operator?

One primary reason is that it is similar to $\operatorname{tr} A^tB$ that is an inner product over $n\times n$ matrices.
In the case of energy density of harmonic maps, $e(f)\mathrel{:=}\frac{1}{2}\lvert df\rvert^2$ is very natural operator because it is similar to (up to a constant $m$) the kinetic energy formula $E=\frac{1}{2}mv^2$ in physics.
But these are not sufficient to not consider the determinant (or any other operator) case. I want to know: Is the following expression meaningful and can it reveal nice properties of the space as well as trace case? or that is same as trace case?
$$K(f)\mathrel{:=}\int_M\det_g(f^*h)d\mathrm{vol}_g.$$
It is also helpful remember that the trace is $\sum_i\lambda_i$ and determinant is $\prod_i\lambda_i$.

A: It suffices to understand  the special case of a linear map $T:U\to V$ where $U,V$ are Euclidean vector spaces. (Think $U=T_pM$, $V=T_{f(p)}N$, $T=df(p)$.)
Suppose first that $n=\dim V\leq \dim U=m$.
Let $\lambda_1,\dotsc, \lambda_n, $ be the eigenvalues of the symmetric nonnegative operators $TT^*:V\to V$, multiplicities included. Then (see Lemma 1.1 in The co-area formula) there exist Euclidean coordinates $x^1,\dotsc, x^{m}$ on $U$ and Euclidean coordinates  $y^1, \dotsc, y^n$ on $V$ such that $T$ is described un these coordinates  by
$$
y^i=\sqrt{\lambda_i} x^i,\;\;\forall i=1,\dotsc, n.
$$
Denote by $g_V$ the inner product on $V$ and by $g_U$ the inner product.  Then
$$
g_V=\sum_{i=1}^n (dy^i)^2,\;\;T^* g_V= \sum_{i=1}^n \lambda_i (dx^i)^2.
$$
We deduce $\DeclareMathOperator{\tr}{tr}$
\begin{align*}
\tr_{g_U} T^*g_V&{}=\sum_i \lambda_i=\tr TT^*, \\
\det\limits_{g_U} T^*g_V&{}=0.
\end{align*}
In this case, more useful in applications is the  Jacobian of $T$, $\DeclareMathOperator{\Jac}{Jac}$
$$
\Jac(T)\mathrel{:=}\prod_{i=1}^n\lambda_i =\det T T^*.
$$
The Jacobian  of $T$ plays an important role in the coarea formula,
$$
\int_M \Jac_x(f) u(x) dV_g(x)=\int_N\left(\int_{f^{-1}(y)} u(x) dV_{f^{-1}(y)}(x)\right) dV_h(y),\;\;\forall u\in C_0(M).
$$
This contains the change-in-variables formula as a special case.
If $m=\dim  U<\dim V$, then  we can find  Euclidean  coordinates $x^1,\dotsc, x^m$ and Euclidean coordinates $y^1,\dotsc, y^n$ on $V$ such that, in these coordinates $T$ is described by
$$ y^i=\sqrt{\mu_i}x^i,\;\;\forall i=1,\dotsc, m,\;\;y_j=0,\;\;j>m,
 $$
where $\mu_1,\dotsc, \mu_m$ are the eigenvalues of the symmetric nonnegative operator $T^*T:U\to U$. (To see this apply the previous result to the map $T^*:V\to U$.)
In this case
\begin{align*}
\tr_{g_U} T^*g_V&{}=\sum_{i=1}^m \mu_i=\tr T^*T, \\
\det\nolimits_{g_U} T^*g_V&{}= \prod_{i=1}^m \mu_i=\det T^*T.
\end{align*}


text:
Q: Extracting text from PDF -Tokenize TypeError When trying to extract text from PDF's using Textract, I get a TypeError: "cannot use a string pattern on a bytes-like object". Can anyone be helpful with what might be an solution?
When I print(text), I get the text from the PDF I want extracted, though in a bit strange format. However, text[0] etc only contain numbers..?
import textract
import os
from nltk.tokenize import word_tokenize

for filename in os.listdir('Harbour PDF'):
if '.DS_Store' == filename:
    continue
filename = 'Harbour PDF/' + filename
print(filename)

text = textract.process(filename)
print(text)

tokens = word_tokenize(text)
keywords = [word for word in word_tokenize(text,'english',False)]

Error:
File "scrapePort.py", line 15, in
    tokens = word_tokenize(text)
  File "/Users/Rasmus/anaconda3/lib/python3.6/site-packages/nltk/tokenize/init.py", line 143, in word_tokenize
    sentences = [text] if preserve_line else sent_tokenize(text, language)
  File "/Users/Rasmus/anaconda3/lib/python3.6/site-packages/nltk/tokenize/init.py", line 105, in sent_tokenize
    return tokenizer.tokenize(text)
  File "/Users/Rasmus/anaconda3/lib/python3.6/site-packages/nltk/tokenize/punkt.py", line 1269, in tokenize
    return list(self.sentences_from_text(text, realign_boundaries))
  File "/Users/Rasmus/anaconda3/lib/python3.6/site-packages/nltk/tokenize/punkt.py", line 1323, in sentences_from_text
    return [text[s:e] for s, e in self.span_tokenize(text, realign_boundaries)]
  File "/Users/Rasmus/anaconda3/lib/python3.6/site-packages/nltk/tokenize/punkt.py", line 1323, in
    return [text[s:e] for s, e in self.span_tokenize(text, realign_boundaries)]
  File "/Users/Rasmus/anaconda3/lib/python3.6/site-packages/nltk/tokenize/punkt.py", line 1313, in span_tokenize
    for sl in slices:
  File "/Users/Rasmus/anaconda3/lib/python3.6/site-packages/nltk/tokenize/punkt.py", line 1354, in _realign_boundaries
    for sl1, sl2 in _pair_iter(slices):
  File "/Users/Rasmus/anaconda3/lib/python3.6/site-packages/nltk/tokenize/punkt.py", line 317, in _pair_iter
    prev = next(it)
  File "/Users/Rasmus/anaconda3/lib/python3.6/site-packages/nltk/tokenize/punkt.py", line 1327, in _slices_from_text
    for match in self._lang_vars.period_context_re().finditer(text):
TypeError: cannot use a string pattern on a bytes-like object

A: You may need to decode your data first.
text.decode("utf-8")

A: I had the same problem, Try this
 tokens = word_tokenize(text.decode("utf-8"))


text:
Q: How do I download Calibre on Ubuntu? I know nothing about code. I'd need a blow-by-blow, subtle as an atomic bomb explanation of how to download Calibre on Linux, with Ubuntu.

A: Calibre does not recommend using the versions supplied in your linux distro.
Instead go to the terminal and issue the following command.
sudo -v && wget -nv -O- https://download.calibre-ebook.com/linux-installer.sh | sudo sh /dev/stdin

Be prepared to type in your password when the sudo programs asks for it and press enter. Calibre is a complex piece of software, but it's excellent at detecting dependencies in your environment and downloading then symlinking the packages to use.
When done, just type calibre to start up this program. I've been using it for years and find it's an excellent way to manage both personal and professional files I've collected over time. Its built-in reader for epub is usually pretty good.

A: It's in the ubuntu software center.  Open the orange icon in the upper left and search for calibre.


text:
Q: How do I find my synced folder when using Vagrant to host a PostgreSQL database? As per the PostgreSQL wiki, I cloned a vagrant file preloaded with PostgreSQL onto my hard drive.
I am now trying to use that in conjunction with a .py and .sql file that I had been writing. The Vagrant documentation suggests that I should be able to cd straight into a folder called /vagrant once I have done vagrant up and vagrant ssh but whenever I try to do that, I get the following error message:
-bash: cd: /vagrant: No such file or directory
I am assuming it is something inside my Vagrantfile. The Vagrant documentation said this behaviour should happen by default, but I added in the extra line:
config.vm.synced_folder ".", "/vagrant"
But that did nothing.
So I want to know how I can access my /vagrant shared/synced folder. Can you help?

A: The Vagrantfile from https://github.com/jackdb/pg-app-dev-vm looks a bit old and still has the version 1 syntax -
You can add the missing folder within the version 2 syntax part, so Vagrantfile like
# -*- mode: ruby -*-
# vi: set ft=ruby :

$script = <<SCRIPT
echo I am provisioning...
date > /etc/vagrant_provisioned_at
SCRIPT

Vagrant.configure("2") do |config|
  config.vm.provision "shell", inline: $script
  config.vm.synced_folder  ".", "/vagrant"
end

Vagrant::Config.run do |config|
  config.vm.box = "ubuntu/trusty64"
  config.vm.box_url = "https://atlas.hashicorp.com/ubuntu/boxes/trusty64"
  config.vm.host_name = "postgresql"

  config.vm.share_folder "bootstrap", "/mnt/bootstrap", ".", :create => true
  config.vm.provision :shell, :path => "Vagrant-setup/bootstrap.sh"

  # PostgreSQL Server port forwarding
  config.vm.forward_port 5432, 15432
end

Better would be to use version2 syntax (syntax1 is obsolete for a few years now) - the following will work
# -*- mode: ruby -*-
# vi: set ft=ruby :

$script = <<SCRIPT
echo I am provisioning...
date > /etc/vagrant_provisioned_at
SCRIPT

Vagrant.configure("2") do |config|
  config.vm.provision "shell", inline: $script

  config.vm.box = "ubuntu/trusty64"
  config.vm.box_url = "https://atlas.hashicorp.com/ubuntu/boxes/trusty64"
  config.vm.host_name = "postgresql"

  config.vm.synced_folder  ".", "/mnt/bootstrap"

  config.vm.provision :shell, :path => "Vagrant-setup/bootstrap.sh"

  # PostgreSQL Server port forwarding
  config.vm.network "forwarded_port", guest: 5432, host: 15432
end

Using this you dont need to specify a /vagrant shared folder as you read its here by default


text:
Q: How to export to multiple sheets in excel from jasper report I am working on a report with iReport that have many subreports.
I want to have two other sheets in the excel file when generating the report from my application.
When searching the internet I found answers about creating a break in the report, having the option "Ignore pagination " in the subreports "true" , but it is still not clear for me.
What are my options to control how and when a new sheet is created

A: In jasper report there are different ways to achieve new sheet both in jrxml and in java code. The default behavior is to create a new sheet for every page. I will illustrated the 3 most common ways with relative problem in using them.

Ignore pagination and break element

Method
set isIgnorePagination="true" on the jasperReport tag and add
<break>
  <reportElement x="0" y="0" width="100" height="1" uuid="c5371aa4-2eb4-4ab9-8cae-39f50da3317b"/>
</break>

when you need a new sheet.
Problem: The report will not be beautiful if you export also to pdf (since its ignoring pagination)

Use the jrxml properties

Method
To avoid creating new sheet on every new page, set property
net.sf.jasperreports.export.xls.one.page.per.sheet="false"

And when you want it to create a new sheet before or after an reportElement add relative property:
net.sf.jasperreports.export.xls.break.before.row="true"
net.sf.jasperreports.export.xls.break.after.row="true"

Problem: The columns on every sheet will be the same and this can result in ugly colspan on different sheet's

Use java and controll the sheet's as you like (loading different reports)

Method
List<JasperPrint> sheets = new ArrayList<JasperPrint>();
for (int i=1;i<=8;i++){
   JasperPrint print = JasperFillManager.fillReport("subReport_" + i + ".jasper", paramMap, connection);
   sheets.add(print);
}
JRXlsxExporter exporter = new JRXlsxExporter();
exporter.setExporterInput(SimpleExporterInput.getInstance(sheets));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(new File("text.xlxs"));
SimpleXlsxReportConfiguration configuration = new SimpleXlsxReportConfiguration();
configuration.setSheetNames(sheetNames): //sheets names is an array of the different names.
configuration.setOnePagePerSheet(false); //remove that it break on new page
configuration.setDetectCellType(true);
exporter.setConfiguration(configuration);
exporter.exportReport();

Problem: You can not use this method if you are using jasper report server.


text:
Q: ExactTarget API - Contracts Assembly Missing We are starting to do development against the ET API and I am having trouble getting it set up.  In VS 2010, when I add the service reference and configure the web.config according to the documentation I get the following error.  I would really appreciate any help.

Reference.svcmap: Could not load file or assembly 'Contracts,
  Version=9.0.1.3, Culture=neutral, PublicKeyToken=null' or one of its
  dependencies. The system cannot find the file
  specified.    App_WebReferences/etAPI/

A: This isn't particular to ExactTarget - Visual Studio just doesn't know where the .dll is located. Likely solutions:

*

*Add the assembly to your project's local \bin folder.

*Add the assembly to the GAC

A: I wasn't able to add the ET API to our website project but I was able to add it to a separate Class Library project and then call the methods from my website.  Consider this issue closed for me.  Thank you for your help!


text:
Q: Why does my python Pandas Gooey interface not execute the Pandas commands? I am new to python and pandas in general. I managed to create a simple merge script, now i want to carry that script over to a GUI interface using Gooey.
Example:
I have two files that are made up of this type of data.
One csv contains 3 columns named [A, B, C]
The second csv contains [A, D, E]
I want to merge this files such as they become [A, B, C, D, E]
If I run this part of the code by itself it works:
          load1 = pd.read_csv("*.csv")
          load2 = pd.read_csv("*.csv")
          merged = load2.merge(load1, on='A',how='right')
          merged.to_csv("itworks.csv", index=False)

However when I try to do it in Gooey, it executes and completes but it appears it never executes what is in def merge().
Question: Why is the merge function not executing?
 from __future__ import print_function
    import pandas as pd
    import numpy as np
    import glob
    import os
    import json
    from argparse import ArgumentParser
    from gooey import Gooey, GooeyParser
    import argparse

    @Gooey

    def main():
        parser = argparse.ArgumentParser()
        parser = GooeyParser(description='Example')
        parser.add_argument(
            'load1',
            action='store',
            help='Choose carefully',
            widget='FileChooser',

            )
        parser.add_argument(
            'load2',
            action='store',
            help='Choose carefully',
            widget='FileChooser',
            )

        args = parser.parse_args()

        return args

    def merge(load1, load2):

      load1 = pd.read_csv("*.csv")
      load2 = pd.read_csv("*.csv")
      merged = load2.merge(load1, on='A',how='right')
      merged.to_csv("itworks.csv", index=False)

      return merge

    if __name__ == '__main__':
        conf = main()