text:
Q: Uncountable infinite sum of $a_r>0$ It is not necessarily true that $\sum_{i=1}^\infty a_i = \infty$, even if $a_i>0 \forall i$. One simple example would be the geometric series.
However, this sum is taken for natural value $i$ i.e. it's summing countable infinite many values. Therefore, I wonder if this is true if $\sum_{r \in R} a_r$ can converge, where $R$ is the real number set?
I don't even know how to write the sum down, so is this "sum" even "well-defined"?

A: Let $(a_i)_{i\in I}$ such that $a_i>0$ for all $i\in I$ and $S:=\sum_{i\in I}a_i<+\infty$, we will show that $I$ is countable. For $n\in\mathbb{N}^*$, let $I_n=\{i\in I\ |\ a_i\geqslant\frac{1}{n}\}$, since $a_i>0$ for all $i\in I$, we have
$$ I=\bigcup_{n\in\mathbb{N}^*}I_n $$
If $I$ is not countable, then at least one $I_n$ is uncountable, let $p\in\mathbb{N}^*$ such that $I_p$ is not countable. There exists $J\subset I_p$ a finite set such that $\text{card}(J)\geqslant p(S+1)$ and since $a_i>0$ for all $i\in I$ we have :
$$ S\geqslant\sum_{i\in J}a_i\geqslant\sum_{i\in J}\frac{1}{p}=\frac{\text{card}(J)}{p}\geqslant S+1>S $$
which is not.


text:
Q: TSQL - Query help for generating incremental sequence numbers Need help on a query to generate a two incremental values on below table.
Both the BatchNo and BatchSequenceNo should begin at 1.
The BatchSequenceNo should increment by 1, up to 500 rows.
At 501 row, the BatchNo should be incremented by 1 (ie BatchNo = 2) and
the BatchSequenceNo should reset to 1.
BatchNo values needs to incremented by 1, for every 500 rows.
CREATE TABLE #tblBatch
(
    BatchId INT NOT NULL IDENTITY(1,1) PRIMARY KEY,
    Sname VARCHAR(50) NOT NULL,
    BatchNo int,
    BatchSequenceNo int
)

---Load some sample data
INSERT INTO #tblBatch(Sname)
    SELECT TOP 2010
        'A -SampleText-' + CAST(row_number() over(order by t1.number) as varchar) as N
    FROM
        master..spt_values t1
    CROSS JOIN
        master..spt_values t2

A: The easiest way is to base your BatchNo/BatchSequenceNo numbers on your BatchId using calculated columns
CREATE TABLE #tblBatch(
   BatchId  INT   NOT NULL IDENTITY(1,1) PRIMARY KEY,
   Sname VARCHAR(50) NOT NULL,
   BatchNo as (BatchId-1) / 500 + 1,
   BatchSequenceNo as BatchId % 500
 )

A: You can use modulo and division to do this.
    Select
CAST(((row_number() over(order by t1.number) / 500)+1) as int) as BatchNo,
CAST(((row_number() over(order by t1.number)-1 % 500)+1) as int) as BatchSequenceNo
    from   master..spt_values t1
           cross join master..spt_values t2

A: Use division and modulo operators to get the batchno and batchsequenceno respectively.
Select top 2010
 1+(row_number() over(order by t1.number)-1)/500 as batch_no
,'A -SampleText-'+cast(1+(row_number() over(order by t1.number)-1)%500 as varchar(100)) as N
from master..spt_values t1
cross join master..spt_values t2

Sample Demo

A: rextester: http://rextester.com/GUSA26703
create table #tblbatch (
    batchid  int   not null identity(1,1) primary key
  , sname varchar(50) not null
  , BatchSequenceNo int
  , BatchNo int
);

insert into #tblBatch(Sname,BatchSequenceNo,BatchNo)
Select top 2010
    Sname = 'A -SampleText-'+cast(row_number() over(order by t1.number) as varchar)
  , BatchSequenceNo = ((row_number() over(order by t1.number) -1)%500)+1
  , BatchNo = ((row_number() over(order by t1.number) -1)/500)+1
from   master..spt_values t1
  cross join master..spt_values t2

select
    minN=min(batchid)
  , maxN=max(batchid)
  , minBatchSequenceNo=min(BatchSequenceNo)
  , maxBatchSequenceNo=max(BatchSequenceNo)
  , BatchCount=count(*)
  , BatchNo
  from #tblbatch
  group by BatchNo
  order by BatchNo

results in:
+------+-------+--------------------+--------------------+------------+---------+
| minN | maxN  | minBatchSequenceNo | maxBatchSequenceNo | BatchCount | BatchNo |
+------+-------+--------------------+--------------------+------------+---------+
|    1 |   500 |                  1 |                500 |        500 |       1 |
|  501 |  1000 |                  1 |                500 |        500 |       2 |
| 1001 |  1500 |                  1 |                500 |        500 |       3 |
| 1501 |  2000 |                  1 |                500 |        500 |       4 |
| 2001 |  2010 |                  1 |                 10 |         10 |       5 |
+------+-------+--------------------+--------------------+------------+---------+

rextester setup: http://rextester.com/UWIAU84781
with n as (select n from (values(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) t(n))
, d as (
        /* start from 0 */
  --select n=row_number() over (order by (select 1))-1
        /* start from 1 */
  select n=row_number() over (order by (select 1))
    from         n as deka
      cross join n as hecto
      cross join n as kilo
      cross join n as [tenk]
      --cross join n as [hundredk]
      --cross join n as mega
)
, batch as (
  select
      n
    /* start from 0 */
    --, BatchSequenceNo=(n%500)+1
    --, BatchNo=(n/500)+1
    /* start from 1 */
    , BatchSequenceNo=((n-1)%500)+1
    , BatchNo=((n-1)/500)+1
    from d
)
select
    minN=min(n)
  , maxN=max(n)
  , minBatchSequenceNo=min(BatchSequenceNo)
  , maxBatchSequenceNo=max(BatchSequenceNo)
  , BatchCount=count(*)
  , BatchNo
  from batch
  group by BatchNo
  order by BatchNo

results in:
+------+-------+--------------------+--------------------+------------+---------+
| minN | maxN  | minBatchSequenceNo | maxBatchSequenceNo | BatchCount | BatchNo |
+------+-------+--------------------+--------------------+------------+---------+
|    1 |   500 |          1         |                500 |        500 |       1 |
|  501 |  1000 |          1         |                500 |        500 |       2 |
| 1001 |  1500 |          1         |                500 |        500 |       3 |
| 1501 |  2000 |          1         |                500 |        500 |       4 |
| 2001 |  2500 |          1         |                500 |        500 |       5 |
| 2501 |  3000 |          1         |                500 |        500 |       6 |
| 3001 |  3500 |          1         |                500 |        500 |       7 |
| 3501 |  4000 |          1         |                500 |        500 |       8 |
| 4001 |  4500 |          1         |                500 |        500 |       9 |
| 4501 |  5000 |          1         |                500 |        500 |      10 |
| 5001 |  5500 |          1         |                500 |        500 |      11 |
| 5501 |  6000 |          1         |                500 |        500 |      12 |
| 6001 |  6500 |          1         |                500 |        500 |      13 |
| 6501 |  7000 |          1         |                500 |        500 |      14 |
| 7001 |  7500 |          1         |                500 |        500 |      15 |
| 7501 |  8000 |          1         |                500 |        500 |      16 |
| 8001 |  8500 |          1         |                500 |        500 |      17 |
| 8501 |  9000 |          1         |                500 |        500 |      18 |
| 9001 |  9500 |          1         |                500 |        500 |      19 |
| 9501 | 10000 |          1         |                500 |        500 |      20 |
+------+-------+--------------------+--------------------+------------+---------+

A: I hope you like this:
WITH cte_Tally AS (
    SELECT
        ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) n
    FROM (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) a(n) --10
    CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) b(n) -- 100
    CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) c(n) -- 1,000
    CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) d(n) -- 10,000
)
SELECT ROW_NUMBER() OVER (PARTITION BY n % 500 ORDER BY n) AS [Sequence], n % 500 AS [Sequence], n
FROM cte_Tally
ORDER BY n

redpajama_set_name: RedPajamaStackExchange


text:
Q: General solution to homogeneous 1D wave equation I know that the general solution to the homogeneous 1D wave equation is f(x-vt) or f(x+vt). But how is this actually obtained? Was it just an educated guess, and if so how can we be sure it is the general solution?

A: (Too long for a comment.)
Those are actually not the most general solutions. For instance, since the wave equation is linear, you can add those two solutions and get another solution. In fact, you can add any number of particular solutions together (the result of which is called superposition).
The most general solution is the one where you add together all possible solutions, which you can see here in Eq. (41). If you follow the derivation there, you should see why (41) is the most general solution; essentiallly, it covers all possible solutions by first determining that all solutions must be of some form (with a given $m$, in the site's notation), and then they obtain the general solution by summing over all $m.$

A: The wave equation is of the form
\begin{equation}{\tag{1}}
u_{tt} - c^2 u_{xx} = 0
\end{equation}
Note that if we define the differential operator $L$ by
$$L(u) := u_{tt} - c^2 u_{xx}$$
Then $(1)$ becomes
$$L(u) = 0$$
If we factor $L$ we have
\begin{equation}{\tag{2}}
L(u) = \left(\frac{\partial}{\partial t} - c \frac{\partial}{\partial x}\right)\left(\frac{\partial}{\partial t} + c \frac{\partial}{\partial x}\right)u
\end{equation}
Let $v = u_t + c u_x$, then we have two first-order PDE's
\begin{equation}{\tag{3}}
v_t - c v_x = 0
\end{equation}
and
\begin{equation}{\tag{4}}
u_t + c u_x = v
\end{equation}
Since $(3)$ is a transport-type equation it has the solution
$$v(x,t) = j(c + ct)$$
where $v(x) = u(x,0)$. So, $(4)$ becomes an inhomogenous transport equation, namely
\begin{equation}{\tag{5}}
u_t + c u_x = j(x+ct)
\end{equation}
The solution to $(5)$ is
$$u(x,t) = h(x - ct) + \int_{0}^{t} j(x + (s-t)c + cs) ds$$
where $u(x,0) = h(x)$. Now if $G' = j$ then we have
\begin{align*}
u(x,t) &= h(x-ct) + \int_{0}^{t}j(x + (2s - t)c)ds\\
&= h(x-ct) + \frac{1}{2c}\left[G(x+(2s-t)c)\Biggr|_{0}^{t}\right]\\
&= h(x-ct) + \frac{1}{2c}\left[G(x+ct) - G(x-ct)\right]\\
&= f(x+ct) + g(x-ct)
\end{align*}
where $g := h - G/2c$ and $f:= G/2c$. Thus the general solution to $(1)$ is
$$u(x,t) = f(x+ct) + g(x-ct)$$
I hope this answers most of your question :)


