text:
Q: Not receiving mail from api developed using flask-restful and flask-mail and deployed on AWS Lambda I made an API which has mail function (async). I can able to receive email when i run the API locally, But not able to receive email when deployed over AWS Lambda. Is it require extra configurations ?
All imports
# coding=utf-8

import datetime
import os
from functools import wraps
from threading import Thread

from flask import Flask, request
from flask_cors import CORS
from flask_mail import Mail, Message
from flask_oslolog import OsloLog
from flask_restful import Api, Resource

Configuration Class Defination
class BaseConfig(): #configuration Base Class
    ENV = 'development'
    MAIL_SERVER = 'HOST_STRING'
    MAIL_PORT = 'PORT_NUMBER_INT'
    MAIL_USE_SSL = True
    MAIL_USERNAME = "USERNAME"
    MAIL_PASSWORD = "PASSWORD"
    MAIL_DEFAULT_SENDER = MAIL_USERNAME
    MAIL_DEBUG = True
    MAIL_SUPPRESS_SEND = False

    # Flask
    DEBUG = True
    SECRET_KEY = os.urandom(24)
    log_file = '/var/log/APP_PROJECT/flask_g.log'

class ProdConfig(BaseConfig): # Prod Config Class
    ENV = 'production'
    DEBUG = False
    MAIL_DEBUG = False

Initialising App
app = Flask(__name__)
app.config.from_object(BaseConfig)
mail = Mail(app) # Initialising mail
cors = CORS(app)
api = Api(app, catch_all_404s=Flask)
log = OsloLog(app)

Asynchronous Wrapper Function definition
def async_task(f):
    """ Takes a function and runs it in a thread """

    @wraps(f)
    def _decorated(*args, **kwargs):
        thr = Thread(target=f, args=args, kwargs=kwargs)
        thr.start()

    return _decorated

def send_email(recipients):
    sender = 'user@email.in'
    subject = 'TEST MAIL : SUBJECT'
    text_body = "TEST MAIL : TEXT_BODY"
    html_body = None
    app.logger.info("send_email(subject='{subject}', recipients=['{recp}'], text_body='{txt}')".format(sender=sender,
                                                                                subject=subject,
                                                                                recp=recipients,
                                                                                txt=text_body))
    msg = Message(subject, sender=sender, recipients=[recipients])
    msg.body = text_body
    msg.html = html_body

    _send_async_email(app, msg)

@async_task
def _send_async_email(flask_app, msg):
    """ Sends an send_email asynchronously
    Args:
        flask_app (flask.Flask): Current flask instance
        msg (Message): Message to send
    Returns:
        None
    """
    with flask_app.app_context():
        mail.send(msg)

Resource Class Defination
class indexResource(Resource): # Index Resource
    def get(self):
        app.logger.info('GET : indexResource')
        return {"message": 'WORKING FINE', 'ip': request.remote_addr}

class mail_resource(Resource):
    def get(self, email): # GET '/mail/mail_to_address@email.com
        try:
            send_email(email)
            return "Mail Sent"
        except Exception as e:
            app.logger.warning('Error : {}'.format(e.message))
            return "Error {}".format(e.message)

Registering / Adding Resources
api.add_resource(indexResource, '/')
api.add_resource(mail_resource, '/mail/<email>')

Running Script
if __name__ == '__main__':
    app.run()

i used Zappa for server less deployment at AWS-Lambda.


text:
Q: How to restrict decimal values in openbravoerp If user is entering 678.98 then it should display only 678 in one of the field of a window.

I have declare that field as numeric in database and number type reference in tables and columns in openbravo.

A: Use Math.floor()
import java.lang.Math;
...
value = 678.98;

roundeddown = Math.floor(value); // roundeddown == 678

See also this page about another rounding example.

Working directly with PostgreSql, use the floor() function
To insert data
INSERT INTO table ... VALUES( floor(678.98) ) ...

To select data
SELECT floor( field ) FROM table WHERE ....

A: Set Integer type reference in tables and columns in openbravo.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Passing PHP MySQL Result Object to Function I'm trying to take a MySQL result row and pass it to a function for processing but the row isn't getting passed. I'm assuming this is because the actual row comes back as a object and objects can't get passed to function?
E.G
function ProcessResult($TestID,$Row){
    global $ResultArray;
    $ResultArray["Sub" . $TestID] = $Row["Foo"] - $Row["Bar"];
    $ResultArray["Add" . $TestID] = $Row["Foo"] + $Row["Bar"];
}

$SQL = "SELECT TestID,Foo,Bar FROM TestResults WHERE TestDate !='0000-00-00 00:00:00'";
$Result= mysql_query($SQL$con);

    if(!$Result){
        // SQL Failed
        echo "Couldn't find how many tests to get";
    }else{

        $nRows = mysql_num_rows($Result);

        for ($i=0;$i<$nRows;$i++)
        {
            $Row = mysql_fetch_assoc($Result);

            $TestID = $Row[TestID];

            ProcessResult($TestID,$Row);
        }

    }

What I need is $ResultArray populated with a load of data from the MySQL query. This isn't my actual application (I know there's no need to do this for what's shown) but the principle of passing the result to a function is the same.
Is this actually possible to do some how?
Dan

A: mysql_query($SQL$con); should be mysql_query($SQL,$con); The first is a syntax error. Not sure if this affects your program or if it was just a typo on here.
I would recommend putting quotes around your array keys. $row[TestID] should be $row["TestID"]
The rest looks like it should work, although there are some strange ideas going on here.
Also you can do this to make your code a little cleaner.
if(!$Result){
    // SQL Failed
    echo "Couldn't find how many tests to get";
}else{

    while($Row = mysql_fetch_assoc($Result))
    {
        $TestID = $Row['TestID'];

        ProcessResult($TestID,$Row);
    }

}

A: mysql_fetch_assoc() returns an associative array - see more
If you need an object, try mysql_fetch_object() function - see more
Both array and object can be passed to a function. Thus, your code seems to be correct, except for one line. It should be:
$Result= mysql_query($SQL, $con);

or just:
$Result= mysql_query($SQL);


text:
Q: How to "reset" next indexPath.row to become current indexPath.row?  -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

self.selectedTrack = self.SPTrackList[indexPath.row];
self.selectedTrackRow = indexPath.row;

self.nextTrack = self.SPTrackList[indexPath.row +1];

[self playTrack:self.selectedTrack];

}

Hi -- How can I "reset" self.nextTrack to become self.selectedTrack?  I've tried self.nextTrack = self.selectedTrack, but that will only work once.  I'm guessing I need to traverse -- if that's the right word -- and move the indexPath of self.selectedTrack and self.nextTrack forward?
- (IBAction)nextPressd:(id)sender {
[self playTrack:self.nextTrack];

//self.nextTrack now be new self.selectedTrack via indexPath.row??

  }

Thanks!

A: If you need to play the next track from your array, you need to keep track the current playing track and that index. You can do it like:
- (IBAction)nextPressd:(id)sender
{
   self.selectedTrackRow += 1;
   self.nextTrack = self.SPTrackList[self.selectedTrackRow];
   [self playTrack:self.nextTrack];
}


text:
Q: CodeIgniter: How to check either one of the fields is not empty from the required fields Either one of form fields 'room_number', 'pos_token', 'banquet_token' has to be filled in order to continue. That was the requirement and I wrote this code and ended up with conflicts with other parts of the code and it didn't work at all.
$room_number = $this->input->post('room_number');
$pos_token = $this->input->post('pos_token');
$banquet_token = $this->input->post('banquet_token');

if(isset ($room_number) && strlen($room_number) && ($pos_token) && strlen($pos_token) && ($banquet_token) && strlen($banquet_token) ) {
    return true;
    }
else {
    return true;
    }

A: you need to set rules for input fields
$this->form_validation->set_rules('username', 'Username', 'required');
if ($this->form_validation->run() == FALSE)
  {
    //run your code on success here
  }
else
  {
    //run your code on failure here
  }

A: You need to return false on the condition fails like
if(isset ($room_number) && strlen($room_number) && ($pos_token) && strlen($pos_token) && ($banquet_token) && strlen($banquet_token) ) {
    return true;
}
else {
    return false;
}

