text:
Q: Scraping Google News with Rvest for Keywords I want to compare News Article from different countries for the usage of a specific keyword.
My idea is to scrape Google News using RCrawler:
RCrawler(website = "https://news.google.com/topics/CAAqIggKIhxDQkFTRHdvSkwyMHZNREZqY0hsNUVnSmtaU2dBUAE?hl=de&gl=DE&ceid=DE%3Ade", MaxDepth = 5, Keywordfilter = c("Keyword"), KeywordAccuracy = 99)
And then just counting the results that I'm getting back.
Im not sure if this is the best method or if its even correct but I'm new to R and its the best method i can currently think of.

A: Since you're using Google News, instead of scraping this way, an easier method would be to access the RSS feed for that particular keyword and pull that into a dataframe. Luckily, there is the {tidyRSS} package that you can use to do just this.
An example of what a feed looks like is with this URL:
https://news.google.com/rss/search?q=apple&hl=en-IN&gl=IN&ceid=IN:en

Learn how to customize this URL here. You can search by geolocation if you wish.
After you install tidyRSS, you can implement it like so:
library(tidyRSS)

# I will search for the keyword Apple

keyword <- "https://news.google.com/rss/search?q=apple&hl=en-IN&gl=IN&ceid=IN:en"
# From the package vignette

google_news <- tidyfeed(
  keyword,
  clean_tags = TRUE,
  parse_dates = TRUE
)

This gives you a dataframe with many variables that describe each article. You can choose which ones to keep.


text:
Q: Web Service roda mas ao consumir método dá erro Lutei para configurar meu web service no IIS. Ele sobe, mostrando a tela de que o WS está ok. Acontece que quando eu passo um parâmetro para ele dá esse erro:
REQUEST ERROR
The server encountered an error processing the request. See server logs for more details.

O IIS está num servidor AMAZON(Cloud).
Meu método
public TPDV getCnpjParceiro(string cnpj)
        {
            V99_WEBEntities db = new V99_WEBEntities();
            TPDV pdv = new TPDV();
            List<string> lista = new List<string>();

            var resultado = (from _lista in db.T_PDV
                             where _lista.CNPJ == cnpj
                             join _st in db.T_CRM_StatusPDV on _lista.CNPJ equals(_st.DE_Cnpj)
                             join _sc in db.T_Script on _st.IT_Status equals((int)_sc.TipoStatus)
                             select new
                             {
                                 _lista.CNPJ,
                                 _lista.RazaoSocial,
                                 _lista.Endereco,
                                 _lista.CaminhoLogo,
                                 _lista.Bairro,
                                 _lista.Cidade,
                                 _st.IT_Status,
                                 _st.DT_TransacaoV,
                                 tecnico = _sc.TipoScript == "T" ? _sc.Script : null,
                                 central = _sc.TipoScript == "C" ? _sc.Script : null
                             }).ToList();

            foreach (var lis in resultado)
            {
                pdv.CNPJ = lis.CNPJ;
                pdv.RazaoSocial = lis.RazaoSocial;
                pdv.Endereco = lis.Endereco;
                pdv.CaminhoLogo = lis.CaminhoLogo;
                pdv.Bairro = lis.Bairro;
                pdv.Cidade = lis.Cidade;
                pdv.ScriptCentral = lis.central;
                pdv.ScriptTecnico = lis.tecnico;
            }

            return pdv;

        }

Passo o parâmetro assim:
meu_ip/WebServiceSuporteTecnico/SuporteTecnicoServiceWS.svc/pesquisa/um_cnpj_da_minha_base

A: resolvi. O erro era o seguinte: Quando eu subi os arquivos para o IIS que está em uma máquina remota na Amazon, eu enviei também o meu web.config. O banco de dados que eu estou usando, se encontra na mesma máquina. Conversando com o cara que administra o Amazon aqui na empresa, ele me disse que o IP não é um IP real, é um IP mascarado, que aponta para o IP real, para que o mundo externo não tenha conhecimento do IP real. Como ele estava tentando acessar o banco por esse IP, ele não conseguia sair, pois é só um IP fictício e dava esse pau. Quando abri o Event Viewer do servidor e vi o erro de underlying open() do banco de dados, aí pude saber que era um problema com a conexão e era isso que estava dando o erro. Bem, peguei o IP do web.config e alterei tudo para localhost, pois o banco e o iis estão no mesmo ambiente físico, logo o BD está em localhost. Fiz isso e agora está funcionando.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Appending string input to a list I'm using Python 2.7 and developing an application in both Ubuntu and Windows. On Windows it works fine---no issues. But on Ubuntu it seems to be doing something odd on this bit:
numberoffiles = raw_input('\nHow many files would you like to compare? ')
numberoffiles = int(numberoffiles)

filelist = []
for i in range(numberoffiles):
    myfilename = raw_input('\nEnter a file path: ')
    filelist.append(myfilename)
print filelist

I'm expecting a list of file names in the format:
['path/to/file1.ext','path/to/file2.ext',...]

But Python is adding double quotes and spaces, so that I get:
["'/path/to/file1.ext' ", "'/path/to/file2.ext' ",...]

If it's a quirk, I can get around it, but I'd like to understand what I'm doing wrong or what exactly is happening here. Any answers would be appreciated.

A: You will need to check your input. If you are giving the input as '/path/filename' then even on windows you will have the double quotes added. Ensure you don't add quotes when you are providing the input.

A: My money is on the extra quotes (and trailing spaces) being part of the input you are providing to the script.


text:
Q: Выполнить функцию PHP через несколько секунд после старта страницы сайта Привет.
На ХешКод я нашел вот такой код.
Код cookie хорошо работает. Спасибо, что вы есть.
Вопрос
Как сделать, чтобы функция:
function my_echo_div() {
        echo 'New member!Old member :)';
    }

выполнилась после старта страницы сайта через 30 секунд?

A: PHP может только, скажем так, "сгенерить" Вам страницу, а некие функции через 30 секунд после загрузки напишите на JavaScript.
Ну а если уж очень хочется, можно пойти плохим путем и сделать что-то подобное:
<? $thisStr = 'Ваш код'; ?>

Но это плохая практика.
A: Решил проблему так
$hashcode = file_get_contents("html.html");

   echo $hashcode;

Подробности напишу на блоге Pixel.com


text:
Q: Prevent generation of proxy classes in Reference.cs when adding/updating a web reference I have a web service and a client. The classes used in parameters and return types are in a common DLL shared by both. However, whenever I update the web reference, visual studio generates copies of the classes with the same names and public properties and methods. Then the solution won't compile because the client code tries to use the versions in the common DLL. I can solve the problem by deleting the "duplicate" classes every time I update the web reference, and adding a using statement to point at the common dll's namespace. Is there a way to fix this permanently?
UPDATE: See my comments below. This is a "feature" of asmx web services. There is no way around it other than one of the following:
1) Use a more modern type of web service.
2) Don't use a common DLL
3) Manually fix every time you update the web reference, as in the original question above.

A: This is a "feature" of asmx web services. There is no way around it other than one of the
 following:

*

*Use a more modern type of web service.

*Don't use a common DLL

*Manually fix every time you update the web reference, as in the original question above.

Sources: Other stackoverflow questions:

*

*"Reuse existing types" is ignored when adding a service reference

*How does Visual Studio 2008 and svcutil decide which types to re-use from referenced assemblies when generating a web service proxy class?