text:
Q: how to pass data from a form to another form that is previously instantiated from any other form? I have three forms(form1,form2,form3), my main form is form1, from that i opened form2 taking some data and i have an update button on form2 that will take me to form3, now i want that whatever user writes on form3 is updated to form2, how can i make it possible using c#.net?
(i opened form2,form3 using showdialog() method)
//reference to form2
Form2 SecondaryForm = new Form2(mainForm);<br/>
SecondaryForm.ShowDialog();

//in the constructor of Form2 save the reference of Form1
Form1 form1 = null

Form2(Form1 mainForm)
{
    form1 = mainForm;
}

//then instead of creating a new MainForm again just use reference of Form1

form1.updateText(data);
this.Close()

i have used the above code but i am getting nullreference exception on form1.updateText(data);

A: I just tried this. i created two forms, each form with a button and textbox. In Form1
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 SecondaryForm = new Form2(this);
        SecondaryForm.ShowDialog();
    }

    public void updateText(string txt)
    {
        textBox1.Text = txt;
    }

Then in Form2
    Form1 form1 = null;
    public Form2(Form1 mainForm)
    {
        form1 = mainForm;
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        form1.updateText(textBox1.Text);
        this.Close();
    }

I used this and it worked and i got no exceptions

A: Just pass the form 2 reference to form three while instantiating it.. similarly as you did for form1 while opening form2. then from form3 use the form2 reference to call updatetext method which should be a public method on form2
here is code for all 3 forms, you can update any form from others, i have made it so that you can access form1 and form2 in form3.
using System;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public  Form2 frm2;
        public  Form3 frm3;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        public void updateText()
        {
            this.textBox1.Text = "";
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (frm2 == null)
                frm2 = new Form2(this);

                frm2.ShowDialog();
        }
    }
}

using System;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        public Form1 refToForm1;

        public Form2(Form1 f1)
        {
            refToForm1 = f1;
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (refToForm1.frm3 == null)
                refToForm1.frm3 = new Form3(this);

            refToForm1.frm3.ShowDialog();
        }

        public void UpdateForm2(string txt)
    {
        this.textBox1.Text = txt;
    }

    }
}

using System;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form3 : Form
    {
        Form2 refToForm2;
        public Form3( Form2 f2)
        {
            refToForm2 = f2;
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Pass any data to Form1;
            refToForm2.refToForm1.updateText();

            //Pass data to form2
            refToForm2.UpdateForm2("from form3");
        }
    }
}

A: Although it may not be appropriate for your data, maybe you could consider your forms as 'Views' for an underlying 'Model' that represents all your data? If so, you can create an instance of your 'Model' class and give all 3 forms a refernce to it. See here for some explanation of 'View' and 'Model'.


text:
Q: Is the difference between GET v POST in convention or by design? Background:
Looking at some links like these below, I noticed two unique sets of descriptions for GET versus POST.

*

*One description states that the difference is in how the information is sent: GET sends that information through the URL whereas POST sends that information through the HTTP request body.

*Another description states that the difference is in which way that
information is sent: GET sends information to the server whereas POST
requests information from the server.

I find these descriptions to be lacking for the following reasons:

*

*What if I want to get something from the server (GET) but I am sending a large amount of data first (eg. 50MB of text) so I would need to send it in the HTTP request body (POST). Would it be OK to use POST to get something from the server?

*What if I don't want sensitive information to be stored in the URL, is it OK to instead use POST everytime?

*The jquery GET function has the same method signature as the jquery POST function (see documentation), specifically it can also send data as A plain object or string that is sent to the server with the request, which I interpret as being added to the HTTP request body. If data for GET can be sent via the HTTP request body, then to me, this contradicts most of these sites that claim that as one of the differentiating descriptions of POST vs GET.

*Nothing's to stop me from creating API endpoints which are GET but behave like POST (or PUT, or DELETE or PATCH)

Question:
Is the lack of strict descriptions because of my poor understanding, because of the ad hoc development process for HTTP/Ajax or is it something else entirely?
Supporting Links:

*

*HTTP Request Methods

*GET vs. POST

*GET vs POST: Key Difference between HTTP Methods

*jQuery - AJAX get() and post() Methods


text:
Q: How to get current logged in user with open id connect identity jwt bearer net core Hello I am trying to get current user but nothing seems to work every resource I find brings null.
this is the code in my startup
            services.AddIdentityServer()
                .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

            services.AddAuthentication()
                .AddIdentityServerJwt();

            services.Configure<JwtBearerOptions>(
    IdentityServerJwtConstants.IdentityServerJwtBearerScheme,
    options =>
    {
        var onTokenValidated = options.Events.OnTokenValidated;

        options.Events.OnTokenValidated = async context =>
        {
            await onTokenValidated(context);

        };
    });
            services.ConfigureApplicationCookie(o => {
                o.ExpireTimeSpan = TimeSpan.FromDays(5);
                o.SlidingExpiration = true;
            });

            services.Configure<DataProtectionTokenProviderOptions>(o =>
       o.TokenLifespan = TimeSpan.FromHours(3));


text:
Q: Projection for using ArcGIS as CAD I want to use ArcGIS to map my apartment. How can I create a projection file (with which parameters)?

A: You do not need a projection if your coordinates are arbitrary.  If you are going to use a basemap to pick a corner of the building provided by Arcmap then you are stuck with WGS84.  Autocad offers free trial and complete student edition if you are a student.  There are many open source drafting programs to choose from but your question does not state an OS so I can't make a recommendation...either way that's an easy search and I am sure it has been covered here.
You could also draw it in paint or some other drawing program and geo-rectify the image in arcmap using satellite imagery.
Here is something to keep in mind:
GIS is a poor architectural drafting program and AutoCAD is a poor GIS program.


text:
Q: Pipelined designs with outputs in differentes delay clocks I have a pipelined design that ends in 13 clock cycles when the input value is not close to zero, but when the input is close to zero, the design only needs about 4 clock cycles, because of all the intermediate calculus is not needed. Therefore, my question is: Is it possible make a pipelined design where the output is delayed two differents number of clock cycle?
Actually I think this question has not sense because I have never seen a similar question or design with this specs.

A: If the design is fully pipelined, skipping later pipeline steps doesn't gain you anything and introduces flow control problems. That's why it's uncommon.
If your design consisted just of this one component, adding a second output port that reports results early if possible would be easy, but it would make life harder for the surrounding components that now have to integrate two streams of result data where results may appear on both during the same cycle.
If I were tasked to design the surrounding logic, I'd probably look into your component and see that it has a guarantee that nine cycles after a result on the "early" path there will be no result on the "regular" path, so I can just delay by nine cycles and merge without introducing a FIFO (which would have additional error states).
The other issue is that if results arrive out of order, I need a tagging system to identify them, which adds even more logic.
Out-of-order processing is often done in black box models, e.g. if you have a bus system like PCIe, the components send packets to each other and responses are generated as they become ready -- for example an access to main memory could be satisfied immediately (as the memory is mapped and the mapping is cached), with a slight delay (the memory is mapped, but the mapping needs to be looked up) or with a long delay (the memory is swapped out and needs to be brought back from the harddisk) -- but these are generally high-level operations.
Again, the premise for all of this is that this is a fully pipelined computation that is optimized for throughput (i.e. one input, one output per cycle).


text:
Q: what is functions to add sass in visual studio code how to add sass in vs code
I cannot add sass in my vs code. please can anyone help me ! because aim a beginner i wrote "sass- init" by looking at a youtube video


text:
Q: Feeding contact details into servicem8 I am about to work on a project involving WordPress and ServiceM8 API. One of the idea is to use web leads on the wp side and feed them through the API into ServiceM8. I had a look at the ServiceM8 API Reference online, and could find requests for job contacts, but not contacts by themselves. I reckon that contacts will be kept in the ServiceM8 app. Is it somehow possible to create new contacts (and to update/delete them) using the ServiceM8 API?
Thanks,
Jemy09

A: There's two ways you could do this:

*

*Create the leads as Companies in ServiceM8. The companies endpoint in the ServiceM8 API is how you manage clients. Regardless of whether they're actually companies or individuals, they are always accessed through the Companies endpoint. Once you've created a Company you can add CompanyContacts to store their contact details.

*E-mail the leads to the ServiceM8 account's Inbox address. This is probably a better option, as the user will be able to see the number of pending leads by checking the number of unread messages in their ServiceM8 Inbox. You'll also be able to convert the leads directly to ServiceM8 jobs, and you won't be cluttering up the client database with spammy submissions.
More info here - https://support.servicem8.com/hc/en-us/articles/202583884-How-the-inbox-job-card-auto-fill-feature-works-
And overview of the Inbox here - https://support.servicem8.com/hc/en-us/articles/200272654-What-is-the-ServiceM8-Inbox-


text:
Q: Example of a discontinuous function for which limit of the differential quotient exists in $\mathbb R\cup\{-\infty,+\infty\}$ I am just asking this question for my verification of own answer.
I have taken as example the function $f(x)=1/x$ if $x\neq 0$ and $0$ if $x=0$.
Here $\lim_{x\to 0}\frac{f(x)-f(0)}{x-0}=+\infty$.Is this example correct?
Note: I am also asking this question for sharing what I know or learn with other members in the community.

A: It is correct. Note that an example of a continuous such function is $x\mapsto\sqrt[3]{x}$ at $x=0$.


text:
Q: Login info going as plain text - How to make it unreadable I'm doing a login form that uses jquery to pass data from the form to the script and back. I've noticed the email and password are being sent as plain readable text. I also noticed that in other site like this very one, or gmail or others, the login info isn't readable like mine is. How can I do this? Somehow, sending this info as plain text doesn't look very... professional.

A: you have several options here:

*

*Use HTTPS protocol to send the login informations.

*You can hash/encrypt your login info on the client side, upload it/process the form, and decrypt and process the login info on your server. SO have several Q/A answers regarding this process:

*

*Two-way password encryption without ssl

*Secure login: public key encryption in PHP and Javascript
However, options #2 is not really an options, if the encryption key are also submitted in plain text over the internet.


text:
Q: Calculate Tweets Per day I need to write a function which calculates the number of tweets that were posted per day.
Function Specifications:

*