and for your condition you need to check with OR condition like
if( ( isset ($room_number) && strlen($room_number)) ||
    ( isset ($pos_token) && strlen($pos_token)) ||
    ( isset ($banquet_token) && strlen($banquet_token))
  ) {

A: Just use the || OR operator in your if statement. and return false if the test fails.
$room_number = $this->input->post('room_number');
$pos_token = $this->input->post('pos_token');
$banquet_token = $this->input->post('banquet_token');

 if(!empty($room_number) || !empty($pos_token) || !empty($banquet_token))
    return true;
else
    return false;

A: $room_number = $this->input->post('room_number');
$pos_token = $this->input->post('pos_token');
$banquet_token = $this->input->post('banquet_token');

if($room_number=="" || $pos_token=="" || $banquet_token=="")
    return true;
else
    return false;


text:
Q: Where is she? or Where is she at? Which sentence is grammatically correct?  I have been trying to find the answer to this for a couple years.  I hear people saying both of these types of sentences and I keep wondering which is grammatically correct.  I have researched online but cannot find out, so I decided to ask you.  thank you.

A: Both are acceptable. The first is uncontroversial and I do not discuss it here.
It is common usage to say things such as "She is at the cinema", "He is at the bar", "She was at the races", "He is at home". The "Where is he/she at?" questioning construction parallels these statements so finds itself in frequent and acceptable usage.
The "at" is redundant. It is not needed because the questions could be more concisely put as "Where is she/he?".
This redundancy, and the efforts of seventeenth and eighteenth century grammarians to align English with Latin, lead some people to say it is ungrammatical to end with "at". But it is not: see https://www.merriam-webster.com/words-at-play/prepositions-ending-a-sentence-with for a reasoned historical discussion.


text:
Q: Carbon initial date value Maybe I'm not seeing the forest because of the trees but here's what I am facing:
$week_start = new Carbon();
$week_start->setISODate($year,$week);  //2016 , 21

$init = $week_start; //I am assigning the datetime created to $init variable (1)

$min_sqldate = $week_start->toDateString(); //string of date
$max_sqldate = $week_start->addDays(6)->toDateString(); //string of date adding 6 days

At this point $init variable already has a value of $max_sqldate. (2)
How is this possible? How should I keep my initial variable so I can use it later on ?
Value of $init in case (1):
 Carbon {#328 ▼
      +"date": "2016-05-23 16:58:36.000000"
      +"timezone_type": 3
      +"timezone": "Europe/Helsinki"
    }

Value of $init in case (2):
 Carbon {#328 ▼
      +"date": "2016-05-29 17:00:34.000000"
      +"timezone_type": 3
      +"timezone": "Europe/Helsinki"
 }

A: Carbon provides a copy() method that will return a "fresh" copy of the instance, e.g.
$init = $week_start->copy();

By default in PHP, when copying an object using equals, you won't end up with an independent copy. You can also work around this using the clone keyword.
See http://php.net/manual/en/language.oop5.references.php


text:
Q: How to extract the "ZTlhMDNhOGVkZV8xNTY3Mjk3MjAw" value from the respective response in JMeter? This value "ZTlhMDNhOGVkZV8xNTY3Mjk3MjAw" is dynamic Response:
{
  "service_name": "signup",
  "message": "Sign Up has been done successfully",
  "global_error": "",
  "error": [],
  "data": {
    "session_key": "8f29d7c93e7089841208e94a7d98fc22",
    "user_profile": {
      "user_id": 65,
      "user_unique_id": "e9a03a8ede",
      "dob": "Dec 06, 1998",
      "first_name": "FC7155313",
      "last_name": "FC1791398",
      "user_name": "FCwqim178",
      "email": "fc_slekjbp@mailinator.com",
      "phone_no": "3362239492",
      "balance": "0",
      "status": "2",
      "image": "http://dummy.projects.com/app/assets/img/default_user.png",
      "currency": "$",
      "profile_status": 1,
      "require_otp": false,
      "existing_user": 0,
      "master_country_id": null,
      "master_state_id": "3919"
    },
    "verification_link": "http://dummy.projects.com/activation/ZTlhMDNhOGVkZV8xNTY3Mjk3MjAw",
    "send_email_otp": false,
    "send_phone_otp": false
  },
  "response_code": 200
}

I am using JMeter and want to pass "ZTlhMDNhOGVkZV8xNTY3Mjk3MjAw" value in next API.
This value "ZTlhMDNhOGVkZV8xNTY3Mjk3MjAw" is generating dynamic for each new user registration.
But my regex is not working.
The regular expression that I wrote:
,"verification_link":"http://dummy.projects.com/activation/(.+?)","send_email_otp":

Template: $1$
Match No.: 1

A: Your response seems to be a JSON entity therefore there is a high change that it looks like:
{
  "service_name": "signup",
  "message": "Sign Up has been done successfully",
  "global_error": "",
  "error": [

  ],
  "data": {
    "session_key": "8f29d7c93e7089841208e94a7d98fc22",
    "user_profile": {
      "user_id": 65,
      "user_unique_id": "e9a03a8ede",
      "dob": "Dec 06, 1998",
      "first_name": "FC7155313",
      "last_name": "FC1791398",
      "user_name": "FCwqim178",
      "email": "fc_slekjbp@mailinator.com",
      "phone_no": "3362239492",
      "balance": "0",
      "status": "2",
      "image": "http://dummy.projects.com/app/assets/img/default_user.png",
      "currency": "$",
      "profile_status": 1,
      "require_otp": false,
      "existing_user": 0,
      "master_country_id": null,
      "master_state_id": "3919"
    },
    "verification_link": "http://dummy.projects.com/activation/ZTlhMDNhOGVkZV8xNTY3Mjk3MjAw",
    "send_email_otp": false,
    "send_phone_otp": false
  },
  "response_code": 200
}

so this "send_email_otp" bit can easily go to the next line and your regular expression will not match anything in this situation.
I would recommend amending your regex to look something like:
"verification_link":\s?"http://dummy.projects.com/activation/(\w+)"

Demo:

References:

*

*JMeter: Regular Expressions

*Using RegEx (Regular Expression Extractor) with JMeter

*Perl 5 Regex Cheat sheet

A: Your regex matches only the first part of your URL, and not the part that you actually want. Try this instead:
http:\/\/dummy\.projects\.com\/activation\/(.+)\",

Regex Demo
The (.+?) part matches between 1 and unlimited time, as few times as possible (called lazy match, indicated by +?). So you match the first character of whatever comes after activation/ and then stop. You do not get the entire value, as you want.


text:
Q: Review scraping form tripadvisor I am new to web scraping in python3. I want to scrape the reviews of all the hotels in dubai but the problem is I can only scrape the hotel review which I describe in the url. Can anyone show me how I can get all of the hotel reviews without implicitly giving url of each hotel?
import requests
from bs4 import BeautifulSoup

importurl = 'https://www.tripadvisor.com/Hotel_Review-g295424-d302778-Reviews-Roda_Al_Bustan_Dubai_Airport-Dubai_Emirate_of_Dubai.html'
r = requests.get(importurl)
soup = BeautifulSoup(r.content, "lxml")
 resultsoup = soup.find_all("p", {"class" : "partial_entry"})
#save the reviews to a test text file locally
for review in resultsoup:
review_list = review.get_text()
print(review_list)
with open('testreview.txt', 'w') as fid:
    for review in resultsoup:
        review_list = review.get_text()
        fid.write(review_list)

A: you should find the index page of all hotel, get all the link into a list, than loop the url list to get comment.
import bs4, requests
index_pages = ('http://www.tripadvisor.cn/Hotels-g295424-oa{}-Dubai_Emirate_of_Dubai-Hotels.html#ACCOM_OVERVIEW'.format(i) for i in range(0, 540, 30))
urls = []
with requests.session() as s:
    for index in index_pages:
        r = s.get(index)
        soup = bs4.BeautifulSoup(r.text, 'lxml')
        url_list = [i.get('href') for i in soup.select('.property_title')]
        urls.append(url_list)

out:
len(urls): 540


text:
Q: Filebeat to Logstash timezone issue Using Filebeat, and Logstash 7.9.
Customer logfiles have timestamps in local timezone.
Want to let Logstash know in which timezone filebeat lives.
Am able to do that via adding:
processors:
  - add_locale:
      format: abbreviation

in filebeat.yml, and in logstash filter using the event.timezone via:
    grok {
          match => { "message" => "%{DATESTAMP:logdate} %{GREEDYDATA:jsonmess}"}
    }
    date {
      match => ["logdate", "yy-MM-dd HH:mm:ss,SSS"]
      timezone => "{{ event.timezone }}"
    }

Problem is that filebeat options for the timezone format are "offset" and "abbrevation", but logstash expects only "canonical id's" !
How can i make this work ?

A: You can use the offset in the timezone option in the Logstash date filter.
For example, the following config will work without problems.
date {
    match => ["logdate", "yy-MM-dd HH:mm:ss,SSS"]
    timezone => "-03:00"
}

Also, the way you are referencing the event.timezone field is wrong, you should use %{[event][timezone} and not {{ event.timezone }}
Try to change your config to
date {
    match => ["logdate", "yy-MM-dd HH:mm:ss,SSS"]
    timezone => "%{[event][timezone]}"
}


text:
Q: Python: How to dynamically assign variable in tkinter's checkbutton I am trying to generate a few check buttons based on a list.
I have created an iteration and try to generate the check buttons. I struggle however with assigning 'variable' option. I have tried to use 'self.bttn%d' % i to assign variable option to each of the buttons, but every time I try to get the value via the self.bttn0.get() method it returns None.
Could you explain me please how to solve the problem?
def create_widgets(self):
    #Create whole menu
    my_menu = [("Dish 1", 24.99),
               ("Dish 2", 19.99),
               ("Dish 3", 14.99),
               ("Dish 4", 7.99)]
    menu_pos = len(my_menu)
    self.bttnx = my_menu[0][1]

    # ----- LABEL 'Title' -----
    Label(self,
          text = "Make an order by choosing one or more dishes from our menu."
          ).grid(row = 0, column = 0, sticky = W)

    # ----- BUTTONS -----
    for i in range(menu_pos):
        exec('self.bttn' + str(i) + ' = ' + 'BooleanVar()')
        #Check-buttons
        Checkbutton(self,
                    text = my_menu[i][0] + " / " + str(my_menu[i][1]) + "nok",
                    variable = 'self.bttn%d' % i
                    ).grid(row = i + 1, column = 0, sticky = W)

    Button(self,
           text = "Update",
           command = self.update_menu
           ).grid(row = 5, column = 0, sticky = W)

A: You could create your variables in a sequence, and address them at button creation.
Something like this:
bool_vars = [BooleanVar() for _ in range(menu_pos)]
for idx, var in enumerate(bool_vars):
    Checkbutton(self,
                text=my_menu[idx][0] + " / " + str(my_menu[idx][1]) + "nok",
                variable=var
                ).grid(row=idx+1, column=0, sticky=W)


text: Q: Win10 loads more after loading So my win10 pc started loading insanely long. At first it loads usually, then black screen shows with loading icon and it takes about 10x longer than usual boot. Then I get to see Please Wait and after that Welcome screen which also lasts forever. When PC finally boots up everything is super slow and stuttering. I have to restart PC a few times until I get normal boot time. Mbar checked - no viruses. Also HDD led is on during that black screen with loading icon. What is happening? It used to happen very rarely, but since last week almost everyday.


text:
Q: Installation of github on a windows SERVER I see on github for windows it's for windows 7 and 8.
can you install it on windows server 2008 r2?
i have a fire walled server that is for our .net code as our team foundation server so I was going to use the same server to host our source control for cocoa/mac applications we have...

A: If you are after a Git server (as in able to host git repos), you can consider, on Windows, the Bonobo Git server.
It knows how to interface with IIS, and is compatible with various Windows releases, including  windows server 2008 r2.


text:
Q: PHP SQL Query listing WHERE=? Hello I'm trying to learn php. I'm using phpmyadmin with xampp. I want to listen according to the following query:
"$add='SELECT * FROM movielibrary WHERE username="$libraryuser"';

But there is no element coming to the mylibrary.php page. When I try to echo $libraryuser, it is correct but when I write to the sql query, it's not matching and my table is blank. My username is "info" and if I write
"$add='SELECT * FROM movielibrary WHERE username="info"';

It is correct but I need to do $libraryuser.
What should I do?
This are the screenshots for my problem:
this is when i write to username='info' it is okey
this is when i write to $libraryuser there is no listing
I also tried
'username'=$libraryuser , "username"=$libraryuser , username='$libraryuser , username="$libraryuser

but it did not work.
<?php
    require_once("config.php");
session_start();

$libraryuser=$_SESSION['user'];

echo $libraryuser;
$add='SELECT * FROM movielibrary WHERE username="$libraryuser"';

echo "

 Logout

";

    echo "My Library
";

if($result=mysqli_query($conn,$add)) {

    echo "

                Movie Name

                Director

                Cast

                Year

                Runtime

            Movie Genre

";
            while($read=mysqli_fetch_array($result)){
        echo "

                $read[movie_name]

                $read[director]

                $read[movie_cast]

                $read[year]

                $read[runtime]

                $read[movie_genre]
            	";
            }
}
        echo "

";

?>

A: You need to replace the query
'SELECT * FROM movielibrary WHERE username="$libraryuser"';

with
"SELECT * FROM movielibrary WHERE username='$libraryuser'";

then it will work.


text:
Q: How to ReGenerate String Array using Some Keyword My Question is that I have An String array of 5 Contains Value as follow :
red, green, yellow, white, black
Now I am searching some text using EditText, If User Enters : "re" then my array should be like this :
Search String 1 : re
output array should be: Red, Green

Search String 2 : w
Output Array should be: yellow, white

Thanks in Advance,

A: For the AutoCompleteTextView to provide results with one character input, add this line;
textView.setThreshold(0);


text:
Q: what' does the "heroes$!:Observable;"mean? what' does the "heroes$!:Observable<Hero[]>;"mean? And what' does the "heroes$?:Observable<Hero[]>;"mean?

A: The ! is the manual type assertion operator to remove null and undefined from the type. You can read more about type assertions here.
The ? means it's optional, it can be undefined. It's a shortand for heroes$: Observable<Hero[]> | undefined. The documentation for mapping modifiers is here.
When you have strict settings enabled in your tslint.json, the compiler will complain about class properties that are not initialised where you declared then nor in the consrtuctor. For this you can do two things.

*

*Mark them with the optional ? modifier, or use an union type with undefined.

*Use ! to manually assert the type, and silence the compiler. With this you actually mean: "You can't know, but I know better this property will allways have a value". This is good when Angular sets the property. (like @Input(), @ViewChild(..., {static: true}))


text:
Q: Subset dataframe by removing rows with same values in a specific column I would like to subset my dataframe by removing rows which have same values in a specific column.
Here my dataframe:
        ID    Area        Date    Day
1    21009  4390.0  1979-12-27   4835
2    24005   178.5  1979-12-27   4835
3    27001   484.3  1979-12-27   4835
4    27002   758.9  1979-12-27   4835
5    38003   133.9  1979-12-27   4835
6    33014   272.0  2004-02-01  13637
7    33029    98.8  2004-02-01  13637
8    34003   164.7  2004-02-01  13637
9    23118   220.8  2007-01-18  14502

My output should be:
     ID    Area        Date    Day
1    21009  4390.0  1979-12-27   4835
2    33014   272.0  2004-02-01  13637
3    23118   220.8  2007-01-18  14502

I tried but didn't work:
df <- subset(df, Day == unique(Day))

and
df <- df[df == unique(df$Day), ]

Whereas the following code only return me a vector with unique(df$Day), which is good, but I need all the dataframe subsetted:
df <- unique(df[ , 4] )

A: Use duplicated:
df[!duplicated(df$Day), ]

#      ID   Area       Date   Day
# 1 21009 4390.0 1979-12-27  4835
# 6 33014  272.0 2004-02-01 13637
# 9 23118  220.8 2007-01-18 14502


text:
Q: Arrays vs malloc? If you want a dynamically allocated array ofint size, there two ways you can get that in C:
int* array = new int [size]; //method 1
int* array2 = malloc (sizeof(int) * size); //method 2

When should you use each method?

A: If you're in C, the second one.
If you're in C++, use std::vector<int> if you can; otherwise use the first one (rarely needed).

A: Another option, if the array will not be that big is to allocate it on the stack as a VLA:
int array[size];

This will automatically free the memory when the variable leaves the scope, which may or may not be what you want. If you intend to use the variable outside the function it's allocated in, use the malloc way.

A: Another option (especially when memory needs to be zeroed):
int *array3 = calloc(size, sizeof array3[0]);

This protects against overflows (which must be checked in size * sizeof array[0] manually).


text:
Q: Getting Handler Error in Response of AWS Lambda function Test Created a lambda function to retrieve value from dynamodb.When I am testing the function I am getting an error in response?

Couldn't find any answer on the internet.

A: Your function should be named lambda_handler
def lambda_handler(event,context):

The documentation provides more information on this here:
https://docs.aws.amazon.com/lambda/latest/dg/python-handler.html

A: Seems like in line 6 you have used

def handler(event,context):

instead of

def lambda_handler(event,context):

If you want to keep using def handler(event,context): you also need to enter this in 'Handler' option in 'Runtime Settings'


text:
Q: why tts isn't changing the languge in Android Fragment but works fine in Activity? So I have been trying to change the TTS language inside a fragment but it isn't working but same code works fine inside MainActivity. I don't understand why. I have checked other solutions but none worked for me. I have tried different solution , solution but even this isn't working.
public class HomeFragment extends Fragment  implements TextToSpeech.OnInitListener{
    private static final int TTS_DATA_CHECK = 1;
    private TextToSpeech engine;
    private SettingsViewModel settingsViewModel;
    private EditText textMsg;
    private Button button;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        engine = new TextToSpeech(getContext(),this);
        settingsViewModel = new ViewModelProvider(getActivity()).get(SettingsViewModel.class);
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        textMsg = view.findViewById(R.id.textMsg);
        button = view.findViewById(R.id.playButton);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                engine.speak(textMsg.getText().toString(), TextToSpeech.QUEUE_FLUSH, null,null);
            }
        });
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        settingsViewModel.getLanguage().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(String s) {
                Log.d("LANGUAGE_SELECTED",s);
                switch (s){
                    case "ENGLISH":
                        engine.setLanguage(Locale.ENGLISH);
                        break;
                    case "FRENCH":
                        engine.setLanguage(Locale.FRENCH);
                        break;
                }
            }
        });
    }

    @Override
    public void onInit(int status) {
        if(status==TextToSpeech.SUCCESS){
            int result = engine.setLanguage(Locale.ENGLISH);
            if(result == TextToSpeech.LANG_MISSING_DATA
                    || result== TextToSpeech.LANG_NOT_SUPPORTED){
                Toast.makeText(getContext(),"Not supported",Toast.LENGTH_LONG).show();
            }
        }else{
            Toast.makeText(getContext(),"TTS is missing",Toast.LENGTH_LONG).show();
        }
    }

}

