Continuous function $h \colon [0, 1) → \Bbb R$ which is bounded but does not attain either of its bounds.

Question: I am trying to find a continuous function $h \colon [0, 1) →\Bbb  R$ which is bounded but does not attain either of its bounds.
I'm having no luck so any tips would be great thanks.
Answer: Try $h(x)=x\cdot \sin\frac1{1-x}$.
Comment: [Helpful graph](http://imgur.com/MN8Opz0.png)
Comment: Use Spivak! An excellent reference for such naughty functions.
Answer: It is not possible as follows. Let M,m denotes sup and infimum of the bounded set {h(x):x\in [0,1)}. If M is not attained there must exist a sequence x_{n} such that h(x_{n}) converges to M. Now being infinite and bounded we take a subsequence of {x_{n}} which converges to a point a. If a\neq 1, then h(x_{n})=f(a)=M. Hence a=1. Similarly, we will get, h(1)=m. But then this means, m=M which means the function is constant.


Date display differences in node templates

Question: In a node template, if I use the following:
{{ content.field_event_start_date }}

The correct localized date and time will be displayed.  For example:
Tuesday, February 14, 2017 @ 9:00am EDT
However, if I only want to display the time part and use the following:
{{ node.field_event_start_date.value|date("g:ia") }}

The incorrect time is displayed:
1:00pm
There appears to be a +4h offset when using the TWIG date() filter.
Drupal's Timezone is set to "America/New York".
How can I display only the time part so that it correctly displays the following?
9:00am
Also, can you please explain what conversion Drupal is performing on the time under the covers?
Thank you.
Answer: The proper thing to do here is to configure your field output to use the proper formatter.  On the Manage Display for your content type, eg admin/structure/types/manage/page/display, change the formatter for your field_event_start_date field to Custom, then click on the gear and change the format to 'g:ia'.  You should then be able to use {{ content.field_event_start_date }} in your template.
The standard Twig date() filter doesn't use the date.formatter service, so timezones and localization settings will not be honored.
TwigExtension defines a custom filter for Drupal that will call out to DateFormatter::format() called format_date().  This should work
{{ node.field_event_start_date.value|format_date("custom", "g:ia") }}

This apparently only works for Timestamp fields and not datetime or daterange fields.
Comment: Thanks for your reply and explanation.  I tried your suggestion, but it seems that it will only work if the particular field is of type "timestamp".  The field that I am using is of type "date".  Here's what Drupal output when I tried:

`Exception: The timestamp must be numeric. in Drupal\Component\Datetime\DateTimePlus::createFromTimestamp() (line 172 of core/lib/Drupal/Component/Datetime/DateTimePlus.php).`

Anything else that I can try?  Thanks again!
Comment: I'm not 100% certain about the syntax there, as I don't think I have ever used this directly.
Comment: @kvjava1 Sorry about that; Twig is pushing the limits of what I do in Drupal 8 and I am not sure how to extract the timestamp in a template.  I assume using the custom formatter, and using the 'g:ia' format isn't an option?
Comment: It's ok.  Can you clarify (and/or give an example of) what you mean by "using the custom formatter, and using the 'g:ia' format"?
Comment: I even tried converting the "datetime" to a "timestamp" and then doing `{{ node.field_event_start_date.value|date('U')|format_date("custom", "g:ia", "America/New_York") }}`, but that didn't work either. :(  If I use "PST" for the timezone instead of "America/New_York", then it works, but I'm in "EST" so I don't like that hack. :(  Trying to figure out what's going on with Drupal internals...?
Comment: Using date('U') in addition to formate_date('custom', ...) did the trick for me! thanks!
Answer: You can preprocess your node in THEME.theme (or in a module if you prefer, note that my field is 'field_date' you will need to adapt to your field machine name).
I copy the field using another display formatter. I'm using datetime_custom formatter, but you can use whatever you want.
function THEME_preprocess_node(&$variables) {
  $node = $variables['node'];

  // Extract the hour from the field_date so we can easily display concert_time
  if(!empty($node->field_date)){
    $variables['concert_time'] = $node->field_date->view([
      'type' => 'datetime_custom',
      'settings' => ['date_format' => 'H:i'],
    ]);
  }
}

Then in your twig
{{ concert_time }}


Getting started with vmware vSphere

Question: I am just getting started with virtualisation after being pointed towards it via another question on SF. I have installed vmware vSphere on one of our servers (HP ProLiant DL360 3.0GHz, 4GB RAM, 70GB HDD in Raid 1).
I have a few questions regarding vmware and virtualisation in general.
1) The server has two NIC's. When using vmware vsphere, is there any benefit in connecting both?
2) If I get some IP addresses from our ISP is it as simple as adding a route to our router that points the virtual instances's static IP?
3) Is vSphere really free? Ive registered and installed my license and I have any servers with more than 4 cores.
4) I have a server running Windows Server 2008 on an identical HP ProLiant server. How simple is it to convert it to a virtual server?
Thanks!
Answer:
VMware actually recommends at least 4 NICs for a single standalone virtual server.  Two for the console connection and two for the virtual machines.  Once you get into a clustered setup then you'll want to add two more for vMotion, but that's later on.
Yep.
It can be if you are using the ESXi license.  You don't get some features, but if you don't need those features (clustering, HA, etc) then you are fine.
If you purchase vCenter then you get the VMware converter which can quickly and easily convert physical servers to virtual machines.  Without VMware converter you can still do it, but it's a bit harder and takes a few steps to get it done.
Comment: Thanks! For very low level use would 2 NIC's be adequate? I'm not sure that I can add more NIC's to the server. Nor do I know how to configure them in vmware vSphere!
Comment: Yes, use one for the host console and one for the VMs.  As long as you've got on open PCIx or PCIe slot you can add more NICs to a DL360.  As long as the NIC is supported in VMware you just need to connect it to the correct vSwitch using the VMware Client and it'll start using it.
Answer:
The server has two NIC's. When using vmware vsphere, is there any benefit in connecting both?

Absolutely.  You can distribute the network load of multiple virtual machines across the two interfaces, which -- depending on your network topology -- may yield performance benefits.  You also get enhanced reliability, since if properly configured your virtual machines will continue to have network access if one of the interfaces fails (or a cable is pulled, or a switch port fails, etc).

If I get some IP addresses from our ISP is it as simple as adding a route to our router that points the virtual instances's static IP?

Managing network on a virtual machine is typically the same as managing networking on a physical machine, provided you've got your VMware instance configured correctly.  VMware typically acts as switch, connecting the "internal" layer network of vmware to your external layer 2 network.
So, "yes" is the short answer.

Is vSphere really free? Ive registered and installed my license and I have any servers with more than 4 cores.

I think the basic version here.  There are fancier features that are available as additional cost options.  They become more attractive as your number of physical hosts grows larger.

I have a server running Windows Server 2008 on an identical HP ProLiant server. How simple is it to convert it to a virtual server?

Converting a physical host into a virtual machine is not especially difficult.  For Windows, it usually means installing some new device drivers (since you will effectively be swapping out your video adapter and network cards with new ones).  VMware provides a tool to make the process easier but you nesed to purchase it.  You obviously need to figure out how to get the data from your physical disk onto a virtual disk image -- tools like Ghost or any of various similar systems can help with this.
Answer:
You can split the traffic/network roles between the physical NICs which will typically allow you to tune the overall network performance based upon your VMs' network requirements
That depends on how your overall network is setup in relations to the host - simplest configuration examples may be to have your VMs sitting within your DMZ on the assigned ISP subscriber network
Yes, the "pay hook" is when you have multiple hosts and want to manage them under a unified view, then the licensing starts...
VMware provides tools as well as 3rd party publishers which help in the conversion, their degrees of automation will vary, but most of the tasks can also be performed manually as well (e.g. mainly swapping out device drivers - physical for virtual)

Getting started with vmware vSphere


static variable lifetime

Question: Suppose I have a static variable in a class:
class Example {
    public static var one:One = new One;
}

Will 'one' being instanciated at my program startup (even if I never use it), or just at the first time I use it?
Answer: I guess if you ask the question, it's because you only want the object to be created if you use it. In that case, what you should do is implement lazy creation of the object. Something like that would work:
class Example {

    private static var one_:One = null;

    public static function get one():One {
        if (!one_) one_ = new One();
        return one_;
    }

    // If the variable is not read-only, you also need a setter:
    public static function set one(v:One):void {
        one_ = v;
    }

}

Now you are sure that one will only be created if you directly refers to it using Example.one in your code.
Comment: There's no general rule about it, it depends on what you are trying to do. But this is not a singleton pattern anyway, just a static variable (which also may or may not be a good idea, depending on your needs).
Comment: A simple Singleton, right? I've heard its not a good practice to use a Singleton. But I didn't understand why.
Answer: First time you will use the Class Example
Answer: It'd be at startup. But there should be "links" to this class.

direct usage of this class somewhere in code
you have imports with this class

So if this class compiled-in, it'd instantiated at start-up.
Correct me if I'm wrong.
Actually it's really easy to test :)

static variable lifetime


Orphaned Page Checker

Question: Hey guys I have a large website I am trying to clean out; there are a ton of pages and quite a few of them are orphaned. (a page with no pages that link to it, IE, a page that can't be gotten to).
Is there an online service or a program that will find orphaned pages?
Comment: Not an answer, but the term you are looking for is "Orphaned" pages. That terminology may help your search. Might not too. ;)
Comment: There are tools that will compare your web site against the file system and show the orphans (and lots of other data).  The name of  the one I once used escapes me...
Comment: For comparing, maybe: `wget -P reachable --mirror --page-requisites site` and `diff -qr reachable htdocs`
Answer: I used Macromedia Dreamweaver's Site Report > Check Links > Orphan Pages as well as online free service http://www.dead-links.com/ .
I also used unix grep to double check a few randomly.
Comment: If I'd seen this question when it was first posted I would have suggested the same thing
Answer: You didn't mention what web server you are running, but here is a link to a similar question with some answers specific to IIS:
Is there an easy way to generate a report on "dead" files in IIS?

Orphaned Page Checker


bootstrap alert not working

Question: I am trying to make an alert using bootstrap and its not wokring. In the mozilla firebug console its showing
ReferenceError: $ is not defined