A: There`s no way to do that.
However, I think we have a design problem here. When we create a web service, we expect that our clients don't need to reference any dll from us. Only the types exposed by the web service should be enough for their use (web services are all about interoperability, imagine your client app written in Java, you can't reference the .NET dll).
That's why these types are created when you reference a web service. In my opinion, you should only rely on the classes generated by the web service in your client app. Remove the reference to the shared dll from the client project.
This doesn't direct answer your question, but provides an alternative for your issue.

A: I had the same problem, but I had neglected to add the reference the correct assembly with the request/response types in my client. Once I added that reference, and ensured that the "Reuse types" checkbox was on in the Add Service Reference dialog, it worked properly.

A: In the domain class, set AnonymousType=false to prevent generating class with prefix unexpected when adding the web reference
     [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = false)]
but this only ensure that the class, auto-gen in Reference.cs has the same structure as the domain class.
A way to walk aroud this is to serialize/deserialize to the domain object.


text:
Q: Change in permalink structure made javascript cookie not work correctly My site needs a mechanism where a user is sent to agreement page when he visits the site for the first time. Once he accepts the agreement, it is saved in cookie. He can browse any page directly after that.
I am using javascript  for cookie and it was working fine as long as the permalink setting was default one(http://mydomain.com/?p=123).
As soon as I made change in permalink and made it postname (http://mydomain.com/sample-post/) it started showing a problem.
(The change in .htaccess file was done as recommended by wordpress)
The problem is: the user is again and again redirected to the agreement page even if he clicks on agreement button.
Following is the code.
In header.php
        setCookie("requested_url", document.URL, 4);
        var agreement = getCookie("agreement");

        if(agreement == "yes"){
            var requested_url = getCookie("requested_url");
        }

        else{
            window.location.assign("http://mydomain.com/?page_id=22");
        }

In header.php, it checks if the cookie named agreement is set to yes. If yes then do nothing. If not set to yes then redirect to agreement page(/?page_id=22). The agreement(cookie) is set in this page.
In page_id=22(page-22.php)
       <script type = "text/javascript">

            function yesbutton()
                {
                    setCookie("agreement", "yes", 5);
                    window.location.assign(getCookie("requested_url"));
                }

                </script>

        <div class="agreementButton">
            <input type = "button" onclick = "yesbutton()" value = "Accept">
        </div>

After digging through the code, I found that in header.php  the value of agreement is not being accessed correctly.
In page-22.php setCookie("agreement", "yes", 5); is working fine. I can do an alert and get its value(yes) here.
But when I do alert of the same cookie in header.php it alerts blank space.
In header.php this code returns a blank popup.
        var agreement = getCookie("agreement");
        alert(agreement);

This clearly means the cookie(agreement) that is being set to yes in page-22.php is not being accessed in header.php correctly. But why this is happening I could not get any clue. Strange is when the permalink is default one everything works fine. As soon as permalink is set to postname, the cookie(agreement) becomes blank in header.php.
Update: setCookie and getCookie functions that exists in both header.php and page-22.php.
        function setCookie(cname, cvalue, exdays) {
            var d = new Date();
            d.setTime(d.getTime() + (exdays*24*60*60*1000));
            var expires = "expires="+d.toGMTString();
            document.cookie = cname + "=" + cvalue + "; " + expires;
        }

        function getCookie(cname) {
            var name = cname + "=";
            var ca = document.cookie.split(';');
            for(var i=0; i<ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0)==' ') c = c.substring(1);
                if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
            }
            return "";
        }

These two functions are working fine in both pages.
The problem is:
      setCookie("agreement", "yes", 5);

    that is done in page-22.php sets cookie correctly.

But when the same cookie is accessed in header.php with
       var agreement = getCookie("agreement");

       the value of agreement is blank.

       alert(agreement) returns blank space.

Any clues/hints are welcome.

A: From comment:
There is not enough information to answer your question. All your code is javascript, not PHP. Additionally, there is no function named "setCookie" or "getCookie" in javascript, and you don't state what libraries you are using.
The answer is most likely that your setCookie function is using the current page path (cookies have a URL path component to them), and thus other pages on different URLs cannot access those cookies, but there's no real way to tell without seeing that code as well.
For JS problems along these lines, you should try a different Stack, this is not a WordPress specific question, but a general javascript issue.


text:
Q: Obtain coordinates of a Polygon / Multi-polygon around a point in python I am using plotlys scattermapbox to draw a polygon around a point object. I'd like to draw a polygon that covers 'x' mile radius from a POI.
I found this that is helpful: https://plotly.com/python/filled-area-on-mapbox/. However, in my case I need to dynamically define the polygon and obtain it's corresponding coordinates.
How do I render and fill a polygon around a center point? Can I use mapbox to get the polygon geometry? We define polygon geometry as x miles from the center.
For reference: https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#fill
Original question here: Draw a polygon around point in scattermapbox using python

A: *

*using this helper https://github.com/Turbo87/utm to transform between GPS (WSG84 / EPSG:4326) and UTM

*you expressed that POI circle/polygon radius as a distance x miles hence need to work with UTM projections to express radius as a distances

*have used UK hospitals as sample POI data.  Without significant zoom levels circles will not display as they are only 1 mile radius.  It will be simple to plug in any other dataframe with latitude and longitude columns

*used a scatter mapbox as sample plot, then added layer that are POI circles/polygons

import shapely.geometry
import utm
import pandas as pd
import geopandas as gpd
import requests, io, json
import plotly.express as px

# need to use UTM to express radius as a distance. UTM is zoned, so if GPS coords are very widely distributed
# distance will be incorrect.  zone is estimated from first GPS coordinate
# returns geopandas dataframe re-projected to GPS co-ordinates
# radius is expressed in metres
def circles(lonlat, radius=10 ** 4):

    utm_coords = utm.from_latlon(lonlat[:, 1], lonlat[:, 0])
    utmcrs = gpd.GeoDataFrame(
        geometry=[shapely.geometry.Point(lonlat[0, 0], lonlat[0, 1])], crs="EPSG:4326"
    ).estimate_utm_crs()

    return gpd.GeoDataFrame(
        geometry=[
            shapely.geometry.Point(easting, northing).buffer(radius)
            for easting, northing in zip(utm_coords[0], utm_coords[1])
        ],
        crs=utmcrs,
    ).to_crs("EPSG:4326")

# get some public addressess - hospitals.  data that can be scattered
dfhos = pd.read_csv(io.StringIO(requests.get("http://media.nhschoices.nhs.uk/data/foi/Hospital.csv").text),
    sep="¬",engine="python",)

# generate circles of diameter 1 mile, which is 1609.34 metres
gdf = circles(dfhos.head(20).loc[:, ["Longitude", "Latitude"]].values, radius=1609.34)

fig = (
    px.scatter_mapbox(
        dfhos.head(20),
        lat="Latitude",
        lon="Longitude",
        color="Sector",
        hover_data=["OrganisationName", "Postcode"],
    )
    .update_traces(marker={"size": 10})
    .update_layout(
        mapbox={
            "style": "open-street-map",
            "zoom": 9,
            "center":{"lat":gdf.loc[0,"geometry"].centroid.y, "lon":gdf.loc[0,"geometry"].centroid.x},
            "layers": [
                {
                    "source": json.loads(gdf.geometry.to_json()),
                    "below": "traces",
                    "type": "line",
                    "color": "purple",
                    "line": {"width": 1.5},
                }
            ],
        },
        margin={"l": 0, "r": 0, "t": 0, "b": 0},
    )
)
fig.show()


text:
Q: SQL Server scheduling by script I created a job to execute a procedure every 5 minutes but the job has no history of being run and also when I execute exec sp_help_jobactivity @job_name = 'Update Subscription flags', I get empty result. I also checked sysjobschecdules that has 0 for next_run_date and time. My procedure is compiled and works fine when i execute it manually. I'm not sure what exactly is wrong here. Here's the schedule:
--Add a Job to SQL Server Agent
GO
EXEC msdb.dbo.sp_add_job
     @job_name = N'Update Subscription flags'; -- the job name
GO

GO
EXEC msdb.dbo.sp_add_jobstep
     @job_name         = N'Update Subscription flags' -- Job name specified in sp_add_job
    ,@step_name        = N'Step - Set subscription flags to false' -- step name
    ,@database_name    = 'db' --Database Name
    ,@command          = N'EXEC UpdateSubscriptionFlags;' -- SQL Command
GO

--Attach server name. Not needed if you are creating job on same server.
EXEC msdb.dbo.sp_add_jobserver
     @job_name     = N'Update Subscription flags'
    ,@server_name = N'DESKTOP-3DR2LAE\SQLEXPRESS'; -- LOCAL by default
GO

GO
EXEC msdb.dbo.sp_add_schedule
     @schedule_name          = N'Daily - Every 5 Minutes' -- specify the schedule name
    ,@freq_type              = 4 -- 4 indicates job is scheduled daily, refer msdn link for reference
    ,@freq_interval          = 1 -- The days that a job is executed and depends on the value of
    ,@freq_subday_type       = 4 --At specified time (At specific time/second/minutes/hours)
    ,@freq_subday_interval   = 5 --Run every 5 min once the job is scheduled

GO

--Attach Created Job name to Schedule name
GO
EXEC msdb.dbo.sp_attach_schedule
     @job_name         = N'Update Subscription flags' -- Job Name
    ,@schedule_name    = N'Daily - Every 5 Minutes' ; -- Schedule Name
GO


text:
Q: The argument 'length' is smaller than minimum of '1' (Parameter 'length' ) in Azure function I am calling an azure function from my azure data factory. the function takes a json array as the body. I am able to run the function from Postman but when I try to call it from Azure data factory, I get error as

" [Error] Executed 'Function1' (Failed,
Id=a48a3829-e923-4c12-bc8d-edaa2ff04c43, Duration=284ms)The argument
'length' is smaller than minimum of '1' (Parameter 'length')"

The body is same as passed in Postman as in ADF. Why this weird behaviour. Anyone Anyidea? I dont hv any other parameter as length.


text:
Q: POE-Component-IRC crashes under Windows 7 64-bit I'm trying to run the Perl module POE-Component-IRC using Perl v5.12.13 with ActiveState under Windows 7 64-bit and each time it is run it crashes Windows. I'm pretty sure it's something to do with this module since the only lines I have in the script is shown below.
use strict;
use warnings;
use POE qw(Component::IRC);

When I run this file Windows gets the gets the generic "This program has stopped responding" error message.
According to http://code.activestate.com/ppm/POE-Component-IRC/ it appears that it is compatible with my Perl version and version of Windows.
Any thoughts or ideas would be appreciated. I'd contact the developer on SourceForge but every time I report a but I get an error.

A: Check that you have latest version - 6.78.
Did you install it with ppm? In that case you should test it - run cpan -t POE::Component::IRC.
Correct place for reporting bugs is bug tracker


text:
Q: Add JavaScript and HTML to IFRAME, and print IFRAME to printer There are multiple posts dealing with part of these topics, but none that puts them together.
On a given page, I wish to create a new IFRAME, add some JavaScript to it which will print the page to a printer, and add some HTML to it which will be printed.
Below is my attempt with a live demo at http://jsbin.com/UDUCADI/2/.  It prints, but prints the parent page and not the IFRAME.
How do I just print the IFRAME?
<!doctype html>

        <meta charset="utf-8" />
        <title>Print IFRAME</title>

        <button id="printIt">Print</button>

Print this text!

Don't print this!

A: EDITED
There are actually a few things wrong. One of it is you're mixing jQuery and the DOM api. Second would be that you add the script tag to the body of the iframe and then set the HTML of the body again, overwriting the script tag. Third: you're using script.text, which should be script.innerHTML.
$(function () {
$('#printIt').click(function(){
    var iframe   = document.createElement('iframe');
    document.body.appendChild(iframe)
    iframe.contentWindow.document.body.innerHTML = $('#stuffToPrint').html();
    var script   = document.createElement("script");
    script.innerHTML  = "window.print()";
    iframe.contentWindow.document.body.appendChild(script);
})
});

Working version at: http://jsbin.com/UDUCADI/5/


text:
Q: Invalid template file on custom module Issue
Exception #0 (Magento\Framework\Exception\ValidatorException): Invalid template file: 'TT::calculator.phtml' in module: 'Magento_Catalog' block's name: 'calculator.tab'
Layout Location:
app/code/TT/Calculator/view/frontend/layout/catalog_product_view.xml
<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
    <referenceBlock name="product.info.details">
        <block class="Magento\Catalog\Block\Product\View" name="calculator.tab" template="TT::calculator.phtml" group="detailed_info">
            <arguments>
                <argument translate="true" name="title" xsi:type="string">Calculator</argument>
            </arguments>
        </block>
    </referenceBlock>
</body>
</page>

Template Location:
app/code/TT/Calculator/view/frontend/templates/calculator.phtml
Questions

*

*I've seen some solutions where the *.phtml file is saved in app/design but I'm trying to get this to work in app/code. What have I missed?

*Also, does this "extend" catalog_product_view.xml or replace it?

A: Your template file location should be TT_Calculator::calculator.phtml
<block class="Magento\Catalog\Block\Product\View" name="calculator.tab" template="TT_Calculator::calculator.phtml" group="detailed_info">
        <arguments>
            <argument translate="true" name="title" xsi:type="string">Calculator</argument>
        </arguments>
    </block>

A: 1.You have to change the code to TT_Calculator::calculator.phtml:
<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
    <referenceBlock name="product.info.details">
        <block class="Magento\Catalog\Block\Product\View" name="calculator.tab" template="TT_Calculator::calculator.phtml" group="detailed_info">
            <arguments>
                <argument translate="true" name="title" xsi:type="string">Calculator</argument>
            </arguments>
        </block>
    </referenceBlock>
</body>
</page>

2.Magento will check all the layout (XML file) in all the modules and merge them, not extend.

A: I have resolved this issue now. The problem was the allow symlink of the system config:
php bin/magento config:set dev/template/allow_symlink 1 --lock-env


text:
Q: How to omit code block based on arguments to context manager? Lets's see this example:
with mycontextmanager(arg1='value', arg2=False):
    print 'Executed'

Is there a way to not execute code block (print 'Executed') within a context manager based on argument, eg: when arg2 is not False?

A: An other option is to use a special ConditionalExecution context manager whose __enter__ methods returns an action that conditionally raises a SkipExecution exception. The __exit__ method suppresses only this exception.
Something like the following:
class SkipExecution(Exception): pass

class ConditionalExecution(object):
    def __init__(self, value, arg):
        self.value = value
        self.arg = arg
    def __enter__(self):
        def action():
            if not self.arg:
                raise SkipExecution()
        return action
    def __exit__(self, exc_type, exc_value, tb):
        if exc_type is SkipExecution:
            return True
        return False

Used as:
In [17]: with ConditionalExecution(1, True) as check_execution:
    ...:     check_execution()
    ...:     print('Hello')
    ...:
Hello

In [18]: with ConditionalExecution(1, False) as check_execution:
    ...:     check_execution()
    ...:     print('Hello')

In [19]:

However the problem is that you have to add a call to the value returned.
The problem is that __exit__ is called if and only if __enter__ returned succesfully, which means you can't raise an exception in __enter__ to block the execution of the code block.
If you want you can modify this solution so that the call to check_execution() can be done in the first line, like:
In [29]: with ConditionalExecution(1, True) as check_execution, check_execution():
    ...:     print('Hello')
Hello

In [30]: with ConditionalExecution(1, False) as check_execution, check_execution():
    ...:     print('Hello')

Using a Skipper helper-context manager:
class SkipExecution(Exception): pass

class Skipper(object):
    def __init__(self, func):
        self.func = func
    def __call__(self):
        return self.func() or self
    def __enter__(self):
        return self
    def __exit__(self, *args):
        pass

class ConditionalExecution(object):
    def __init__(self, value, arg):
        self.value = value
        self.arg = arg
    def __enter__(self):
        def action():
            if not self.arg:
                raise SkipExecution()
        return Skipper(action)
    def __exit__(self, exc_type, exc_value, tb):
        if exc_type is SkipExecution:
            return True
        return False

I don't think there is anyway to do this without at least an explicit function call as in the above example.

A: Perhaps like this, assuming your context manager supports a "whatever" property which exposes the value it got in arg2 when initialized:
with mycontextmanager(arg1='value', arg2=False) as ctx:
    if ctx.whatever:
        print 'Executed'


text:
Q: Can I get the bluetooth data of vehicles in SUMO through traci? I'm a new user of SUMO and TraCI. I have equipped vehicles with bluetooth in SUMO using configuration file. Now I wonder if I could get the bluetooth data using TraCI?(e.g. TraCI4matlab)
Thanks for your suggestion!

A: The bluetooth devices in SUMO are just for (simulated) vehicle detection. There is no data transfer.


text:
Q: Anchor SuggestionPopup to TextView I have a problem with a custom PopupWindow associated with a TextView with the method setSuggestionPopup.
When I click in the TextView and my layout scrolls up so that the TextView is not covered by the virtual keyboard my custom popup doesn't scroll and it covers the TextView.
Is there a way to anchor it to the TextView so that they are both scrolled as if they were a single object?
I associate the PopupWindow to TextView like that:
popupBinding = PasswordPopupBinding.inflate(LayoutInflater.from(getContext()));
View suggestionView = popupBinding.getRoot();
PopupWindow suggestionPopup = new PopupWindow();
suggestionPopup.setContentView(suggestionView);
binding.passwordTextView.setSuggestionPopup(suggestionPopup);


text:
Q: program/game design workflow Programmer Types:
Do you write extensive design documents for your programs or games?
Is using UML the standard method of diagramming your use cases?
Do you run the whole gamut of diagrams or sort of pick and choose along the way depending on the scope of your software and the number of developers on the team?

A: First,

If you make documentation, it should have a "clear" reason/purpose.
  And this purpose is identify nature of your documentation.

Secondly:

Do not think documentation just in a "written form" or word document.
  It may be in any form.Even it can be  a "video" in which some guy
  explain your major architecture decisons and why they choose
  it[motivation]

Well, suppose that you want new team members "easily grab" what you are doing,how you are doing, and why you are doing this way.[ Be carefull all depends on your problem nature]

*

*UML use case diagram  may can give overall picture of your functional
requirements. It simply states who will use your system, and what they can
do with your system.

*Short memos which state the important non-functional requirements

*Short memos which states your major architecture decision and why you give this decisions

*Maybe a component diagrams which shows your important components and their interfaces

*If application tapology is important then may be a UML deployment diagram which shows how your system will be physically deployed.

But after all you can not document evething and you should not .You can generate whole system UML class diagram automatically with a UML tool, but how can this help a novice.

*

*But you can put class diagrams for classes that do important and tricky
parts and draw sequence diagrams for those tricky parts which show how
they collaborate with other classes while they perform important and
tricky responsibilities.

The key for documentaion is puting yourself into your "audience" [ who
  will read your doc] and ask yourself

*

*If I was this document potantial "audience" will i read this document? [ If not why you make doc]

*If I read this doc, will it help me in some way? [ it is effective]

Lastly, we do not live in "ideal word"...Sometimes you may find yourself doing doc for no real audience and no real reason just because of some "politics" and you should earn money
Well, in this situation UML will help. Draw boring, with many details [ genarally auotumatically generated] diagrams which no one read or understand but say "Oh you have extensive documentaion". In our software industry, UML is overemphasized, and many guys "buy" even bad doc if there is a UML diagrams in it.
That's all folks...


text:
Q: OS/X mimetype handler I'd like to write a small script that implements RFC4709 for OS/X.
I started off by creating an application bundle that registers the application/xml+davmount mimetype and launches a simple python script.
It doesn't make a lot of sense to me to make this a .app bundle, because the application is very short-lived, and it also doesn't seem like the best idea to get people to install it into /Applications
As a complete newbie in anything related to programming OS/X, what would be the best way to implement this RFC effectively, with the ultimate endgoals allowing users to click a link with the application/xml+davmount mimetype, which then automatically mounts the share (after asking for username and password).

A: Make it a .app bundle, installed in Applications/Utilities (or really, anywhere).  Bundles are the right thing on OS X.  But if you really don't want to install it in Applications, how about somewhere under /Library or ~/Library, using a package rather than a drop in app.  But I know I'd prefer the .app version... easier to uninstall.


text:
Q: Django - How can I pass information from my google map to my view? I am using Django and I have my map set up like this in my index.html:

First I want to initiate the map with markers from my database which fit within the shown area. Then add the ability for the user to change the shown area (drag or zoom) and press a button which will query my database based on the newly shown area of the map. How can I tell what area my map is currently showing?
I'd also like to query my database when the user clicks on a marker using information stored in that marker, how can I pass information to my view onclick?

A: You can get the bounding box from the map and then send that data as a query parameter in a GET request to your django server, which can then perform a spatial query on your data in that bounding box and send data back to your map. It would look something like this.

index.html

<!DOCTYPE html>

  <button onclick="sendBounds()">Click me to send bounds!</button>

views.py

from django.contrib.gis.geos import Polygon
from rest_framework import generics

from .models import Model
from .serializers import ModelSerializer

class ModelAPIView(generics.ListAPIView):
    lookup_field = 'pk'
    serializer_class = ModelSerializer

    def get_queryset(self):
        bounds = self.request.GET.get('bounds')
        # Probably need to cast all these string coordinates to floats here
        geom = Polygon.from_bbox(bounds)
        queryset = Model.objects.filter(poly__contained=geom)

        return queryset

    def get_serializer_context(self, *args, **kwargs):
        return {'request': self.request}

urls.py

from django.urls import path

from .views import ModelAPIView

urlpatterns = [
    path('api/models/', ModelAPIView.as_view(), name='model-list'),
]


text:
Q: How to find existence of .Net Framework Data Provider for MySql on Mono Ubuntu? After solving basic porting issues, I was trying to connect to MySql database from ASP.NET Mono project.
Whenever, I try to connect to the database, the following error is thrown (please run the snippet):

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>Error 500</title>

Application Exception

System.ArgumentException

Unable to find the requested .Net Framework Data Provider.  It may not be installed.

Description: HTTP 500.Error processing request.

Details: Non-web exception. Exception origin (name of application or object): System.Data.

Exception stack trace:

  at System.Data.Common.DbProviderFactories.GetFactory (System.String providerInvariantName) [0x00036] in <filename unknown>:0
  at System.Data.Entity.Infrastructure.DependencyResolution.DefaultProviderFactoryResolver.GetService (System.Type type, System.Object key, System.Func`3 handleFailedLookup) [0x0003b] in <filename unknown>:0