A: First you need to initialize TTS in main activity like this -
public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener {

    private static final int TTS_DATA_CHECK = 101;
    static TextToSpeech engine;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        engine = new TextToSpeech(this,this);
    }

    @Override
    public final void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101)
        {
            if (resultCode != TextToSpeech.Engine.CHECK_VOICE_DATA_PASS)
            {
                final Intent tnt = new Intent(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                startActivity(tnt);
            }
        }
    }

    @Override
    public void onInit(int status) {
        if(status==TextToSpeech.SUCCESS){
            if(TTS_DATA_CHECK == TextToSpeech.LANG_MISSING_DATA
              || TTS_DATA_CHECK== TextToSpeech.LANG_NOT_SUPPORTED){
                Toast.makeText(this,"Not supported",Toast.LENGTH_LONG).show();
            }
        }
    }

    static public TextToSpeech getInstance() {
        return engine;
    }

}

Then you have to call the TTS instance inside Fragment like this. Note that, MainActivity is the parent activity of the given Fragment.
Now replace the following code in your Fragment with this code -
@Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.d("VMA","OnActivityCreated");
        settingsViewModel.getLanguage().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(String s) {
                Log.d("VMA","LANGUAGE_SELECTED " + s);
                switch (s){
                    case "FRENCH":
                        MainActivity.getInstance().setLanguage(Locale.FRENCH);
                        break;
                    case "ENGLISH":
                        MainActivity.getInstance().setLanguage(Locale.ENGLISH);
                        break;
                }
            }
        });
    }

Also, you can remove the rest of the TTS code from Fragment. You don't that anymore.


text:
Q: fopen failed to open stream: No space left on device in /home/ I get this error "failed to open stream: No space left on device in /home/..." when I try to copy to one of the directory. The error comes only for one of the directories. I have tried other directories and there it works fine.
Also df -i etc shows enough free nodes. I do have enough free disk space on device. My disk quota is unlimited. Anybody can help?


text:
Q: Adjust PDF options for PhantomJS I use PhantomJS for PDF generation.
This is my command:
./phantomjs rasterize.js <someurl> test.pdf

It generates pdf file but:

*

*The PDF looks nothing like the original website

*I can't set the page orientation

*Also is there any other options I can use for pdf generation?

The following change to rasterize.js also doesn't seem to work:
{ format: system.args[3], orientation: 'Letter', margin: '1cm' }

A: Rasterize.js is a very basic example of screen capture. There are some default values in this example that you can change to your needs.

*

*page.viewportSize
Simulates the size of the window like in a traditional browser. In rasterize.js, it's { width: 600, height: 600 } ; not a common resolution and you may need to change this.

*

*page.paperSize
Defines the size of the web page when rendered as a PDF. There are two modes : Manual (given a width and a height) or automatic (given a format). Do not hesitate to read the webpage documentation and the wiki page.
In your case, orientation: 'Letter' is invalid.
Supported formats are 'A3', 'A4', 'A5', 'Legal', 'Letter', 'Tabloid'.
Supported orientation are 'portrait' and 'landscape'.
Take a look at the source code and change it to your needs !


text:
Q: Ribbon bar designer shows empty ribbon control for VSTO Excel Application in Visual Studio 2019 I have a C# add-in that I am developing in Visual Studio 2019.

*

*I have a single custom ribbon control that appears as a new tab in Excel whenever I run the add-in.

*The NBWRibbon01.Designer.cs contains code for the custom ribbon groups and buttons shown below.

*The application builds and runs without error.

However, when I launch the Designer for the same custom ribbon in Visual Studio 2019, I get an empty ribbon bar control shown below.

Has anyone encountered this issue?  I am guessing that I will need to completely re-create the ribbon bar from scratch.

A: First of all, make sure the VSTO design-time adapter add-in is enabled in Excel.

Also check out the code-behind files, most probably any of them was edited to ruin the ribbon designer.
The Ribbon designer is good as a starting point in Visual Studio. But it doesn't support all the features that the Fluent UI provides. So, I'd suggest moving to the raw XML markup. You can design the base UI using the ribbon designer in Visual Studio and then export the custom markup to the ribbon XML. Read more about that in the How to: Export a ribbon from the Ribbon Designer to Ribbon XML article.


text:
Q: Assembly output is being weird So i am making a calculator in assembly like i would in c or c++ or any other language but the output is being really weird it is printing all of them out then taking input
NOTE: THIS IS IN x86_64 ASM THAT IS WHY I AM USING 64 BIT REGISTERS FOR THE ARGS
NOTE: THIS IS NOT CLOSE TO DONE I AM JUST WORKING ON TAKING INPUT
main.asm
section .data
    p1 db "Enter first number: "
    p2 db "Enter seccond number: "
    p3 db "Enter operation", 0xa, "1)Add", 0xa, "2)Subtract",0xa, "3)Multiply",0xa, "4)Divide", 0xa, "> "
    p1len equ $-p1
    p2len equ $-p2
    p3len equ $-p3
section .bss
    n1 resb 8
    n2 resb 8
    op resb 8
section .text
    global _start
_start:
    call _doN1
    call _doN2
    call _doOps
    mov rax, 60
    mov rdi, 0
    syscall
_doOps:
    mov rax, 1
    mov rdi, 1
    mov rsi, p3
    mov rdx, p3len
    syscall
    mov rax, 0
    mov rdi, 0
    mov rsi, op
    mov rdx, 8
    syscall
    ret
_doN1:
    mov rax, 1
    mov rdi, 1
    mov rsi, p1
    mov rdx, p1len
    syscall
    mov rax, 0
    mov rdi, 0
    mov rsi, n1
    mov rdx, 8
    syscall
    ret
_doN2:
    mov rax, 1
    mov rdi, 1
    mov rsi, p2
    mov rdx, p2len
    syscall
    mov rax, 0
    mov rdi, 0
    mov rsi, n2
    mov rdx, 8
    syscall
    ret

Output:
Enter first number: Enter seccond number: Enter operation
1)Add
2)Subtract
3)Multiply
4)Divide
> 3
Enter seccond number: Enter operation
1)Add
2)Subtract
3)Multiply
4)Divide
> 6
Enter operation
1)Add
2)Subtract
3)Multiply
4)Divide
> 1


text:
Q: Add custom culture to web service? I have a web service on a server for which i won't be able to manage regional settings. My web methods need a date format "d.M.YYYY", so when i make a call to a web method and pass date-time string, the server should parse this string into a date format "d.M.YYYY" only, with date separator "."
In my desktop application i am doing this with the following code:
 public partial class MainF : Form
 {
   CultureInfo customCulture = new CultureInfo(CultureInfo.CurrentCulture.Name);

      public MainF()
      {
           InitializeComponent();

           customCulture.DateTimeFormat.ShortDatePattern = "d.M.yyyy";
           customCulture.DateTimeFormat.DateSeparator = ".";
           Thread.CurrentThread.CurrentCulture = customCulture;
      }
      private void DisplayDate(string date)
      {
        string output="";
        DateTime myDate;
        if (!DateTime.TryParse(input, customCulture, DateTimeStyles.None, out myDate))
        {
           MessageBox.Show("Date cannot be parsed!");
        }
        else
        {
           MessageBox.Show(myDate.ToShortDateString());
        }
      }
 }