*It should take a pandas dataframe as input.
It should return a new dataframe, grouped by day, with the number of tweets for that day.

*The index of the new dataframe should be named Date, and the column of the new dataframe should be 'Tweets', corresponding to the date and number of tweets, respectively.

*The date should be formated as yyyy-mm-dd, and should be a datetime object.

My code is :

def number_of_tweets_per_day(df):

    df = pd.DataFrame(twitter_df['Date','Tweets'], columns =['Date', 'Tweets'])

    df['Date'] = pd.to_datetime(df['Date'], format = '%Y%m%d')
    df['Tweets'] = df['Tweets'].astype(str)

    grouped = pd.df.groupby(['Date'],['Tweets'])
    final = pd.df.count()

    return final

However when I try to run command 'number_of_tweets_per_day(twitter_df.copy())' I get an error saying twitter_df not defined.
DF:

Expected output:

Attached links to an image of input dataframe and image of expected output.
What am I doing wrong?

A: You can use DataFrame.groupby with pd.Series.dt.date to group and use GroupBy.count here.
def tweets_per_day(df):
    df['Date'] = pd.to_datetime(df['Date'], format='%Y%m%d')
    return df[['Tweets']].groupby(df['Date'].dt.date).count()
  # return df['Tweets'].groupby(df['Date'].dt.date).count()
  # if you want output to be `Series`

tweets_per_day(twitter_df)

Output on dummy df:
d = pd.to_datetime(['2019-11-29', '2019-11-30']).repeat(10)
df = pd.DataFrame({'Tweets':'anything', 'Date':d})
df
#      Tweets       Date
#0   anything 2019-11-29
#1   anything 2019-11-30
#2   anything 2019-11-29
#3   anything 2019-11-30
#4   anything 2019-11-29
#5   anything 2019-11-30
#6   anything 2019-11-29
#7   anything 2019-11-30
#8   anything 2019-11-29
#9   anything 2019-11-30
#10  anything 2019-11-29
#11  anything 2019-11-30
#12  anything 2019-11-29
#13  anything 2019-11-30
#14  anything 2019-11-29
#15  anything 2019-11-30
#16  anything 2019-11-29
#17  anything 2019-11-30
#18  anything 2019-11-29
#19  anything 2019-11-30

tweets_per_day(df)

            Tweets
Date
2019-11-29      10
2019-11-30      10

A: The groupby() technique demonstrated by @Ch3steR certainly works.  Here are two other approaches, using value_counts() and resample():
Create the data frame (and set data type):
import pandas as pd

df = pd.DataFrame({'Date':  ['2019-11-30'] * 5 + ['2019-11-29'] * 6,
                   'Tweets': 'x'}
                 )
df['Date'] = pd.to_datetime(df['Date'], format='%Y-%m-%d')

The value_counts() approach:
def tweets_per_day_2(df):
    return df['Date'].value_counts().sort_index()

result = tweets_per_day_2(df)
print(result)

2019-11-29    6
2019-11-30    5
Name: Date, dtype: int64

And the resample() approach:
def tweets_per_day_3(df):
    return df.set_index('Date').resample('D').count().sort_index()

result = tweets_per_day_3(df)
print(result)

            Tweets
Date
2019-11-29       6
2019-11-30       5


text:
Q: Please explain me what the do_action does I am trying hard  to understand do_action but not understanding.
I was studying the blane theme. And  they have this code in sidebar.php

        <?php do_action( 'before_sidebar' ); ?>
        <?php if ( ! dynamic_sidebar( 'sidebar-1' ) ) : ?>

                <?php get_search_form(); ?>

<?php _e( 'Archives', 'blain' ); ?>

                    <?php wp_get_archives( array( 'type' => 'monthly' ) ); ?>

<?php _e( 'Meta', 'blain' ); ?>

                    <?php wp_register(); ?>

<?php wp_loginout(); ?>

                    <?php wp_meta(); ?>

        <?php endif; // end sidebar widget area ?>

But i don't get  what is the second line i.e
 <?php do_action( 'before_sidebar' ); ?>
doing. When i remove this line still it outputs the same result.
Can anybody please explain with some example.

A: If you hook some functions to the before_sidebar action, they will be executed in your code. Your action is now probably without any function hooked, so it returns nothing.
Example:
<?php
add_action( 'before_sidebar', function() {
  echo 'Try me!';
});
add_action( 'before_sidebar', function() {
  echo 'Yep. ';
}, 1);

// this should output "Yep. Try me!"
<?php do_action( 'before_sidebar' ); ?>

The third argument is a priority. In my example I've set the priority to 1 to the second function and it will be executed at first place.
For more information take a look at WP Codex do_action, and add_action.


text:
Q: How to use a variable named 'type' in Scala class definition? I have to create a class that in its definition contains a variable named 'type', for example like this:
case class testEntity (
   type: String,
   val: String
)

Is there any possible to do that?