$('#openAlert').click(function () {

The code is as follows.May i know what is missing.I am including jquery as well as bootstrap js files.

<title>Twilio Messages (Send message Example)</title>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css" rel="stylesheet">
<link href="http://getbootstrap.com/2.3.2/assets/css/bootstrap-responsive.css" rel="stylesheet">

Twilio Messages (Send message Example)

                <form class="form-signin" action="#Twilio" method="post">

                            Enter Number to send:

                            <input type="text" name="toNumber" maxlength="10" placeholder="Enter 10 digits number to send" value="+16822037149"/>

                                <button type="button" class="close" data-dismiss="alert">×</button>
                                The number to send an SMS to. This field accepts formatted and unformatted US numbers, e.g. +14155551212, (415) 555-1212 or 415-555-1212.

                                To send message from SandBox Account. The Number has to be verified

                            Enter Message to send:

                            <textarea name="body" maxlength="160" placeholder="Enter message to send">
                            </textarea>

                                <button type="button" class="close" data-dismiss="alert">×</button>
                                The text of the message you want to send, limited to 160 characters.

                            <button class="btn" type="submit" id="openAlert">Send</button>

                </form>

      <button href="#" type="button" class="close">×</button>

Alert title

Roses are red, violets are blue...

Comment: make sure you include jquery with a correct path
Comment: @ubercooluk this is there
Comment: where is that..?i cant see
Comment: @ubercooluk 3rd line from bottom
Answer: Include your scripts to  and then use alert()or whatever you library call you are making,
As you are calling the library functions before loading library
$('#openAlert').click(function () {
      $('#le-alert').addClass('in'); //
.................

should be *after*

Remember: You need to include JS library first and then you can use the functions as $ is to be initialized
Answer: This should work:

      <button href="#" type="button" class="close">×</button>

Alert title

Roses are red, violets are blue...

Please make sure to include jquery before calling any jquery dependencies and custom functions based on jquery.
Comment: Though I already got an answer but your answer is also useful so +1
Answer: You need to include a script reference to jQuery.

Answer:
Make sure you imported jQuery plugin in your code
Make sure jQuery plugin is loaded before using(wrapping inside document handler function).

The simplest check to verify jQuery is loaded or not is
if (typeof jQuery != 'undefined') {
    // do operation's here
}

Or
if (window.jQuery) {
    // jQuery is available.
}

DEMO
Comment: I didnt downvote your que.The person who downvoted must have looked at  your question as case of ignorance.
Answer: Your reference to the jQuery file needs to be placed just before your script that uses the $ function.
You have got it nearly right by placing all your js at the bottom.
But you need to make sure that the jQuery file is referenced before anything else that is going to try and use it.

bootstrap alert not working


Sum of powers of a field's element equals zero

Question: Assume that we have a finite field $\mathbb{F}_q$ and an element $a\in\mathbb{F}_q$ s.t. $\mathrm{ord}(a)=9$. I want to prove that
$$1+a^{3}+a^{-3}+1+a^{3}+a^{-3}+1+a^{3}+a^{-3}=0$$
I know that this should hold by some coding theory property but I cannot prove it.
Comment: @HenningMakholm I made a mistake so it needs only to hold for $b=0$. I have made the edits. Can you give any hints?
Comment: To begin, divide by $3$. Then let $b=a^3$.
Answer: If $a$ has order $9$, then $a^3$ has order $3$, and so $1,a^3, a^{-3}$ are all different, and each of them is a root of $x^3-1$.
In a field, a nonzero polynomial cannot have more roots than its degree, so $1+a^3+a^{-3}$ is the sum of the three roots of $x^3-1$. But the sum of the roots of a monic polynomial (that has the maximal number of roots) is exactly minus the next-to-highest coefficient, which is $0$ in this case.

Alternatively, rewrite your goal by multiplying by powers of $a^9$ to
$$ 1+a^3+a^6+\cdots+a^{24}=0 $$
and apply the formula for a finite geometric series, giving
$$ \frac{a^{27}-1}{a^3-1} = 0 $$
But the numerator here is $a^{27}-1=(a^9)^3-1=1^3-1=0$.
Comment: @mgus: Such a polynomial splits into linear factors $(x-a_1)(x-a_2)(x-a_3)$, which multiplies out to $x^3-(a_1+a_2+a_3)x^2+\cdots-a_1a_2a_3$. (If the latter were _not_ the polynomial you're looking at, you could subtract them and get a nonzero polynomial of degree $<3$ which has $a_1$, $a_2$ and $a_3$ as roots, but that is impossible).
Comment: Can you elaborate on your last statement "the sum of the roots of a monic polynomial (that has the maximal number of roots) is exactly minus the next-to-highest coefficient"? It would be nice if you can pinpoint some reference to a proof or related literature.


How to query to Fetch Data of each Name in List for a Date Range

Question: I have a table like

Name
Total
Date

A
10
2020-12-01

B
5
2020-12-01

A
10
2020-12-02

B
15
2020-12-02

now I have a List of Name and Date List Like
@NameList = '[A],[B],[C],[D]'
@DateList =  '[2020-12-01],[2020-12-02],[2020-12-03],[2020-12-04]'

How to query to fetch data for each name and date available in @NameList and @DateList?
Expected Result

Name
Total
Date

A
10
2020-12-01

B
5
2020-12-01

C
0
2020-12-01

D
0
2020-12-01

A
10
2020-12-02

B
15
2020-12-02

c
0
2020-12-02

D
0
2020-12-02

A
0
2020-12-03

B
0
2020-12-03

c
0
2020-12-03

D
0
2020-12-03

A
0
2020-12-04

B
0
2020-12-04

c
0
2020-12-04

D
0
2020-12-04
Comment: Hi @DaleK , Name List And Date Rand Coming From UI
Answer: How about a JSON approach?
Assuming that the names and dates never contain a double quote, you can turn them to JSON strings with string functions, and unnest each list as rows with openjson(). The last step is to bring the original table with a left join.
declare @NameList nvarchar(max) = '[A],[B],[C],[D]';
declare @DateList nvarchar(max) =  '[2020-12-01],[2020-12-02],[2020-12-03],[2020-12-04]';

select n.name, coalesce(t.total, 0) as total, d.dt
from openjson('[' + replace(replace(@NameList, '[', '"'), ']', '"') + ']')
    with(name nvarchar(max) '$') n
cross join openjson('[' + replace(replace(@DateList, '[', '"'), ']', '"') + ']')
    with(dt date '$') d
left join mytable t on t.name = n.name and t.date = d.dt

Answer: You can break apart the lists using string_split() and then use left join to bring in the existing data:
declare @NameList nvarchar(max) = '[A],[B],[C],[D]';
declare @DateList nvarchar(max) =  '[2020-12-01],[2020-12-02],[2020-12-03],[2020-12-04]';

select v.name, v.date, coalesce(t.total, 0) as total
from string_split(@namelist, ',') n cross join
     string_split(@datelist, ',') d cross apply
     (values (replace(replace(n.value, '[', ''), ']', ''),
              convert(date, replace(replace(d.value, '[', ''), ']', ''))
             )
     ) v(name, date) left join
     yourtable t
     on t.name = v.name and t.date = v.date

The only real trick here is to use apply to remove the square braces.
Here is a db<>fiddle.
Answer: use this
select t1.name,t2.[date]  from
[table] t1
cross apply [table] t2

Comment: Please illustrate how this solves the OPs problem? It doesn't appear to take into account any of the ranges concerned.
Comment: While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.


Store input from a text field in a PHP variable

Question: Store the users input from a text field in a variable. Any ways to do this?
Comment: Do one of the zillion tutorials out there, this question seems just plain lazy to me.
Answer: HTML:
<input type="text" name="firstname" />

PHP-onsubmit (untested)
<?php
   $firstname = $_POST["firstname"];
?>

Comment: Thank you! Sorry to ask such a dumb question.
Comment: what's there to test? In the worst case scenario, it will generate a notice.
Comment: Untested...  Sheesh, you mean you couldn't be bothered to write a full unit test and a selenium interface test suite for this answer?  Talk about lazy... ;-)
Comment: I think a lazy question deserves a proportional response.
Answer: if you have a form with that textarea and you submit that form, you'll have the value in your global $_GET or $_POST-array (depending on whats the methot of your form).
you can access this value by typing $_GET['nameofyourtextarea'] (or the same with $_POST)


nodejs server only works when started from cli

Question: I'm trying to run a node app on my personal blog, which does display the static content, but cannot send POST calls back to the server when I start the server via systemctl. However when I run node index the server starts up and can send POST requests with JSON back to the server. How can I fix my systemd unit to properly start it up with equivalent ability to simply typing node index?
Systemctl service file:
[Unit]
Description=systemd node unit
Documentation=https://XXXX.com
After=network.target

[Service]
Environment=NODE_PORT=7070
Type=simple
User=ubuntu
ExecStart=/usr/bin/node /XXXX/XXXXXX/XXXXXXXX/XX/index.js
Restart=on-failure

[Install]
WantedBy=multi-user.target

Additional context:
-to route to my nodejs server, I use an nginx reverse proxy(:7070->example.com/something)
-my nodejs application functions perfectly fine on my local computer with the node index command
-node -v yields me:
v10.15.0

Answer: A lot of Node.js apps expect to have their working directory be the directory in which they are stored. But your systemd unit doesn't change the working directory.
You should set the working directory appropriately.
[Service]
WorkingDirectory=/wherever/you/installed/it


Ubuntu 16.04 Postfix works, but email goes to SPAM


Obter valores Checkbox criados dinamicamente

Question: Desenvolvendo uma aplicação python utilizando o framework Flask para realizar um cadastro simple
Estou com o seguinte problema, eu tenho um cadastro de licitações e essas licitações podem ter várias categorias, as categorias são cadastradas pelo usuário e aparecem na tela de cadastro da licitação em forma de checkbox para o mesmo ir selecionando as devidas categorias
Até a parte listar todos os checkbox na tela da licitação, foi tranquilo e está funcionando, porém agora eu não sei qual é a maneira mais correta de se obter os ids das solicitações listadas. Existe uma forma simples de percorrer todo um grupo de checkboxes, afinal não sei o id deles por que são criados de acordo com oq está salvo no banco.
A solução que pensei, foi buscar todos os ids de categoria no banco e ir buscando de acordo com o padrão que cirei para o nome, mas isso não me parece a forma mais correta.
Para exemplificar melhor o problema, segue o código reduzido da minha página html e das minhas funções no controller
Página html
<form action="{{url_for('gravar_licitacao')}}" method="POST" role="form">
  Categorias:
  {% for categoria in categorias %}
    <input type="checkbox" id="cbCat{{ categoria._id }}" value="{{ categoria._id }}">{{categoria.nome}}
  {% endfor %}

  <input type="submit" value="Enviar" class="btn btn-default"/>
</form>

Controller
@app.route("/cadastro_licitacao")
def cadastro_licitacao():
    categorias = Categoria.query.all()
    return render_template("licitacao/cadastro_licitacao.html", categorias = categorias)

@app.route("/gravar_licitacao", methods=["GET", "POST"])
def gravar_licitacao():
    if request.method == "POST":
        #QUAL È A MANEIRA CORRETA PARA EU OBTER UMA LISTA COM AS CATEGORIAS AQUI

    return redirect(url_for("lista_licitacoes"))

Comment: Da uma olhada aqui...
https://stackoverflow.com/questions/31859903/get-the-value-of-a-checkbox-in-flask
espero que tenha ajudado !
Answer: pode obter os dados do formulário assim:
if request.method == "POST":
    valor = request.form["id"]

Comment: O problema é que mão sei o id dos checkboxes para passar para o método. Eles são criados dinamicamente e esse é o meu problema


Issue With a String Not Able To Concatenate

Question: The desktop client we use with our phone system has an API which allows us to capture the telephone number of the phone as it rings.
In order to use the API you reference a DLL and specify.
using TelephonyProxy;

public class program
{

    private static Commander commander;
    private static Listener listener;

    static void Main()
    {
        commander = new Commander();
        listener =  new Listener();
        SubscribeToListener();
    }

    private static void SubcribeToListener()
    {
        Debug.WriteLine("Subscribe To Listener");
        listener.Connect += OnConnect;
        listener.Disconnect += OnDisconnect;
        listener.Offering += OnOffering;
        listener.Ringback += OnRingback;
    }

    private static void OnOffering(string name, string number)
    {
        Debug.WriteLine(number + "abc");
    }
}

The issue is the OnOffering is called correctly and the telephone number is in the number variable. However the debug only shows the number and not the "abc". In testing it seems you can concatenate anything in front of number but anything after is ignored.
Have you any idea why that might be?
Thanks for any input you can give this.
Comment: `Debug.WriteLine(number + "abc");` those are not speech marks that the debugger will recognise
Comment: @silkfire apparently it seems to have also swallowed OP as well...
Comment: Does number end with \0 ? Anything after \0 won't be rendered. Example: `var test = "a\0b"; Debug.WriteLine(test); // only prints a`
Comment: @AlfieGoodacre I was wondering about those, but the application won't compile if they're present so I suspect that isn't his problem.
Comment: @silkfire It seems to be a logical conclusion. StringBuilder, String.Concat, and C# 6 string interpolation will all achieve the same thing as string+string. If it isn't showing up using string+string, then it won't with any of the others. A string containing `\0` is a plausible reason as to why the remainder of the string would not be printed to Output window. Can you think of any others?
Comment: @john Probably there's a black hole right after the phone number that swallows everything that comes after :)
Comment: have you tried other string concatenation methods? like `Debug.WriteLine($"{number}abc");`
Comment: @john: I have tested it in `Visual Studio`, and the `Output` window does not show anything after `\0`. Add an answer because it is interesting issue.
Comment: @apocalypse As per Goos' answer, try string interpolation (if on C# 6.0 or higher) and see if that works?
Comment: @silkfire: string interpolation does not help. `\0` still exists in result string. It's the `output` window issue.
Comment: @apocalypse Why do you think that the string ends with `\0`? Btw, why are you replying for viperdudeuk?
Comment: @silkfire I believe they're just trying the answers out to see what's plausible
Comment: @silkfire That's possible, too!
Comment: OP - did my answer solve your issue? If so, can you accept my answer, please?
Answer: ASCII character 0 (represented in the debugger as \0) is sometimes used to terminate strings. If you're dealing with something like a COM device, etc., this may be the case.
For example:
Debug.WriteLine("a\0b");

will only output "a". ASCII character 0 is not printed, nor are any of the subsequent characters. Naturally, appending something to such a string will mean that anything after \0 in the original string, nothing will appear.
If you're dealing with COM, look at the string in the debugger and see if \0 is on the end.
You could remove it using replace:
Debug.WriteLine(number.Replace("\0", "") + "abc");

Comment: Thanks, that sorted it.


How upload files to current working directory in Google Colab notebook?

Question: I uploaded a Jupyter notebook to Google Colab. The notebook accessed a couple of images from local path /images/pic1.png How to upload data to the directory in Colab where the notebook is running? Please note that these are temporary files. So, I don't mind them being deleted on terminating the session.
I used Files upload feature but it doesn't seem to upload to Google Drive. I want to upload the folder with the same hierarchy as in the local environment without needing any change in the paths of the files in the code.
Answer: The better way I've found is mounting a folder in your Google Drive. Upload the image folder to your drive. After that, in your notebook you write:
from google.colab import drive
drive.mount('/content/drive')

After you allow the authentication, you can work using the path "/content/drive/My Drive" with the path for your image folder. Like that:
from IPython.display import Image
Image("/content/drive/My Drive/images/pic1.png")

See more in the notebook with documentation: https://colab.research.google.com/notebooks/io.ipynb


Fit textarea width to the longest line of text

Question: How do I make a textarea increase its WIDTH while the user is typing. Basically I need the WIDTH of the textarea to be only to the length of the longest line.
This is what I came up with. But when the user hits ENTER still the width increases. How do I make the textarea to fit only to the size of its text?
$(document).on("click blur keyup", ".fT", function() {
      var newWidth = ($('#tfd').val().length)*10;
      $('#tfd').width(newWidth);
});

Comment: You cannot use $('#tfd').val().length because it will calculate the value of the whole text (not one line). You need to check for '\n' in your textarea value and make an array out of all text that ends with \n and determine the longest one then
Comment: @progrAmmar: thanks. like `if(keycode == '13'){` ?
Comment: Yes you can use that code it will mean you are checking for the largest line on each 'enter' key press. Even then you will have to look for the largest line on each enter key press
Answer: As @progrAmmar mentioned, $('#tfd').val().length measures the total length for your text, not the width of the longest line.
In fact your newWidth is just an approximation and will not be correct at all if a user types non ASCII characters.
One way to approxmiate the length is to place a pre element somewhere, set visibility:hidden and font-size and font-family the same as your textarea,  and update this element with the new content whenever the user types.
By measuring this pre element's width you can get a good approximation for the text.
Comment: thanks. Isn't there a css rule that could be refreshed using keyup() in jQuery to adjust its width?


Batch API error: ResponseText: {"errors":[{"message":"Not acceptable format: json"}]}

Question: When running a batch process on Drupal 8, the following error is returned:
ResponseText: {"errors":[{"message":"Not acceptable format: json"}]}

The HTTP response is HTTP POST / 406
I can see the route is defined ok for the batch callback with the JSON support there:
select * from router where name like '%system.batch_page%' \G;
*************************** 1. row ***************************
           name: system.batch_page.html
           path: /batch
pattern_outline: /batch
            fit: 1
          route: C:31:"Symfony\Component\Routing\Route":970:{a:9:{s:4:"path";s:6:"/batch";s:4:"host";s:0:"";s:8:"defaults";a:2:{s:11:"_controller";s:52:"\Drupal\system\Controller\BatchController::batchPage";s:15:"_title_callback";s:57:"\Drupal\system\Controller\BatchController::batchPageTitle";}s:12:"requirements";a:2:{s:7:"_access";s:4:"TRUE";s:7:"_format";s:4:"html";}s:7:"options";a:4:{s:14:"compiler_class";s:34:"\Drupal\Core\Routing\RouteCompiler";s:12:"_admin_route";b:1;s:12:"_no_big_pipe";b:1;s:14:"_access_checks";a:1:{i:0;s:20:"access_check.default";}}s:7:"schemes";a:0:{}s:7:"methods";a:2:{i:0;s:3:"GET";i:1;s:4:"POST";}s:9:"condition";s:0:"";s:8:"compiled";C:33:"Drupal\Core\Routing\CompiledRoute":312:{a:11:{s:4:"vars";a:0:{}s:11:"path_prefix";s:0:"";s:10:"path_regex";s:12:"#^/batch$#sD";s:11:"path_tokens";a:1:{i:0;a:2:{i:0;s:4:"text";i:1;s:6:"/batch";}}s:9:"path_vars";a:0:{}s:10:"host_regex";N;s:11:"host_tokens";a:0:{}s:9:"host_vars";a:0:{}s:3:"fit";i:1;s:14:"patternOutline";s:6:"/batch";s:8:"numParts";i:1;}}}}
   number_parts: 1
*************************** 2. row ***************************
           name: system.batch_page.json
           path: /batch
pattern_outline: /batch
            fit: 1
          route: C:31:"Symfony\Component\Routing\Route":858:{a:9:{s:4:"path";s:6:"/batch";s:4:"host";s:0:"";s:8:"defaults";a:1:{s:11:"_controller";s:52:"\Drupal\system\Controller\BatchController::batchPage";}s:12:"requirements";a:2:{s:7:"_access";s:4:"TRUE";s:7:"_format";s:4:"json";}s:7:"options";a:3:{s:14:"compiler_class";s:34:"\Drupal\Core\Routing\RouteCompiler";s:12:"_admin_route";b:1;s:14:"_access_checks";a:1:{i:0;s:20:"access_check.default";}}s:7:"schemes";a:0:{}s:7:"methods";a:2:{i:0;s:3:"GET";i:1;s:4:"POST";}s:9:"condition";s:0:"";s:8:"compiled";C:33:"Drupal\Core\Routing\CompiledRoute":312:{a:11:{s:4:"vars";a:0:{}s:11:"path_prefix";s:0:"";s:10:"path_regex";s:12:"#^/batch$#sD";s:11:"path_tokens";a:1:{i:0;a:2:{i:0;s:4:"text";i:1;s:6:"/batch";}}s:9:"path_vars";a:0:{}s:10:"host_regex";N;s:11:"host_tokens";a:0:{}s:9:"host_vars";a:0:{}s:3:"fit";i:1;s:14:"patternOutline";s:6:"/batch";s:8:"numParts";i:1;}}}}
   number_parts: 1
2 rows in set (0.00 sec)

Just wondering if anyone else has encountered this error for the Batch API processing and may have some suggestions on it.
Answer: In our case, we had to turn off Cloudflare's Query String Sort option. See here --> https://support.acquia.com/hc/en-us/articles/360022037774-Resolving-Not-acceptable-format-json-error-HTTP-code-406-in-batch-operations
Here is the drupal issue too --> https://www.drupal.org/project/drupal/issues/2879023


Semirings related

Question: How to prove a distributive near-semiring $(S,+,.)$ with multiplicative identity $1$ is additive subcommutative?
[ Hints: A non empty set $S$ with two binary operations $'+'$ and $'.'$  is called  near-semirirng if the following conditions are satisfied:
$(i) a+(b+c)=(a+b)+c$
$(ii) a.(b.c)=(a.b).c$
$(iii)  a.(b+c)=a.b+a.c$  $\forall$  a, b, c $\in S$ (left distributive law)
Distributive near-semiring means in addition with all above three conditions, $(a+b)c=ac+bc$ $\forall$ $a,b,c \in S $ (right distributive law)
 also satisfied.
A near-semiring with multiplicative identity means that there is an element $1 \in S$ such that $a.1=1.a=a$ $\forall  $ $ a \in S$
A near-semiring $(S,+,.)$ is said to be additive subcommutative  if $a+b+c+d=a+c+b+d$ $\forall a,b,c,d \in S$]
Comment: anybody help me
Answer: I tried to prove the question as in the following way:
$(1+1)(a+b)=1(a+b)+1(a+b)=a+b+a+b$ ....(1)(use right distributive law)\
Also $(1+1)(a+b)=(1+1)a+(1+1)b=a+a+b+b$...(2) (use left and right distributive laws)
From equations $(1)$ and $(2)$, we have $a+b+a+b=a+a+b+b$. Is it enough  to prove additive subcommutative? Is it correct or not?
Comment: Please anybody help me to find exact solution.

Semirings related


Puppet: conditional restart of service

Question: Is it possible to conditionally skip refresh events on a service resource? Or alternatively: Is it possible to prevent a service resource inside a class to be refreshed when the class is notified?

Context: I have a Puppet module containing the following manifest (simplified):
class foo(
  Boolean pre_process_service  = true,
  Boolean auto_restart_service = true
) {
  if $pre_process_service {
    exec { 'process config':
      ... # details including a pretty complex command - should be hidden in my module
      notify => Service['foo'],
    }
  }

  service { 'foo':
    ensure => 'running',
    enable => true,
  }
}

which might be used like so:
file { 'config':
  ... # copies config from somewhere
}

class { 'foo':
  auto_restart_service => false,
  subscribe            => File['config'],
}

How can I avoid restarting the service when the user specifies auto_restart_service => false?
Note that the user of the module decides how to provide the configuration (copying files, checking out a Git repository,...) so I can't do that inside my module. Instead the class subscribes to the resource providing the configuration. As long as the user goes with the default of auto_restart_service = true everything works fine and even disabling the preprocessing of the configuration works correctly. However, when the user specifies auto_restart_service = false the service will still restart since the service resource is refreshed when the class is notified. Wrapping the service resource into an if block like I did with the exec resource doesn't work either since the service resource does multiple things:

It starts the service if it isn't running
It enables the service if it isn't enabled
It restarts the service if notified

I only want to conditionally prevent (3) from happening while always doing (1) and (2). Is there a way to do this?
Answer: I don't think there's a way to not refresh the service when you notify the class. However, you can try to conditionally override how Puppet should restart the service with the restart attribute of the service resource.
Something like this:
if $auto_restart_service {

  # Let the provider handle the restart
  $_attr = {}

} else {

  # Let Puppet execute `true` instead of actually restarting the service
  $_attr = { 'restart' => '/usr/bin/true' }

}

service { 'foo':
  ensure => 'running',
  enable => true,
  *      => $_attr,
}

Answer: The idea from tectux is really nice. I've enhanced the if conditions. I have decided to use script for custom fact.
modules/autofs/facts.d/autofs.sh
#!/bin/sh
DECISION=`test -f /usr/bin/docker && /usr/bin/docker ps -q |grep -q . && echo no`

if [ "x$DECISION" == "x" ] ; then
    DECISION=yes
fi
echo '{'
echo '  "autofs": {'
echo "     \"do_automatic_restart\": \"$DECISION\""
echo '  }'
echo '}'

So, the output of the script
# modules/autofs/facts.d/autofs.sh
{
  "autofs": {
     "do_automatic_restart": "yes"
  }
}

Now we can use the custom fact
if $facts['autofs']['do_automatic_restart'] == "no" {
    $_attr = { 'restart' => "logger puppet agent: automounter is NOT going to be RESTARTED due to active containers on a host" }
} else {
    $_attr = {}
}

Puppet: conditional restart of service


É possível remover a opção todos os arquivos no explorador de arquivos?

Question: Com accept posso setar quais formatos são aceitos.

<input type="file" accept="image/png">

Ele filtra, porém no explorador ainda é possível selecionar todas os arquivos como na foto.

É possível remover essa opção e deixar somente a que quero?
Comment: @FelipeDuarte você pode ter visto essa opção indisponível ou desabilitada em um programa específico feito em outra linguagem. No navegador, pelo menos nos maiores não existe essa limitação.
Comment: pega o nome do arquivo, e corta a string os ultimos 4 caracteres (que será a extensao do arquivo), ai basta ter um array de extensoes que sao aceitas, e verificar se a extensao está no array, se estiver cadastra, se não, avisa ao usuario que o arquivo n foi enviado
Comment: Essa validação já está feita, porém só queria saber se é possível eliminar o 'todos os arquivos' do select no explorador, se eu não me engano, já vi essa opção desabilitada na hora de escolher os arquivos.
Answer: Utilizando apenas HTML Não é possível.
Isso porque janela de pesquisa do arquivo na tag input file é do Sistema Operacional. O atributo accept comunica o Sistema Operacional o tipo ou tipos de arquivos aceitos inicialmente, ajudando o usuário a encontrar os arquivos aceitos, mas nada impede que a opção "Todos os arquivos" seja selecionada.
Somente programas sendo executados diretamente no sistema operacional e com permissão para explorar arquivos no computador conseguem fazer esse tipo de limitação conforme pode ver na imagem abaixo:

Se sua aplicação conseguisse se comunicar com alguma outra sendo
  executada no Sistema Operacional isso seria possível.
Answer: É possível apenas setar o padrão de início... que vem marcado, mas se quiser, dá pra mudar a extensão do arquivo na hora de explorar arquivos, assim como está na tua imagem.
Mas dá para receber os arquivos e tratar na hora de cadastrar ou realmente guardar os arquivos, fazer a verificação de extensão
Answer: A opção utilizada apenas deixa os tipo desejado marcado como padrão. Não é possível remover essa opção (pelo menos até hoje).
Eu creio que a melhor coisa a se fazer no caso de não querer arquivos de determinados tipos é validando através do servidor (usando NodeJS, PHP ou outras linguagens, por exemplo).


Prevent multiple unwanted fetch requests sent during re-rendering

Question: I built a react-app using react-hook-speech-to-text. It converts speech to text and sends this text to a mongodb database via a backend node server. If a user says "hello world", then it will convert this to a string and store it in an array called results.
The I app built was supposed to send each string once to the database but it sends multiple fetch requests and fills up the database with unnecessary copies of the same string. Below is the code I have written in the App.js file. I want it to only send one fetch request per new string converted to text.
import React from 'react';
import useSpeechToText from 'react-hook-speech-to-text';

export default function App() {
  const {
    error,
    interimResult,
    isRecording,
    results,
    startSpeechToText,
    stopSpeechToText,
  } = useSpeechToText({
    continuous: true,
    useLegacyResults: false,
  });

  if (error) return
Web Speech API is not available in this browser
;

  return (

          Recording: {isRecording.toString()}

        <button
          className='bg-white text-indigo-400 px-4 py-2 rounded border-white border-2 transition hover:bg-indigo-400 hover:text-white'
          onClick={isRecording ? stopSpeechToText : startSpeechToText}
        >
          {isRecording ? 'Stop Recording' : 'Start Recording'}
        </button>

          {results.map((result) => {
            try {
              fetch('http://localhost:8000/api/commands', {
                method: 'POST',

                headers: {
                  'Content-Type': 'application/json',
                },
                body: JSON.stringify({ command: result.transcript }),
              })
                .then((res) => res.json())
                .then((myRes) => console.log(myRes));
            } catch (error) {
              console.log('Error posting data: ' + error);
            }
            return
{result.transcript}
;
          })}
          {interimResult &&
{interimResult}
}

  );
}

Comment: Have you looked into the `useEffect()` hook?
Comment: Yeah, i had tried it first but was unable to get it to work. Do you know a way to implement useEffect hook here?
Comment: I tried, and it seems like the `results` array is very voltaile and is constantly changing, which means the `useEffect` will constantly get triggered even if I specify `results` as a dependency. It might help to add a delay using debounce to the whole process of sending requests.
Answer: I recommend to create a separate component for one result item. There you can add a useEffect hook.
The dependency of the useEffect should basically the thing that would make a re-fetch necessary if it changes, i.e. probably your result.transcript.
That is easy if result.transcript is just a string, then you could just pass transcript to the component, put it into the dependencies and the fetch parameters.
The result of the fetch then needs to be passed back by some kind of callback instead of just returned.


How to add custom matchers to jasmine globally?

Question: I'd need a replacement for the jasmine.addMatchers function gone in version 1.3. The current API allows to add matchers to a describe block, but I'd prefer to be able to use my matchers everywhere without adding them again and again.
Is there a global way to add own matchers to jasmine 3.1.0?
Comment: Have you tried creating a module of the matchers and just instantiating them wherever you want to use them?
Comment: @ManuelBlanco No, I actually don't have a clue how to do it. Anyway, I'd like my matchers to be available everywhere without any additional work, just like the build-in matchers are.
Answer: https://github.com/JamieMason/add-matchers can be used to write matchers which work in all versions of Jasmine, as well as Jest.
var addMatchers = require('add-matchers');

addMatchers({
  // matcher with 0 arguments
  toBeEvenNumber: function(received) {
    // received : 4
    return received % 2 === 0;
  },
  // matcher with 1 argument
  toBeOfType: function(type, received) {
    // type     : 'Object'
    // received : {}
    return Object.prototype.toString.call(received) === '[object ' + type + ']';
  },
  // matcher with many arguments
  toContainItems: function(arg1, arg2, arg3, received) {
    // arg1     : 2
    // arg2     : 15
    // arg3     : 100
    // received : [100, 14, 15, 2]
    return (
      received.indexOf(arg1) !== -1 &&
      received.indexOf(arg2) !== -1 &&
      received.indexOf(arg3) !== -1
    );
  }
});

Answer: Note that I have not tried this in jasmine 3.1, but this is how I am doing the same in jasmine 2.8:
Place this in any code block that gets run before your tests:
jasmine.getEnv().beforeEach(() => {
  jasmine.addMatchers({
    toBeAwesome(util, customEqualityTesters) { ... }
  })
});

Comment: The question acknowledges this is possible ("The current API allows to add matchers to a describe block") and states that it is insufficient for purposes of the question ("I'd prefer to be able to use my matchers everywhere without adding them again and again").
Comment: This code does not need to be in a describe block. It can be anywhere, even be placed in the global scope if you like, as long as it is run before your tests. It is essentially creating a global `beforeEach` that is not tied to a single describe. So, technically, yes these matchers are still being added for each describe block, but for the purposes of your own code you only need to specify them once.
Comment: This global `beforeEach` sounds hacky, but I guess, it'd do what I want. I've tried the other solution first and it it worked, so I'll stick with it.
Comment: This is a much better answer than `add-matcher` lib. `add-matcher` is awesome but doesn't allow you to customize failure messages like you can do with matchers written for Jasmine. Also you can swap `beforeAll` instead of `beforeEach` and it should be a little better.
Comment: And what file is this supposed to be written in? (remember all tests have random run-order)
Answer: With jasmine-core version 3.8 (possibly already with 3.1) the answer by Andrew Eisenberg no longer works.
Therefore I have created a beforeAll() outside my tests (= outside of all describe-blocks), which is thereby executed before all tests.

If you work with Angular you can place it in src/test.ts.

Inside the beforeAll() I simply call jasmine.addMatchers(myCustomMatcher):
beforeAll(() => jasmine.addMatchers(myCustomMatcher));


Could not deduce (Functor r) from (MonadRandom r)

Question: The simple following code
import Control.Monad
import Control.Monad.Random

psum :: (MonadRandom r) => Int -> r Double -> r Double
psum n x = fmap sum $ replicateM n x

yields the error:
Could not deduce (Functor r) arising from a use of `fmap'
    from the context (MonadRandom r)

This is weird to me because of
class (Monad m) => MonadRandom m where ...

in Control.Monad.Random.Class source file, and since monads are functors, GHC should have deduced that r is a functor in my context. I also tried to import Control.Monad.Random.Class with no success.
Adding manually the Functor constraint on r works, but I find this quite ugly.
What am I missing here ?
Answer: Theoretically monads are functors, but sadly Functor is not a superclass of Monad for no good reason.
Instead of adding Functor r you can also use liftM instead of fmap.
Edit: There really seems to be no good reason. The classes were introduced together in Haskell 1.3, and superclasses already existed and were used for MonadPlus and MonadZero.
Comment: Aha. I'm doing too much mathematics. Thank you sir.


i want to take raw_input and see if any of it is in a list, and if so, print the whole raw_input

Question: I have a list of breakfast choices. Then, I ask the user what they like for breakfast. If anything they type is in the list, then I want to print out the user's answer. How do I do this?
def bfast_choices():
    choices = ['eggs', 'bacon', 'toast', 'pancakes']
    choice = raw_input('> ')
    if choice in choices:
        print "%s is a great breakfast" % choice
    else:
        print "%s is gross" % choice

This works if the user only inputs 'eggs' or 'bacon' or 'toast' or 'pancakes'. However, I'd like it to work if they input 'eggs and bacon' or 'steak and eggs' or 'pancakes and waffles and coffee'  etc... Is this possible for python to check and see if at least one of the words in the list is in the input then print the whole input if it is?
Comment: Sure. Add `'a, b, z, and q'` to your list. Is this your actual question, or only sample code?
Comment: What if someone entered "bacon and pretzels". Seeing that pretzels is not in the list, what is the expected output for that?
Comment: for my purposes i would want it to print out "bacon and pretzels is a great breakfast"
Answer: I am assuming if the user inputs the string 'a, b, z, and q' you want your variable 'choice', to be a list of [a,b,z,q]. To do this, look into the string.split() and string.strip() commands.
Answer: You can use "if item in list"
foodItem= raw_input("Enter choice:  ")

menu=["food1", "food2",  "food3"]

if foodItem in menu:
  print(foodItem)

For list of foods:
foodItems= ["food1",  "food2"]

menu=["food1", "food4",  "food3"]

for item in foodItems:
 if item in menu:
  print(item+"is available")

The remaining question is, getting user inputs into a list, you can do it in so many ways.
The usual and easy way is this:
foodItem= raw_input("Enter food(separated by ","):  )
foodItems=[i for i in foodItem.split(", ")]

Answer: If I understood you correctly you can try this:
def bfast_choices():
    choices = ['eggs', 'bacon', 'toast', 'pancakes']
    choice = raw_input('> ')
    tmp = choice.split(' ')
    for item in tmp:
        if item in choices:
            print "%s is a great breakfast" % choice
            return

    print "%s is gross" % choice

bfast_choices()

You use the method split(' '). It returns a list of words in the input. If the input is eggs and pizza, the list will be ['eggs', 'and', 'pizza']. And then you iterate through the list and if at least one of the items from the list is in the list choices it prints that it is a great breakfast. This is just to give you an idea. You can modify it further to cover other possible scenarios.


Truncated expectation equality

Question: can somebody please explain me how following equality works:
$E [|X|^pI(|X| \leq x) ] = \int_0^x y^pdP(|X| \leq x) = x^pP(|X| > x) + p\int_0^x y^{p-1}P(|X| > y) dy$.
First one should be just the definition of the expectation but i can't get the second one. I thought about partial integration but failed doing it.
Answer: The identity doesn't look quite right. If $Y$ is a nonnegative RV with cumulative distribution function $F(y):=P(Y\le y)$ and tail probability function $R(y):=P(Y>y)=1-F(y)$, then
$$
E[Y^pI(Y\le x)]=\int y^pI_{(0,x]}(y)dF(y)=\int_0^x y^pdF(y)
=-\int_0^xy^pdR(y)\tag1$$
and using integration by parts the RHS of (1) equals
$$
\left.-y^pR(y)\right\vert_0^x +\int_0^xR(y)py^{p-1}dy=-x^pP(Y>x)+\int_0^xpy^{p-1}P(Y> y)dy,\tag2
$$
but this isn't what your identity is saying. Expressed in terms of $F$ we can similarly obtain
$$
E[Y^pI(Y\le x)]=x^pF(x)-\int_0^xF(y)py^{p-1}dy=x^pP(Y\le x)-\int_0^xpy^{p-1}P(Y\le y)dy,\tag3
$$
which also doesn't agree with your formula.
Comment: Thank you for the detailed answer! I found a mistake in my original identity on the RHS and edited it, so now it looks more similar to your (2) but it is still not exactly the same as you already mentioned.
I will think about it.
Answer: This is basically integration by parts for Riemann Stieltjes integrals. See here for example: http://www.math.mcgill.ca/labute/courses/255w03/L3.pdf
So literarily, $\int_0^x udv =uv|_{0}^x-\int_0^x vdu$. If the CDF $P(|X|\leq x)$ is differentiable, then this is back to the usual Riemann integration by parts.

Truncated expectation equality


Does LocalDate.parse silently correct day number?

Question: String s = "2020 Jun 31";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MMM dd");
LocalDate date = LocalDate.parse(s, formatter);
System.out.println(date);

Output:
2020-06-30
Why does 31 turn into 30 without any warnings or exceptions?
Answer: DateTimeFormatter has a ResolverStyle that affects how strict or lenient the parser should be with invalid date and time values. To get an exception in this case you need to set the resolver style to STRICT.
You also need to use u (year) instead of y (year-of-era) in the format string.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu MMM dd")
                                  .withResolverStyle(ResolverStyle.STRICT);

The default resolver type is SMART:

Using smart resolution will perform the sensible default for each field, which may be the same as strict, the same as lenient, or a third behavior. Individual fields will interpret this differently.
For example, resolving year-month and day-of-month in the ISO calendar system using smart mode will ensure that the day-of-month is from 1 to 31, converting any value beyond the last valid day-of-month to be the last valid day-of-month.
Comment: Now it refuses to parse the string "2020 Jun 30": Text '2020 Jun 30' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {MonthOfYear=6, YearOfEra=2020, DayOfMonth=30},ISO of type java.time.format.Parsed
 at java.time.format.DateTimeFormatter.createError(Unknown Source). What causes this?
Comment: @Daniel apparently you have to change the pattern to use `u` ("year") instead of `y` ("year of era") - I've updated the answer to reflect that. It's not clear to me what the difference is but I see there are more questions about this https://stackoverflow.com/questions/29014225/what-is-the-difference-between-year-and-year-of-era and https://stackoverflow.com/questions/41177442/uuuu-versus-yyyy-in-datetimeformatter-formatting-pattern-codes-in-java?rq=1
Comment: @Joni That's only logical when you think about it. Strictly speaking with `yyyy MMM dd` the date 2020 Jun 31 could have been in year 2020 before Christ/before the common era or in 2020 anno Domini/current era (this year). So you can't parse into an unambiguous date, so the strict resolver style causes the formatter to refuse to parse at all. See for example [this answer by Meno Hochschild](https://stackoverflow.com/a/41182911/5772882).
Answer: The ResolverStyle is an enum that offers three different approaches: strict, smart and lenient. The smart option is the default. It can be set using withResolverStyle(ResolverStyle). The following code will throw an exception:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.ResolverStyle;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        String s = "2020 Jun 31";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("u MMM d")
                                        .withResolverStyle(ResolverStyle.STRICT)
                                        .localizedBy(Locale.ENGLISH);
        LocalDate date = LocalDate.parse(s, formatter);
        System.out.println(date);
    }
}

However, it will work without any exception for the day as 30 i.e. the output will be 2020-06-30 for String s = "2020 Jun 30".
Check Resolving section at https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html for more details.


EntityManager remove() call not updating database

Question: I have a basic Java project setup using JPA. I have classes which are annotated properly and can insert data into my PostgreSQL database without any trouble.
My question... and I may find that I need to add more detail here...
Is that I'm calling "em.remove(myObject)" where 'em' is an EntityManager. I can see the changes to the object when debugging but upon completion of the application my changes are not reflected in the database.
Will the call to .remove() update the database or do I also need to add a .flush() call? I've tried Googling this and must be missing something.
Thanks!
Comment: If it's not a detached instance then the remove call should work. If it's detached you'll need to make it managed first with `Object managed = em.merge(myObject);` and then call remove on `managed`.
Comment: Are you reading the object from the database in the same transaction before you remove it?
Comment: Yes, it is part of the same transaction.
Comment: if you are doing this inside a transaction are you submitting the transaction at the end?
Answer: I found that I also needed to define a cascade type.
@ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "QUESTION_ID", nullable = false)
    private Question question;

Comment: you should only add the cascade if you want the remove to remove the associated Question object as well. A cascade.REMOVE means that the remove on myObject will be executed on the Question object as well
Answer: The remove call should remove the entity from the database. However, depending on your caching setup this may not happen immediately. And if you have some constraint that would be violated by the removal, then when it does try to update the database it will throw an exception and the removal will have failed. If you really need to guarantee that it happens or fails immediately, then yes, you will need to call flush.


Uso do atributo ID nas tags

Question: É apropriado o uso do atributo ID nas tags ? Em quais casos eu poderia usá-lo?
Quais versões do HTML suportariam esse tipo de referência? Nesse caso, o ID tem sempre a função de seletor?
Em quais outras tags podemos usar ID e que não têm uso recorrente desse atributo como as ?
Essas dúvidas vêm de uma amostra de código HTML que eu estava vendo e que tinha o seguinte:
<link href="link/pro/css/file.css" rel="stylesheet" id="theme"/>

Answer: É apropriado o uso do atributo ID nas tags ? Em quais casos eu poderia usá-lo?
Sim é apropriado desde que haja apenas um elemento com a ID. Por isso, deve haver cuidado no seu uso. Hoje em dia, com o jQuery largamente aceito, é muito mais comum usar-se classes, mesmo para acessar elementos JavaScript, pois selecionar um elemento via classe é tão fácil quanto via ID:
Via ID:
elemento = $("#id")
Via classe: elemento = $(".classe")
Quais versões do HTML suportariam esse tipo de referência? Nesse caso, o ID tem sempre a função de seletor?
Todos os elementos HTML podem ter um ID. O HTML, por ser uma linguagem extremamente semântica, não imputa um sentido de funcionalidade diretamente, mas sim de significado. O ID identifica o elemento dentro do documento. As funcionalidades podem ser das mais diversas. Por exemplo, você poderia usar o ID para identificar até mesmo um produto no banco de dados:

Obs: note que eu usei um prefixo em vez de deixar o número puro. Isso pra evitar ao máximo a duplicação de IDs na página. Outro objeto, como por exemplo  poderia acabar tendo o mesmo atributo ID por acidente.

Uso do atributo ID nas tags


Limit of floor function

Question: How to prove that $\lim_{n\to \infty } \left(\sqrt{2} n-\left\lfloor \sqrt{2} n\right\rfloor \right) $ doesn't exist?
I've tried to show that every $L\in\Re$ is not a limit.
It's pretty easy for  $L>1$ and $L<-1$.
The main problem is when $-1\leq L\leq 1$ .
It is an homework question, so i should use the basic limit definition ($\epsilon$).
Thanks!
Comment: What have you tried?  Note that the quantity you are looking at is the fractional part of $n\sqrt{2}$.  How does this quantity change as you go from $n$ to $(n+1)$?
Comment: Please edit so the question is in the body, not just the title. Also, please explain what you mean by the symbol, $L$, as you don't relate it to the question anywhere. Also, why does it matter whether the proof uses the basic limit definition --- is this a homework problem?
Comment: I'll edit my question.
Comment: Note that $0 \leq (\sqrt{2}n - \lfloor \sqrt{2}n \rfloor) < 1$, hence limit L if it exists must satisfy $0\leq L \leq 1$. Now you need to show that for any L in this range the definition of limit can't be satisfied.
Comment: there will some trouble with checking the cases $L = 0$ and $L = 1$, rest should not be that difficult.
Comment: Thank you all for your comments, especially Aaron for his helpful hint.
Answer: Let $\{x\} = x - \lfloor x\rfloor = x $ (mod 1) be the fractional part of $x$.
Suppose such a limit L exists. Then given any $\epsilon > 0$, there would have to exist an $N$ s.t. for all $n \ge N$, we would have $|\{n\sqrt{2}\} - L| < \epsilon$. Now, as Aaron said, calculate
$|\{(n+1)\sqrt{2}\} - \{n\sqrt{2}\}| = |\sqrt{2} - (\lfloor (n+1)\sqrt{2}\rfloor - \lfloor n\sqrt{2} \rfloor)| > 1/3$
This leads us to consider $\epsilon = 1/6$, say. Supposing our inequality holds for $n = N$, the above shows that even the very next term $\{(N + 1)\sqrt{2}\}$ must land farther away from $L$ than $\epsilon$. So no such $N$, and therefore no such limit, can exist.
Explicitly calculating the first few $\{n\sqrt{2}\}$ leads to the intuition that the sequence "moves around a lot"; this can be made precise and is a special case of the equidistribution theorem, which is itself an instance of the ergodic theorem.
Comment: Thank you. Although I understood Aaron hint I coulden't write in a formal way. Now it is much clearer.

Limit of floor function


Logical relations between relations

Question: I'm interested in properties of relations. Things like completeness (connected, total), transitivity, euclideanness, symmetry and so on. I am interested in the logical connections between these relations. For example, symmetry implies not asymmetry. Or a reflexive, weakly connected relation is complete.
Is there a neat summary of these sorts of properties and their connections?
Comment: http://en.wikipedia.org/wiki/Relation_algebra, also http://en.wikipedia.org/wiki/Logical_matrix
Answer: Relation between relations, huh? A compilation of properties of relation classes, and then how those properties are related?
Wikipedia on Binary relations has a table near the bottom where you can compare relation classes a little. Mostly these kinds of comparisons are straightforward to prove.
Unexpectedly, an area where these properties are manipulated and interact is in the area of Modal logic, where a given axiom implies a relation among the worlds of a Kripke structure. A number of very minor derivations are of the form "S4 + X = S5, because adding the X axiom adds the symmetric property to a transitive worlds relation which implies that it is an equivalence relation" (modulo actual correct use of those properties!).
Comment: What I'm looking for is a compilation of the logical connections between [these concepts](http://en.wikipedia.org/wiki/Binary_relation#Relations_over_a_set)
Comment: @Seamus: did you look at the table further down on that page, having columns some of the properties, and rows some relation classes?
Comment: @Mitch yes. I'm not interested in types of relation in that sense. I'm interested in facts like "transitivity and antisymmetry imply acyclicity". This has nothing to do with equivalence classes or other types of relations.
Comment: @Seamus: well, it sorta does have something to do with equivalence classes, since if you add some properties together, they might imply some more properties, and a relation class name is a convenient way to refer to a bundle of properties. I modified my answer to include another area to look at where you might see some inferences made.
Comment: @Mitch fair enough. But only some collections of relational properties have names. So it seems a long way round to get at connections among relations to talk about the types of ordering they define, for example.
Comment: @Seamus: Sure, but the named classes are often a set of properties you care about, and you care about them because there are so many properties implied by only a few initial properties. That is, instead of taking every possible combination of properties to see which other properties they might imply, it's actually easier to look at the named classes. Rather than looking for a list of the kind you want (which doesn't seem to exist), a good exercise maybe you should try and come up with the list yourself (take pairs of properties and see what they imply). Then compare with the table of classes.
Answer: Is this the kind of summary you are looking for?
http://anglocatholicninjas.wordpress.com/2007/03/20/transitive-symmetric-and-reflexive-relations/
http://en.wikipedia.org/wiki/Equivalence_relation
Comment: I was looking for something more comprehensive

Logical relations between relations


Contrasts in a Completely Randomized Design (Unbalanced)

Question: Four catalysts that may affect the concentration of one component in a three-component liquid mixture are being investigated. Consider a completely randomized experiment, where $n_1 = 5$, $n_2 = 4$, $n_3 = 3$, and $n_4 = 4$. Suppose that prior to running the experiment the investigator wanted to make the following
comparisons:
(a) Average of Catalyst 1 and 2 vs Average of Catalyst 3 and 4
(b) Catalyst 1 vs Catalyst 2
(c) Catalyst 3 vs Catalyst 4.
Answer: In a balanced design I understand that in order to be a contrast the condition $\sum\limits_{i = 1}^a c_i = 0$ needs to be satisfied, where the $c_i$ are the coefficients of the $\mu_i$ in the contrasts. So for example, in a balanced design the contrast for Part (c) would be $\Gamma = \mu_3 - \mu_4$.
In an unbalanced design the condition changes to $\sum\limits_{i = 1}^a n_ic_i = 0$. But I'm confused. $\Gamma = \mu_3 - \mu_4$ no longer works. So do we have to make up coefficients so that the condition is satisfied? For example, for Part (c), knowing that $n_3 = 3$ and $n_4 = 4$, then $\Gamma = 4\mu_3 - 3\mu_4$ would be a contrast.
Is this correct?
Answer: There are not enough residuals here (16) for a useful check of normality.
And you say nothing about whether group variances are equal. You say nothing about
checking assumptions,
so I'm wondering whether unequal sample sizes are the only challenge here.
If normality and homoscedasticity assumptions are warranted, then of course
you could do a standard ANOVA.
Here are simulated normal data with unequal standard deviations.
set.seed(2020)
x1 = rnorm(5,20,3);  x2 = rnorm(4,25,2)
x3 = rnorm(3,45,3);  x4 = rnorm(4,40,4)
x = c(x1,x2,x3,x4)
g=as.factor(c(1,1,1,1,1, 2,2,2,2, 3,3,3,4, 4,4,4))

Stripcharts give an overview of the simulated data. (With sample sizes 5 and below
it seems inappropriate to use boxplots.)
stripchart(x ~ g, pch=20, ylim=c(.5,4.5))

Assuming normal data, equal variances. A standard ANOVA finds strong evidence that population means are unequal.
anova(lm(x ~ g))

Analysis of Variance Table

Response: x
          Df  Sum Sq Mean Sq F value    Pr(>F)
g          3 2134.79  711.60  63.235 1.267e-07 ***
Residuals 12  135.04   11.25
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Then ad hoc tests (b) and (c) can be done directly, using pooled t tests.
For my simulated data, Groups 1 and 2 differ significantly, but groups 3 and 4 don't.
t.test(x1,x2, var.eq=T)$p.val
[1] 0.003257274
t.test(x3,x4, var.eq=T)$p.val
[1] 0.3804501

And you can combine groups to test (a), also with pooled t tests.
The first two groups differ from the second two.
t.test(c(x1,x2), c(x3,x4), var.eq=T)$p.val
[1] 3.458586e-07

To avoid false discovery, you could use the Bonferroni method,
testing at the 1.67% level, which is achieved for both significant results.
Assuming normal data, not necessarily equal variances.
In R, the procedure oneway.test implements a version of ANOVA that adjusts
DF(Resid) as necessary to compensate for different sample variances.
(The approach is the same as for the Welch t test--extended to more than
two groups.) Then ad hoc tests can be done using Welch two-sample t tests.
Results are essentially the same as when group variances are (here wrongly)
assumed equal.
oneway.test(x ~ g)

        One-way analysis of means (not assuming equal variances)

data:  x and g
F = 55.357, num df = 3.0000, denom df = 5.8291, p-value = 0.0001112

t.test(x1,x2)$p.val
[1] 0.003708631
t.test(x3,x4)$p.val
[1] 0.3492354

Not assuming normal data. Here we use the same pattern of analysis,
but using nonparametric tests: Kruskal-Wallis for all four groups, and
two-sample Wilcoxon tests for ad hoc comparisons.
For my simulated data the findings are the same, but P-values are somewhat
smaller, perhaps reflecting the smaller powers of the nonparametric tests.
kruskal.test(x ~ g)

        Kruskal-Wallis rank sum test

data:  x by g
Kruskal-Wallis chi-squared = 13.335, df = 3, p-value = 0.003966

wilcox.test(x1,x2)$p.val
[1] 0.01587302
wilcox.test(x3,x4)$p.val
[1] 0.4
wilcox.test(c(x1,x2), c(x3,x4))$p.val
[1] 0.0001748252

Comments. If you are sure about normality and equal population variances, then you may want to pursue the use of contrasts. (Also, if this happens to be a textbook exercise on contrasts.) If not, you should use alternative procedures to
compare the four groups, and use ad hoc procedures that share assumptions with
those procedures.


Erro ao registrar informações no banco de dado

Question: Olá, comecei a aprender php e mysql a pouco tempo. No momento estou tentando fazer uma espécie de sistema de postagens, mas não estou conseguindo gravar as informações no DB. Se puderem ajudar a encontrar o que tem de errado, será ótimo
 :).
Um formulário é submetido e o action manda para esse arquivo:
<?php

require_once('db.class.php');

$titulo = $_POST['titulo'];
$texto_postagem = $_POST['descricao'];

date_default_timezone_set('America/Sao_Paulo');
$data = date("d/m/Y");
$hora = date("H:i");

$objDb = new db();
$link = $objDb-> conecta_mysql ();

$sql = "insert into postagens(titulo, descricao, data, hora) values($titulo', '$texto_postagem', '$data', '$hora') ";

//executar a query
if(mysqli_query($link, $sql)){
    echo 'Postagem armazenada com sucesso';
} else {
    echo 'Erro ao registrar postagem!';
}

?>
E esse arquivo chama esse:
<?php
class db {

    private $host = 'localhost';

    private $usuario = 'root';

    private $senha = '';

    private $database = 'sistema_postagens';

    public function conecta_mysql(){

        $con = mysqli_connect($this->host, $this->usuario, $this->senha, $this->database);

        if(mysqli_connect_errno()){
            echo 'Erro ao tentar se conectar com o BD MySQL: '.mysqli_connect_error();
        }

        return $con;

    }
}
?>

Quando roda, aparece o echo 'Erro ao registrar postagem!'
Comment: Se você não sabe o que está errado, não mascare o erro com uma mensagem que não te ajuda em nada. Ao invés de exibir mensagens como "Vish! Deu erro" exiba a mensagem real do erro com a função `mysqli_error`. Aliás, falta uma aspa simples antes de `$titulo` na sua SQL.
Comment: Muito obrigada! Consegui encontrar o erro com mysqli_error :)
Answer: Você se esqueceu da aspas no inicio do titulo em values
<?php

require_once('db.class.php');

$titulo = $_POST['titulo'];
$texto_postagem = $_POST['descricao'];

date_default_timezone_set('America/Sao_Paulo');
$data = date("d/m/Y");
$hora = date("H:i");

$objDb = new db();
$link = $objDb-> conecta_mysql ();
//AQUI VOCÊ ESQUECEU Da aspas mude $titulo' para '$titulo'
$sql = "insert into postagens(titulo, descricao, data, hora) values('$titulo', '$texto_postagem', '$data', '$hora') ";

//executar a query
if(mysqli_query($link, $sql)){
    echo 'Postagem armazenada com sucesso';
} else {
    echo 'Erro ao registrar postagem!';
}


How do you customize the Show instance for a Haskell record?

Question: I have a Haskell record data type that looks like this:
data Client = Client { clientId :: Int
                     , nickname :: Text
                     , clientSink :: Maybe (WS.Sink WS.Hybi00)
                     , clientRoom :: Maybe Room
                     }

I can't derive a Show instance from this because of WS.Sink has no Show instance.
How can I make a Show instance that excludes just the clientSink field, but prints the rest of the record fields like a normal record?
Should I just create a custom Show instance for WS.Sink?
Comment: I would make a dummy `Show` instance for `WS.Sink`.
Answer: Add a Show instance for WS.Sink
instance Show WS.Sink where show a = "Sink"

or whatever dummy value you want.
Answer: I'm not sure you really want an instance of Show, in this case. From the docs.

Derived instances of Show have the following properties, which are compatible with derived instances of Read:

The result of show is a syntactically correct Haskell expression containing only constants, given the fixity declarations in force at the point where the type is declared. It contains only the constructor names defined in the data type, parentheses, and spaces. When labelled constructor fields are used, braces, commas, field names, and equal signs are also used.

This does come with the caveat that it applies only to derived instances, but I'm a stickler for contracts, and have gotten used to assuming that read . show is effectively a no-op. You'd run into this same problem again when trying to automatically derive an instance for Read of course, so it's not like you would be introducing a semantic error by using Show now, it's just a matter of preference.
Depending on your context (taking a wild guess, you're trying to debug by printing intermediate values somewhere?) defining another typeclass and implementing a toString-like function might work best for you without being potentially misleading as to the show functionality of your instance. E.g.,
class ToString a where
    toString :: a -> String

instance ToString Client where
    toString c = "Client {"
                 ++ shows (clientId c) ", "
                 ++ shows (nickname c) ", "
                 ++ shows (isJust (clientSink c)) ", "
                 ++ show (clientRoom c)
                 ++ "}"

And then if you wanted to turn this into a Show instance it's as simple as
instance Show Client where
    show = toString


Quebrar linhas em um determinado espaço de caracteres em Python

Question: Olá, criei um programa em Python para criar uma sequencia de P.A., só que quero que o print do resultado dos numeros quebrem apos 100 caracteres, para o resultado ficar dentro da tela.
alguem pode me ajudar??
texto = 'Calculadora de Progressão Aritmética'
print('=' * 100)
print(f'{texto: ^100}')
print('=' * 100)
a1 = input('Digite o primeiro termo da P.A.: ')
r = input('Digite a razão da P.A.: ')
ter = input('Quantos termos da P.A. deseja visualizar? ')
cont = 0
if a1.isdigit() and r.isdigit() and ter.isdigit() or '-' in a1 or '-' in r:
    for i in range(0, int(ter)):
        cont = cont + 1
        if True:
            an = int(a1) + (cont - 1) * int(r)
        print(f'{an}', end=', ')
    print(f'sao os {ter} primeiros termos da P.A.!', end=' ')
else:
    print('Digite somente números e/ou o número de termos é positivo.')

Comment: Bem vindo. Próximos blocos de código, insira ``` para abrir e ``` para fechar o bloco de código
Comment: Talvez isso te ajude: https://pt.stackoverflow.com/questions/359166/formatação-de-saída-de-dados-no-python
Answer: Para isso, utilize a bilbioteca textwrap que possui a função wrap que recebe o texto e a quantidade máxima de caracteres que você deseja por linha, retornando uma lista de strings que respeitam o tamanho definido.
Se você tem a string referente a sua P.A.:
pa = '1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15'

Para exibí-la em múltiplas linhas com tamanho máximo de 10, por exemplo, bastaria fazer:
from textwrap import wrap

for line in wrap(pa, width=10):
    print(line)

A saída seria:
1, 2, 3,
4, 5, 6,
7, 8, 9,
10, 11,
12, 13,
14, 15

Perceba que não necessariamente as linhas terão 10 caracteres de tamanho, mas todas respeitarão o tamanho máximo de 10, sem quebrar o conteúdo ao meio.
Mudando para width=30 teriamos:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15

Fonte: https://xkcd.com/353/
Comment: Aproveitou ainda para fazer graça na resposta kkk
Answer: Estou postando minha resposta como um complemento à resposta do @Woss. Sua pergunta especifica que você quer tratar sua string de resultado para ter no máximo 100 para que seu conteúdo caiba na tela.
Minha resposta aborda o problema de maneira diferente, por isso quero deixar aqui como alternativa, para que algum futuro visitante tenha outras opções de solução para o mesmo problema.
Ao invés de limitar o número de caracteres por linha, você pode limitar quantos termos por linha você quer e mostrá-los como "colunas".
Código
from itertools import cycle

a1, r, ter = 1, 2, 30

# nosso "paginador"
itens_por_linha = 6
ends = [''] * (itens_por_linha - 1)
ends.append('\n')
# ends = ['', '', '', '', '', '\n']

for item, end in zip(range(a1, r * ter, r), cycle(ends)):
    print(f"{item: >5d}", end=end)

Veja rodando no Repl.it
Resultado
    1    3    5    7    9   11
   13   15   17   19   21   23
   25   27   29   31   33   35
   37   39   41   43   45   47
   49   51   53   55   57   59

Explicação do código
range(start, stop, step) (#docs)
Como você mesmo já usou no seu código, eu uso o range para gerar a P.A. Sendo:

a1 o parâmetro start;
r * ter será o stop para garantir que o tamanho do range gerado tenha exatamente N elementos definidos pela variável ter;
r será o step

a1, r, ter = 1, 2, 10
pa = list(range(a1, r * ter, r))

print(pa)
# [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
print(len(pa))
# 10

print(*objects, end='\n') (#docs)
Na minha solução, faço uso do parâmetro end que a função print aceita para controlar quando devo quebrar a linha.
for i in range(3):
    print(i)
# Resultado:
# 0
# 1
# 2

for i in range(3):
    print(i, end=" ")
# Resultado:
# 0 1 2

zip(*iterables) (#docs)
O função zip é utilizada para percorrer N iteráveis "paralelamente". Exemplo:
nums = [1, 2, 3]
letras = ['A', 'B', 'C']
simbolos = ['!', '@', '#', '$']

for num, letra in zip(nums, letras):
    print(f"{letra}{num}", end=', ')
# A1, B2, C3

for num, letra, simb in zip(nums, letras, simbolos):
    print(f"{letra}{num}({simb})", end=', ')
# A1(!), B2(@), C3(#)

Note que zip sempre para de iterar no seu iterável mais curto, no exemplo acima simbolos tem tamanho 4, porém a iteração para após o 3º item pois nums e letras têm apenas 3 itens.
Você pode usar o zip fora do for, pois o retorno de zip é um iterável também. Veja:
nums = [1, 2, 3]
letras = ['A', 'B', 'C']
simbolos = ['!', '@', '#', '$']

lista_1 = list(zip(nums, letras))
lista_2 = list(zip(nums, letras, simbolos))

print(lista_1)
# [(1, 'A'), (2, 'B'), (3, 'C')]

print(lista_2)
# [(1, 'A', '!'), (2, 'B', '@'), (3, 'C', '#')]

itertools.cycle(iterable) (#docs)
Na minha solução utilizo o cycle para criar uma repetição infinita dos caracteres que quero usar como end do print. Veja um exemplo simples:
from itertools import cycle

abc = cycle("ABC")
nums = range(1, 6)

for letra, num in zip(abc, nums):
    print(f"{letra}{num}", end=", ")
# A1, B2, C3, A4, B5,

par_impar = ('par', 'ímpar')
nums = range(5)

lista = list(zip(nums, par_impar))
print(lista)
# [(0, 'par'), (1, 'ímpar'), (2, 'par'), (3, 'ímpar'), (4, 'par')]

String formatting
No print da solução uso a formatação >5d, que significa:
print(f"{item: >5d}")
#             │││└── "d": formatação para números inteiros
#             ││└─── "5": largura do resultado
#             │└──── ">": alinhamento a direita
#             └───── " ": preenchimento com espaços

Exemplos:
item = 123

print(f"{item: >5d}")  # "  123"
print(f"{item: <5d}")  # "123  "
print(f"{item: ^5d}")  # " 123 "
print(f"{item:_>5d}")  # "__123"
print(f"{item:0>7d}")  # "0000123"

Veja PyFormat.info e a documentação para maiores informações.

Dito isso, agora você já deve entender o que o meu código faz, basicamente:

Cria a string que será usada como separador entre os termos da PA.
Se itens_por_linha for 4, cria um iterador infinito que gera 3 strings vazias e 1 quebra de linha (['', '', '', '\n', '', '', '', '\n', '', ...]).
Estes caracteres são usados pelo print para definir se o algoritmo quebrará a linha, ou printará o termo na mesma linha.
Percorre a PA e os o gerador de limitadores "paralelamente" usando zip
Printa o resultado
Comment: Muito boa sacada, Obrigado!
Answer: Comentei as partes que eu inseri. Achei melhor quebrar pro número e não simplesmente pelo tamanho da linha para evitar que um número fique quebrado entre linhas.
texto = 'Calculadora de Progressão Aritmética'
print('=' * 100)
print(f'{texto: ^100}')
print('=' * 100)
a1 = input('Digite o primeiro termo da P.A.: ')
r = input('Digite a razão da P.A.: ')
ter = input('Quantos termos da P.A. deseja visualizar? ')
cont = 0
linha = 0  ### Nova linha de código
if a1.isdigit() and r.isdigit() and ter.isdigit() or '-' in a1 or '-' in r:
    for i in range(0, int(ter)):
        cont = cont + 1
        if True:
            an = int(a1) + (cont - 1) * int(r)
        print(f'{an}', end=', ')
        ### Novas lihas de código ###
        if linha>=100:
            print('\n')
            linha = 0
        else:
            linha += len(str(an)) + 2 # tamanho do número e mais dois dígitos do espaço e vírgula
        ##############################
    print(f'sao os {ter} primeiros termos da P.A.!', end=' ')
else:
    print('Digite somente números e/ou o número de termos é positivo.')

Outra solução seria somar dotas as respostas em um texto como resposta += f'{an}, ' e usar resposta[i:100+i] dentro de um for, mas quebrariam números no meio.


Compartilhar bibliotecas de código entre aplicações

Question: No meu cenário tenho várias aplicações distintas (desktop) que são criadas das mais diversas formas, em suma, podem ser agrupadas naquelas que utilizam a mesma DLL. O funcionamento de cada aplicação depende que o as toda a aplicação seja instalada, junto com as DLLs, o que causa repetição desses arquivos na máquina do usuário. Tratando-se de bibliotecas proprietárias, não padrões do Windows, existe alguma forma de torná-las acessíveis para todas as aplicações com um só arquivo? Tendo em vista que não está ao meu alcance mudar diretamente no código o relacionamento do programa com a biblioteca.
Comment: prefiro manter as duplicações, apesar de ser "a mesma biblioteca" podem haver versões diferentes... pra evitar que falte alguma, no inicio da aplicação verifico a existência e faço download se necessário. Dessa forma, o usuário só precisa receber o .exe, que ele se encarrega de receber todas as dependências
Answer: Imagino que esteja usando o .NET Framework então é só colocar essas DLLs no GAC (Global Assembly Cache). No .NET Core é bem diferente, e que é o jeito moderno de se programar em C#.
O GAC é o local onde ficam todas DLLs necessárias para a máquina toda e não exclusivas de uma aplicação. Tem que tomar um pouco de cuidado para fazer isso, tem que pensar como vai administrar isso porque pode começar dar problemas nas atualizações, um dos motivos que acabaram com isso no .NET Core. Por isso em muitos casos compensa ter a duplicação e não usar GAC.


Auditioning for Orchestra

Question: I would like to ask a question for an audition piece. I would like to play Brahms cello sonata 1 e minor, the Allegro non troppo for an orchestral audition. It is a piano and cello duet but I will not have an accompaniment when I audition. Do you think this is acceptable to play for an audition? I am afraid that it will not be received well without the accompaniment of the piano.
Thank you.
Comment: What level -- school, grad school,   local civic orchestra?
Answer: Ask the person organizing the audition.
Often for professional orchestra auditions, you would be expected to play (probably at sight) excerpts from orchestral parts, supplied by the audition committee. Remember they are auditioning your ability to play in an orchestra section, not your ability as a soloist.
Answer: The Brahms will be just fine.  You may also be given some orchestral excerpts to sight read.  They, too, will sound rather empty without the full orchestra supporting them!
Remember, the orchestra is recruiting players and WANTS to discover that you are a good enough player.  They aren't looking to reject you for 'breaking audition rules'.
Answer: It will have less impact without the piano accompaniment, to be honest, but it shouldn't affect the audition panel's opinion of your playing.  Did you ask the orchestra if they can provide an accompanist?
Answer: Brahms Em is one of the absolute standard works for cello. Definitely a suitable choice for an audition (in fact I reckon it's mandatory for many jobs). Chances are you will have accompaniment... bring the score to the audition at any rate, the conductor may play the piano part or at least read it and hear the proper thing in their head.
(If you've not actually rehearsed the piece with a pianist, then it may not be a good idea to let them accompany you, could throw you off more than help...)
As the others have said, in an audition for an orchestral position, it's quite as important that you're able to sight-read decently well, i.e. you'll probably be handed at least one simple accompaniment passage from some symphony and expected to get it right on first reading. Likely, you'll also be given some technically demanding passage that may require nasty thumb position or something – just don't panic if that happens, they'll want to know your limits, but it's natural that most players won't get it anywhere near perfect at first sight.

Auditioning for Orchestra


is ball movement count if the golf is affected by wild animals?

Question: For instance, if a squirrel picks away the golf, is it count for movement or just remain the original position?
Answer: This would come under Rule 18 - Ball at rest moved by outside agency
Essentially there is no penalty to the player, and the ball should be replaced. Note that you need to be sure it was an outside agency that moved the ball - neither wind nor water count.


How to find important features in unsupervised data?

Question: I have data that defines the characteristics of an elevator. This data contains hundred of fields (height, weight, speed, number of persons inside the elevator, etc...). From this data, I want to classify the elevators according to their complexity. For example, I want to find which elevators share the same properties even if they are slightly different in some characteristics.
To tackle this problem, I was thinking of finding the most important features of the elevator first and later group them according to the results. But I don't know if I should use Random Forest to find the most important features so that I could group them with the help of K-means.
Should I use Random forest to find the most important features of an elevator? Or, should I use any other model like feature importance or correlation map?
How to know which statistical model should I choose?
Comment: have hundreds of features is pretty normal and people usually will not call it a huge dataset.
Answer: The question you may ask first is what defines "important feature".
Random forest is a supervised learning algorithm, you need to specify a label first then the algorithm will tell you which feature is more important respect the given label. In other words, specifying different label will have different results for variable importance.
Without using the label, algorithm such as PCA will define the variable that have large variance is important, which is another good starting point. This is intuitive because variable with large variance usually has more information and variable with zero variance means everyone is the same, and therefore this feature can be less useful.
Comment: PCA selects directions (vectors) that account for maximum variation in data, which is a combination of the directions determined by the original variables. How does it define the variable that has large variance?
Comment: You can have a look at Andrew Ng's notes on PCA for very simple and concise explanation : https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=11&ved=2ahUKEwjxv_HX-N3nAhWOyKYKHdVgARAQFjAKegQIAxAB&url=http%3A%2F%2Fcs229.stanford.edu%2Fnotes%2Fcs229-notes10.pdf&usg=AOvVaw0rw90j9FZXWcrz1GMAi8Vj
Comment: If PCA transforms several features of data into some principal components, how can we understand the output of PCA related to the input features? And if PCA outputs more than 2 PCs, how we interpret that?
Answer: This looks like a good use case to use chi-squared feature selection. You can find more about its implementation in python and also some examples with documentation here. What this method does is it keeps only the features which have higher effect on your label
Comment: chi-squared work with unsupervised data? please note that I have quantitative and categorical data. Do I need to remove categorical data to use chi-squared?
Comment: it does work those values, yes. Yet, it will not work with negative values.From your description of the problem, it seems to me that, you can also bin your continuous features.
Comment: Can I put several features in the same bin?
Comment: You can bin them, but for every feature, you should have its separate bins.


Not getting data from Sqlite database tables

Question: I working on android application in which i wanted to get data from Sqlite database table.
Even if the data is present in the table its giving me error.
Code:
 public List<Mikats> getAllMikats() {
            List<Mikats> contactList = new ArrayList<Mikats>();
            // Select All Query
            String selectQuery = "SELECT  * FROM " + TABLE_NAME_2;

            SQLiteDatabase db = this.getWritableDatabase();
            Cursor cursor = db.rawQuery(selectQuery, null);

            // looping through all rows and adding to list
            //cursor.moveToFirst()
            int rows=cursor.getCount();
            if (rows>0) {
                do {
                    Mikats mikat = new Mikats();

                    int mid=cursor.getInt(1);
                    String sqlectEventTitle="select * from "+ TABLE_NAME_1 +" where "+ KEY_MID+" = "+mid;
                    SQLiteDatabase db2 = this.getWritableDatabase();
                    Cursor cursor1=db2.rawQuery(sqlectEventTitle, null);
                    if(cursor1.moveToNext())
                    {
                        String Title=cursor1.getString(cursor1.getColumnIndex("EventTitle"));
                        mikat.setEventTitle(Title);
                    }
                    mikat.setEjamatID(Integer.parseInt(cursor.getString(0)));

                    mikat.setMikatID(Integer.parseInt(cursor.getString(1)));

                    mikat.setStartDate(cursor.getString(2));

                    mikat.setEndDate(cursor.getString(3));

                    mikat.setBlock(cursor.getString(4));

                    mikat.setFloor(cursor.getString(5));

                    mikat.setGate(cursor.getString(6));

                    String masjid=cursor.getString(7);
                    mikat.setMasjid(masjid);

                    mikat.setAutoID(Integer.parseInt(cursor.getString(8)));

                    mikat.setSeatNo(cursor.getString(9));

                    // Adding contact to list
                    contactList.add(mikat);
                } while (cursor.moveToNext());
            }

            // return contact list
            return contactList;
        }

Line of Error:
int mid=cursor.getInt(1);

Logcat:
09-17 11:51:57.904: W/System.err(19441): android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
09-17 11:51:57.904: W/System.err(19441):    at android.database.AbstractCursor.checkPosition(AbstractCursor.java:580)
09-17 11:51:57.904: W/System.err(19441):    at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:214)
09-17 11:51:57.914: W/System.err(19441):    at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:41)
09-17 11:51:57.924: W/System.err(19441):    at com.example.busahebaapp.MikatHandler.getAllMikats(MikatHandler.java:113)
09-17 11:51:57.924: W/System.err(19441):    at com.example.busahebaapp.ViewEvents.onCreate(ViewEvents.java:57)
09-17 11:51:57.934: W/System.err(19441):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
09-17 11:51:57.944: W/System.err(19441):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
09-17 11:51:57.944: W/System.err(19441):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
09-17 11:51:57.944: W/System.err(19441):    at android.app.ActivityThread.access$1500(ActivityThread.java:117)
09-17 11:51:57.954: W/System.err(19441):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
09-17 11:51:57.964: W/System.err(19441):    at android.os.Handler.dispatchMessage(Handler.java:99)
09-17 11:51:57.974: W/System.err(19441):    at android.os.Looper.loop(Looper.java:123)
09-17 11:51:57.974: W/System.err(19441):    at android.app.ActivityThread.main(ActivityThread.java:3683)
09-17 11:51:57.984: W/System.err(19441):    at java.lang.reflect.Method.invokeNative(Native Method)
09-17 11:51:57.994: W/System.err(19441):    at java.lang.reflect.Method.invoke(Method.java:507)
09-17 11:51:57.994: W/System.err(19441):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
09-17 11:51:58.004: W/System.err(19441):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
09-17 11:51:58.004: W/System.err(19441):    at dalvik.system.NativeStart.main(Native Method)
09-17 11:53:24.805: W/jdwp(19441): Debugger is telling the VM to exit with code=1

Please help me i am not understanding cause of error.
I have made sure that data is present in the table.
Comment: Why have you commented //cursor.moveToFirst()?
Comment: it was wrong for my logic
Comment: You should check if (cursor != null && cursor.moveToFirst()) ... do {} while();
Comment: @Tarun thanx sir...every time when i need to fetch the value i should write this?
Comment: +1 for figuring out that you can deal with your SQLite database on the desktop.  So many people don't grok that.
Answer: Just change with this:
if (rows>0) {

cursor.moveToFirst();

do{

 // get data here from database...

}while(cursor.moveToNext());

}

And also when first time your cursor move to First position when it is not null and its count must be >0.. and the value must be started with 0 not from 1... So change
int mid=cursor.getInt(0);

Comment: everytime when i want to fetch the value i should make it as ursor.moveTofirst(); ???
Comment: whenever you fetch data from database call cursor.moveToFirst() before do while loop and  its count must be >0
Comment: @ShrimantBajiraoPeshawe-I It depends what you want to do.  moveToFirst(), er, moves to the first row.
Answer: there is only one value in database so read it as 0 index not 1 and cursor starts from 0.
use cursor.moveTofirst();
int mid=cursor.getInt(0);

Comment: everytime when i want to fetch the value i should make it as ursor.moveTofirst(); ???


Eliminar separação de palavra por quebra de linha - php

Question: Boa tarda pessoal,
O código abaixo extrai o texto de um pdf e imprime na tela.
Só que as separações por quebra de linha não são eliminadas, e as palavras que foram separadas por quebra de linha aparecem da seguinte forma: 'sem - pre'.
Eu tentei usar $DCM_conteudo = str_replace(" - ", "", $DCM_conteudo);, porém somente os hifens são excluídos (e não as quebras de linha) .
Alguém sabe como identificar e excluir as quebras de linha?
<?php

// Include conexão com o bd e com Composer autoloader.
include_once 'conexaoBD/conexao.php';
include 'vendor/autoload.php';

ini_set('default_charset', 'UTF8');
set_time_limit(6000);

$file_tmp = $_FILES['file']['tmp_name'];
$file_fnl = $_FILES['file']['name'];

// Parse pdf file and build necessary objects.
$parser = new \Smalot\PdfParser\Parser();
$pdf    = $parser->parseFile($file_fnl);

$DCM_conteudo = $pdf->getText();
$DCM_conteudo = str_replace(" - ", "", $DCM_conteudo);
$DCM_nome = $file_fnl;

echo $DCM_conteudo;

?>

### Att: Pedaço do texto extraído do pdf.

Neste con - texto, ganhou destaque a Lei n° 6.458/2019, de autoria dos vereadores, que obriga restaurantes, lanchonetes, bares e similares, barracas de praia e vendedores ambulantes a usar e fornecer a seus clientes apenas canudos fabricados exclusivamente com material biodegradável ou reci - clável.
Comment: preg_replace( "/\r|\n/", "", $yourString ); <- Tenta usar assim pra remover as quebras de linha
Comment: Provavelmente a quebra de linha fica após o hífen, então não bastaria remover `" - \n"`?
Comment: @AndersonCarlosWoss Tentei, e também tentei  " - \n\r" , mas nenhum funcionou.
Comment: @EdwardRamos Também não resolveu.
Comment: Renata, adicione na pergunta um trecho do texto que possua essa parte com o hífen e a quebra de linha para vermos como está
Comment: @AndersonCarlosWoss Adicionei um pedaço do texto extraído do pdf na pergunta, e em destaque, como aparece a palavra separada pela quebra de linha.
Answer: Nesse caso da leitura vem de um padrão externo do Adobe, pode experimentar o método junto ao já utilizado.
$DCM_conteudo = str_replace("\n", "", $DCM_conteudo);
$DCM_conteudo = str_replace("\r", "", $DCM_conteudo);