But in my webservice where should i put the definition for date format,date separator and current thread culture = custom culture??? In every single method or not? Sorry but i am not too familiar with web services by now. Thank you in advance!

A: If you wanna supply custom format, you need to use DateTime.TryParseExact method instead of DateTime.TryParse. For example;
if(DateTime.TryParseExact(input, customCulture.DateTimeFormat.ShortDatePattern,
                          customCulture, DateTimeStyles.None, out myDate))
{
    MessageBox.Show("Date cannot be parsed!");
}

Exact is the difference between these two methods which points to custom format.
By the way, I don't see any input in your code as a variable maybe you might mixing it with date or output variables..


text:
Q: How faster could a dedicated chip do sequential squaring modulo operations to break a time crypto capsule? I'm facing a very real problem and, sadly, I cannot find the answer on my own: I'm hitting my limit as a programmer because my hardware knowledge is not sufficiently advanced at all.
It's an issue I'm encountering during the development of the system (I need to find safe parameters value which depends on the answer to the question I'm asking here) (maybe crypto.SE would be better but crypto.SE seems more about theoretical questions about math/cryptography).
For a project I'm working on I need to use a "time capsule cryptosystem". More specifically the following one, invented by Rivest (the 'R' in 'RSA'):
Rivest's time capsule crypto puzzle
It is an inherently sequential operation: parallelization here is of no use. An attacker could use a botnet of million computers: it wouldn't help. One million ASIC chips wouldn't help either. The solution can only be found sequentially, by design.
Now I need to approximate (one or two orders of magnitude off is ok: an approximation 10x faster/slower or even 100x faster/slower ain't really an issue) how much faster could a dedicated chip solve that puzzle compared to a fast CPU (a fast core, really).
Basically solving that puzzle consists in doing a lot of squarings modulo n. Let's consider there's no "attack" on that puzzle: I've chosen bit enough RSA integers etc.
Would a GPU help compared to a CPU here? A FPGA? Would a dedicated chip like some ASIC chip help?
If any of these would help, how can I determine how much faster it could be than  a fast CPU?
I'd need some back-of-the-envelope calculation and, as I stated previously, an approximation about 10x or 100x the actual answer ain't that a big problem.
I guess my question boils down to something like (but feel free to rewrite if I'm mistaken): knowing that the problem is inherently sequential and consists in repeated squaring modulo n operation, can you build/program some hardware to only do sequential squaring modulo operations and how much faster would it be than an actual CPU?

A: I don't have a definitive answer because it would take a bit of analysis. It also depends on the CPU, how many bits etc. But for a ballpark number.
FPGA's have been built that will do a divide operation in 1 clock cycle. A general purpose CPU/ALU can take 20 to 100 clock cycles. DSP processors will likely take less clock cycles. So we can say a FPGA is 100x faster.
That's just the divide operation (which gives you the modulo also).
You would still have to account for memory transfers. Would a dedicated FPGA need to do this? A general purpose CPU would definitely need to do it. This makes the FPGA all the more faster if it could eliminate most of its memory transfers.  At this point 1000x improvement seems realistic.
However, I didn't read the algorithm but I'm guessing there's some table updates/lookups, this would probably require memory transfers to/from the FPGA, which slows down the FPGA processing to be more equivalent to the CPU processing. Even if the FPGA has dedicated extra fast memory, this would still cause that 1000x guesstimate to drop somewhat.
Anyways, my estimate would be a 100x-1000x speed improvement with an FPGA in the best of circumstances.
UPDATE
I came across this article http://research.microsoft.com/apps/pubs/default.aspx?id=70636 (a little dated 2008) but probably still applicable. It is called "Where's the Beef? Why FPGAs are so fast" They did various timing comparisons including 128-bit AES encryption. For the AES encryption they were able to get about a 4000 times increase from the simplistic software implementation to a highly optimized FPGA. Although, I think there were also software optimizations that could be made that reduced that 4000 times number.
I don't know if the state-of-the-art FPGA/Custom Hardware has improved dramatically compared to state-of-the-art CPUs of today, so I don't know how applicable this info is any longer. But, I still think the 100x to 1000x is a good estimate as I would assume that the software would be optimized.

A: CPU:
The problem really does depend on the speed of the CPU. We already have diverged from the ballpark range presented in the article, as in 2012 we did not have commercially available 10GHz CPUs. In this case, it would be rather difficult because we're dealing with several factors:

*

*CPU speed

*L1 and L2 cache size

*Bus speed

*Algorithm optimization

*Available CPU architecture

*Memory speed

*Cache misses

So I'm going to stick with the "35 year algorithm" based off their original prediction.
GPU:
A GPU isn't going to help in this case. These devices are all about paraellelization and aren't going to help with this kind of algorithm.
FPGA/ASIC:
In this scenario, it's entirely possible to design an FPGA/ASIC that would do an entire operation in one tick. Since we don't care about the actual division result, and only care about the result mod N, we could theoretically make this fairly fast. However it's extremely difficult to estimate the exact speed we could achieve. This would be based off many factors:

*

*The algorithm we use.

*The size/speed of the components.

*The actual hardware components used.

*The quality of the components used.

*The build process used.

If we could estimate that our FPGA/ASIC would run at 1 MHz, which would complete the problem in ~2.53 years.
On another hand, if we could somehow develop and FPGA/ASIC that would run at 1 GHz, then we would complete the problem in ~22 hours.


text:
Q: How to find if a substring from a string vector is contained in another group/vector/list c++ let me give an example:I have three groups of strings which will have a fixed size, I thought of using lists. Let's say I name them Red, Green, Blue:
std::string Red[] = {"apple", "rose mary", "watermelon"};
std::string Green[] = {"cucumber", "avocado", "pine tree"};
std::string Blue[] = {"sea", "lake"};

I have found examples here where we search one item inside each of these lists, and they find it if the string matches, for example in that case I should have :
std::string myinput = "watermelon";
if (std::find(std::begin(Red), std::end(Red), myinput) != std::end(Red))
{
  cout << "found " << myinput << " in Red" <<  endl;
}

Ok so far, but I want something different:
I want to scan a vector with 1000 elememnts, and myinput belongs to one of those elements which I access like this:
for (int j = 0; j < Vector.size(); j++){
    if (Vector[j].message ==  contains a string from one of the groups ){
        cout<< Vector[j].message << endl;}
}

The Vector[j].message will be a string which has this format:
"flag: She adores watermelon"
"flag: They visited the lake"
"flag: He has cucumber for salad"
"flag: Wacamole made of avocado"

You see that the substring flag is common in all strings of the vectors. However, the watermelon doesn't exist in another group of strings.
The goal is to scan each group of lists and find that the element of the vector
"flag: She adores watermelon" is listed in group Red. This should not be listed in the group yellow just because of the substring "flag".
Also, I want the substring to contain the whole string stated in the group, for example if the Vector contains an element like "flag: the plant has many pines" , this should not be listed to the Green group, it should be uncategorized.
Then these messages should be categorized and printed in different colors, red first in red colour etc.
First, do you agree with lists' idea? Do you suggest a more efficient way? What do you suggest for the substring search?
Excuse the lame examples and if my description in the title is not clear. I am new to this and looking for ideas.

A: You can use regular expressions.  Instead of this:
{"apple", "rose mary", "watermelon"}

Use this:
std::regex red("apple|rose mary|watermelon");

Then for each input line:
if (std::regex_search(line, red)) {
    // it's red
}

You can then create a vector<pair<regex, string>> and name each pattern:
vector<pair<regex, string>> patterns = {
    {"apple|rose mary|watermelon", "red"},
    {"cucumber|avocado|pine tree", "green"},
    {"sea|lake", "blue"},
};

This way you can easily iterate over all the patterns and get the color for any match.


text:
Q: Finding N random neighbors in radius in 2D Currently, I am tweaking my implementation of Boids algorithm.
This algorithm requires fixed-radius near neighbors search. For each boid (it could be 50-100k of them) you want to check all neighbors in some radius (usually it is equal to boid view range).
However, I found that the algorithm works well if I just check not all but just around 30 randomly chosen neighbors. Randomness is key here so k-nearest neighbors algorithm is not ideal.
So I am looking for fast way to find these 30 random neighbors in a given radius. Before I was using KDTree from nanoflann library to perform a fixed radius search. I guess the complexity of such search in the worst case scenario when all boids have the same position is at least O(n). I was wondering if the search of k random neighbors in a given radius can be done with complexity around O(k*log(n)) and if so which algorithm could be used.


text:
Q: multiple attributes being affected at once When I change the stats.hp or base_stats.hp value for the Creature class, it always sets both values at once, which is a problem because it means I cannot reset the creature's hp to it's base value. Here's some of the code that deals with this
class Stats:

    def __init__ (self,hp,height,strength,speed,skill,agility,perception):
        x = random.randint(-2,2)
        self.hp = hp+x
        x = random.randint(-10,10)
        self.height = height+x
        x = random.randint(-2,2)
        self.strength = strength+x
        x = random.randint(-2,2)
        self.speed = speed+x
        x = random.randint(-1,1)
        self.skill = skill+x
        x = random.randint(-2,2)
        self.agility = agility+x
        x = random.randint(-2,2)
        self.perception = perception+x

class Creature:

    def __init__ (self,name,stats,top_image,side_image):
        self.name = name
        self.base_stats = stats
        self.stats = stats
        # More code here for rest of attributes

Maybe the problem is because the Creature.stats and Creature.base_stats are referencing the same stats variable?
(edit)
The stats referenced in the __init__ of the Creature class is a Stats object

A: Yes. They reference the same object. You could use copy, instead.
from copy import copy
self.base_stats = copy(stats)
self.stats = copy(stats)

A: the stats in your __init__ function is an object of Class Stats correct?  therefore you are assigning the SAME object to self.base_stats and self.stats.  So any update to either of those will affect the other because you are changing the ONLY Stats object that your creature has as an attribute.
class Creature:

    def __init__ (self,name,stats,top_image,side_image):
        self.name = name
        self.base_stats = stats
        self.stats = stats


text:
Q: Сборка программы, использующей OpenSSL, для разных линуксов Есть кроссплатформенная программа заказчика под Window/OsX/Linux - C++/Qt/Qml. С линуксами возникает проблема линковки Qt с openssl. Если компилирую программу на LinuxMint, то на Debian при запуске программа ругается на несовместимую версию openssl. На Ubuntu проблем не возникает. При этом, напрямую openssl в программе не используется. Если не ошибаюсь, только QNetworkAccessManager. То есть, openssl используется опосредственно через Qt либы.
Какие есть варианты решения этой проблемы? Есть ли возможность собирать один бинарник для Mint, Ubuntu и Debian?
По-умолчанию Qt динамически загружает openssl либы из системы. Но при сборке самой Qt используется конкретная либа openssl, которая может быть несовместима с openssl на целевой системе. Debian использует более свежие либы, чем Mint и Ubuntu. Как это разрулить - не понятно.

A: Если программа устанавливается в отдельную папку (как многие делают в /opt/) есть такой вариант.
1 LD_LIBRARY_PATH
Скопируй нужную версию libcrypto и libssl в папку с программой и сделай симлинки на libcrypto.so.1.1, libssl.so.1.1 и на libcrypto.so.1.0.0 .
Это поломает системный линковщик и все запустится хорошо.
Есть ещё моменты с glibc. Для запуска на старых дистрах понадобится сборка под manylinux.
2 LD_PRELOAD
Более аккуратный способ, который используют многие проприетарщики.
Также скидываем нужные библиотеки в папку с приложением и делаем обертку для запуска.
#!/bin/bash
LD_PRELOAD=./libcrypto.so ./my-programm

3 И если проект не большой, то линкуйте статический файл.

A: Сделать свой набор библиотек с которыми вы будете деплоить приложение. Это не единственные грабли на которые вы наступите пытаясь пользоватся системными библиотеками.


text:
Q: How do you reference example request body in rAML? Is it possible to reference a json block from within the same rAML file for request/response examples? From the spec there does not appear to be a way to do this other than having an external file; but I'd like to have the example and schema live next to each other if possible. Much like how you can use schema:
schemas:
  - awesomeSchema: |
      { ... }
# Is this possible?
examples: |
  - awesomeExample: |
      { ... }

/awesome:
  get:
    responses:
      200:
       body:
          application/json:
            schema: awesomeSchema
            example: awesomeExample

A: While it's not part of the spec, it's actually supported, since RAML is a superset of YAML which does have a syntax for DRY-ing repeated blocks. Quoting the spec:

Repeated nodes (objects) are first identified by an anchor (marked with the ampersand - "&"), and are then aliased (referenced with an asterisk - "*") thereafter.

Applying that to your example:
/awesome:
  get:
    responses:
      200:
       body:
          application/json:
            example: &awesomeExample |
              {
                id: 123,
                type: "foobar"
              }
/delicious:
  get:
    responses:
      200:
        body:
          application/json:
            example: *awesomeExample

A: It will be possible in RAML 1.0, have a look at https://github.com/raml-org/raml-spec/issues/107


text:
Q: Prob. 10, Chap. 5 in Baby Rudin: If $f(x)\to 0$, $g(x)\to 0$, $f^\prime(x)\to A$, $g^\prime(x)\to B$ as $x\to 0$, and $B\neq 0$, then $f(x)/g(x)\to$ Here is Prob. 10, Chap. 5 in the book Principles of Mathematical Analysis by Walter Rudin, 3rd edition:

Suppose $f$ and $g$ are complex differentiable functions on $(0, 1)$, $f(x) \to 0$, $g(x) \to 0$, $f^\prime(x) \to A$, $g^\prime(x) \to B$ as $x \to 0$, where $A$ and $B$ are complex numbers, $B \neq 0$. Prove that
  $$ \lim_{x \to 0} \frac{ f(x) }{ g(x) } = \frac{A}{B}. $$
  Compare with Example 5.18. Hint:
  $$ \frac{ f(x) }{ g(x) } = \left\{ \frac{ f(x) }{x} - A \right\} \cdot \frac{x}{ g(x) } + A \cdot \frac{ x }{ g(x) }. $$
  Apply Theorem 5.13 to the real and imaginary parts of $f(x)/x$ and $g(x)/x$.

Now here is Theorem 5.13:

Suppose $f$ and $g$ are real and differentiable in $(a, b)$, and $g^\prime(x) \neq 0$ for all $x \in (a, b)$, where $-\infty \leq a < b \leq +\infty$. Suppose
  $$ \frac{f^\prime(x)}{g^\prime(x)} \to A \ \mbox{ as } \ x \to a. \tag{13} $$
  If
  $$ f(x) \to 0 \ \mbox{ and } \ g(x) \to 0 \ \mbox{ as } \ x \to a, \tag{14} $$
  or if
  $$ g(x) \to +\infty \ \mbox{ as } \ x \to a, \tag{15} $$
  then
  $$ \frac{f(x)}{g(x)} \to A \ \mbox{ as } \ x \to a. \tag{16}$$
  The analogous statement is of course also true if $x \to b$, or if $g(x) \to -\infty$ in (15). Let us note that we now use the limit concept in the extended sense of Definition 4.33.

Here is Definition 4.33:

Let $f$ be a real function defined on $E \subset \mathbb{R}$. We say that
  $$ f(t) \to A \ \mbox{ as } \ t \to x, $$
  where $A$ and $x$ are in the extended real number system, if for every neighborhood $U$ of $A$ there is a neighborhood $V$ of $x$ such that $V \cap E$ is not empty, and such that $f(t) \in U$ for all $t \in V \cap E$, $t \neq x$.

My effort:

By Theorem 5.13, we note that
  $$ \lim_{x\to 0} \frac{ \Re f(x)}{x} = \lim_{x\to 0} \frac{ \Re f^\prime(x)}{1} = \Re A, $$
  $$ \lim_{x\to 0} \frac{ \Re g(x)}{x} = \lim_{x\to 0} \frac{ \Re g^\prime(x)}{1} = \Re B, $$
  $$ \lim_{x\to 0} \frac{ \Im f(x)}{x} = \lim_{x\to 0} \frac{ \Im f^\prime(x)}{1} = \Im A, $$
  and
  $$ \lim_{x\to 0} \frac{ \Im  g(x)}{x} = \lim_{x\to 0} \frac{ \Im  g^\prime(x)}{1} = \Im B. $$
  So
  $$\lim_{x \to 0} \frac{ f(x) }{x} = \lim_{x\to 0} \frac{ \Re f(x) + \iota \Im f(x) }{x} = \lim_{x\to 0} \frac{\Re f(x) }{x} + \iota \lim_{x\to 0} \frac{\Im f(x) }{x} = \Re A + \iota \Im A = A,$$
  and
  $$\lim_{x \to 0} \frac{ g(x) }{x} = \lim_{x\to 0} \frac{ \Re g(x) + \iota \Im g(x) }{x} = \lim_{x\to 0} \frac{\Re g(x) }{x} + \iota \lim_{x\to 0} \frac{\Im g(x) }{x} = \Re B + \iota \Im B = B.$$
  Since $B \neq 0$, therefore
  $$\lim_{x \to 0} \frac{ x }{g(x)} = \frac{1}{B},$$
  and so
  $$
\begin{align}
\lim_{x\to 0} \frac{ f(x) }{ g(x) } &= \lim_{x\to 0} \left[ \left\{ \frac{ f(x) }{x} - A \right\} \cdot \frac{x}{ g(x) } + A \cdot \frac{ x }{ g(x) } \right] \\
&= \lim_{x\to 0} \left\{ \left( \frac{ f(x) }{x} - A \right)  \frac{x}{ g(x) } \right\} \ + \  \lim_{x\to 0} \left( A \cdot \frac{ x }{ g(x) } \right) \\
&= \lim_{x\to 0} \left( \frac{ f(x) }{x} - A \right)  \lim_{x\to 0} \frac{x}{g(x)} \ + \ A \lim_{x\to 0} \frac{ x }{ g(x) } \\
&= 0 \cdot \frac{1}{B} + A \frac{1}{B} \\
&= \frac{A}{B}.
\end{align}
$$
  In the above chain we have been able to split the limit into a sum and then into a product because all the limits involved exist.

Is my reasoning correct and rigorous enough for Rudin? If so, then is my presentation good enough as well? Have I used Rudin's hint correctly?
If not, then what is wanting in my attempt?

A: TL;DR: I can't see nothing wrong with your reasoning!
The main deal (and why we use the somewhat crazy hint) is that it's quite difficult to split $\frac{f(x)}{g(x)}$ into real and imaginary parts directly; besides, if $B\neq 0$, its (for example) real part may as well be $0$.


text:
Q: how to get latitude/longitude from one geo address using Qt c++ on windows? Its is possible get the coordinates(latitude and longitude), of a geo location using just the geo address (country, state, city, street, etc...), on Qt c++?
I know the libraries QGeoCoordinates, QGeoLocation and QGeoAddress, but i don´t know if is possible get coordinates from an address through them.
Every help is welcome.

A: I needed some time to master this but finally I got it working.
At first I tried the classes mentioned by you: QGeoAddress, QGeoLocation, QGeoCoordinate:
// standard C++ header:
#include <iostream>

// Qt header:
#include <QGeoAddress>
#include <QGeoCoordinate>
#include <QGeoLocation>

using namespace std;

int main()
{
  // build address
  QGeoAddress qGeoAddr;
  qGeoAddr.setCountry(QString::fromUtf8("Germany"));
  qGeoAddr.setPostalCode(QString::fromUtf8("88250"));
  qGeoAddr.setCity(QString::fromUtf8("Weingarten"));
  qGeoAddr.setStreet(QString::fromUtf8("Heinrich-Hertz-Str. 6"));
  QGeoLocation qGeoLoc.setAddress(qGeoAddr);
  QGeoCoordinate qGeoCoord = qGeoLoc.coordinate();
  cout
    << "Lat.:  " << qGeoCoord.latitude() << endl
    << "Long.: " << qGeoCoord.longitude() << endl
    << "Alt.:  " << qGeoCoord.altitude() << endl;
  return 0;
}

This compiles and run but the output is not very enjoying:
$ ./testQGeoAddress
Qt Version: 5.6.2
Lat.:  nan
Long.: nan
Alt.:  nan

So, what's wrong with the code? Leaning back and thinking a little bit about this I got a clue: There is some kind of service missing which could transform the address into the coordinates. What could this be? maps.google.com or something similar?
I googled a while and finally found hits concerning the Qt location library. After experimenting and fiddling a while, I finally got this running example:
File testQGeoAddress.pro:
SOURCES = testQGeoAddress.cc

QT += widgets
QT += positioning
QT += location

File testQGeoAddress.cc:
// standard C++ header:
#include <iostream>
#include <string>

// Qt header:
#include <QApplication>
#include <QGeoAddress>
#include <QGeoCodingManager>
#include <QGeoCoordinate>
#include <QGeoLocation>
#include <QGeoServiceProvider>

using namespace std;

int main(int argc, char **argv)
{
  cout << "Qt Version: " << QT_VERSION_STR << endl;
  // main application
#undef qApp // undef macro qApp out of the way
  QCoreApplication qApp(argc, argv);
  // check for available services
  QStringList qGeoSrvList
    = QGeoServiceProvider::availableServiceProviders();
  for (QString entry : qGeoSrvList) {
    cout << "Try service: " << entry.toStdString() << endl;
    // choose provider
    QGeoServiceProvider qGeoService(entry);
    QGeoCodingManager *pQGeoCoder = qGeoService.geocodingManager();
    if (!pQGeoCoder) {
      cerr
        << "GeoCodingManager '" << entry.toStdString()
        << "' not available!" << endl;
      continue;
    }
    QLocale qLocaleC(QLocale::C, QLocale::AnyCountry);
    pQGeoCoder->setLocale(qLocaleC);
    // build address
    QGeoAddress qGeoAddr;
    qGeoAddr.setCountry(QString::fromUtf8("Germany"));
    qGeoAddr.setPostalCode(QString::fromUtf8("88250"));
    qGeoAddr.setCity(QString::fromUtf8("Weingarten"));
    qGeoAddr.setStreet(QString::fromUtf8("Heinrich-Hertz-Str. 6"));
    QGeoCodeReply *pQGeoCode = pQGeoCoder->geocode(qGeoAddr);
    if (!pQGeoCode) {
      cerr << "GeoCoding totally failed!" << endl;
      continue;
    }
    cout << "Searching..." << endl;
    QObject::connect(pQGeoCode, &QGeoCodeReply::finished,
      [&qApp, &qGeoAddr, pQGeoCode](){
        cout << "Reply: " << pQGeoCode->errorString().toStdString() << endl;
        switch (pQGeoCode->error()) {
#define CASE(ERROR) \
case QGeoCodeReply::ERROR: cerr << #ERROR << endl; break
          CASE(NoError);
          CASE(EngineNotSetError);
          CASE(CommunicationError);
          CASE(ParseError);
          CASE(UnsupportedOptionError);
          CASE(CombinationError);
          CASE(UnknownError);
#undef CASE
          default: cerr << "Undocumented error!" << endl;
        }
        if (pQGeoCode->error() != QGeoCodeReply::NoError) return;
        // eval. result
        QList<QGeoLocation> qGeoLocs = pQGeoCode->locations();
        cout << qGeoLocs.size() << " location(s) returned." << endl;
        for (QGeoLocation &qGeoLoc : qGeoLocs) {
          qGeoLoc.setAddress(qGeoAddr);
          QGeoCoordinate qGeoCoord = qGeoLoc.coordinate();
          cout
            << "Lat.:  " << qGeoCoord.latitude() << endl
            << "Long.: " << qGeoCoord.longitude() << endl
            << "Alt.:  " << qGeoCoord.altitude() << endl;
        }
        qApp.exit(0);
      });
    return qApp.exec();
  }
  return 0;
}

Build with g++ in cygwin on Windows 10 (64 bit):
$ qmake-qt5

$ make
g++ -c -pipe -fno-keep-inline-dllexport -O2 -std=gnu++11 -Wall -W -D_REENTRANT -fexceptions -DQT_NO_DEBUG -DQT_WIDGETS_LIB -DQT_LOCATION_LIB -DQT_QUICK_LIB -DQT_GUI_LIB -DQT_POSITIONING_LIB -DQT_QML_LIB -DQT_NETWORK_LIB -DQT_CORE_LIB -I. -I/usr/include/qt5 -I/usr/include/qt5/QtWidgets -I/usr/include/qt5/QtLocation -I/usr/include/qt5/QtQuick -I/usr/include/qt5/QtGui -I/usr/include/qt5/QtPositioning -I/usr/include/qt5/QtQml -I/usr/include/qt5/QtNetwork -I/usr/include/qt5/QtCore -I. -I/usr/lib/qt5/mkspecs/cygwin-g++ -o testQGeoAddress.o testQGeoAddress.cc
g++  -o testQGeoAddress.exe testQGeoAddress.o   -lQt5Widgets -lQt5Location -lQt5Quick -lQt5Gui -lQt5Positioning -lQt5Qml -lQt5Network -lQt5Core -lGL -lpthread

$ ./testQGeoAddress.exe
Qt Version: 5.6.2
Try service: mapbox
GeoCodingManager 'mapbox' not available!
Try service: osm
Searching...
Reply:
NoError
1 location(s) returned.
Lat.:  47.8198
Long.: 9.63105
Alt.:  nan

$

Not bad for the first try. About the QGeoCoordinate::altitude() value: this might be not available from Open Street Map (osm).
To check whether the result is correct I resolved the output coordinate in maps.google.com:

The red balloon is the result of the search. I added the blue dot in GIMP to remark the correct position. Well, the search was close to the correct position. The difference might be caused by the limited precision of coordinates...

A: I think it is possible. I never tried though.
Please try with below code.
Note: The address' attributes are normalized to US feature names and can be mapped to the local feature levels (for example State matches "Bundesland" in Germany). (Copied form documentation)
//Create a geo address object.

QGeoAddress *add = new QGeoAddress();

//Assumed for USA.
//Try below order so that search may be bit quicker.
add->setCountry("Country name");
add->setCountryCode("country code");
add->setState("state");
add->setCity("city name");
add->setCounty("county name");
add->setStreet("street name")
add->setPostalCode("Zip Code")

//Create a geo location object

QGeoLocation *loc = new QGeoLocation();
QGeoLocation::setAddress(add); //Set the QGeoLocation object

//Get the coordinates by QGeoCoordinate
QGeoCoordinate cord = loc->coordinate();

//Now get the coordinates for latitude and longitude.
double latitude = cord.latitude();
doublelongitude = cord.longitude();


text:
Q: Inconsistency in definition of characteristics for a linear PDE? Folland versus Fritz John. There seems to be a major inconsistency (perhaps due to my lack of understanding) between what Folland calls a "characteristic" and what I had previously thought was a characteristic.
For example, Folland says that the characteristics of the equation $\partial_x u = 0$ are $\{ \xi : \xi_1 = 0\}$ (in $\mathbb{R}^2$). This confuses me to no end since I thought the characteristic hypersurface was the $x_1$ axis here? According to this definition it's the orthogonal compliment to this. The same issue arises with the heat operator $L=u_t-u_{xx}$ where he says the characteristics are $\{\xi \neq 0 : \xi_x = 0\}$. Aren't the characteristics $t=$ cosntant which are orthogonal to these?
Sorry if this question is elementary but it's given me a real headache and I'm not sure what it is I'm missing here.


text:
Q: UI bug in favicon sprite? Looks like there's a small design bug with the icons in the favicon sprite in the Hot Network Questions section of the page (Maybe they're too close togther? )
I'm using opera 18.0 on Windows 7 (at 110% zoom) <-- Thanks @Shadow Wizard


text:
Q: Updating attributes from check_box I'm using nested models in my first Ruby on Rails app and now I've run into a problem. I have a Survey model that has_many :questions which in turn belongs_to :survey and the model Question has_many :answers. My Answer model then belongs_to :question.
Now I want to update a boolean attribute :guess within my :answers controller. To this end I've created a new action :quiz_guess which looks like this:
      def quiz_guess
         Answer.update(params[:id], guess: false)
             puts("Guess saved")
         redirect_to(:action => 'show', :id => @survey.next, :survey_id => @survey.id)
      end

my view looks like this:
    <%= form_tag quiz_guess_questions_path, :method => :put do %>
       <% for question in @survey.questions do %>

<%= h question.content %>

            <% for answer in question.answers do %>

<%= h answer.content %>
                   <%= form_for :guess do |f| %>
                     <%= f.check_box(:guess, :method => :put) %>
                   <% end %>

            <% end %>
       <% end %>
    <% end %>

Obviously I've read the documentation, as well as this blog post, but I don't understand how to implement it in my controller and view.
With this code I'm not able to update the correct :guess attribute but rather I update a different one (with a different :id). Can anybody shed some light as to what I do wrong?

A: I ended up looking at this Railscast where Ryan Bates shows how to update multiple attributes with fields_for. This is my new view:
   <%= form_tag quiz_guess_questions_path, :method => :put do %>
     <% for question in @survey.questions do %>

<%= question.content %>

         <% for answer in question.answers do %>

            <%= fields_for "answers[]", answer do |f| %>
              <%= answer.content %>
              <%= f.check_box :guess %>
            <% end %>

         <% end %>
     <% end %>
    <%= submit_tag "Guess" %>
   <% end %>

and my new controller:
  def quiz_guess
     Answer.update(params[:answers].keys, params[:answers].values)
     flash[:notice] = "Guess saved successfully."
     redirect_to questions_url
  end


text:
Q: slurm: srun & sbatch different performance with the same settings In a slurm system, when I use srun command to run the program. It runs very slow and seems like only one processor works.
 srun --pty -A free -J test  -N 1 -n 1 -c 1  mpirun -np 16
 $FEAPHOME8_3/parfeap/feap  -log_summary lu.log

But if I write a sbatch script, it can run very quickly and looks like all the processors work.
#!/bin/sh -l
#SBATCH --job-name=test
#SBATCH --account=free
#SBATCH --nodes=1
#SBATCH --ntasks-per-node=24
#SBATCH --cpus-per-task=1
#SBATCH --exclusive
#SBATCH --time=6:00:00

echo ' '
echo ' ****** START OF MAIN-JOB ******'
date

srun -n 16 echo y | mpirun -np 16 $FEAPHOME8_3/parfeap/feap -log_summary lu.log

echo ' ****** END OF MAIN-JOB ******'

#End of script

Could anybody please tell me what's going on?

A: The parameters -N 1 -n 1 -c 1  request one single CPU on one node. Replace them with -n 16  and remove the mpirun ; the srun will handle the MPI startup process.


text:
Q: Got errors when using XMLHttpRequest I have problems when using XMLHttpRequest. One occurs in Chrome; the other in firefox
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4) {
        if (this.status == 200)
            elmnt.innerHTML = this.responseText;
        }
        if (this.status == 404) {
            elmnt.innerHTML = "Page not found.";
        }
    }
}
xhttp.open("GET", file, true);
xhttp.send();