A: To use names that are normally not allowed you have to put them in backticks (`).
Your declaration will look like this:
case class testEntity (
   `type`: String,
   `val`: String
)

Since type and val are both keywords.
EDIT: Also the convention in Scala is to start class names with a capital letter.


text:
Q: I am not able to update list pushed into array using push function and get same old values even after update list

     export class ApproveComponent implements OnInit {
       @Output() public next: EventEmitter<any> = new EventEmitter<any>();
       codes: any[] = [];
       selectedCode: any;

     this.Apiservice.komm.subscribe(data => {
     this.selectedCode = data; //this one give me right values before and efter                                 //changes in list
      console.log('selected kom ' + JSON.stringify(this.selectedKom));
      for (const d of data ) {
          this.codes.push(d.code);
           console.log('codes = ' + this.codes);
           //this.codes.push(d.code); this give me the same values before and               //efter changes

      }
     });

this code has one problem , you can see that i am getting values from service class and pushing list into  this.codes.push(d.code); as soon i populate array using push function and save it than it's ok. but i have update button in template which take me to respective list from where i get all these data list value, when i change the list with new values, i get right values in this code of segment (this.selectedCode) this show me updated values, but this code of segment(this.codes.push(d.code);
console.log('codes = ' + this.codes) ) shows me old values and doest not update the list, I hope i explained it, can some one help me with this how can i solve this issue, any kind of help be appriciated

A: The this.Apiservice.komm Observable might not have data at the beginning, you can do a null check around the for loop:
this.Apiservice.komm.subscribe(data => {
     this.selectedCode = data;

     if(data && data.length > 0)
          for (const d of data ) {
              this.codes.push(d.code);
               console.log('codes = ' + this.codes);
          }
     }
});

If that works, I would suggest you create a private method to handle the logic.


text:
Q: Prolog: Related predicates with permuted arguments Is there a way to declare the following in Prolog without being caught in an endless recursion?
left([X,Y], Z) :- left([Z,X], Y); left([Y,Z], X).

The semantics is that the list represents a vector given by two points and the second argument is a third point lying left of the vector.
A related question is, how one can declare the relation of "left" and "right" given by:
left([X,Y], Z) :- right([Y,X], Z).

without getting an endless recursion.

A: Unfortunately, you cannot do this directly in Prolog. You can express commutative relationships by introducing a predicate that enumerates the permutations for the fact, so for example:
left_of(A, B, C) :- left(A, B, C).
left_of(A, B, C) :- left(C, A, B).
left_of(A, B, C) :- left(B, C, A).

left(a, b, c).

Now the query should be
?- left_of(A, B, C).

Similarly, you should define right_of in terms of left.
Several things worth noting:

*

*Keep the three arguments separate, as shown. It is good practice not to introduce unnecessary structures.

*Prefer explicit clauses, instead of ;. It makes your code far more obvious. The ; is really easy to miss when reading the code; if you use it, put it at the beginning of the line, not in the middle somewhere or at the end

*Prolog implementations that support tabling do not have this problem.


text:
Q: No notification when someone comment my answer Today I answered this question. Later, I failed to get any notifications for comments that were posted for my answer.

My inbox is filled with comments, but no red notification appeared. Why is that?
Note: I'm sure that I didn't have the inbox open in another tab.


text:
Q: Copy&Cut&Paste/Autocomplete doesn't work as expected in Android Studio on Mac Just started to learn Android development, following Udacity exercise Exercise: Toying with FavoriteToys. I noticed that cmd + c, cmd + x doesn't work as expected.(please note it does work in all other apps)
Please look at the following image:

*

*I can cp&ps the comments as expected (i.e line 43 can be copied)

*I can't copy the code (for instance if I try to copy all line 28 it won't copy it, instead it will use the old clipboard i.e will take the comment on line 43 that I just copied)

*I can copy only several characters (for instance if I copy few characters from the end of line 31 it will work)

*I can copy the whole line 29 (that's the only one line of code that I CAN copy)

What did I try:

*

*Restart IDE

*Restart Mac

*Reset Cache/ Rebuild and all other woodo stuff

*Edited idea.properties with ide.mac.useNativeClipboard=True

*My Key mapper looks fine, attaching img (as far as I can see)

*Reinstalling Android Studio (3.5)

*I don't have ClipMenu

Key Mapper:

Possible Duplicate:
Copy-paste is not working in Android Studio on Mac
Will really appreciate any help, Thnaks

A: I noticed that some other features didn't work as well, like highlighting and autocomplete in .java  classes. (it did work in the .xml)
I uninstalled Android Studio 3.5 Uninstall
Install the new version 3.5.1 Android Studio Installation
Really curious if other people had these issues if so, it just UNBELIEVABLE that such a release was made public.
(btw, upgrade to a higher version from Android Studio wasn't possible due to
some conflicts were found in the installation area android studio  error)


text:
Q: how to write a junit test case for a method that has retry logic The retry method precisely looks into a folder for a particular file and returns the file if present .It has a Max retry count for 3 and sleeps for 1 min between 2 retries .If after Max retries file is not present it throws some exception
method is soemthing like this
File getFile(int retryCount){
    File file;
    file =getFilefromLocation();
    if(file!=null) return file
    if(file==null and retryCount>0)
    Thread.sleep(1)
     --retryCount;
    File filePicked =getFile( retryCount)
   }
else return null;
}

A: One possible way is to factor out the part that checks for the presence of the file into its own object and to mock that object.

A: I would make the retry time configurable and make it 1 second for testing.
You can have tests where the file is already there, never there and one where it is added as a background thread. Should take about 5 seconds.
I would also consider shorter retry times more often eg 120 attempts every 1 second instead of 3 times every minute.

A: I will try to give some pointers.
1) Here I would not mock the whole logic to check the presence of the file as it makes part of the behavior of the method under test.
What you want to mock is the part where you actually try to retrieve the file, that is as you invoke getFilefromLocation().
2) Using a short delay between retries is a idea but is it enough to make your test robust?
Not really because you also have to assert that Thread.sleep() was invoked and with the expected value. Not checking that in the unit test means that anybody can remove Thread.sleep() in the getFile() method and the test will still pass. You really don't want that.
Note that you cannot easily mock it : it is static. You should move this statement into a DelayService that you could mock.
3) Actually you  parameterize retryCount. As you write unit tests, you want to validate the behavior of the components according to your requirements. So you should also ensure that the class that depends on getFile(int retryCount) passes effectively the expected parameter : 3.
Besides if you don't want to allow more than a certain retry number, you also have to add this check in the method and assert this rule in the unit test.
According to the two first points, your actual code could be refactored as :
private FileLocator fileLocator; // added dependency
private DelayService delayService; // added dependency

//  constructor to set these dependencies
public MyService(FileLocator fileLocator, DelayService delayService){
    ...
}

File getFile(int retryCount){
    File file;
    file = fileLocator.getFilefromLocation(); // -> change here
    if(file!=null) return file
    if(file==null and retryCount>0){
       delayService.waitFor(); // -> other change here
       --retryCount;
       File filePicked = getFile(retryCount)
    }
    else return null;
}

About the unit test part, you could use Mockito for mocking and mix "simple" unit tests with parameterized tests as some scenarios have a similar behavior with as variance the number of actual retries.
For example retrying 0, 1, 2 and 3 times and finding the file are 4 cases that you can parameterize.
And inversely failing to find the file doesn't need to be parameterized as all retries will should be done to validate the behavior.
Here is a code example relying on JUnit5 and Mockito (not tested) that you could adapt according to your actual code. I just illustrated with the parameterized test. The other test cases should not be more complex to implement.
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.junit.jupiter.api.Assertions;
import org.mockito.Mockito;
import org.mockito.Mock;

private static final long EXPECTED_DELAY_MN = 1;
private static final long RETRY_COUNT = 3;

@Mock
FileLocator fileLocatorMock;

@Mock
private DelayService delayServiceMock;

MyServiceTest myServiceTest;

public MyServiceTest(){
   myServiceTest = new MyServiceTest(fileLocatorMock, delayServiceMock);
}

@ParameterizedTest
@ValueSource(ints = { 0, 1, 2, 3 })
public void getFileThatFailsMultipleTimeAndSuccess(int nbRetryRequired){

    // failing find
    for (int i=0; i < nbRetryRequired; i++) {
        Mockito.when(fileLocatorMock.getFilefromLocation(...)).thenReturn(null);
    }

    // successful find
    File fileByMock = new File(...); //fake file
    Mockito.when(fileLocatorMock.getFilefromLocation(...)).thenReturn(fileByock);
    File actualFile = myServiceTest.getFile(RETRY_COUNT);

    // assertions
    Mockito.verify(delayServiceMock, Mockito.times(nbRetryRequired))
           .waitFor();
    Assert.assertSame(fileByMock, actualFile);

   }
}


text:
Q: How to fetch a specific data from a url? I am trying to develop an android app which fetches data by visiting https://demo.vtiger.com/webservice.php?operation=getchallenge&username=admin.
The output of above url is {"success":true,"result":{"token":"53ba663902fd3","serverTime":1404724793,"expireTime":1404725093}}
But I want only the value of "token", so How can I fetch it from the result of above url?
Thanks for ur help.

A: Use JSONObject class to make an object from this json string.
Then get a token you want from the composed object.

A: String json = "{\"success\":true,\"result\":{\"token\":\"53ba663902fd3\",\"serverTime\":1404724793,\"expireTime\":1404725093}}";
JsonParser parser = new com.google.gson.JsonParser();
JsonElement elem = parser.parse(json);
String token = elem.getAsJsonObject().get("result").getAsJsonObject().get("token").getAsString();
System.out.print(token);

A: Create JSONParser class in your application project.
Refer Below link for JSONParser class:
http://www.learn2crack.com/2013/10/android-json-parsing-url-example.html

then call it from your class
JSONParser jp=new JSONParser();

JsonObject object=jp.getJSONFromUrl(your url);
JsonObject object2=object.getJsonObject("result");

String Token=object2.getString("token");

Thats it...


text:
Q: Remove saved double quotes in string For some unknown reason, some of my saved strings (in db) have a leading and trailing \".
How do I detect and remove these?
my_object.a_string_type_attribute.gsub(/\s|"|'/, '') doesn't do anything.

A: You need to do sth in lines:
YourModel.where('column_name LIKE \'"%"\'').each do |model|
  model.column_name = model.column_name[1..-2]
  model.save
end

It might take a while if you have large database. Make sure to create a backup if you want to run it against your live database.

A: string.strip('"')

should work.


text:
Q: Play audio doesn't work on form submit on iOS I have a form that plays Audio on submit (Vue but nvm).
It works perfect everywhere but not on iOS.
On iOS it works only on click on a button element, but it doesn't work on click on a "return" button on iOS keyboard :(
Why doesn't iOS trusts submit event but it trusts click that works in the same way?
Any tips? Thank you!
I have a "hack" solution:

*

*Remove form onsubmit handler, change type of the button to type="button", add onclick handler to this button and call playAudio() ("return" key will still on keyboard, so this is fine).

*Add onkeyup event to input and call playAudio() on keyCode === 13 (Enter key).
My "hack" solution works fine but is "hack" :(
<form novalidate @submit.prevent="playAudio()">
  <div class="form-group">
    <input
      type="text"
      class="form-control"
      autocapitalize="off"
      autocomplete="off"
      spellcheck="false"
      autocorrect="off"
     />
  </div>

  <button type="submit" class="btn btn-block">Enter</button>
</form>

iOS (xcode simulator) error on form submit:

NotAllowedError: The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.


text:
Q: Way to read data from Kafka headers in Apache Flink I have a project where I am consuming data from Kafka. Apparently, there are a couple fields that are going to be included in the headers that I will need to read as well for each message. Is there a way to do this in Flink currently?
Thanks!

A: @Jicaar, Actually Kafka has added Header notion since version 0.11.0.0. https://issues.apache.org/jira/browse/KAFKA-4208
The problem is flink-connector-kafka-0.11_2.11 which comes with flink-1.4.0, and supposedly supports kafka-0.11.0.0 just ignores message headers when reading from kafka.
So unfortunately there is no way to read those headers unless you implement your own KafkaConsumer in flin.
I'm also interested in readin in kafka message headers and hope Flink team will add support for this.

A: I faced similar issue and found a way to do this in Flink 1.8. Here is what I wrote:
FlinkKafkaConsumer<ObjectNode> consumer = new FlinkKafkaConsumer("topic", new JSONKeyValueDeserializationSchema(true){
    ObjectMapper mapper = new ObjectMapper();
    @Override
    public ObjectNode deserialize(ConsumerRecord<byte[], byte[]> record) throws Exception {
        ObjectNode result = super.deserialize(record);
        if (record.headers() != null) {
            Map<String, JsonNode> headers = StreamSupport.stream(record.headers().spliterator(), false).collect(Collectors.toMap(h -> h.key(), h -> (JsonNode)this.mapper.convertValue(new String(h.value()), JsonNode.class)));
            result.set("headers", mapper.convertValue(headers, JsonNode.class));
        }

        return result;
    }
}, kafkaProps);

Hope this helps!

A: Here's the code for new versions of Flink.
    KafkaSource<String> source = KafkaSource.<String>builder()
            .setBootstrapServers(ParameterConfig.parameters.getRequired(ParameterConstant.KAFKA_ADDRESS))
            .setTopics(ParameterConfig.parameters.getRequired(ParameterConstant.KAFKA_SOURCE_TOPICS))
            .setGroupId(ParameterConfig.parameters.getRequired(ParameterConstant.KAFKA_SOURCE_GROUPID))
            .setStartingOffsets(OffsetsInitializer.latest())
            .setDeserializer(new KafkaRecordDeserializationSchema<String>() {
                @Override
                public void deserialize(ConsumerRecord<byte[], byte[]> consumerRecord, Collector<String> collector) {
                    try {
                        Map<String, String> headers = StreamSupport
                                .stream(consumerRecord.headers().spliterator(), false)
                                .collect(Collectors.toMap(Header::key, h -> new String(h.value())));
                        collector.collect(new JSONObject(headers).toString());
                    } catch (Exception e){
                        e.printStackTrace();
                        log.error("Headers Not found in Kafka Stream with consumer record : {}", consumerRecord);
                    }
                }

                @Override
                public TypeInformation<String> getProducedType() {
                    return TypeInformation.of(new TypeHint<>() {});
                }
            })
            .build();


text:
Q: Java Decimal Format issue zero (0.00) I have a problem with the formatter, when I give a 0.00 return +0,00 E but I would like to 0,00 E.
String PATTERN = "###,##0.00\u00a0\u00A4";
DecimalFormatSymbols SYMBOLS = DecimalFormatSymbols.getInstance(Locale.FRANCE);
DecimalFormat FORMATTER_SIGN = new DecimalFormat(PATTERN, SYMBOLS);
FORMATTER_SIGN.setNegativePrefix("-\u00a0");
FORMATTER_SIGN.setPositivePrefix("+\u00a0");
FORMATTER_SIGN.format("0.00") // this

A: I can get rid of the "+" when I remove the line
FORMATTER_SIGN.setPositivePrefix("+\u00a0");

or change it to
FORMATTER_SIGN.setPositivePrefix("");

Resulting in

0,00 €

PS: Your format call doesn't work for me, I need to do something like this:
FORMATTER_SIGN.format(Double.valueOf("0.00")); // this

A: You could create your own DecimalFormat that is aware of zeros (simplified example):
class ZeroAwareDecimalFormat extends DecimalFormat {
    private final DecimalFormat zeroFormat;

    public ZeroAwareDecimalFormat(String posNegPattern, String zeroPattern) {
        super(posNegPattern);
        zeroFormat = new DecimalFormat(zeroPattern);
    }

    @Override
    public StringBuffer format(long number, StringBuffer result, FieldPosition fieldPosition) {
        if (number == 0L) {
            return zeroFormat.format(number, result, fieldPosition);
        } else {
            return super.format(number, result, fieldPosition);
        }
    }

    // Override the other methods accordingly.
    // set... methods should be propagated to super and zeroFormat.
}


text:
Q: TickTuple does not work I have a storm topology, in which I have a bolt which reads from database and puts into a kafka queue in a batch. It gets more than 20K rows in about 5secs. But the bolt does not receive the tick tuple. And eventually I receive heap space error. So I have limited the count to 10k to push the messages to kafka queue. And when reading from db is finished, I started to get tick tuple messages.
The spout calculates the next data to fetch from the db and gives it to bolt, table name and time range.
protected static boolean isTickTuple(Tuple tuple) {
        return tuple.getSourceComponent().equals(Constants.SYSTEM_COMPONENT_ID)
                && tuple.getSourceStreamId().equals(Constants.SYSTEM_TICK_STREAM_ID);
    }
@Override
public Map<String, Object> getComponentConfiguration() {
    Config conf = new Config();
    int tickFrequencyInSeconds = 5;
    conf.put(Config.TOPOLOGY_TICK_TUPLE_FREQ_SECS, tickFrequencyInSeconds);
    return conf;
}`

Version of Storm is  0.9.3

A: When you call Submitter.submitTopology, you have to pass topology configuration as one of the arguments.
It's likely that you configured tick tuple frequency somewhere else but didn't put it to conf that will be delivered to topology.


text:
Q: Update view from function when function calculate value using the same view I have a View that that contains two columns. Column c1, and column c2.

*

*c1 is updated by a function getPrice().

*The problem is that get getPrice() calculate is´s value by using column c2.
This causes mysql to send out error message :

ERROR 1424 (HY000): Recursive stored functions and triggers are not allowed

Is there any way to resolve this?

A: SELECT and UPDATE can be decoupled through a temporary table: select new values into temporary table and update source table from it.


text:
Q: AngularJs Directive - attribute scoped variable not binding Accompanying plunker (in coffeescript, but javascript below)
I cannot get an attribute-scoped variable (@) to bind in a directive.
Here's the directive code:
app.directive('myDirective', [
  function() {

    var compileFn, config, linkFn;

    linkFn = function($scope, element, attr) {
      return alert("foo: " + $scope.foo);
    };

    compileFn = function() {
      return linkFn;
    };

    return config = {
      compile: compileFn,
      scope: {
        foo: '@myDirectiveFoo'
      }
    };
  }
]);

and the HTML:

I'd expect the value that's alerted would be 'bar', but instead it's undefined.  What am I missing?

A: Short answer: to get the expected value foo in your link function you have to observe the attribute:
attr.$observer('myDirectiveFoo', function(value){
    console.log(value);
    console.log($scope.foo);
});

both console outputs will give you the expected bar value. Why? the attribute value must be interpolated and this will happen after the link function was called.
Long answer: The documentation stated for the attr object that is passed to the link function:

Use $observe to observe the value changes of attributes that contain interpolation (e.g. src="{{bar}}"). Not only is this very efficient but it's also the only way to easily get the actual value because during the linking phase the interpolation hasn't been evaluated yet and so the value is at this time set to undefined.

Let's have a look at a modified version of you example. It shows also the differences between = und @ scoping.
This is our html:

This is the controller:
app.controller('MainCtrl', function($scope, $timeout, $interpolate){
  $scope.name = 'roy';
  $timeout(function(){
    $scope.name = 'michael';
  },4000);
});

As you can see, we have a name property that will change from roy to michael after 4 seconds.
This is the directive:
app.directive('myDirective', function() {
    return {
      scope: {
        foo: '@myDirectiveFoo',
        bar: '=myDirectiveBar'
      },
      link: function ($scope, iElement, iAttrs, controller) {
          console.log('link foo: '+$scope.foo);
          console.log('link bar: '+$scope.bar);
          iAttrs.$observe('myDirectiveFoo',function(value){
              console.log('link observed foo: '+$scope.foo, value);
          });
          $scope.$watch('bar', function(newValue, oldValue){
              console.log('watch', oldValue, newValue);
          });
          console.log('link done');
      },
      controller: function($scope){
          console.log('controller foo:'+$scope.foo);
          console.log('controller bar:'+$scope.bar);
      }
  };
});

We have two isolated scope properties. foo configured as one-way-binding and bar configured as two-way-binding. In the controller output we will see, that the two-way-binding ($scope.bar) is available immediately and the one-way-binding ($scope.foo) is not. In the link function we have the same result. If the linking is done we will see that the observer and the watcher will fire with the current (and expected) values. The observer and the watcher will fire again if the name property changed their value after 4 seconds.
see it live @ PLUNKR


text:
Q: Share data between ActiveJob and Controller Every n seconds application is requesting a remote JSON file that provides live prices for securities in the Trading system. JSON has a block with the data I need (marketdata) and a block with the current dataversion(version and seqnum).
Right now I use ActionController::Live (with EventSource on the client side) to push updated data to the browser. All actions are done within one method:

*

*opening SSE connection;

*forming dynamic URL;

*pulling new data from remote server;

*comparing/reassigning seqnum value;

*updating database if needed.

So my goal now is to separate pulling & updating the database (ActiveJob) with pushing updated values to the browser (ActionController::Live). To accomplish this I need:

*

*either to store somewhere on the server side seqnum & version to share between controller and background job;

*or monitor databases for the latest changes in the updated_at fields.

So basically I have two questions:

*

*What is more efficient between the two options above?Are there any other good approaches?

*(in case the first one has a right to exist) How to implement this approach?

A: Considering the fact that you might have, for example, multiple rails process running, I believe it becomes quite hard for you to let activejob talk directly to rails controller in some way.
Defintely store seqnum and version, I wouldn't rely on updated_at in any case, it's too easy to get it updated randomly and so end up sending stuff to the client without any real reason. Also in this case they seem like very solid fields to point out if the file has been updated.
With polling
That being said, you want to "signal" ActionController::Live in some way and I'm afraid polling here is your only option, unless on your client side there is a specific moment when it needs to know if the file has been updated, in which case you might want to use websockets or something similar.
So, something like
cached_request = YourCachedRequest.latest # Assuming it returns a single record
updated        = true
loop do
  if updated
    updated = false
    response.stream.write cached_request.serialize_in_some_way
  end
  current_version = cached_request.version # use seqnum too if you need
  cached_request = cached_request.reload
  updated = true if cached_request.version > current_version
  sleep 20.0
end

Without polling
If you want an option that doesn't involve polling, you can only go for websockets I believe. However you have a more efficient option:
Create a mini application (evenmachine/sinatra/something light) where the clients will poll (you can pass through your main application to distribute this to differente nodes of this mini application), the point of this app is only to reroute messages from your main application to polling clients.
Now, you can create an internal API endpoint for your main application that it's used only by delayed job. Delayed job will hit this endpoint only when it notices that the fetched JSON is actually updated relative to the one currently stored. If that's the case, it will hit your main app API endpoint which in turn will send a message (again, probably through an HTTP API endpoint, this time on your mini app) to all your mini app instances, which in turn will send them to your clients.
In this way, you don't overload your main server but only these mini-nodes which can have localized outages (which is a big advantage, instead of having a big system outage).


text:
Q: Understanding ends as equalizers While reading Fosco Loregian's "This is the (co)end, my only (co)friend" I found the following remark:

The product on the left ranges over objects in the category, but I'm confused by the so-called "double product" on the right, which seems to range over morphisms. In programmer-speak, that seems like a "type error" to me! Could someone "unpack" that part of the formula with a bit more detail?

A: It is not perfectly clear to me what you have a problem with. However, writing $\mathbf{C}_0$ and $\mathbf{C}_1$ for the collections of objects and morphisms of $\mathbf{C}$, and writing $\text{dom}, \text{cod} : \mathbf{C}_1 \to \mathbf{C}_0$ for the maps sending a morphism to its domain and codomain respectively. The right hand side would be $$\prod_{f \in \mathbf{C}_1} F(\text{dom}(f),\text{cod}(f)).$$
But this could be also written as
$$\prod_{(c,c')\in \mathbf{C}_1^2} \left( \prod_{f \in \hom(c,c')} F(c,c')\right).$$

A: Glad to see that my article is being studied :)
Another way to visualize the situation is the following, which generalizes to the enriched context:
The end of $T\colon {\bf C}^\text{op}\times {\bf C}\to {\bf D}$, for ${\bf C},{\bf D}\in {\cal V}\text{-}{\bf Cat}$ is the limit of the diagram
$$
\prod_{c\in \bf C} T(c,c) \rightrightarrows \prod_{c,c'\in\bf C} T(c,c')^{{\bf C}(c,c')}
$$
where $X^V$ denotes the power of an object of $\bf D$ with an object of $\cal V$.
Obviously, this characterization works only when these powers exist, but this is a rather mild condition. Coends in enriched setting are defined and used in [Gra80, §2.3] and [Dub70]: I warmly invite you to use these as references.
Thanks again for your patience in reading my paper!


text:
Q: DialogFragment not recognizing finish() method Hello ultimately what I am looking to do is to have a DialogFragment show on screen to confirm that the user wants to exit the app. If the user says that they do wish to close the app the app shuts down. If the user does not the DialogFragment goes away.
I have seen the finish() method called in the onClick method. However this does not work for me.
exitDialog.setPositiveButton("Shutdown", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            //Exit the app.
           finish();
        }
    });

The error that I get is that "finish()" cannot be resolved. I am wondering if the issue has to do with the fact that I am using finish() in a DialogFragment class? Or is it something else?
Thanks

A: Fragments don't have finish(). You probably want to finish the whole activity:
getActivity().finish()

A: finish() is a method that belongs to the Activity.
Try using :
getActivity().finish();

A: You can use :

*

*getDialog().dismiss();  to close the dialog

*getActivity().finish(); to finish the current Activity.


text:
Q: Round up prices to end with 99p My table name is products and i am trying to update products_price so all prices have 99p at the end.  Can you help?
Also this request is a bit simpler (i'm new to SQL!) I want to update all records as follows
anything in  categories where parent_id is >0 I need the script to update all records to zero.

A: Q1
So, you want all prices to be truncated and then add 0.99 currency units.  The function to truncate a value to 0 decimal places varies between DBMS; I'm assuming it is called TRUNC, but it might be called FLOOR or something else in your DBMS:
UPDATE Products
   SET Products_Price = TRUNC(Products_Price) + 0.99;

You don't need a WHERE clause here.  I'm assuming there are no negative prices; if that's a possibility, then you need to be a little cleverer with your assignment (maybe a CASE expression; maybe you have a function SIGN, SIGN, SIGNUM available).
Note that I'm assuming that the p referenced is pence, as in 'pounds (Sterling) and pence'.  If the price was between £0.00 and £0.99, the result will be £0.99; if the price was between £1.00 and £1.99, the result will be £1.99; etc. The TRUNC or FLOOR will remove any fractional part from the price, and the addition of 0.99 then means that the result is of the form £x.99 for (non-negative) integer values of x.
Q2
Making some assumptions about what you meant:
UPDATE Categories
   SET Anything = 0
 WHERE Anything > 0
   AND Parent_ID > 0;

If you meant that you want to update the products table in some way, then you need to be a lot more precise in your question.

Q2 revisited
From a comment:

I want to update all parent_id values in my categories table to zero where parent_id > 0.

Presumably, there must be some parent_id values which are null or negative, so you need:
UPDATE Categories
   SET Parent_ID = 0
 WHERE Parent_ID > 0

If there are no nulls and no negatives, then you can run an even simpler update:
UPDATE Categories
   SET Parent_ID = 0

It will set to zero those rows which already have a parent ID of zero as well as those that do not.  This might hit the logs a bit harder than the more selective update (as in, there will be more changes to record in the logical log or equivalent for your DBMS), but unless there are vast numbers of records and most of them already have a zero parent ID and the DBMS does not recognize when a record does not change and writes log records for unchanged rows, then you're unlikely to notice the difference

A: Set price to have 99p at end:
update products_price set price = floor(price)+0.99;

Set parent_id to 0:
update categories set parent_id = 0 where parent_id > 0;


text:
Q: How to display sqlite database in the form of cards in android? This is my code how i store the data in sqlite database.Now i want that all the data from the database display in the form of cards in other activity suppose when i press showdb button then the data displayed.
public class ConfigureNode extends AppCompatActivity implements
        LocationListener,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

    private static final String TAG = "LocationActivity";
    private static final long INTERVAL = 1000 * 10;
    private static final long FASTEST_INTERVAL = 1000 * 5;
    private SQLiteDatabase db;
    Button btnFusedLocation, btnPushData;
    TextView tvLocation;
    EditText Latval, LongVal,NodeId;
    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    Location mCurrentLocation;
    String mLastUpdateTime;
    public String DBPath;
    public static String DBName = "sample";
    public static final int version = '1';
    public static Context currentContext;

    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        createDatabase();
        Log.d(TAG, "onCreate ...............................");
        //show error dialog if GoolglePlayServices not available
        if (!isGooglePlayServicesAvailable()) {
            finish();
        }
        createLocationRequest();
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

        setContentView(R.layout.activity_configure_node);
        tvLocation = (TextView) findViewById(R.id.tvLocation);

        btnFusedLocation = (Button) findViewById(R.id.btnShowLocation);
        Latval = (EditText) findViewById(R.id.latVal);
        LongVal = (EditText) findViewById(R.id.longVal);
        NodeId=(EditText)findViewById(R.id.NodeId);
        btnPushData = (Button) findViewById(R.id.btnPushLoc);
        btnPushData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                insertIntoDB();
            }
        });
        btnFusedLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateUI();
            }

        });

    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "onStart fired ..............");
        mGoogleApiClient.connect();
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "onStop fired ..............");
        mGoogleApiClient.disconnect();
        Log.d(TAG, "isConnected ...............: " + mGoogleApiClient.isConnected());
    }

    private boolean isGooglePlayServicesAvailable() {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (ConnectionResult.SUCCESS == status) {
            return true;
        } else {
            GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
            return false;
        }
    }

    @Override
    public void onConnected(Bundle bundle) {
        Log.d(TAG, "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected());
        startLocationUpdates();
    }

    protected void startLocationUpdates() {
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) this);
        Log.d(TAG, "Location update started ..............: ");
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.d(TAG, "Connection failed: " + connectionResult.toString());
    }

    @Override
    public void onLocationChanged(Location location) {
        Log.d(TAG, "Firing onLocationChanged..............................................");
        mCurrentLocation = location;
        mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
        updateUI();
    }

    private void updateUI() {
        Log.d(TAG, "UI update initiated .............");
        if (null != mCurrentLocation) {
            String lat = String.valueOf(mCurrentLocation.getLatitude());
            String lng = String.valueOf(mCurrentLocation.getLongitude());
            tvLocation.setText("At Time: " + mLastUpdateTime + "\n" +
                    "Latitude: " + lat + "\n" +
                    "Longitude: " + lng + "\n" +
                    "Accuracy: " + mCurrentLocation.getAccuracy() + "\n" +
                    "Provider: " + mCurrentLocation.getProvider());
            LongVal.setText(lng);
            Latval.setText(lat);
        } else {
            Toast.makeText(ConfigureNode.this,"location not detected ",Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopLocationUpdates();
    }

    protected void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(
                mGoogleApiClient, (LocationListener) this);
        Log.d(TAG, "Location update stopped .......................");
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mGoogleApiClient.isConnected()) {
            startLocationUpdates();
            Log.d(TAG, "Location update resumed .....................");
        }
    }
    protected void createDatabase(){
        db=openOrCreateDatabase("PersonDB", Context.MODE_PRIVATE, null);
        db.execSQL("CREATE TABLE IF NOT EXISTS persons(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name VARCHAR,address VARCHAR,NodeId VARCHAR);");
    }

    protected void insertIntoDB(){
        String name = Latval.getText().toString().trim();
        String add = LongVal.getText().toString().trim();
        String Nodid=NodeId.getText().toString().trim();
        if(name.equals("") || add.equals("")||Nodid.equals("")){
            Toast.makeText(getApplicationContext(),"Please fill all fields", Toast.LENGTH_LONG).show();
            return;
        }

        String query = "INSERT INTO persons (name,address,NodeId) VALUES('"+name+"', '"+add+"', '"+Nodid+"');";
        db.execSQL(query);
        Toast.makeText(getApplicationContext(),"Saved Successfully", Toast.LENGTH_LONG).show();
    }

}