Version Information: <tt>4.2.1 (Stable 4.2.1.102/6dd2d0d Thu Nov 12 09:52:44 UTC 2015)</tt>; ASP.NET Version: <tt>4.0.30319.17020</tt>

Powered by Mono

Excerpt from web.config:
<entityFramework>
<providers>
  <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6"/>
  <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
</providers>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework" >
  <parameters>
    <parameter value="mssqllocaldb"/>
  </parameters>
</defaultConnectionFactory>
</entityFramework>

*

*How do I figure out that the requested .Net Framework Data Provider is indeed installed?

Any help is much appreciated!

A: You can list all providers, using this code (taken https://msdn.microsoft.com/en-us/library/12kxkt25(v=vs.80).aspx). In my environment provider with invariant name MySql.Data.MySqlClient" was not listed
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Common;
using System.Data;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable table = DbProviderFactories.GetFactoryClasses();

            // Display each row and column value.
            foreach (DataRow row in table.Rows)
            {
                foreach (DataColumn column in table.Columns)
                {
                    Console.WriteLine("{0}:{1}",column.ColumnName,  row[column]);
                }
                Console.WriteLine("----------------------------");
            }

        }
    }
}


text:
Q: Fonts aren't displaying uniformly some elements on my website display perfectly, while other elements of the same font look grainy and choppy. I can't figure out why since I specify the style in the same way.
Here's my website:
http://violetoeuvre.com/
The side bar navigation (me, about, writing contact) is totally fine while the paragraph, h2, and footer styles are grainy and look like a rough version of the same type face.
CSS:
    /* Fonts */
    @import url(http://fonts.googleapis.com/css?family=Playfair+Display:400,700,900,400italic,700italic,900italic);

Funky styles:
h2 {
        font-family: 'Playfair Display', sans-serif, 20px;
        font-weight: 100;
        line-height: 2em;
        color: #000000;
        letter-spacing: -1px;
        margin: 0;
}

h3 {
        font-family: 'Playfair Display', sans-serif, 12px;
        font-weight: 100;
        line-height: 2em;
        color: #000000;
        letter-spacing: -1px;
        margin: 0;

}

#foot a:link {
        font-family: 'Playfair Display', sans-serif;
        font-size: 15px;
        font-weight: 100;
        color:#000;
        text-decoration: none;
        letter-spacing:0.2em;
}