I'm working locally, i.e. all protocols are file://
In chrome, where I have added parameter --allow-file-access-from-files, this.status is 0. Why?
In firefox, the status is 200, but there will be a XML parsing error when the included file has code like this:
<script>
alert(-1<1);
</script>

and an XML parsing syntax error occurred indicating 10th character.
Why? I guess firefox does not recognize '<' between script.
Are they bugs or some issues I don't know yet?


text:
Q: Achieve an output of 0-5v using 2 hall sensors as the inputs I am modifying a kids ride-on car to use brushless motors with VESCs, but I wish to use 1 hall sensor pedal for accelerator and a 2nd identical pedal for regenerative braking.
I have seen that a server tester can be used between a hall sensor accelerator and an ESC or VESC where the server tester can convert the hall sensor 1-4v signal to PWM for the ESC quite easily, as can be seen here:
https://www.youtube.com/watch?fbclid=IwAR3_tVIt20qbNBgBcchpa_ioEIgs-w6Vu9u-UVrzC7BLmhRJMzwLWKs_U_Q&v=cceUTv6tAaA
I want to have an accelerator pedal, when released leaves the motor just coasting and no regenerative braking enabled yet, but when the brake pedal is pressed regenerative braking starts to come into effect. I would also like the accelerator pedal signal to be ignored when the brake pedal starts to be depressed, so the brake pedal overrides the accelerator pedal when both are depressed.
I was thinking this could possibly be done with some op amps, but as it has been around 40 years since I did any electronic theory I have no idea to design such a circuit now.
I will start doing some research meanwhile, but some suggestions would be greatly appreciated. Thanks in advance.
Any help in the way of example circuitry would be greatly appreciated