A: From what I can see you have added data to your database. You now need to retrieve data from your database via a query.
Imagine I was storing a bunch of templates in a database, and then want to display all of these in cards or a list.
What I tend to do is create an object, such as Template.java. This object will have getter and setter methods.
I then perform a query on the database fetching all data in there and assigning each one to these Template objects.
I can then create a custom list view for example to display them in a list of cards. To create this custom list I give it an array of all the Template objects I have fetched from the database and in this custom adapter class set the values and styling.
Here are some coding examples:
Fetching from database and creating custom list:
public void populateListView() {
        templates.clear();
        final String query = "SELECT * FROM tableTemplates ";
        Cursor c1 = db.selectQuery(query);
        if (c1 != null && c1.getCount() != 0) {
            if (c1.moveToFirst()) {
                do {
                    template = new Template();
                    template.setTemplateName(c1.getString(c1
                            .getColumnIndex("templateName")));
                    template.setBuildingNumber(c1.getString(c1
                            .getColumnIndex("buildingNumber")));
                    template.setGroupNumber(c1.getString(c1
                            .getColumnIndex("groupNumber")));
                    template.setRemote(c1.getString(c1
                            .getColumnIndex("remote")));
                    template.setFrequency(c1.getString(c1
                            .getColumnIndex("frequency")));
                    templates.add(template);

                } while (c1.moveToNext());
            }
        }
        c1.close();

        adapter = new TemplateCustomAdapter(
                getApplicationContext(), templates);
        presetList.setAdapter(adapter);

        adapter.notifyDataSetChanged();
    }