These are functioning fine:
#emma_home a:link{
        font-family: 'Playfair Display', serif;
        font-size: 75px;
        font-weight: 200;
        color:rgba(255,255,255,1);
        text-decoration: none;
        letter-spacing:-4px;
    }
#nav_menu a:link{
        font-family: 'Playfair Display', serif;
        font-size: 30px;
        font-weight: 100;
        color:rgba (255,255,255,1);
        text-decoration: none;
        text-align: center;
        letter-spacing:0.2em;
}

#side_wrapper_text a:link{
        font-family: 'Playfair Display', sans-serif;
        font-size: 32px;
        font-style: italic;
        font-weight: 100;
        color:#000000;;
        text-decoration: none;
        text-align: right;
        letter-spacing:0.2em;

}

Also, on a PC the top Emma and Navigation (writing, blog, contact) are about 20 pixels ABOVE the black line, but on my Mac, the letters touch the white like I want.
What gives with these discrepancies??
Thanks.

A: I think you should move font-size property from font-family tag
and add it
font-family: sans-serif;
font-size : 12px;

check this W3 Schools they define 2 properties
Browsers behave differently with css some adapt the error some not
EDIT
You can save yourself from repeating code by putting the selector that have same styles mostly and then you can overwrite that style. for ex
h2,h3 {
    font-family: 'Playfair Display', sans-serif;
    font-size : 20px;
    font-weight: 100;
    line-height: 2em;
    color: #000000;
    letter-spacing: -1px;
    margin: 0;
}
h3 {
    font-size: 12px;
}

I see your a link has font weight property double than you defined for other so that may be the case for a tags but i dont see any other significant difference

A: I was confused as to why Playfair Display appeared grainy in my headings and paragraphs, but NOT in my sidebar navigation.
After some frustration, I realized that the typeface just looks bad at a certain (small) font.
Search for Playfair:
http://www.google.com/fonts/
As you can see, Normal 400 looks very weird, but in larger, bold, or italic styles, it looks just fine.  The only thing to do was to choose a similar typeface for smaller styles, so I'm using Jacques Francois.

A: I'm a designer that works mostly in web but occasionally print as well. I think your issue may actually be with the Playfair font itself which I have just discovered is missing certain font styles when it displays on PCs (Macs look fine). I would test with another font before losing much more time.

A: As far as I can see IE prefers ttf format over woff and that specific exports is wrong. I simply downloaded the google font mercurial repo any converted original (otf) files with font squirrel, now it works.


text:
Q: Update state with useEffect from another page using React hooks I want to update state with data from another page. After trying to update state I'm getting error:

index.js:1375 Warning: A component is changing a controlled input of type text to be uncontrolled. Input elements should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component.

How to properly update state using hooks ??
const [data, changeData] = useState({
    name: '',
    email: '',
    phone: '',
    cv: '',
    documents: '',
    rodo: false,
    regulations: false,
  });

  useEffect(() => {
    if (location.data) {
      changeData((prevState) => {
        return { data: { name: location.data.name } };
      });
    }
  }, []);

Input

                <input
                  value={data.name}
                  id='name'
                  name='name'
                  onKeyPress={handleKeyPress}
                  onChange={(e) => handleChangeData(e, 'name')}
                  type='text'
                  placeholder='Imię i nazwisko'
                />

A: Side-effect of coming from Class based component. What you were trying to do in your code is replace entire previous state stored in data with new object that looked like below:
{ data: { name: location.data.name } }

In Hooks world you define individual item to have individual useState but to continue on what you are working on here's the fix:
const [data, changeData] = useState({
  name: '',
  email: '',
  phone: '',
  cv: '',
  documents: '',
  rodo: false,
  regulations: false,
});

useEffect(() => {
  if (location.data) {
    changeData({
      ...data,
      name: location.data.name
    });
  }
}, []);

Ideally you should be defining individual items in the state something like below:
const [name, changeName] = useState('');
const [email, changeEmail] = useState('');
....
const [rodo, changeRodo] = useState(false);

And then in your useEffect hook you will change individual item like below:
useEffect(() => {
  if (location.data) {
    changeName(location.data.name);
  }
}, []);

This way, name is always defined, and thus the <input />s value was always set, or controlled. Read on


text:
Q: Get EXIF data of a particular image/photo in cameraroll I am using ALAssetsLibrary to list details of photos present in cameraroll. But how to get details of a particular selected photo from cameraroll using ALAssetsLibrary?
Assume i selected ABC.jpeg from cameraroll. I want to display the exif details of only ABC.jpeg. Not exif details of other photos present in cameraroll.
 - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

   UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
   self.imageView.image = image;

   NSLog(@"image %@\ninfo: %@",image, info);
   [picker dismissViewControllerAnimated:YES completion:NULL];

    ALAssetsLibrary* library = [[ALAssetsLibrary alloc] init];
    [library enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
        if (group) {
            [group setAssetsFilter:[ALAssetsFilter allPhotos]];
            [group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop){
                if (asset){

                    NSDictionary *data = [[asset defaultRepresentation] metadata];
                    NSLog(@"%@",data);
                }
            }];
        }
    } failureBlock:^(NSError *error) {
        NSLog(@"error enumerating AssetLibrary groups %@\n", error);
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {

    [picker dismissViewControllerAnimated:YES completion:NULL];

}

A: ok here is the code how to get the asset of a media picker with the image picker:
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
   UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
   self.imageView.image = image;

   NSLog(@"media image info: %@", info);

    //use assetLib
    NSURL *imageURL = [info objectForKey:UIImagePickerControllerReferenceURL];
    if(imageURL) {
        [self getPictureInfoFromAssetURL:imageURL
                                 success:^(NSDictionary*)alInfo {
                                           NSLog(@"asset lib image info: %@", alInfo);
                                 } failure:^(NSError *error) {
                                           NSLog(@"error reading asset lib image info: %@", error);
                                 }];
    }

    [picker dismissViewControllerAnimated:YES completion:NULL];
}