text:
Q: Different Li Sizes Could you please assist with how to make one of my Lis Could you please assist with how to make one of my LisCould you please assist with how to make one of my LisCould you please assist with how to make one of my Lis

Home

Home

body {
    margin: 0px;
    background-repeat: no-repeat;
}

#pageTop {
    height: 172px;
}

nav {
  margin: 0px auto;
  overflow: scroll;
  width: auto;
  height: 95px;
}

nav ul {
    margin: 0px auto;
    overflow: scroll;
}

nav ul li {
    display: inline-block;
    height: 70px;
    text-align: center;
    float:left;
    overflow: hidden;
}

A: Hmmm, I think you could make use of the nth-child CSS selector here.
I assume you want the fourth
 to take up the width of three normal
 elements (as defined in your existing CSS), so the width we want will be: 10.66666667% * 3 = 32%.
Delete the extra 2
 elements in your HTML, and use nth-child(4), like so:
nav ul > li:nth-child(4){
    width: 32%;
}

Now, the fourth
 element will be three times the width of the other ones. Here's a JSFiddle to show you what this achieves. (I set a temporary background colour so you can see the fourth one.) If you have any questions, let me know!


text:
Q: Why does my saved fragment is always null? I'm trying to save my fragment instance (at least i'd like to save model instance) in my app. I have a bottom navigation activity and this fragment get a straem of data from a ble device. I want to give te opportunity to the user so navigate in fragments while receiving data. I can do it but when I came back to the acquisition fragment it creates another instance of the object that get data so I lose controll of the one is currently working. So I want to save fragment instance. I tried every answer from this and from android developers description.
As you can see from my code here I save only a boolean now to try if it works.
@Override
public void onSaveInstanceState(@NonNull Bundle saved) {
    // call superclass to save any view hierarchy

    out.println("Saving...");
    out.println(start);
    if (!start)
    {
        /*Gson gson = new Gson();
        String json= gson.toJson(model);
        out.println(json);
        outState.putString("MODEL", json);*/
        saved.putBoolean("START", start);
    }
    super.onSaveInstanceState(saved);

}