The custom list adapter:
public class TemplateCustomAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<Template> templateList;

    public TemplateCustomAdapter(Context context, ArrayList<Template> list) {
        this.context = context;
        templateList = list;
    }

    @Override
    public int getCount() {

        return templateList.size();
    }

    @Override
    public Object getItem(int position) {

        return templateList.get(position);
    }

    @Override
    public long getItemId(int position) {

        return position;
    }

    /**
     * Here we inflate our layout with the view row xml file.
     * What the file does is set the look of each row of the list view.
     * */
    @Override
    public View getView(int position, View convertView, ViewGroup arg2) {
        final Template template = templateList.get(position);

        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.view_row, null);
        }

        /**
         * Set the layout components with the object variable and return to the activity/fragment.
         * */
        final TextView templateName = (TextView) convertView.findViewById(R.id.name);
        templateName.setText(template.getTemplateName());

        return convertView;
    }

}

This may help with the list adapter


text:
Q: Job Scheduler doesn't work if app is killed I have looked at many other threads on this. However, none of this seems to help.
I need to set up job scheduler that runs everyday at 3PM.
Here is my service class:
public class AttendanceCheckScheduler extends JobService {
    private AttendanceCheckTask mAttendanceCheckTask;

    private static final String TAG = "AttendanceCheckScheduler";

    @Override
    public boolean onStartJob(JobParameters params) {

        mAttendanceCheckTask = new AttendanceCheckTask();
        mAttendanceCheckTask.execute();
        jobFinished(params, false);
        return true;
    }

    @Override
    public boolean onStopJob(JobParameters params) {

        mAttendanceCheckTask.cancel(true);
        return false;
    }

    private class AttendanceCheckTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            // some long running task...
            Toast.makeText(getApplicationContext(), "Task run", Toast.LENGTH_SHORT).show();

            return null;
        }

        @Override
        protected void onPostExecute(Void s) {
            super.onPostExecute(s);
        }
    }
}

And this is how I am scheduling the job in ActivityHome.
public class ActivityHome extends AppCompatActivity {

    private static final int JOB_ID = 100;
    private JobScheduler jobScheduler;
    protected JobInfo jobInfo;

    private static final String TAG = "ActivityHome";

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

        // other irrelevant codes here...

        ComponentName componentName = new ComponentName(this, AttendanceCheckScheduler.class);
        JobInfo.Builder builder = new JobInfo.Builder(JOB_ID, componentName);

        builder.setPeriodic(5000); // every 5 seconds for testing purpose...
        builder.setPersisted(true);

        jobInfo = builder.build();

        jobScheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
        jobScheduler.schedule(jobInfo);

        Toast.makeText(this, "job scheduled", Toast.LENGTH_LONG).show();
    }
}

Everythings seems to work fine and I am receiving the toast message Task run every 5 seconds as set above.
But when the app is killed (by clearing all task in multitask window), I stop receiving the toast messages.
How do I keep it running even if the app is killed ?
P.S: I want some task to perform once everyday at 3PM.

A: For background task for long time when your app is killed, you need to implement AlarmManager or WorkManager. WorkManager was in beta but now its ready only for Android X, just implement the dependency and copy paste WorkManager class code from google and put your task.
WorkManager latest dependency:
 implementation "androidx.work:work-runtime:2.2.0"