- (void)getPictureInfoFromAssetURL:(NSURL *)url
                           success:(void (^)(NSDictionary *alInfo))success
                           failure:(void (^)(NSError *error))failure {
    ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
    [assetslibrary assetForURL:url
                   resultBlock: ^(ALAsset *myasset) {
                       ALAssetRepresentation *rep = [myasset defaultRepresentation];
                       if(success {
                            success([rep metadata]);
                   }
                  failureBlock: ^(NSError *err) {
                      if (failure) {
                          failure(err);
                      }
                  }];
}


text:
Q: Attempt to invoke virtual method void android.widget.ImageView.startAnimation on a null object reference I want when a user clicks on "ans_three_btn_one" button than a dialog appears and in that dialogbox, I want to implement rorate animation on sunburst imageview. The only problem in this code is "sunburst.startAnimation". If I remove this line then code work properly but no animation. With this line of code my app crashing. Appreciate If you help me.
    public class GamePlay extends AppCompatActivity implements View.OnClickListener    {

    Button ans_three_btn_one;

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

        ans_three_btn_one = findViewById(R.id.ans_three_first_btn);
        ans_three_btn_one.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Dialog first_prize_dialog = new Dialog(this,android.R.style.Theme_Black_NoTitleBar_Fullscreen);
        first_prize_dialog.setContentView(R.layout.activity_first_prize);
        first_prize_dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        first_prize_dialog.show();

        ImageView sunbrust = findViewById(R.id.sunbrust_img);
        //----Error area start ---
        sunbrust.startAnimation(AnimationUtils.loadAnimation(v.getContext(),R.anim.rotate));
        //----Error area end ---
    }

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.startAnimation(android.view.animation.Animation)' on a null object reference

Application terminated.

A: You have missed first_prize_dialog before findViewById.
It will be
ImageView sunbrust = first_prize_dialog.findViewById(R.id.sunbrust_img);


text:
Q: How to separate comma separated and where condition in LINQ I have a giftcardamounts in database table.
Column contains dollar and comma separated values.
There are 40 rows.
Ex:
row 1: giftcardamounts : ($10,$20,$30,$40,$50)
row 2: giftcardamounts : ($100,$200,$30,$40,$50)
row 3: giftcardamounts : ($10,$20,$300,$400,$500)
...etc

From frontend there is an input is giftcardselectedamount
Ex: giftcardselectedamount=500
Based on this input amount in need to write LINQ query on dollar and comma separated list of Values.
Please help me how to write this.

A: Like commenters have noted, you should show some effort in reaching to an answer. Also your question isn't quite clear. Are you asking to return the row with a matching amount? If so you can try the following approach, which returns the first row that contains the dollar amount specified:
void Main()
{
    var data = new[] {
        "$10,$20,$30,$40,$50",
        "$100,$200,$30,$40,$50",
        "$10,$20,$300,$400,$500"};

    var giftcardSelectedAmount = 500M;

    var matchingRow = data.FirstOrDefault(x => x
        .Split(',')
        .Any(v => decimal.Parse(v, NumberStyles.Currency) == giftcardSelectedAmount));

    Console.WriteLine(matchingRow);
}

I can easily modify this answer to return all matching rows, a count of occurrences, or a count of rows with occurrences. Let me know if you need any of these modifications and I can modify my answer to add these.


text:
Q: Tangent spaces and local approximations of manifolds I'm approaching differential geometry from a physicist's perspective in the hope of understanding GR more thoroughly.
I've been told that, intuitively, the tangent space $T_{p}M$ to a point $p$ on a manifold $M$ is "the best linear approximation to the manifold $M$ at that point". What is meant by this?
Is it meant in the sense that the tangent vectors at that point provide the best linear approximation of functions on the manifold at that point? Does this extend for a sufficiently small neighbourhood around a given point?
In the context of GR, is this a mathematical implementation of the equivalence principle, in the sense that the $T_{p}M$ is flat and so the laws of physics are those of special relativity (SR) on $T_{p}M$. The laws of physics on $M$ are therefore SR for a sufficiently small neighbourhood of $M$ around a given point?

A:
I've been told that, intuitively, the tangent space $T_{p}M$ to a point $p$ on a manifold $M$ is "the best linear approximation to the manifold $M$ at that point". What is meant by this?

This statement is meaningful if your manifold is embedded in an higher dimensional Euclidean space $\mathbb{R}^{n}$. It is very much like a linear tangent to a $1D$ curve. For example, see this illustration from Wikipedia of a tangent plane to a sphere

Lets look at manifolds embedded in $\mathbb{R}^{3}$. If, for example, you can write your manifold as $z=f\left(x,y\right)$ around $p$, and you expand this function into its Taylor series
$$z=f\left(x,y\right)\approx f\left(p\right)+\nabla f\left(p\right)\cdot\left(\left(x,y\right)-p\right)+\dots$$
then
$$z=f\left(p\right)+\nabla f\left(p\right)\cdot\left(\left(x,y\right)-p\right)$$
is the tangent place. $T_{p}M$ is this plane as a vector space.

In the context of GR, is this a mathematical implementation of the equivalence principle, in the sense that the $T_{p}M$ is flat and so the laws of physics are those of special relativity (SR) on $T_{p}M$. The laws of physics on $M$ are therefore SR for a sufficiently small neighbourhood of $M$ around a given point?

Yes. It means that by changing coordinate system at a point, your metric can be transformed into the Minkowski metric $\eta_{\mu\nu}$.

A: This interpretation is not a good one when we talk about manifolds from a intrinsic point of view (i.e., not embedded in Euclidean space), and understanding the intrinsic point is part of the requirements and power of differential topology and also GR.
One good point of view is the following:
Suppose you are at a point $p$ on a manifold: imagine the surface of the Earth, for instance. How would you be able to distinguish directions intrinsically, using only information from Earth itself? You can try looking at the curves passing through $p$. There are some which are obviously distinct from the others in terms of directions, but there are some which may be getting very close to themselves. They are not equal as curves, but it seems like they are "tangentially" equal. Well, now you are in trouble, because if you wanted to measure if they are tangentially equal or not directly, you would need to know what are the "geometrical" tangent vectors: an information which you may not have. You could, if you knew you were inside an Euclidean space, but the fact is that you don't. What now?
Let's be more primitive about what we mean by directions. Our view of tangents is fairly intricate if you think about it. Let's discard it for a while. Imagine you and me are at the point $p$, and then we agree to start moving. I feel that it is getting hotter, and you feel that is getting colder. Well, certainly, whatever definition of direction we use, this should mean that we've gone to different directions. Now let's come back to the point $p$, and start moving again. This time, we did not sense such a difference on heat, but instead on pressure. We must have gone different directions again. Heat, pressure etc are all things intrinsic to Earth. This idea may go somewhere.
Now, let's take a small leap of faith: we propose, as inhabitants of the Earth, that there are sufficiently many measurements (heat, pressure etc) that we can do in order to fully distinguish directions.
Let's mathematize the discussion above. We are at a point $p \in M$. A measurement is a smooth function $f:M \to \mathbb{R}$. We are following curves $\gamma: I \to M$ such that $\gamma(0)=p$. Now, my curve then determines an object $D_{\gamma}$ which takes the measurements and give me how they are varying when I go through $p$, i.e., it is an object of the form
$$D_{\gamma}: C^{\infty}(M) \to \mathbb{R}$$
$$f \mapsto (f \circ \gamma)'(0). $$
This is, by definition, a tangent vector: the operator $D_{\gamma}$.
And you can check that there are sufficiently many smooth functions on the manifold $M$ to guarantee that we can distinguish the tangent space as a $n$-dimensional vector space as expected.

A: The following is not really a mathematical answer, but here we go anyway, to clear up some misconceptions.
There is no such thing as "laws of physics on $T_pM$ are those of special relativity", for the following reason. The vectors in the space $T_pM$ is only supposed to give you some directions to point towards. The actual spacetime is just the manifold $M$. More precisely, assuming you already know what an event (a point in $\Bbb R^4$ spacetime) is in the context of special relativity, an event in the context of general relativity is a point on the manifold $M$. The vectors/points on $T_pM$ are not events by definition.
The following statement is one I am not even sure about (I haven't really studied general relativity/pseudo-Riemannian geometry yet). You should ask an expert to double-check.
Since there is the notion of curvature in GR but not in SR (or more precisely, the curvature in SR is simply zero everywhere), it cannot be the case that laws of physics on a small open set in $M$ is the same as those of SR unless the curvature on the small open set is zero.


text:
Q: Ubuntu apt-get update stuck at Reading package list... 0% I am connecting via ssh to this ubuntu machine, when doing apt-get update it gets stuck at "Reading package list... 0%". Help, please.
Update: I tried installing something manually, but it won't let me neither. Also when connecting to the machine it displays "System information disabled due to load higher than 8.0", I checked using top, but there is no other process running there.

A: Could be IPv6 problem. Try running it with sudo apt-get update -o Acquire::ForceIPv4=true && sudo apt-get dist-upgrade -o Acquire::ForceIPv4=true
Had same problem. Found answer here: 16.04 apt-get update hangs


text:
Q: DropdownSearch with a controller? I'm trying to find a controller for my selecteditem in dropdownsearch button. Another post says that there is a dropdownsearch controller but i cant find it anywhere. Any assistance?
DropdownSearch<String>(
                            dropdownSearchDecoration: InputDecoration(
                                border: OutlineInputBorder(
                                    borderRadius:
                                        BorderRadius.circular(15)),
                                contentPadding:
                                    EdgeInsets.only(left: 20, right: 10)),
                            mode: Mode.MENU,
                            items: [
                              "Test 1",
                              "Test 2",
                              "Test 3",
                            ],
                            onChanged: print,
                            selectedItem: diagnosisDropdown),


text:
Q: Opposite of "mind your own business" I'm looking for an idiomatic counterpoint/antonym to "mind your own business", to the effect of "everything is everyone's business" or that solely minding one's own business means missing out on improvements. Whether or not that's true is another story, but looking for an idiom.
For context, "mind your own business" is a truism used to justify non-involvement in affairs outside of one's own immediate control, but in a more collaborative society or organization built on consensus, there is some understanding that others' affairs benefit from some degree of input or co-decision-making by the people affected by the decision. I'm looking for an idiom one would use to reinforce that consensus isn't always as narrow as "meddling".

A: "No man's an island." -- This is a common expression indicating that social support is needful for everyone, and that no one exists independent of others.

A: "It takes a village to raise a child" would be an appropriate answer, but only in the context of child-rearing. "Never send to know for whom the bell tolls; it tolls for thee" is another well-known statement suggesting that I am affected by what happens to another, and that therefore harm to another may be my concern.
Neither of these is a complete answer, but they may provide partial answers.

A: I was thinking about it some more and I don't know if I have the idiomatic version of the phrase, but the story of the blind men and the elephant fits. It takes more than one perspective to understand the whole. (E.g., if each "minded his own business" they would not understand the elephant.)

A: "Having your wits about you" would be an idiom that refers to generally paying close attention to the situation around you but it's not a direct opposite of mind your own business.
"Having eyes on the back of your head" is another option that refers to being cautious of what's happening around you but again it's more related to general situational awareness versus being nosey about other people's personal business.
I can't think of a common idiom that suggests it's good to pry into other people's business, maybe that's because idioms are based on common sense and reflect the traditions of our society. In my personal experience it's generally considered bad form to pry into other people's business when it doesn't concern you.


text:
Q: Advanced php, PDF to HTML How to load pdf content as HTML, without javascript, but using advanced php techniques. I've doing research, and I'm stack.
The cool stuff I've found was :

*

*andreasgal.com/2011/06/15/pdf-js/

*http://view.samurajdata.se/
But I'm totally want convert PDF to HTML, no more.


text:
Q: Accessing parent through unsaved child association (has_many through) I have payments with one transaction associated with each payment. The transactions can be associated with payments, deposits, etc. so I need a :through relation.
The Payment class:
class Payment < ActiveRecord::Base
  has_many :payment_transactions
  has_many :transactions, :through => :payment_transactions
end

And the Transaction class:
class Transaction < ActiveRecord::Base
  has_one :payment_transaction, :inverse_of => :transaction
  has_one :payment, :through => :payment_transaction
end

And finally the PaymentTransaction class:
class PaymentTransaction < ActiveRecord::Base
  belongs_to :payment
  belongs_to :transaction
end

When adding the transaction to the payment I would like to be able to access the parent information (the payment attributes) from within the newly created transaction:
2.1.0 :001 > p = Payment.new
 => #<Payment id: nil, state: "new", created_at: nil, updated_at: nil>
2.1.0 :002 > p.save
 => true
2.1.0 :003 > p.transactions.build()
 => #<Transaction id: nil, myid: nil, parent_class_is: nil, created_at: nil, updated_at: nil>
2.1.0 :004 > p.transactions.first.payment
 => nil

I am looking for a way to access the payment from the newly created transaction associated with the payment - but no luck. The payment is saved, however the transaction is still not committed to the database. Only when the payment is saved and the associated transaction is stored I get access to the parent object:
2.1.0 :005 > p.save
2.1.0 :008 > p.reload
2.1.0 :009 > p.transactions.first.payment
=> #<Payment id: 3, state: "new", created_at: "2014-01-28 09:23:13", updated_at: "2014-01-28 09:23:13">

Using the :inverse_of is not possible with :through associations. :(

Edit 1:
Tried to access the parent via a proxy association:
app/concerns/transaction_proxy.rb
module TransactionProxy

  private

  def my_owner
    proxy_association.owner
  end

end

The payment model:
has_many :payment_transactions
has_many :transactions, -> { extending TransactionProxy }, :through => :payment_transactions

Loading the payment:
2.1.0 :006 > p = Payment.first
  Payment Load (0.2ms)  SELECT "payments".* FROM "payments" ORDER BY "payments"."id" ASC LIMIT 1
 => #<Payment id: 1, state: "new", created_at: "2014-01-28 12:31:11", updated_at: "2014-01-28 12:31:11">

Setting the transaction:
2.1.0 :007 > p.transactions.build()
 => #<Transaction id: nil, myid: nil, parent_class_is: nil, created_at: nil, updated_at: nil>

Query the transaction:
2.1.0 :005 > p.transactions.first
 => #<Transaction id: nil, myid: nil, parent_class_is: nil, created_at: nil, updated_at: nil>

2.1.0 :007 > p.transactions.first.payment
 => nil

and trying to use the proxy:
2.1.0 :006 > p.transactions.first.my_owner
NoMethodError: undefined method `my_owner' for #<Transaction:0x00000103e44450>

I assume that the .my_owner on a transaction should return the owner (payment) of that transaction?

A: Your code looks confusing to me!

Polymorphic
I think you'd benefit from a polymorphic association on the transactions model. This will allow your transactions to belong to either payments, deposits or any model
Your use of a through relation means transactions can only be associated with payments and transaction & payment objects have to be created before you can associate them:
class Transaction < ActiveRecord::Base
  belongs_to :transactable, polymorphic: true
end

class Payment < ActiveRecord::Base
  has_many :transactions, as: :transactable
end

class Deposit < ActiveRecord::Base
  has_many :transactions, as: :transactable
end

class Reward < ActiveRecord::Base
  has_many :transactions, as: :transactable
end

Extrabutes
If you want to keep your has_many :through association, you can use the ActiveRecord Association Extensions proxy_association object to retrieve the data you need
We made a script to extra join-table data, which you'll be able to adapt to pull child-object attributes:
#app/models/concerns/image_caption.rb
module ImageCaption

        #Load
        def load
      captions.each do |caption|
              proxy_association.target << caption
      end
        end

        #Private
        private

        #Captions
        def captions
                return_array = []
                through_collection.each_with_index do |through,i|
                        associate = through.send(reflection_name)
                        associate.assign_attributes({caption: items[i]})
                        return_array.concat Array.new(1).fill( associate )
                end
                return_array
        end

        #######################
        #      Variables      #
        #######################

        #Association
        def reflection_name
                proxy_association.source_reflection.name
        end

        #Foreign Key
        def through_source_key
                proxy_association.reflection.source_reflection.foreign_key
        end

        #Primary Key
        def through_primary_key
                proxy_association.reflection.through_reflection.active_record_primary_key
        end

        #Through Name
        def through_name
                proxy_association.reflection.through_reflection.name
        end

        #Through
        def through_collection
                proxy_association.owner.send through_name
        end

        #Captions
        def items
                through_collection.map(&:caption)
        end

        #Target
        def target_collection
                #load_target
                proxy_association.target
        end

end

#app/models/message.rb
has_many :image_messages
has_many :images, through: :image_messages, extend: ImageCaption

If you'd like me to modify this code for you, please ask in the comments!


text:
Q: Find the minimum number +ve number in c++? I want to find the minimum number using STL in C++, I know the syntax should be min(x,y). But I want to find the minimum +ve numbers in the list. Not inlcuding the -ves. How do I do that?
P.S My numbers are in an array

A: For finding the minimum number, it makes sense to use std::min_element. Fortunately, it comes with an optional comparison parameter, which we can make use of: (sample here)
auto pos = std::min_element(std::begin(arr), std::end(arr),
    [](const T &t1, const T &t2) {return t1 > 0 && (t2 <= 0 || t1 < t2);}
);

You just have to be careful to take into account that if it's comparing a positive t1 to a negative number, it should always be true. If none of the elements are positive, this will give the location of the first number in the array. If 0 should be treated as part of the positives, change t1 > 0 to t1 >= 0 and t2 <= 0 to t2 < 0.

A: I'd use std::accumulate with a suitable operation:
auto minpos = std::accumulate(myrange.begin(), myrange.end(), MAX_VALUE,
                              [](T acc, T x)
                              { return (x > 0 && x < acc) ? x : acc; });

Here T is the type of your elements and MAX_VALUE is the maximal value of that type (e.g. defined as  std::numeric_limits<T>::max()).

A: First use the remove_if algorithm to move all the negative numbers to the end of the collection, then call min_element on the positive range. In C++11
auto pos = remove_if(coll.begin(), coll.end(), [](int x){ return x < 0; });
auto min = *min_element(coll.begin(), pos);

If you're not using C++11 just replace the lambda with a pre-canned functor from  like less<>

A: You may use std::min_element with Boost::filter_iterator
Something like:
struct is_positive_number {
  bool operator()(int x) const { return 0 < x; }
};

void foo(const std::vector<int>& numbers)
{
    typedef boost::filter_iterator<is_positive_number, base_iterator> FilterIter;

    is_positive_number predicate;
    FilterIter filter_iter_begin(predicate, begin(numbers), end(numbers + N));
    FilterIter filter_iter_end(predicate, end(numbers + N), end(numbers + N));

    FilterIter it = std::min_element(filter_iter_begin, filter_iter_end);

    if (it != filter_iter_end) {
        // *it is the min elem
    } else {
        // no positive numbers.
    }
}


text:
Q: Suppose the gcd (a,b) = 1 and c divides a + b. Prove that gcd (a,c) = 1 = gcd (b,c) I am lost.
So far...
If $\gcd (a,b) = 1$, by Bezout's Formula
$ax + by = 1$
If $c|(a+b)$, then
$cf = a+b$
Then,
$a (x-y) + cfy = 1$
$b(yx) + cfx = 1$
Am I on the right track? Any suggestions?

A: It is true that two nonzero integers $a$ and $b$ are relatively prime if and only if there are integers $x$ and $y$ with $ax+by=1$.  With this in mind, your last equation gives the desired result.

A: Note that $\gcd(a,b)$ has the following property:
For every $d$ such that $d\mid b$ and $d\mid a$, we must have $d\mid \gcd(a,b)$. In other words, every common divisor of $a$ and $b$ is a divisor of $\gcd(a,b)$
We are given $cf=a+b$. Let $d:=\gcd(a,c)$, then we can write:
$$
d(c'f - a') = b
$$
Where $a':=a/d$ and $c':=c/d$. Which means that $d\mid b$, and hence $d\mid\gcd(a,b)=1$. but that is only possible if $d=1$. A similar argument works for $\gcd(b,c)$.

A: Hint $\ $  more conceptually: $\ a,b\,$ are coprime to $\,a+b,\,$ since, e.g. $\,(a,a+b)=(a,b) = 1,\,$ therefore we conclude that $\,a,b\,$ are coprime to every factor of $\,a+b,\,$ including $\,c.$
Remark $\ $ Note that the above proof does not use Bezout's identity so it hold in much more general rings with gcds, e.g. higher-dimensional polynomial UFDs such as $\,\Bbb Q[x,y]$

A: Bezout's identity says that there exists two integers x and y such that ax+by = gcd(a,b). In addition, if you have some positive integer d, such that there exists integers x and y with ax+by=d, then it is not necessary that d = gcd(a,b). If d is the smallest positive integer for which you can find integers x and y with ax+by=d, then it is true that d=gcd(a,b). Since you have found integers such that bx+cy = 1, there can be no smaller positive integer than 1, and it follows that gcd(b,c)=1. The result follows similarly for gcd(a,c).

A: Perhaps it is easier to proceed this way: Let $k$ be a common factor of $a$ and $c$, say $a=kd$ and $c=ke$. (We want to show that $k=1$.) Since $a+b=cf$ for some integer $f$, we get that $$b=cf-a=kef-kd=k(ef-d),$$ so $k$ divides $b$, and therefore it is a common factor of $a$ and $b$. Since their only common factor is $1$, by assumption, it follows that $k=1$, as we wanted. Exactly the same argument gives that $b$ and $c$ must be relatively prime as well.

To address your argument: (There is a small typo in your last equation: $yx$ should be $y-x$.) The argument you give is correct, but it is not because Bezout's formula gives you an "if and only if":
If $ax+by=d$, then $akx+bky=kd$, so clearly, knowing that a linear combination of $a$ and $b$ equals $t$ does not mean that $t$ is the greatest common divisor of $a$ and $b$. What we get from Bezout's result is that $t$ is a multiple of $\mathrm{gcd}(a,b)$ – This is what the proof gives us: That any linear combination of $a,b$ is a multiple of their greatest common divisor, and this greatest common divisor is precisely the smallest positive integer that can be represented as a linear combination of $a$ and $b$.
In the specific case that $ax+by=1$, (but only in that case), we can indeed conclude that $a$ and $b$ are relatively prime, because the equation gives us that $\mathrm{gcd}(a,b)$ divides $1$, so we in fact have $\mathrm{gcd}(a,b)=1$.

A: If by contradiction, $(a,c)=(b,c)=m>1$ then $m|a,m|b$ and $m|c$, which means that there exist an $m>1$ that simultaneously divides both $a$ and $b$ which then implies that $gcd(a,b)\geq m$ which contradicts our assumption.


text:
Q: Integral over the hypersphere Assume I have a diagonal matrix $L$ of size $n$. I want to compute the following integral:
$$I_n(L) \equiv \int_{(\mathbb{S}^{n-1})^2} \mathrm{d}\sigma(x)  \mathrm{d}\sigma(x') \exp[n x^\top L \, x']$$
In which $\mathbb{S}^{n-1}$ is the unit sphere in $\mathbb{R}^n$, and $ \mathrm{d}\sigma$ is the usual measure on $\mathbb{S}^{n-1}$, with $\int_{\mathbb{S}^{n-1}} \mathrm{d}\sigma(x) = 2 \pi^{n/2}/\Gamma(n/2)$.
I am looking for either a general form of $I_n(L)$ or simply an asymptotic of $\frac{1}{n}\log I_n(L)$ as $n \to \infty$.
I tried but could not find such results. Any help would be appreciated. Thanks !

A: There is a way to get an infinite series using the expansion of $\exp$, however, it may be more efficient to compute the result using quadrature. The steps below first expand $\exp$, and use the multinomial theorem to get a polynomial expansion for the integrand. Taking the integral inside the sum to the monomials we can evaluate the integral directly to obtain an analytic (closed form) expression for the integral.
For clarity, first denote the integral by $I$, i.e.
\begin{align}
  I := \int_{S_n}\int_{S_n}\exp(n \textbf{x}^T L \textbf{y}) d\sigma_n d\sigma_n
\end{align}
Power series for exp
If we first consider the expansion of the function argument in the integral,
\begin{align}
  \exp(n \textbf{x}^T L \textbf{y}) =& \sum_{k=0}^\infty \frac{(n\textbf{x}^T L \textbf{y})^k}{k!} \\
 =& \sum_{k=0}^\infty \frac{\left(n \sum_{r=1}^M x_r L_{rr}y_r \right)^k}{k!} \tag{1}
\end{align}
It is well known that the series converges uniformly, and the spherical integral is linear (see [1]), which means we can take the integrals inside the summation,
\begin{align}
  I = \sum_{k=0}^\infty \frac{n^k}{k!} \int_{S_n}\int_{S_n}\left( \sum_{r=1}^M x_r L_{rr}y_r \right)^kd\sigma_n d\sigma_n \tag{2}
\end{align}
Use of the multinomial theorem
Using the multinomial theorem on the inner bracket gives,
\begin{align}
\left( \sum_{r=1}^M x_r L_{rr}y_r \right)^k =& \sum_{j_{1} + \ldots + j_{M} = k} \frac{k!}{j_{1}!\ldots j_{M}!} \prod_{t=1}^M (L_{tt} y_t x_t)^{j_t} \tag{3}
\end{align}
We can then put (3) into (2) and distribute the integrals further over the addition to give,
\begin{align}
  I = \sum_{k=0}^\infty \frac{n^k}{k!}\sum_{j_{1} + \ldots + j_{M} = k} \rho_k \int_{S_n}\int_{S_n} \prod_{t=1}^M (L_{tt} y_t x_t)^{j_{t}}d\sigma_n d\sigma_n \tag{4}
\end{align}
where $\rho_k = \frac{k!}{j_{1}!\ldots j_{M}!} $.
Integrating a monomial
The spherical integral of a monomial is discussed in detail in [2], but the main result gives,
\begin{align}
  \int_{S_n}\int_{S_n} \prod_{t=1}^M (L_{tt} y_t x_t)^{j_{t}}d\sigma_n d\sigma_n = \left\{ \begin{array}{rl} \left( 2\frac{\prod_{t=1}^M\Gamma(q_{t})}{\Gamma(\sum_{t=1}^M q_t)} \right)^2 \prod_{t=1}^M L_{tt}^{j_{t}} & : j_{t} \mbox{ all even} \\ 0& : \mbox{otherwise} \end{array} \right .\tag{5}
\end{align}
Where $q_{t} = \frac{1}{2} (j_{t} + 1)$. Putting (5) into (4) then gives,
\begin{align}
I =& 4 \sum_{k=0}^\infty \frac{n^k}{k!}\sum_{j_{1} + \ldots + j_{M} = k \\ \forall t \mod(j_{t},2) = 0 } \rho_k \left(\frac{\prod_{t=1}^M\Gamma(q_{t})}{\Gamma(\sum_{t=1}^M q_{t})} \right)^2 \prod_{t=1}^M L_{tt}^{j_{t}} \tag{6}
\end{align}
Simplification
Since the terms are non-zero only when all of the the $j_t$, and hence $k$, are even; after some cancellations, the sum can be written,
\begin{align}
I =& 4 \sum_{k=0}^\infty \sum_{j_{1} + \ldots + j_{M} = k} \frac{n^{2k}}{\prod_{t=1}^M (2j_{t})!}\left(\frac{\prod_{t=1}^M\Gamma(j_{t} + \frac{1}{2})}{\Gamma(\frac{M}{2} + \sum_{t=1}^M j_{t})} \right)^2 \prod_{t=1}^M L_{tt}^{2j_{t}} \\
 =& 4 \sum_{k=0}^\infty \frac{n^{2k}}{\Gamma(\frac{M}{2} + k)^2} \sum_{j_{1} + \ldots + j_{M} = k}\prod_{t=1}^M \frac{\left(\Gamma(j_{t} + \frac{1}{2}) L_{tt}^{j_{t}}\right)^2}{ (2j_{t})!}\tag{7}
\end{align}
[1] Baker, John A., Integration over spheres and the divergence theorem for balls, Am. Math. Mon. 104, No. 1, 36-47 (1997). ZBL0877.26008.
[2] Folland, Gerald B., How to integrate a polynomial over a sphere, Am. Math. Mon. 108, No. 5, 446-448 (2001). ZBL1046.26503.


text:
Q: In p5.js, is it possible to load a gif in the setup or preload function, and then use that gif multiple times elsewhere? I have a class (lets call it "Enemies"), I want them to attack me when close enough (It will display an animated gif, that looks like a bite).
I've gotten all of this to work, except the only way I could figure it out, was by putting loadImage("attack.gif"), in the class. That got laggy really quick, since every time an enemy would spawn, it would have to reload that gif.
I've tried to use a loaded gif from the setup(), in my class, but all of their attacks were in sync.
Is there another way to do this?

A: You can preload the gif (or gifs) and store them in a array which you can reuse later to draw in multiple places (e.g. multiple spawned enemies in your case).
Here's a basic example that demonstrates:

*

*loading images into an array

*spawning objects on screen (re)using the loaded images

let images;
let enemies = [];

function preload(){
  // load images and store them in an array
  images = [
 loadImage("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAMAAAD04JH5AAAAPFBMVEX///8AAADf399fX19/f38/Pz+/v78fHx+fn58XFxeHh4cPDw+np6fX19fHx8evr6+3t7dvb2/39/dPT08jn1NmAAAA+UlEQVR4nO3ZSRKCMBBAUQnzPHj/u7qwOwtS0QhBwfpviaH9bDTG2w0AAAAAgNNLE2HC7zF6T0oAAQT8Q0CTC1M8Df61gywxek8TIcAq5anKXUsIIICACwaMmWhlept5OUvGCAH2o3iLqN8FBBBAwJcDJt3U1Dqsk+1O538/Z0mtU6aPAypnuu4JjfNKwJKKAAIIuEzAi+lxvPuFSQABBJwnoHY2JFu4U4ID7GYqzpYs+KiLAAIIOHPA7D+aWZsPCdh1Wk4AAQRcJ2CRQ5ai1yu9XrnnK/YfqWb9SuqfsoQ/xpoehSf+x1PHHtcTQAABPwsAAAAAAOAYD7+UFrmL/czUAAAAAElFTkSuQmCC"),  loadImage("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAMAAAD04JH5AAAAclBMVEX///8AAAAMDAwUFBRtbW20tLTKysrr6+s0NDSMjIzo6OgrKytzc3Py8vJKSkolJSWSkpIODg5jY2OlpaW7u7ubm5urq6tEREQaGhr29vZRUVHg4ODDw8Pc3Nw/Pz9VVVWAgIDU1NQ3NzdcXFx6enovLy+wzkUiAAACjElEQVR4nO2a63qCMAxAlU5QEEEUuSMivP8rjptS2iid0qmfOT/XfM0BHGlLZjMEQRAE+ShMXQBTXn79aAgQ6tIE4u1cgG0sTWAvJrBHARRAART4bIFEvUm8Fsk/nxe3p1BH60RskJsIXX+FcnsKkp5GBAQv8nGyEQFHtoCDAiiAAihwP38gXyAAE592LbYhW6B0u1QJnX9nKS2y09d0mTIqv5n+R2KGH0pAW6IACqAACqDAewtYGwaPQGHEY+OsaQRK1WTJoLiMC1PLSQToyI4FULeVBR/3M4nA+nGBeztNFEABFEABcQFgM7WDBHZc2N2NnrgAcVYMWQ7F5Rkb54BF688CkkABFEABFEABWsDcvEBgUGRjm8YdAthtHTbItR2gQp7Z8kQh3mWw4if2ND5M83jPaVoZAIEN0CcCPEciTSCFBPg7IFEAeATAcas8gRz6DfDLJKLKEli+WqAEPgEDbzN5AgYgoPOnEfIELEiA/9YhT8CHBPgTIYkC0TsK+FzYdh8EgWma2lMNdsH5OqHihS1r6E1YhOGxxuurUn4+hhsvTcOxtgUItVg3OH3jRB4FLZrbDfbYwawb1IHy6T4gYPPTeJcL3/Obvv4fg7plV+yJBYDt+TsJHL9eIESBFwtAi/wvE+BXp1MJXFfjQF8fJXD2LYYSOEMcoB449JXCYl3f6JpD2EFqoaxHbLu51hRFU6tp/xIldEGtnho7HzmcFixU00WgsoP3692iKopVVczzZVka1S3xfVJQw8B6Ejj3fAbg49HI9hwFUAAFUOB/BYDDDeUwqUDBCwyO6dzSal7QPcY027oL6pJQk9fJjOEVdjVKjxqSJAE2f0+h13M2XCok3NiIIMgX8guBhVuAILp8rwAAAABJRU5ErkJggg=="),
     ];
}

function setup(){
  createCanvas(600, 600);
  imageMode(CENTER);
}

function draw(){
  background(255);
  // update + draw enemies
  for(let i = 0; i < enemies.length; i++){
    enemies[i].update();
  }
  text("click to spawn", 10, 15);
}

function mousePressed(){
  // pick a random image
  let randomImage = images[int(random(images.length))];
  // make a new enemy
  enemies.push(new Enemy(randomImage, mouseX, mouseY));
}

class Enemy {
  constructor(skin, x, y) {
    this.skin = skin;
    this.position = createVector(x, y);
    this.velocity = createVector(random(-1,1), random(-1,1));
  }
  update(){
    // add velocity
    this.position.add(this.velocity);
    // check borders and flip direction (roughly)
    if(this.position.x < 0 || this.position.x > width ||
       this.position.y < 0 || this.position.y > height){
       this.velocity.mult(-1);
    }
    // render
    push();
    blendMode(MULTIPLY);
    image(this.skin, this.position.x, this.position.y);
    pop();
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.0/p5.min.js"></script>

In the example above I'm using base64 encoded images to avoid CORS issues, however you should be fine loading your custom images instead.
The idea is to store the images globally so you can re-use them later when instantiating new enemies. (If you have a couple of images individual variables per image should do, otherwise an array will make it easier to manage)
Notice in Enemy constructor simply receives a reference to the previously loaded image:
// when declared
constructor(skin, x, y) {
    this.skin = skin;
// when intantiated
new Enemy(randomImage, mouseX, mouseY)

The only thing left to do is to render the image as needed:
image(this.skin, this.position.x, this.position.y);

Update Based on the comment and shared code the is that each enemy shares the same gif which updates at the same rate with the same frame number in sync.
One option would be to fill the images array with multiple copies of the same image, essentially reloading the gif once per enemy, though that seems wasteful.
Unfortunately p5.Image.get() returns a snapshot of the current frame and there is no magic function to clone a loaded gif, however the undocummented gifProperties holds the necessary data to manually do so:

let images;
let enemies = [];

function preload(){
  // load images and store them in an array
  images = [
    loadImage("data:image/gif;base64,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"),
  ];
}

function setup(){
  createCanvas(600, 600);
  imageMode(CENTER);
}

function draw(){
  background(255);
  // update + draw enemies
  for(let i = 0; i < enemies.length; i++){
    enemies[i].update();
  }
  text("click to spawn", 10, 15);
}

function mousePressed(){
  // pick a random image
  let randomImage = images[int(random(images.length))];
  // offset the start frame of each enemy by one
  let startFrame = enemies.length % randomImage.numFrames();
  // make a new enemy
  enemies.push(new Enemy(cloneGif(randomImage,startFrame), mouseX, mouseY));
}

function cloneGif(gif, startFrame){
  let gifClone = gif.get();
  // access original gif properties
  gp = gif.gifProperties;
  // make a new object for the clone
  gifClone.gifProperties = {
    displayIndex: gp.displayIndex,
    // we still point to the original array of frames
    frames: gp.frames,
    lastChangeTime: gp.lastChangeTime,
    loopCount: gp.loopCount,
    loopLimit: gp.loopLimit,
    numFrames: gp.numFrames,
    playing: gp.playing,
    timeDisplayed: gp.timeDisplayed
  };
  // optional tweak the start frame
  gifClone.setFrame(startFrame);

  return gifClone;
}

class Enemy {
  constructor(skin, x, y) {
    this.skin = skin;
    this.x = x;
    this.y = y;
  }
  update(){
    image(this.skin, this.x, this.y);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.0/p5.min.js"></script>

The cloneGif makes a new object (which means new start frame, etc.), however it should point to the original gif's frames (which hold the pixels / ImageData)
Now each enemy starts at a new frame.
I noticed that changing the delay seems to affect all enemies: once a delay is set to one it seems the underlying imagedata is copied at the same rate.
If you need to have different delay times you can manage still access the same gif frame ImageData, but rather than relying on p5.Image to control the gif playback (e.g. setFrame() / delay()) you'd need manually manage that and render to p5's canvas:

let images;
let enemies = [];

function preload(){
  // load images and store them in an array
  images = [
    loadImage("data:image/gif;base64,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"),
  ];
}

function setup(){
  createCanvas(600, 600);
  imageMode(CENTER);
}

function draw(){
  background(255);
  // update + draw enemies
  for(let i = 0; i < enemies.length; i++){
    enemies[i].update();
  }
  text("click to spawn", 10, 15);
}

function mousePressed(){
  // pick a random image
  let randomImage = images[int(random(images.length))];
  // make a new enemy
  let enemy = new Enemy({frames: randomImage.gifProperties.frames, gifWidth: randomImage.width, gifH: randomImage.height}, mouseX, mouseY);
  // pick a random start frame
  enemy.currentFrame = int(random(images.length));
  // pick a random per gif frame delay (e.g. the larger the number the slower the gif will play)
  enemy.frameDelay = int(random(40, 240));
  enemies.push(enemy);
}

class Enemy {
  constructor(gifData, x, y) {
    this.frames = gifData.frames;
    this.offX = -int(gifData.gifWidth * 0.5);
    this.offY = -int(gifData.gifHeight * 0.5);
    this.currentFrame = 0;
    this.numFrames = this.frames.length;
    this.frameDelay = 100;
    this.lastFrameUpdate = millis();
    this.x = x;
    this.y = y;
  }

  update(){
    let millisNow = millis();
    // increment frame
    if(millisNow - this.lastFrameUpdate >= this.frameDelay){
      this.currentFrame = (this.currentFrame + 1) % this.numFrames;
      this.lastFrameUpdate = millisNow;
    }
     // render directly to p5's canvas context
 drawingContext.putImageData(this.frames[this.currentFrame].image, this.x + this.offX, this.y + this.offY);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.0/p5.min.js"></script>

Also notice the p5.Image does something nice about transparency (even when the original gif is missing it): that's something you'd need to manually address if going this lower level route.


text:
Q: Como eu pego um dado em uma página e coloco em outra? Preciso pegar um dado enviado pelo usuário através do método GET em uma página, colocar esse dado no banco de dados e, em outra página, preciso ler esse dado do banco de dados e escrever na página. No caso, eu tenho uma tabela chamada comandos onde tenho dua colunas nome e valor e quero pegar o dado do campo valorque está na mesma linha onde o campo nome contem o valor LED1
Tentei isso, mas não funcionou:
Página 1
mysql_connect("u541106066_estad","u541106066_ctp","jkf45s6f4sdf4");
$sSQL="Update comandos Set valor='$_GET_["LED1"]' Where nome='LED1'";
mysql_db_query("u541106066_estad",$sSQL);

Página 2
mysql_connect("u541106066_estad","u541106066_ctp","81GDYC2lDC");
$sql = 'SELECT valor FROM comandos';
echo "led=$ql";

A: O que você deseja me parece muito simples, você pode fazer isso desta maneira:

*

*Crie uma classe (arquivo: Database.php) para acessar o banco de dados utilizando PDO, como no exemplo abaixo:

class Database {

 private static $servidor = 'localhost'; // Servidor, no caso poderia ser também localhost
 private static $usuario = 'u541106066_ctp'; // usuário do banco de dados
 private static $senha = 'jkf45s6f4sdf4'; // senha do banco de dados
 private static $banco = 'u541106066_estad'; // nome do banco de dados
 private static $instance = null;

 //inicia a conexão
  public static function getConnection() {
     if (!self::$instance instanceof PDO) {
         try {
             self::$instance = new PDO('mysql:host=' .
             self::$servidor . ';dbname=' .
             self::$banco,
             self::$usuario,
             self::$senha,
             array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
         } catch (PDOException $exc) {
           echo "Erro ao conectar :: {$exc->getMessage()}";
         }
     }
  return self::$instance;
  }

//metodo para trazer vários resultados
  public function fetchAll($query) {
     $con = self::getConnection();
     $stmt = $con->prepare($query);
     $this->execute($stmt);

     if ($stmt->rowCount()) {
        return $stmt->fetchAll(PDO::FETCH_OBJ);
     } else {
       return false;
     }
  }

//metodo para trazer um resultado
 public function fetch($query) {
    $con = self::getConnection();
    $stmt = $con->prepare($query);
    $this->execute($stmt);

    if ($stmt->rowCount()) {
         return $stmt->fetch(PDO::FETCH_OBJ);
    } else {
      return false;
    }
 }

 //executa o PDO
  public function execute(PDOStatement $stmt, array $data = null) {
     try {
           if (isset($data)) {
               $stmt->execute($data);
           } else {
           $stmt->execute();
           }
     } catch (PDOException $exc) {
       echo $exc->getTraceAsString();
       var_dump($exc->getMessage());
     }
  }

 //metodo para inserir e atualizar dados
  public function save($sql, array $data) {

     $con = self::getConnection();
     $stmt = $con->prepare($sql);
     $this->execute($stmt, $data);

     if ($stmt->rowCount()) {
        return true;
     } else {
       return false;
     }
  }

}

*Utilize a classe para pegar os dados do banco, crie um arquivo do tipo index.php e neste arquivo faça o seguinte:

//primeiro você precisa incluir a classe
require_once("Database.php");

//agora você precisa instanciá-la:
$conexao = new Database();

/*
Agora basta chamar o método para a query que você quer buscar no seu banco, através da requisição GET.
- no seu caso /index.php?id=1
- Armazene numa variável o valor que receber
*/
$requisicao_consulta = (isset($_GET['id'])) ? $_GET['id'] : null;
//para post, salva a id no campo hidden
$valor_id = ($_POST['id'] != '') ? $_POST['id'] : null;
//requisição de inclusão/atualização
$requisicao_save = (isset($_POST['action'])) ? $_POST['action'] : null;

if ($requisicao_save != null) {

    $values = [
       'id' => $valor_id,
       'val1' => $_POST['valor1'],
       'val2' => $_POST['valor2'],
       'val3' => $_POST['valor3'],
    ];

} else {

    if ($requisicao_consulta != null) {
        $data = $conexao->fetch("SELECT id,
                                        valor1,
                                        valor2,
                                        valor3
                                 FROM   comandos
                                 WHERE  id='$requisicao_consulta'");
    }

    $message = "- Preencha o formulário abaixo:\n
";

    if (isset($_GET['success-insert'])) {
       $message .= "Dados cadastrados com sucesso!\n
";
    }

    if (isset($_GET['success-update'])) {
       $message .= "Dados atualizados com sucesso!\n
";
    }
}

//agora basta chamar a query com a requisição

if ($requisicao_save == 'insert' && $valor_id == null) {
   $execute = $conexao->save("INSERT INTO comandos
                              (id, valor1, valor2, valor3)
                              VALUES (:id,:val1,:val2,:val3);",
                              $values);
   header('Location: index.php?success-insert');
}

if ($requisicao_save == 'update' && $valor_id != null) {
   $execute = $conexao->save("UPDATE comandos SET
                              valor1=:val1,
                              valor2=:val2,
                              valor3=:val3
                              WHERE id:id;",
                              $values);
  header('Location: index.php?success-update');
}

//a variável $data representa os dados (em objeto) que contém o conjunto de valores trazido pela similaridade da sua requisição, como não é uma coleção, "não" utilizamos $conexao->fetchAll("..."), onde teríamos uma coleção em array. Desta maneira, vamos construir um formulário para preencher os dados que serão alterados (vou escrever em php mesmo, depois você refatora se achar melhor):

$inputs = [];

$action = 'insert';

if (!empty($data)) {

    $action = 'update';
    foreach ($data as $key => $dado) {
    $inputs["{ucwords($key)}\n<input type=\"text\" value=\"{$dado->$key}\" name=\"{$key}\">"];
    }

    $inputs["<input type=\"hidden\" name=\"action\" value=\"update\">"];

} else {

    for ($i=1; $i <= 3; $i++) {
        $inputs["Valor {$i}\n<input type=\"text\" value=\"\" name=\"valor{$i}\">"];
    }

}
$inputs["<input type=\"hidden\" name=\"action\" value=\"{$action}\">"];
$inputs["<input type=\"hidden\" name=\"id\" value=\"{$valor_id}\">"];
$inputs["<input type=\"submit\" value=\"Salvar\">"];
echo "
{$message}
\n";
echo "<form method=\"post\" action=\"{$_SERVER['SCRIPT_NAME']}\" name=\"send\" id=\"send\">\n";
echo implode("\n
", $inputs);
echo "</form>";

A: Na página 2, faz assim:
$res = mysql_db_query($sql);

while ($row = mysql_fetch_assoc($res)) {
    echo $row['valor'];
}


text:
Q: How to do One to many Image matching in opencv? I am working on a Vein pattern recognition project. I have done one to one matching with the SURF detector and it works fine just by giving the filenames. Now, is there a way, I could do one to many comparison and open the image that maximum matches the image? Like enter one filename and compare with it with images in a directory? Is there some built in function that I can use for traversing the images directory?
I am working the project in C++, Ubuntu 12.04LTS, Opencv.
Any help is deeply appreciated.

A: You can use the following function to get all files within given folder.
int getdir (string dir, vector<string> &files)
{
    DIR *dp;
    struct dirent *dirp;
    if((dp  = opendir(dir.c_str())) == NULL) {
        cout << "Error(" << errno << ") opening " << dir << endl;
        return errno;
    }

    while ((dirp = readdir(dp)) != NULL) {
        files.push_back(string(dirp->d_name));
    }
    closedir(dp);
    return 0;
}

After this, all files will be saved in vector<string> files. You can check out here for more info.
P.S. To achieve one-to-many matches, I think you need to loop these files and compare them based on simple one-to-one match and then select the best match.


text:
Q: Spring Cloud AWS support for Spring Boot 2.4 When will Spring Cloud AWS will support Spring Boot 2.4?
What I mean is that which version of Spring Cloud AWS will be supporting Spring Boot 2.4.x?

A: With the next version 2.3 of Spring Cloud AWS, it will support Spring Boot 2.4.x according to one of the contributors (Maciej Walkowiak), see here

Not yet. Spring Cloud AWS 2.3 is compatible with Spring Boot 2.4, it will be released very soon.
I'll keep this issue open till 2.3 is released.