Anyway when I change fragment nothing happens, but I can save it calling this function in onDestroy callback.
    @Override
public void onDestroyView()
{
    super.onDestroyView();
    Bundle saved = new Bundle();
    this.onSaveInstanceState(saved);
    model.stop();
    model.disconnect();
    out.println("Destroy yourself");

}

But in onCreateView and in onCreate my bundle is still null. I don't understand why.
    @Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    out.println(savedInstanceState);
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        start = savedInstanceState.getBoolean("START");
        out.println(start);
    } else {
        start = false;
    }
}

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    out.println(savedInstanceState);
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        start = savedInstanceState.getBoolean("START");
        out.println(start);
    } else {
        start = false;
    }
    model = new ViewModelProvider(this).get(AcquisitionModel.class);

    model.getFreq().observe(getViewLifecycleOwner(), freq -> {
        updateFreq(freq);
    });
    model.getOrder().observe(getViewLifecycleOwner(), order -> {
        updateOrder(order);
    });
    model.getToDrawn().observe(getViewLifecycleOwner(),  toDrown-> {
        draw(toDrown);
    });
    View root = inflater.inflate(R.layout.fragment_acquisition, container, false);

    graph = (GraphView) root.findViewById(R.id.line_graph);
    graph.getViewport().setXAxisBoundsManual(true);
    GridLabelRenderer gridLabel = graph.getGridLabelRenderer();
    //gridLabel.setPadding(64);
    util = new AppUtilis(this.getContext());
    //graph.getViewport().setMaxX(5);

    series = new LineGraphSeries<>();
    graph.getViewport().setScalable(true);
    graph.getViewport().setScrollable(true);
    //series.setThickness(3);

    graph.addSeries(series);

    text= root.findViewById(R.id.frequenza);
    RG = (RadioGroup) root.findViewById(R.id.RG);
    RG.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
    {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            // checkedId is the RadioButton selected

            String nonso = "";
            if (checkedId== R.id.ecg_switch) {
                TextView text= (TextView) root.findViewById(R.id.label);
                text.setText("Frequenza cardiaca (BPM)");
                nonso = "ecg";
            }
            else
            {
                TextView text= (TextView) root.findViewById(R.id.label);
                text.setText("Frequenza respiratoria");
                nonso = "resp";
            }
            model.scambio(nonso);
        }
    });

    B_start= (Button) root.findViewById(R.id.start_stop);
    B_start.setOnClickListener(new View.OnClickListener()
    { //utente pigia il bottone

        @Override

        public void onClick(View v) {

            //controllo se esiste il dispositivo
            if (model.isConnected() || disp != null) {
                boolean ans;
                if (start) {
                    ans = model.stop();
                    if (ans) {
                        start = false;//chiama lo stop
                        B_start.setText("Start");

                        //set colore standard
                        B_start.setBackgroundColor(Color.rgb(3, 218, 197));
                    }
                } else {
                    ans = model.start();
                    if (ans) {
                        start = true;
                        graph.removeAllSeries();
                        series = new LineGraphSeries<>();
                        series.setThickness(3);
                        graph2LastXValue = 0d;
                        graph.addSeries(series);
                        B_start.setText("Stop");
                        B_start.setBackgroundColor(Color.rgb(255, 0, 0));
                    }
                }
            }
            else
            {
                util.alert("Attenzione", "Non sei connesso!");
            }

        }

    });
    B_export = (Button) root.findViewById(R.id.exp);
    B_export.setOnClickListener(new View.OnClickListener()
    { //utente pigia il bottone
        @Override

        public void onClick(View v) {
            Log.d("saving", "premuto");
            if (model.isConnected() || disp != null) {

                util.loading("Sto salvando", false);
                model.stop();
                start = false;//chiama lo stop
                B_start.setText("Start");
                B_start.setBackgroundColor(Color.rgb(3, 218, 197));

                boolean ans = model.saveAll();
                analyzeCough(model.getResp().getFile(), model.fc);

                util.loadingFinished();
                if (ans)
                {
                    util.alert("Successo", "Esportazione avvenuta! Cerca nella cartella Registrazioni nella memoria interna del telefono");
                }
                else {
                    util.alert("Errore", "Esportazione fallita");
                }

            }
            else
            {
                util.alert("Attenzione", "Non sei connesso!");
            }
        }
    });
    share = root.findViewById(R.id.share);
    share.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (model.isConnected() || disp != null) {
                //funzione per condividere i file
                //controllo se non sia già stato fatto un export
                util.loading("Sto salvando", false);
                //model.disconnect();
                start = false;//chiama lo stop
                B_start.setText("Start");
                B_start.setBackgroundColor(Color.rgb(3, 218, 197));
                model.stop();
                boolean ansi = model.saveAll();
                analyzeCough(model.getResp().getFile(), model.fc);
                ArrayList<File> fil = model.getAllFiles();
                util.loadingFinished();
                if (ansi) {
                    StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
                    StrictMode.setVmPolicy(builder.build());
                    //provo la condivisione
                    //prendi i path con una funzione dal model
                    try {
                        Intent sharingIntent = new Intent();
                        sharingIntent.setAction(Intent.ACTION_SEND_MULTIPLE);
                        sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Here are some files.");
                        sharingIntent.setType("text/*");
                        ArrayList<Uri> files = new ArrayList<Uri>();
                        for (int i = 0; i < fil.size(); i++) {
                            files.add(Uri.fromFile(fil.get(i)));
                        }
                        sharingIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, files);
                        startActivity(Intent.createChooser(sharingIntent, "Condividi con"));
                        out.println("Post sharing");
                    } catch (Exception e) {
                        e.printStackTrace();
                        util.alert("Errore", "Condivisione fallita!");
                    }

                } else {
                    util.alert("Errore", "Condivisione fallita");
                }
            }
            else
            {
                util.alert("Attenzione", "Non sei connesso!");
            }

        }
    });
    return root;
}

I also tried to save the fragment from activity as mentioned by someone as answer in the link I posted before but it doesn't work too. Has someone any idea?
Thanks in advance.
EDIT
Here is my onCreate in Activity
    @Override
protected void onCreate(Bundle savedInstanceState) {
    model = new ViewModelProvider(this).get(ConnectionViewModel.class);
    ActivityCompat.requestPermissions(this,
            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.INTERNET},
            REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && !Environment.isExternalStorageManager()) {
        // solo funzioni nuove e solo se non è già stato accettato
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
        Uri uri = Uri.fromParts("package", this.getPackageName(), null);
        intent.setData(uri);
        startActivity(intent);
    }
    try {
        setTheme(R.style.splashScreenTheme);
        super.onCreate(savedInstanceState);
        sleep(2000);
    } catch (Exception e) {
        e.printStackTrace();
    }
    setTheme(R.style.Theme_Ble);
    setContentView(R.layout.activity_main3);
    BottomNavigationView navView = findViewById(R.id.nav_view);
    // Passing each menu ID as a set of Ids because each
    // menu should be considered as top level destinations.
    AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
            R.id.tosse, R.id.grafici, R.id.elettrodi)
            .build();
    NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);

    util = new AppUtilis(this);
    NavigationUI.setupWithNavController(navView, navController);
    Button easter;
    easter = (Button) findViewById(R.id.easterEgg);
    easter.setOnClickListener(new View.OnClickListener()
    {

        @Override
        public void onClick(View v)
        {
            System.out.println("uovooooo");
            Intent intent = new Intent(util.getContext(), SettingsActivity.class);
            System.out.println("Vado a cercare roba");
            startActivityForResult(intent, 3);

        }
    });
    Ble = (ImageButton) findViewById(R.id.IconaBle);
    Ble.setOnClickListener(new View.OnClickListener()
    {

        @Override
        public void onClick(View v)
        {
            final BluetoothManager bluetoothManager =
                    (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
            BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter();

            // Ensures Bluetooth is available on the device and it is enabled. If not,
            // displays a dialog requesting user permission to enable Bluetooth.
            final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled() ||  !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
                /*
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);*/
                util.alert("GPS e Bluetooth", "Per trovare dispositivi devi attivare GPS e Bluetooth");
            }
            else
            {
                Intent intent = new Intent(util.getContext(), BleScan.class);
                System.out.println("Vado a cercare roba");
                startActivityForResult(intent, 2);
            }

        }
    });

}

A: If you save any data in onDestoryView() it means app is closed. And savedInstanceState doesn't survive app close unless it is forcibly closed by system it self. So, onCreate() will print null even you saved the instance. Plus onDestroyView() doesn't necessariliy called always. Sometime os doesn't call onDestroyView(). You should try saving the object inside onPause() or onStop() if user is not leaving the app and you are loading the saved instance.


text:
Q: How do I change the output file in VSCode? In VSCode, while running python, every time I go to print something, I am met with an error. I can see that I am running a virtualenv that I have deleted and can not for the life of me figure out how to change the output. I am sure it is a simple solution, but how does one stop running VSCode output in an old and deleted file, and begin running new code in a working file/directory? I have cycled through every interpreter and run "print("...")" with the same result. I have deleted all virtual environments using "sudo rm -rf venv" and still receive the same error - that there is a missing file or directory. images provided below:
VSCode is [Running] a file I have deleted in Output -
example 1
/bin/sh: file or directory not found
example 2
I tried deleting all virtual environments, running the code in every available interpreter and searching every variation of this question to no avail.

A: Inside of VSCode extension "Code Runner" the settings.JSON file needed to be debugged. The initial curly braces were removed through some operation - and the output for python was:
"python": "python -u";
it needed to be changed to:
"python": "python3";
however the settings changes couldn't be implemented when changing the python output as the entire settings string was missing the first "{" braces - by deleting the entire settings list and leaving "{ }" the settings were reset, Code Runner extension was uninstalled automatically and upon installation, all settings were reloaded correctly (containing the initial curly braces that were missing) Then I was able to change:
"python -u" to "python3" and the output finally showed the commands.
Literal weeks to discover this answer and I tried everything.


text:
Q: Numpy unique function I have a quick question about the numpy unique function. I want to return the unique column values for each row
import numpy as np