A: I found this article. Here it says you have to call jobFinished() in your onPostExecute method of the asyncTask to let the system know the job is done.

jobFinished() requires two parameters: the current job, so that it
  knows which wakelock can be released, and a boolean indicating whether
  you'd like to reschedule the job. If you pass in true, this will kick
  off the JobScheduler's exponential backoff logic for you

I hope it helps.
Scheduling jobs like a pro with JobScheduler

A: There is an option not to kill the application, but it is very rude and it's the hack:
In your Manifest -> inside activity tag -> Add following line
android:excludeFromRecents="true"

Your app not show in recent apps history. So user can't kill the app.
Information is obtained by reference: https://code-examples.net/en/q/26c6cf8


text:
Q: Facebook: Get facebook messages for specific Date? I wanted to get facebook's messages not Feeds. I've searched about it but did not find the solution.
I have also looked into FQL for the same but didn't find any useful things.
Is it possible to get messages from facebook with specific date ? OR just messages ?

A: It's possible you get lastest facebook messages on top of thread(conversation session) by specific time with fql API, such as
SELECT snippet, recent_authors, updated_time FROM thread WHERE folder_id = 0 AND updated_time=1364564697

Also, it's possible you get facebook message by specific time with API within thread. Such as
SELECT body, created_time FROM message WHERE thread_id=1774741570083 AND created_time=1348806942

For your question. Yes. It's possible get facebook message from ALL
  inbox messages by specific DATE(by DATE, not by TIME, as your
  request). Example, get all inbox messages from "Thu Aug 23 2012
  00:00:00 GMT+0800 (MYT)" to "Fri Aug 24 2012 00:00:00 GMT+0800
  (MYT)"

SELECT body, created_time FROM message WHERE thread_id IN (SELECT thread_id FROM thread WHERE folder_id = 0) AND (created_time>=1345651200 AND created_time<1345737600)

Update:
To retrieve sender name and profile photo, you can do

{"query1":"SELECT author_id, body, created_time FROM message WHERE thread_id IN (SELECT thread_id FROM thread WHERE folder_id = 0) AND (created_time>=1345651200 AND created_time<1345737600)","query2":"SELECT id, name, pic_square FROM profile WHERE id IN (SELECT author_id FROM #query1)"}

Update:
  HTTP GET request example, quote the fql query, append to
https://graph.facebook.com/fql?format=json&q=
After that, append &access_token=YOUR_USER_ACCESS_TOKEN at the end:
https://graph.facebook.com/fql?format=json&q=%7B%22query1%22%3A%22SELECT+author_id%2C+body%2C+created_time+FROM+message+WHERE+thread_id+IN+%28SELECT+thread_id+FROM+thread+WHERE+folder_id+%3D+0%29+AND+%28created_time%3E%3D1345651200+AND+created_time%3C1345737600%29%22%2C%22query2%22%3A%22SELECT+id%2C+name%2C+pic_square+FROM+profile+WHERE+id+IN+%28SELECT+author_id+FROM+%23query1%29%22%7D&access_token=ACCESS_TOKEN


text:
Q: Python multivalue list to script I have some scripts that make symbology for different layers in my TOC.
And now I want to merge them into one big script which should have parameters chosen by user to start certain part of script.
For instance I have three layers: GGG, DDD, DDA. The whole script contains code to make symbology for all these layers.
But is it possible to make something like this?

If box "DDD" is checked script run the part of it which will paint only DDD layer.
If it is possible what kind of code I should add to script?
Updated code:
for s in selected:
    if selected == "DDD":
        arcpy.AddMessage("Making a DDD")
        ary = arcpy.mapping.Layer(r"\\SRV-NAS-03\Projects\FIAS_MultiPART.lyr")
        arcpy.mapping.AddLayer (df,ary,"AUTO_ARRANGE")

arcpy.RefreshActiveView()
arcpy.RefreshTOC()

It is taken from this answer to Unable to Provide Input for a MultiValue Parameter Script Tool

A: You can retrieve the values checked in the inputdata parameter using this code:
import arcpy
all_selected = arcpy.GetParameterAsText(0)
selected = all_selected.split(";")

for s in selected:
    if s == "DDD":
        arcpy.AddMessage("Making a DDD")
    # ...

See Setting script tool parameters for reference.


text:
Q: Finding Common Tangent of two circles
It seems like easy question, I know all radii are equal in length but I still didn't manage to find BC, any help?

A: Hint:
Consider the height and the hypotenuse of the right triangle.

A: Consider the triangle $MNO$ with $O$ being the orthogonal projection of $N$ on the segment $[MC]$.
The length of $MC$ is $8$ centimeters. The length of $CO$ is $5$ centimeters.
Therefore the length of $OM$ is $3$ centimeters. Also, you know the length $$MN = MA + AN = 8 + 5$$
Now with the hypotenuse law, you can find that \begin{align}MN^2 &= MO^2 + ON^2 \\ 3^2 + x^2 &= (8+5)^2\end{align}

A: When two circlesof radii $r_1$ and $r_2$  touch each other externally then by pythagorous theorem the length of direc common tangent is given by $T^2+(r_1-r_2)^2=(r_1+r_2)^2$
$$BC=T=\sqrt{(8+5)^2-(8-5)^2}= 2 \sqrt{8\times 5}=4\sqrt{10}$$


text:
Q: How do we check whether element with MinOccurs = 0 returned? I have an xml schema from a third party web service provider.
<xsd:element name="Student">
<xs:sequence>
    <xs:element name="Name" type="xs:string" minOccurs="1"/>
    <xs:element name="Address" type="xs:string" minOccurs="0"/>
    <xs:element name="Gender" type="xs:string" minOccurs="1"/>
</xs:sequence>
</xsd:element>

I am going to consume the dataset returns from this web service in my C# code. Since Address has the minOccurs set to 0, it means the web service can either return value for Address or not returning Address. For example:
Scenario 1:
<Student>
 <Name>Eddie</Name>
 <Gender>Male</Gender>
</Student>

Scenario 2:
<Student>
 <Name>Alice</Name>
 <Address>White House</Address>
 <Gender>Female</Gender>
</Student>

Scenario 3:
<Student>
 <Name>Jenny</Name>
 <Address></Address>
 <Gender>Female</Gender>
</Student>

May I know how do I check, in my C# code whether the web service return Address.
For result set from Scenario 1, I would like to hide the contact Section from my form all together.
For result set from Scenario 2, I would like to display the contact Section on my form, and have the address display.
For result set from Scenario 3, I would like to display the contact Section on my form, but have the Address field in the contact section set to "Address not provided".
May I know could I achieve that?
I know we can check whether the elements hasvalue or isnull. But how do we check whether the result returned by the web service contains the element (Scenario 1)?

A: After some research and testing done, I think I can have something like this:
bool ShowContactFlag = false;
if (Dataset.Tables[0].Columns.Contains("Address"))
{
   ShowContactFlag = true;
}
else
{
   ShowContactFlag = false;
}


text:
Q: Problem running twisted.words example using msn protocol I am currently trying to use the Twisted library specifically twisted words to try and interat with MSN. However when i run the sample script provided by twisted , i get an error. Specifically the error is found here http://i42.tinypic.com/wl945w.jpg . The script can be found over here http://twistedmatrix.com/projects/words/documentation/examples/msn_example.py.
Platform is Vista with Python 2.6
EDIT: Full output:
Email (passport): mypassport@hotmail.com
Password: ******
2009-04-25 10:52:49-0300 [-] Log opened.
2009-04-25 10:52:49-0300 [-] Starting factory <twisted.internet.protocol.ClientFactory instance at 0x9d87e8c>
2009-04-25 10:52:55-0300 [Dispatch,client] Starting factory <twisted.words.protocols.msn.NotificationFactory instance at 0x9e28bcc>
2009-04-25 10:52:55-0300 [Dispatch,client] Stopping factory <twisted.internet.protocol.ClientFactory instance at 0x9d87e8c>
2009-04-25 10:52:55-0300 [Notification,client] Unhandled Error
    Traceback (most recent call last):
      File "/usr/local/lib/python2.5/site-packages/twisted/python/log.py", line 84, in callWithLogger
        return callWithContext({"system": lp}, func, *args, **kw)
      File "/usr/local/lib/python2.5/site-packages/twisted/python/log.py", line 69, in callWithContext
        return context.call({ILogContext: newCtx}, func, *args, **kw)
      File "/usr/local/lib/python2.5/site-packages/twisted/python/context.py", line 59, in callWithContext
        return self.currentContext().callWithContext(ctx, func, *args, **kw)
      File "/usr/local/lib/python2.5/site-packages/twisted/python/context.py", line 37, in callWithContext
        return func(*args,**kw)
    --- <exception caught here> ---
      File "/usr/local/lib/python2.5/site-packages/twisted/internet/selectreactor.py", line 146, in _doReadOrWrite
        why = getattr(selectable, method)()
      File "/usr/local/lib/python2.5/site-packages/twisted/internet/tcp.py", line 460, in doRead
        return self.protocol.dataReceived(data)
      File "/usr/local/lib/python2.5/site-packages/twisted/protocols/basic.py", line 238, in dataReceived
        why = self.lineReceived(line)
      File "/usr/local/lib/python2.5/site-packages/twisted/words/protocols/msn.py", line 651, in lineReceived
        handler(params.split())
      File "/usr/local/lib/python2.5/site-packages/twisted/words/protocols/msn.py", line 827, in handle_USR
        d = _login(f.userHandle, f.password, f.passportServer, authData=params[3])
      File "/usr/local/lib/python2.5/site-packages/twisted/words/protocols/msn.py", line 182, in _login
        reactor.connectSSL(_parsePrimitiveHost(nexusServer)[0], 443, fac, ClientContextFactory())
    exceptions.TypeError: 'NoneType' object is not callable

2009-04-25 10:52:55-0300 [Notification,client] Stopping factory <twisted.words.protocols.msn.NotificationFactory instance at 0x9e28bcc>

A: Since MSN involves SSL connections, you must have pyOpenSSL installed in order to use it.  It seems as though you probably do not.  This isn't a very good way for Twisted to be reporting this missing dependency, though.  I recommend filing a ticket in the Twisted issue tracker for improving this reporting.

A: What happened
This exception you get is when you try to call an object that is None. Check this out :
>>> a = str
>>> a() # it's ok, a string is a callable class
''
>>> a = None
>>> a() # it fails, None a special Singleton not meant to be called

Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    a()
TypeError: 'NoneType' object is not callable