a = np.array([[3, 2, 3, 2, 1, 3, 1, 2, 1, 3, 1, 2, 2, 2, 3, 3],
              [3, 2, 3, 2, 3, 3, 3, 3, 2, 2, 3, 1, 2, 1, 2, 1],
              [3, 3, 3, 2, 3, 3, 3, 2, 2, 2, 3, 2, 2, 3, 1, 1]]) # a.shape is (3,16)

np.unique(a)
array([1, 2, 3]) # not what I want

np.unique(a,axis=1)
array([[1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3],
       [2, 3, 1, 1, 2, 2, 3, 1, 2, 2, 3],
       [2, 3, 2, 3, 2, 3, 2, 1, 1, 2, 3]]) # also not what I want, and I'm not even sure what its doing

np.apply_along_axis(np.unique,1,a)
array([[1, 2, 3],
       [1, 2, 3],
       [1, 2, 3]]) # this is what I want

The problem is that I also want to use other features of np.unqiue, like returning index values. Can anyone help me to get np.unique to work by itself?

A: You can loop over rows and collect unique values:
import numpy as np

a = np.array([[3, 2, 3, 2, 1, 3, 1, 2, 1, 3, 1, 2, 2, 2, 3, 3],
              [3, 2, 3, 2, 3, 3, 3, 3, 2, 2, 3, 1, 2, 1, 2, 1],
              [3, 3, 3, 2, 3, 3, 3, 2, 2, 2, 3, 2, 2, 3, 1, 1]])

arr = np.empty((0,3), int)
for row in a:
    arr = np.append(arr, np.array([np.unique(a)]), axis=0)

Output:
[[1 2 3]
 [1 2 3]
 [1 2 3]]

A: numpy will not be able to return a matrix with rows of different sizes.  your example has exactly 3 distinct values per row which makes np.apply_along_axis work but if you had a value of 4 in one of the rows or only 1s and 2s on a row it would fail.
To obtain what you are looking for you will need to use a normal Python list as the result.  You can build it using a list comprehension:
import numpy as np

a = np.array([[1, 2, 2, 2, 1, 1, 1, 2, 1, 2, 1, 2, 2, 2, 1, 1],
              [3, 2, 3, 2, 3, 3, 3, 3, 2, 2, 3, 1, 2, 1, 2, 1],
              [3, 3, 3, 2, 3, 3, 4, 2, 2, 2, 3, 2, 2, 3, 1, 1]])

r = [ np.unique(row) for row in a ]
print(r)
# [array([1, 2]), array([1, 2, 3]), array([1, 2, 3, 4])]

r = [ np.unique(row,return_index=True)for row in a ]
print(r)
# [(array([1, 2]), array([0, 1])),
#  (array([1, 2, 3]), array([11,  1,  0])),
#  (array([1, 2, 3, 4]), array([14,  3,  0,  6]))]

One thing you could do is build a mask of the values that are the first of their kind on each row.  This can be done using numpy.
Here's one way to do it (hopefully, numpy experts could suggest something less convoluted):
np.sum(np.cumsum(np.cumsum(a==np.unique(a)[:,None,None],axis=2),axis=2)==1,axis=0)

array([[1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
       [1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0]])

Such a mask offers many processing options such as finding indices of the first occurrence on each line (using np.argwhere), erasing/assigning first or subsequent occurrences, and more.


text:
Q: I try to get data once from firestore but I recieve it thrice for each document in a collection
As I have mentioned in the code (in image) I try to get all documents for once but I get it thrice for each document.
  const docs = await db.collection("programs").get();
  docs.forEach((doc) => console.log(doc.data()));

A: I forgot to use componentDidMount in my component where I call this action creator. Now I fixed this


text:
Q: Swift: Extending Array with typed function doesn't work I have a problem with an extension on Array, I'm trying to add a method to detect if there are any duplicates, if I make it a global function it works, however, when I try to make it a method in an Array extension it complains:
extension Array {
    static func hasDuplicates<T:Hashable>(array:Array<T>) -> Bool {
        var map = Dictionary<T,Bool>()

        for var x = 0; x < array.count; x++ {
            let currentItem = array[x] as T
            if map[currentItem] {
                return true
            } else {
                map[currentItem] = true
            }
        }
        return false
    }
}

func hasDuplicates<T:Hashable>(array:Array<T>) -> Bool {
    var map = Dictionary<T,Bool>()

    for var x = 0; x < array.count; x++ {
        let currentItem = array[x] as T
        if map[currentItem] {
            return true
        } else {
            map[currentItem] = true
        }
    }
    return false
}

func testDuplicates() {
    var arrayWithDuplicates = [ "not repeated", "is repeated", "not repeated again", "repeated", "this isn't repeated", "repeated", "is repeated" ]
    var arrayWithoutDuplicates = [ "not repeated", "not repeated again","this isn't repeated", "isn't repeated" ]

    XCTAssert(hasDuplicates(arrayWithDuplicates), "There ARE duplicates")
    XCTAssert(hasDuplicates(arrayWithoutDuplicates) == false, "There AREN'T any duplicates")

    // Shows an error: Cannot convert the expression's type 'Void' to type 'String'
    XCTAssert(Array.hasDuplicates(arrayWithDuplicates), "There ARE duplicates")
    XCTAssert(Array.hasDuplicates(arrayWithoutDuplicates) == false, "There AREN'T any duplicates")
}

What am I doing wrong? or is it a bug in XCode?

A: You cannot use Array as a type without specifying the generic parameter:
Replace:
Array.hasDuplicates(arrayWithDuplicates)

with
Array<String>.hasDuplicates(arrayWithDuplicates)


text:
Q: Как установить серверную ubuntu на mac в качестве виртуальной ОС? Имеется ввиду следующее: как установить ubuntu, чтобы можно было из основной ОС(macOS) подключаться к ubuntu не прибегая к графическому отображению? Как будто ubuntu где-то далеко на чьем-то сервере и я к ней подключаюсь по ssh, т.е. не стандартный способ с помощью virtualBox.

A: Если говорить о запуске виртуальных машин "без окна" в фоновом режиме в контексте virtualbox, то можно это сделать либо жмякнув по имени виртуальной машины и далее "Запустить -> Запустить в фоновом режиме", либо сделать это через консоль:
vboxmanage startvm {"vmname" or UUID} --type headless

Это называется headless режим и прочитать о нём можно тут.


text:
Q: Node js chat bot issue: session.error() I have written a dummy bot using the latest botbuilder version : 3.4.4. My sample code is:
var server = restify.createServer();
server.listen(config.port,config.ip,function () {
try{
console.log('%s listening to %s', server.name, server.url);
console.log("Welcome to Banker Bot!!!!");
}
catch(err){
console.log("Server already in Use" + err);
}

});
var connector = new builder.ChatConnector({
appId: config.MICROSOFT_APP_ID,
appPassword: config.MICROSOFT_APP_PASSWORD

});
var bot = new builder.UniversalBot(connector);
server.post('/api/messages', connector.listen());
var recognizer = new builder.LuisRecognizer(config.model);
bot.dialog('/', [
function (session) {
session.beginDialog('/askName');
},
function (session, results) {
session.send('Hello %s!', results.response);
}
]);
bot.dialog('/askName', [
function (session) {
builder.Prompts.text(session, 'Hi! What is your name?');
},
function (session, results) {
session.endDialogWithResult(results);
}
]);

I am trying to talk to my bot using emulator. I am able to connect to bot as I get : "ChatConnector: Message Received" when I type anything, then I get a session.error(). Please guide me as to where I am going wrong. I am completely novice to chatbot and nodejs.
Thanks in advance

A: In your code you are calling results.response in session.send('Hello %s!', results.response); but here when I have run code results is undefined hence it goes in session.err dialog.


text:
Q: Java option -XX:OnOutOfMemoryError does not work when called through exec in bash script I have a java application and I want to run a script whenever it experiences and OutOfMemoryException
This works great:
$ java -server  -XX:OnOutOfMemoryError="./oom_script %p"  TestOOMClass
Unfortunately my application is run by a bash script in production. The script boils down to this:
cmd='java -server  -XX:OnOutOfMemoryError="./oom_script %p"  TestOOMClass'
##does a lot of checking and cmd building here
exec -a app  ${cmd}

When run like this java never respects the double quotes and thinks %p is the class. how do I prevent this? I've tried double escaping but that doesn't work.

A: Quotes and escaping is an art.  I would suggest you add echo ${cmd} before calling exec so you can see what it looks like then.
I would suggest using
cmd='java -server  -XX:OnOutOfMemoryError=\\"./oom_script %p\\"  TestOOMClass'

instead (untested).  You need it to look like \" when being echoed.

A: Since your program is run as a shell script, I would suggest putting this as the first line in your shell script after the shebang:
set -xv

Then, in the crontab, put 2>&1 at the end of the command line, so STDERR and STDOUT are merged. Crontab usually emails out the STDOUT of a command to root, so you can see what the output is. If not, then apend the following to the end of the command in your crontab:
> /somedir/output.$$ 2>&1

Make sure somedir exists, and after crontab runs your command, you'll see the verbose and debug output. Each line in your shell script will be displayed before it is executed -- both as written and as the shell actually interprets it.
The set -xv becomes very useful in debugging any sell script. There could be all sorts of environmental issues involved between the cronjob and the script running under your login. You might even find a shell issue. For example, crontab usually executes shell scripts in Bourne shell and you probably have Bash or Kornshell as your default shell. Whatever it is, you'll usually find out the issue very quickly when you turn on verbose/debug mode.
You don't even have to do this to the entire script. You can put set -xv anywhere in your script to turn on verbose/debug mode, and set +xv to turn it off.
I could make several pious high minded recommendations (use quotes, don't assume environment things, prefix your command line with "bash -c" to make sure you're using the right shell, etc.), but this would be guessing what could be wrong. In order to really debug this issue, I would need to see the machine, know the OS, see your entire shell script, and understand the entire environment. And, the first thing I would do is add set -xv in your shell script.

A: an alternative i suggest (to bypass the problem, not solve it indeed) is to rung and bash script and access the $PPID:
   PPID   The process ID of the shell's parent.  This variable is readonly.

then kill the process with that ID (please bare in mind that is an untested suggestion)


text:
Q: Give title to background image in HTML I have one multiple div which have one image in right top corner as background. I want to give some information (like title). Can any body tell how this can be achieved in case of background image.
Thanks,
Ashwani

A: You have to give the element that has the background image a title.
Something like:

A: A background image shouldn't convey any information, thus no need for a title (btw do you mean the title attribute on some element or a heading Hn?).
If you want to add a title, then you should use an img element with a correct alt that IE will incorrectly display as a tooltip. The title attribute should add complementary information, you'd better use the alt attribute alone.


text:
Q: eliminar valores repetidos de un grupo con SQL Quiero eliminar valores duplicados de una tabla sql pero no he podido eliminar solo tengo esta query que cuenta los valores repetidos de cada grupo, como puedo agregarle un delete a esta query?, Esta query ya esta filtrada solo no se como colocarle el DELETE

select TRANSIT_F, count(*)
from TBL  where ID_CARGA in (3940630,
3940631,
3940632,
3940633,
3940634,
3940635,
3940636,
3940637,
3940638,
3940639,
3940640,
3940641,
3940642)
group by TRANSIT_F
having count(TRANSIT_F) > 1

Lo que quiero eliminar son los repetidos de cada registro, en una columna tengo el valor unico y en la otra el numero de veces que se encuentra repetido