What you can do
You can't guess it like that, so you'll need to make some debugging.
Apparently, the last line (refactor.connectSSL...) contains three object calls, and one of the object is None.
The first thing you can do, if you are not into debuggers, if to take each element of the line and add, just before it :
assert object1 is None
assert object2 is None

Then you'll have the source of your Exception. After that, check why is this object set to None. You'll probably have to check the doc to see in which case some method that may have initilized it returns None.
May the force...


text:
Q: Editor on TabbedPage on Lenovo tablet does not show all text I have created a simple test app using Xamarin.Forms v. 2.3.4.247 (but the problem is on the newest version of Xamarin.Forms as well) as shown below.
But when I fill the Editor with multiple lines like
This
is
a
test.
This
is
a
test.

On my Lenovo Tablet. If I then tap on the 1st visible line, Only the 1st line is visible, and I cannot scroll down to see more of the Editor.
An example is shown on this picture

The code for the test app
<?xml version="1.0" encoding="utf-8" ?>
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
      xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
      xmlns:local="clr-namespace:TestApp"
      x:Class="TestApp.MainPage">

   <ContentPage Title="Test">
      <Grid ColumnSpacing="0" RowSpacing="0">
         <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
         </Grid.RowDefinitions>
         <Label Text="Title" Grid.Row="0" />
         <ScrollView Grid.Row="1">
            <StackLayout Padding="10,0,10,10" Orientation="Vertical">
               <Label Text="Test" />
               <Button Text="Choose a project" />
               <Label Text="Project description" />
               <Label Text="Date" />
               <DatePicker />
               <Label Text="Employee" />
               <Picker>
                  <Picker.Items>
                     Test
                  </Picker.Items>
               </Picker>
               <Label Text="Payment-type" />
               <Picker />
               <Label Text="Amount" />
               <Entry />
               <Entry />
               <Label Text="Description" />
               <Editor MinimumHeightRequest="150" HeightRequest="150"  VerticalOptions="FillAndExpand" />
               <Button />
            </StackLayout>
         </ScrollView>
      </Grid>
   </ContentPage>
</TabbedPage>

I have only attached the xaml-code, as the C# code only have InitializeComponent
How can I make it possible for the user to scroll in all the text?

A:
If I then tap on the 1st visible line, Only the 1st line is visible, and I cannot scroll down to see more of the Editor.

You put your Editor in ScrollView, that's why you can't scroll the Editor. In your situation, when you try scroll the Editor, it will generate an touch event in system, but both Editor and ScrollView want get this event so that they could scroll. And finally we could see from the effect, the ScrollView intercept this touch events so your Editor can't receive this touch event. As a result, ScrollView could scroll but your Editor can't.
You could use Custom Renderers to handle with this event conflict in native platform. For example, in Android, you could use RequestDisallowInterceptTouchEvent to tell ScrollView do not intercept this touch events :

Called when a child does not want this parent and its ancestors to intercept touch events with onInterceptTouchEvent(MotionEvent).
This parent should pass this call onto its parents. This parent must obey this request for the duration of the touch (that is, only clear the flag after this parent has received an up or a cancel.

Here is my code and it works fine on my side :
Change your Editor to :
<local:MyEditor MinimumHeightRequest="150" HeightRequest="150" />

MyEditor :
public class MyEditor : Editor
{
}

MyEditorRenderer for Android :
public class MyEditorRenderer : EditorRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<Editor> e)
    {
        base.OnElementChanged(e);
    }

    public override bool DispatchTouchEvent(MotionEvent e)
    {
        switch (e.Action)
        {
            case MotionEventActions.Down:
                //Parent.Parent.Parent ==> ScrollViewRenderer
                Parent.Parent.Parent.RequestDisallowInterceptTouchEvent(true);
                //need to handle this touch event
                break;
            case MotionEventActions.Move:
                //Parent.Parent.Parent ==> ScrollViewRenderer
                Parent.Parent.Parent.RequestDisallowInterceptTouchEvent(true);
                break;
            case MotionEventActions.Up:
                break;
            default:
                break;
        }
        return base.DispatchTouchEvent(e);
    }
}

EDIT :


text:
Q: Swift 3 Garbage at End I am trying to receive info from my server but I keep getting the error telling me that there is Garbage at the end. It could be that the file being passed from the server has HTTP info as well but I do not know how to get rid of it. Here is my code:
class ViewController: UIViewController {

//URL to our web service
let URL_SAVE_TEAM = "http://<IP Address>/WebServerTest/api/createteam.php"

//TextFields declarations
@IBOutlet weak var textFieldName: UITextField!
@IBOutlet weak var textFieldMember: UITextField!

//Button action method
@IBAction func buttonSave(sender: UIButton) {

    //created NSURL
    let requestURL = NSURL(string: URL_SAVE_TEAM)

    //creating NSMutableURLRequest
    let request = NSMutableURLRequest(url: requestURL! as URL)

    //setting the method to post
    request.httpMethod = "POST"

    //getting values from text fields
    let teamName=textFieldName.text
    let memberCount = textFieldMember.text

    //creating the post parameter by concatenating the keys and values from text field
    let postParameters = "name="+teamName!+"&member="+memberCount!;

    //adding the parameters to request body
    request.httpBody = postParameters.data(using: String.Encoding.utf8);

    //creating a task to send the post request
    let task = URLSession.shared.dataTask(with: request as URLRequest){
        data, response, error in

        if error != nil{
            print("error is \(error)")
            return;
        }

        //parsing the response
        do {
            //converting resonse to NSDictionary
            let myJSON =  try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.allowFragments) as? NSDictionary

            //parsing the json
            if let parseJSON = myJSON {

                //creating a string
                var msg : String!

                //getting the json response
                msg = parseJSON["message"] as! String?

                //printing the response
                print(msg)

            }
        } catch {
            print(error)
        }

    }
    //executing the task
    task.resume()

}

I am unable to see the issue.


text:
Q: How can you sort an array in Ruby starting at a specific letter, say letter f? I have a text array.
text_array = ["bob", "alice", "dave", "carol", "frank", "eve", "jordan", "isaac", "harry", "george"]

text_array = text_array.sort would give us a sorted array.
However, I want a sorted array with f as the first letter for our order, and e as the last.
So the end result should be...
text_array = ["frank", "george", "harry", "isaac", "jordan", "alice", "bob", "carol", "dave", "eve"]

What would be the best way to accomplish this?

A: Try this:
result = (text_array.select{ |v| v =~ /^[f-z]/ }.sort + text_array.select{ |v| v =~ /^[a-e]/ }.sort).flatten

It's not the prettiest but it will get the job done.
Edit per comment. Making a more general piece of code:
before = []
after = []
text_array.sort.each do |t|
  if t > term
    after << t
  else
    before << t
  end
end
return (after + before).flatten

This code assumes that term is whatever you want to divide the array. And if an array value equals term, it will be at the end.

A: You can do that using a hash:
alpha = ('a'..'z').to_a
  #=> ["a", "b", "c",..."x", "y", "z"]
reordered = alpha.rotate(5)
  #=> ["f", "g",..."z", "a",...,"e"]
h = reordered.zip(alpha).to_h
  # => {"f"=>"a", "g"=>"b",..., "z"=>"u", "a"=>"v",..., e"=>"z"}

text_array.sort_by { |w| w.gsub(/./,h) }
  #=> ["frank", "george", "harry", "isaac", "jordan",
  #   "alice", "bob", "carol", "dave", "eve"]

A variant of this is:
a_to_z = alpha.join
  #=> "abcdefghijklmnopqrstuvwxyz"
f_to_e = reordered.join
  #=> "fghijklmnopqrstuvwxyzabcde"

text_array.sort_by { |w| w.tr(f_to_e, a_to_z) }
  #=> ["frank", "george", "harry", "isaac", "jordan",
  #   "alice", "bob", "carol", "dave", "eve"]

A: I think the easiest would be to rotate the sorted array:
text_array.rotate(offset) if offset = text_array.find_index { |e| e.size > 0 and e[0] == 'f' }

A: Combining Ryan K's answer and my previous answer, this is a one-liner you can use without any regex:
text_array = text_array.sort!.select {|x| x.first >= "f"} + text_array.select {|x| x.first < "f"}

A: If I got your question right, it looks like you want to create sorted list with biased predefined patterns.
ie. let's say you want to define specific pattern of text which can completely change the sorting sequence for the array element.
Here is my proposal, you can get better code out of this, but my tired brain got it for now -
an_array = ["bob", "alice", "dave", "carol", "frank", "eve", "jordan", "isaac", "harry", "george"]

# Define your patterns with scores so that the sorting result can vary  accordingly
# It's full fledged Regex so you can put any kind of regex you want.
patterns = {
  /^f/ => 100,
  /^e/ => -100,
  /^g/ => 60,
  /^j/ => 40
}

# Sort the array with our preferred sequence
sorted_array = an_array.sort do |left, right|
  # Find score for the left string
  left_score = patterns.find{ |p, s| left.match(p) }
  left_score = left_score ? left_score.last : 0

  # Find the score for the right string
  right_score = patterns.find{ |p, s| right.match(p) }
  right_score = right_score ? right_score.last : 0

  # Create the comparision score to prepare the right order
  # 1 means replace with right and -1 means replace with left
  # and 0 means remain unchanged
  score = if right_score > left_score
    1
  elsif left_score > right_score
    -1
  else
    0
  end

  # For debugging purpose, I added few verbose data
  puts "L#{left_score}, R:#{right_score}: #{left}, #{right} => #{score}"

  score
end

# Original array
puts an_array.join(', ')

# Biased array
puts sorted_array.join(', ')


text:
Q: How does Google Docs manage to get paste on click to work? I would like to implement a paste-on-click function, similar to that found in Google Docs.
I can get paste to work when initiated by the user via the context menu, or via a keyboard shortcut (using the onpaste event and friends), but I am unable to work out how to get a paste-on-click style actuation to cause the contents of the system clipboard to get pasted - and, from what I've read, this shouldn't actually be possible!
Does anybody have any clue as to how Google is making this work? :-)

A: Did you read this article that seems to explain clipboard access with the different browsers? Google Docs and Clipboard Access

A: I know this isn't actually a solution, but more of a workaround. But maybe you'll find it worthy and would suit your needs.
Wouldn't be possible to emulate the key press for [Ctrl]+[V]? It will work on most browsers and OSes, but always keep in mind these keys can be changed at OS level anytime.
Any solution more than this kind of workaround may be too cumbersome for your script some times, and there are times when you just don't want to have too many events/listeners.