text:
Q: A well-defined operation on measure algebra Let $(X,\cal{M},\mu)$ be a measure space, and for $E,F\in \cal{M}$  write $E \sim F$ iff $\mu(E \Delta F)=0$. Let $\widetilde{\cal{M}}$ be the set of equivalence classes in $\cal{M}$ for $\sim$; for $E\in \cal{M}$, write $E^{•}\in\widetilde{\cal{M}}$ for
its equivalence class.there is a partial ordering $\subset$ on $\widetilde{\cal{M}}$ defined by saying that, for $E, F\in\cal{M}$ ,
$E^{•}\subset F^{•} \Longleftrightarrow \mu(E\setminusF)=0$
operations $\bigcap,\bigcup,\setminus$ on $\widetilde{\cal{M}}$ defined by saying that
$E^{•}\bigcap F^{•}=(E\bigcap F)^{•}$
$E^{•}\bigcup F^{•}=(E\bigcup F)^{•}$
$E^{•}\setminus F^{•}=(E\setminus F)^{•}$
What does it mean These operation on $\widetilde{\cal{M}}$ is well-defined?

A: Given $A,B,C,D\in \mathcal{M}$ with $A\sim B$ and $C\sim D$:
First we know $\mu(A\setminus B) = 0$ if $A\sim B$:
$$ \mu (A\triangle B) = \mu(A\setminus B\cup B\setminus A) = \mu (A\setminus B)+\mu(B\setminus A) = 0 \tag{$\square$} $$
Now we also have following rules for sets $E,F,G$:
$$ \begin{align}
E\setminus (F\cap G) &= (E\setminus F) \cap (E\setminus G)\tag{$\bullet$}\\
(E\cap F)\setminus G &= E\cap(F\setminus G) \tag{$\star$}
\end{align} $$
You have to show it this way:
$$\begin{align}
 (A\cap C )\triangle (B\cap D) &= \big[(A\cap C)\setminus(B\cap D)\big]\cup\big[(B\cap D)\setminus (A\cap C)\big] \\ &\overset{\bullet}{=} \big[(( A\cap C)\setminus B)\cap ((A\cap C)\setminus D) \big ]\cup \big[((B\cap D)\setminus A)\cap((B\cap D)\setminus C)\big] \\
&\overset{\star}{=} \underbrace{\big[(C\cap (A\setminus B)) \cap (A\cap (C\setminus D)) \big ]}_{=:\ K} \cup \underbrace{[(D\cap (B\setminus A)) \cap (B\cap (D\setminus C))\big]}_{=:\ L}\\
\end{align} $$
So we know that:
$$\mu(K) \le \mu(C\cap(A\setminus B))+\mu(A\cap(C\setminus D) \overset{\square}{=} 0$$
Same goes for $L$ so we now know:
$$ A\cap C \sim B\cap D \quad\Leftrightarrow\quad A^\bullet\cap C^\bullet = (A\cap C)^\bullet$$


text:
Q: What do we call definitions we keep using for objects whose nature has changed? Is there a name for "definitional drift," meaning a word we've used to define something in the past, but the object of definition has changed over time, yet we keep using the same word?
For example, "phone." Back in the 80s, we had phones that were connected to walls with cords. Phones were...well, phones.
Now, we call the device we carry a "phone," even though it's barely a phone. It's primarily designed to a million things other than make phone calls, and if we list the things we do it by frequency, making or taking a phone call would likely be near the bottom of the list.
This is clearly a thing that happens. Is there a name for it?  Can you think of other classic examples of it?
Edit: another example is when we record video on our phone (ha!), we often say we "taped it," or we "have it on tape." But magnetic tape has nothing to do with it anymore.

A: It's a form of semantic drift.

Semantic change (also semantic shift, semantic progression, semantic development, or semantic drift) is the evolution of word usage—usually to the point that the modern meaning is radically different from the original usage.
  - wikipedia

In Blank's typology, the semantic drift of phone, for example, looks like it's based on

Metonymy: Change based on contiguity between concepts, e.g., horn "animal horn" → "musical instrument".
  - ibid

The meaning of the word "phone" has changed because each stage of the development from voice-call phones to smart phones has retained enough similarity to the previous stage for the name to be broadly recognisable and associated with the new device.

redpajama_set_name: RedPajamaStackExchange


text:
Q: wsasend lpnumberofbytesSent I am using wsasend on an IOCP structured server.
There is one problem.
wsabuf [bufcount - 1] .buf = pPacket-> GetPacketBufferPtr ();
wsabuf [bufcount - 1] .len = (int) pPacket-> Get_PacketSize ();
iSendSize + = wsabuf [bufcount - 1] .len;
bufcount ++;
int retval = WSASend (pSession-> socket, wsabuf, bufcount-1, & sendbytes,flag, & pSession-> overlapped_Send, NULL);
if (retval == SOCKET_ERROR)
{

    if (WSAGetLastError ()! = WSA_IO_PENDING)
    {
      ......
    }
}
if (retval == 0)
{
    if (sendbytes! = iSendSize)
    {
       ........
    }
}
.....

In the code above, I save the packet to send to wsabuf and I send it through wsasend.
And finally, I compared sendbytes and iSendSize .
By the way, sendbytes and iSendSize are Different.
I do not know why.

A: the actual number of transferred bytes returned from driver, only when operation is completed. io subsystem copy this value to IO_STATUS_BLOCK.Information transmitted to io operation. as result user get back this value. but of course only after operation is completed.
win32 api use OVERLAPPED in place IO_STATUS_BLOCK - reinterpret cast OVERLAPPED to IO_STATUS_BLOCK and pass this pointer to kernel. so InternalHigh will be containing actual number of transferred bytes, but only after operation will be completed (in case error synchronous returned - io subsystem not fill this field, so it value undefined on error. by sense of course 0).
WSASend get value (after call to kernel) from OVERLAPPED.InternalHigh and if lpNumberOfBytesSent not 0 - copy it here. if you use synchronous socket handle - at this moment io operation already will be completed (io subsystem internal wait for this, before return to caller) and valid value from OVERLAPPED.InternalHigh will be copied to *lpNumberOfBytesSent
in code this will be look like
if (!lpOverlapped)
{
    OVERLAPPED Overlapped = {};
    lpOverlapped = &Overlapped;
}

ZwDeviceIoControlFile(.. reinterpret_cast<IO_STATUS_BLOCK*>(lpOverlapped) ..)

if (lpNumberOfBytesSent)
{
  *lpNumberOfBytesSent = (ULONG)lpOverlapped->InternalHigh;
}

in case asynchronous socket handle, operation usually yet not finished after return from kernel. as result lpOverlapped->InternalHigh yet not filled with correct numbers of bytes. and
*lpNumberOfBytesSent = (ULONG)lpOverlapped->InternalHigh;

got incorrect (undefined, if you and system not init it, say to 0) result.
conclusion - you can not use sendbytes for asynchronous io operation. what here is undefined. you can and need got this value when io is completed. how you got it already depend from how you notified about completion.

*

*if you use BindIoCompletionCallback  - you got it in
FileIOCompletionRoutine in dwNumberOfBytesTransfered
argument

*if you use CreateThreadpoolIo- you got it in
IoCompletionCallback in NumberOfBytesTransferred argument

*if you use own IOCP and  GetQueuedCompletionStatus - you got
back pointer to your lpOverlapped used in call to WSASend (or
some another io function - this is already your task determinate
where this lpOverlapped used ) after operation was completed. at
this point you can call GetOverlappedResult for this
lpOverlapped (bWait you can set to any value - does not matter because operation already completed - the api will return
immediately in any case without wait) and you got actual number of
transferred bytes in lpNumberOfBytesTransferred. however
GetOverlappedResult simply copy lpOverlapped->InternalHigh
value to *lpNumberOfBytesTransferred so you can and direct,
yourself use InternalHigh without call to GetOverlappedResult


text:
Q: change select value when press button i'm still Beginner at this
i have table and i select data between two date range using this code and its working fine for me
$StartDate = "2016-01-01";
$EndDate =  "2016-12-30";
$result = mysql_query("SELECT *FROM users where submit_date BETWEEN '$StartDate' AND '$EndDate'") or die(mysql_error());

then i added 2 data picker and button
echo "<form method=post action=>
".
"
Start Date : 	<input type=date name=StartDate value=$StartDate>
".
"
End Date : 	<input type=date name=EndDate value=$EndDate>
".
"
<input type=submit name=UpdateSelect value=Set>
".
"
</form>";

now i need help with this
how to update the page when i press the sumbit button
to start selecting from the new start date and end date.
i'm sorry for my bad english.
and thanks

A: A small demo of your problem hope will help you and solve your problem. I assume you are using mysqli connection object.

    if (isset($_POST['submit_btn']))
    {
        $start_date = $_POST['start_date'];
        $end_date   = $_POST['end_date'];
        $sql = "SELECT * FROM users where submit_date BETWEEN '$start_date' AND '$end_date'";
        $result = $conn->query($sql);
    }

    $conn->close();
?>

    <title></title>

    <form action="" method="post">

                <input type="date" name="start_date" value=""/>

                <input type="date" name="end_date" value=""/>

                <input type="submit" name="submit_btn" value="Set"/>

    </form>

    <?php
        if (isset($result) && !empty($result))
        {
            if ($result->num_rows > 0) {
                // output data of each row
                while($row = $result->fetch_assoc()) {
                    echo "id: " . $row["id"];. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "
";
                }
            } else {
                echo "0 results";
            }
        }
    ?>

The  is used for input fields that should contain a date.
Depending on browser support, a date picker can show up in the input field.


text:
Q: SQL : Split numeric string from as specific position by using commas as indicator I have two columns in my data. Column1 contains the numeric strings where digits are separated by commas and Column2 contains a number. I want to truncate the column1 by using the column2 as the position identifier for comma starting from right end of the string.

Column1
Column2
Expected_OP

0,12,38,69,96,127,159,187
2
0,12,38,69,96,127

0,0,0,0,0,0,0,0,0,0
3
0,0,0,0,0,0,0

0,0,0,0,0,0
4
0,0

A: Here's a working one, with a bit of trial-and-error:
select column1, column2, substr(column1,1,instr(column1,',',1,length(column1) - length(replace(column1,',','')) - column2 + 1) - 1) from test

db<>fiddle here
(Used postgresql) (Note, there is no error-checking with regards to invalid input (example no commas or too high number in column2)


text:
Q: Assigning OpenCV Matrix into a data structure I build a multithreaded system with OpenCV, which creates some images, assigns them into a vector and sends each image into a different thread.
This is how it looks like:
std::vector<cv::Mat> images;
for (int i = 0 ; i < 10 ; i++) {
    images.push_back(cv::Mat(/* bla bla */));
    cv::Mat& mat = images.back();
    std::thread(some_function_name, &mat)
}
// Wait here for all threads to join (didn't show its code)

It seems that when the thread gets the pointer to the Mat object, the Mat object doesn't anymore exist. Is it possible that although it was immediately assigned to the vector, it was actually destroyed when the loop ended, as it was wiped off the stack?

A: Your problem is actually the fact that you are calling push_back in the loop, which may cause reallocations. If that occurs, the underlying data will be copied, so any pointers or references will be invalidated.
To resolve this, one way would be to size the array ahead of time
std::vector<cv::Mat> images(10);
for (int i = 0 ; i < 10 ; i++) {
    images[i] = cv::Mat(/* bla bla */);
    cv::Mat& mat = images.at(i);
    std::thread(some_function_name, &mat)
}
// Wait here for all threads to join (didn't show its code)


text:
Q: JQuery stopPropagation on .live() when handlers already exist and are bound I'm aware that live calls bubble up through the doccument and that is why I'm having issues.
Unfortunately I'm using third party libraries that bind elements and would like to create a case in which a click event isn't bubbled up to those elements.
using .click() in combination with eventStopPropogation works just fine, however due to the dynamic nature of the content I need to use either live,on,delegate,etc...
Here's a fidddle of my issue. I need to prevent "outer" click from firing when clicking the "inner" div. I can not change the "outer" handler.
Thanks in advance for your help!!
http://jsfiddle.net/99zQM/2/
HTML:

    outer

        inner

Javascript:
$("#outer").bind('click',function(e){
   alert("outer clicked");
});

$("#inner").live('click',function(e){
   alert("inner clicked");
});

A: use on delegate bound to outer and call e.stopPropagation() in inner click handler..this should dothe trick.
try this
updated
$("#outer").bind('click',function(e){
  alert("outer clicked");
});

$('#outer').on('click',"#inner",function(e){
  e.stopPropagation();
  alert("inner clicked");

});

updated fiddle here

A: As you've already remarked, event delegation hinges on event bubbling and the use of a static element. The issue is complicated because there's nothing between the
 and
 elements, but we can get around that.
Set up a dynamic event handler for click events on the #inner element that's bound to #outer, and call event.stopImmediatePropagation() to prevent other event handlers from being executed. The downside is that this is dependent on the order in which the event handlers are bound, so your delegated event handler for #inner has to be bound before your static event handler for #outer.
$('#outer').on('click', '#inner', function(e) {
    console.log('inner');
    e.stopImmediatePropagation();
}).click(function(e) {
    console.log('outer');
});

Take a look at this jsFiddle demo.

A: U can use
$("#outer").bind('click',function(e){
   alert("outer clicked");
});
$('#outer').on('click',"#inner",function(e){
    e.stopImmediatePropagation();
    alert("inner clicked");

});


text:
Q: ¿Qué tipos de nested browsing context existen? Estaba leyendo la documentación para <object> y vi que representa un recurso externo, que puede ser una imagen, un nested browsing context, o un recurso a ser gestionado por un plugin.
Yendo un poco más lejos, he visto que una ventana o pestaña de navegador contiene un browsing context, así como un <iframe> o un <frameset>, y que un anidamiento (nesting) puede tener varias capas de profundidad.
Lo que no me queda claro es ¿qué tipos de nested browsing contexts podemos poner dentro de un object?  Imágenes y plugins, ok, pero non capisco que otros contextos pueden existir...

A: Puede que esté equivocado, pero creo que (salvo excepciones) las imágenes y los plugins no se considerarían nested browsing contexts (contextos de navegación anidados) porque no tendrían contexto propio.
Algunos ejemplos de contenido que puedes poner el el data de un elemento object y con los que se crearía un contexto anidado:

*

*Un archivo HTML (estático). Ej:
<object data="mipagina.html"></object>

*Un archivo de un lenguaje de script (dinámico). Ej:
<object data="mipagina.php"></object>

*Una URL. Ej:
<object data="http://www.alvaromontoro.com"></object>

*Una imagen en formato SVG. Ej:
<object data="miImage.svg"></object>

Aunque realmente los tres primeros casos (y ya puestos, también el cuarto) son el mismo tipo: código de marcado (mark-up language). El primero es HTML estático; el segundo es una página dinámica, pero el resultado es HTML; la URL redirigirá a contenido HTML; y el último es en formato SVG, que está basado en XML.
En esos cuatro casos, se crearía un nuevo contexto de navegación anidado al contexto que incluye la etiqueta object, y en el que podrías tener código con el que se accediera al contexto creador usando window.parent.


text:
Q: Which one is right one in pipelining? I'm studying CPU pipelining, and had a trouble.
I want to know which one is right pipelining in below picture
In my opinion, the first Gantt chart is kinda "structural hazard" becuase "IF" stage is partially overlapped. I think that using one stage for two instruction is not allowed. So I think that second one is right.... Am i right?

A: You are right.
The first chart has two instructions being fetched during the second cycle.  Unless specified otherwise, this cannot be done.
There are circumstances in which this is allowable:

*

*The instruction fetch is divided into two stages, IF1 and IF2, each of which take 1 cycle.  IF1 and IF2 can be overlapped.

*The data path and instruction cache support 2 simultaneous operations.


text:
Q: Sort String in C# and Entity Framework I have a list with a lot of numbers in it. But they are saved as strings because of some additional letters.
I have a list that contains a string column called jointNumber my data is like this :
1b
a1
10
15
2a
20
21
250
3
34
368

Code:
List<ViewTestPackageHistorySheet> lstTestPackageHistorySheets =
         _reportTestPackageHistorySheetRepository.ShowReport(Id)
         .OrderBy(i => new { i.LineNumber, i.JointNumber}).ToList();

But it doesn't work. Why? As you can see I sort it based on two columns the first column works I mean linenumber but it doesn't sort the data based on jointnumber.

A: Without looking at the code at all, I can see that your list is already in alphabetical order.  Did you convert your strings to numeric data types anywhere?


text:
Q: 'HtmlHelper' does not contain a definition for 'DropDownListFor' For some reason, DropDownListFor doesn't work for me, and I can't find a reason why.
My game model:
public class Game
{
    public virtual int GameId { get; set; }
    public virtual string Name { get; set; }
    public virtual Studio Studio { get; set; }
    public virtual Genre Genre { get; set; }
    public virtual List<Level> Levels { get; set; }
}

My controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult MyEditEdit([Bind(Include = "GameId,Name,Genre")] Game game)
{

    if(ModelState.IsValid)
    {
        db.Entry(game).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("MyEdit");
    }
    return View();
}

// GET

public ActionResult MyEditEdit(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    Game game= db.Games.Single(g => g.GameId == id);
    if(game == null)
    {
        return HttpNotFound();
    }
    object genre;
    if(game.Genre == null)
    {
        genre= 0;
    }
    else
    {
        genre= genre;
    }
    ViewBag.GenreList = new SelectList(db.Genres,"GenreId", "name", genre);

    return View(game);
}

My view:
@using GameStore.Controllers
@using GameStore.Models
@model GameStore.Models.Game

@using (Html.BeginForm())
{

            @Html.LabelFor(model => model.Genre, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.DropDownListFor(m=>m.Genre, ViewBag.GenreList, "GenreId", "name")
                @Html.ValidationMessageFor(model => model.Genre, "", new { @class = "text-danger" })

}

The View doesn't even load, and I get the error from the topic of this post. When I write the DropDownListFor lambda code, intelisense doesn't work for m => m.Genre. I have no idea what I'm doing wrong and I'm lost. I googled it and didn't find anything.

A: I am showing a way to populate the DropDownList and almost similar to yours:
Model:
public class Department
{
    public int DepartmentID { get; set; }
    public string Code { get; set; }
}

Controller:
 public ActionResult Index()
 {
    MainDbContext db = new MainDbContext();
    var departments = (from c in db.Departments
                       select new Department
                       {
                          DepartmentID = c.Id,
                          Code = c.Code
                       }).ToList(); //Get department details

    return View(departments);
 }

View - In the view, use the following:
@model List<YourAppName.Models.Department>
@{
    ViewBag.Title = "SampleApp";
}

<select name="Department" id="Departments" class="form-control">
  <option value="0">--Please Select Department--</option>
      @foreach (var item in Model) //Loop through the department to get department details
      {
        <option value="@item.DepartmentID">@item.Code</option>
      }
</select>

Hint: Try not to use ViewBag and the above is for demo purpose. Instead try to use ViewModel.


text:
Q: How to call IQueryable.OrderBy() method with a runtime type for generic parameter? I need to call the OrderBy<T, TKey>(Func<T, TKey>) method with a value for TKey only available at runtime. After reading answers on SO on how to use a variable as a generic parameter, I'm trying the following approach:
string key = "MyProperty";
Type keyType = typeof(T).GetProperty(key).PropertyType;
MethodInfo methodInfo = typeof(MyClass)
                .GetMethod(
                    "MyGenericStaticMethod"),
                    BindingFlags.NonPublic | BindingFlags.Static);
// T is known at compile time.
MethodInfo genericMethodInfo = methodInfo.MakeGenericMethod(new[] { typeof(T), keyType});

var expression = genericMethodInfo.Invoke(null, new object[] { params });

myQueryable.OrderBy(expression);

The problem is, genericMethodInfo.Invoke() returns object and hence cannot be used with OrderBy() which expects an argument of type Func<T, TKey>. However, TKey can be different value types like string,int that are only known at runtime. Can this even be done and if so, how?

A: Method MethodInfo.Invoke() is used to perform method call with provided parameters, and cannot be used to generate expression. To generate lambda Expression that can be used as an argument to .OrderBy() method, use this instead:
string key = "MyProperty";
Type keyType = typeof(T).GetProperty(key).PropertyType;
MethodInfo methodInfo = typeof(MyClass)
    .GetMethod(
    "MyGenericStaticMethod",
    BindingFlags.NonPublic | BindingFlags.Static);
MethodInfo genericMethodInfo = methodInfo.MakeGenericMethod(new[] { typeof(T), keyType });

//this represents parameter of keySelector expression used in OrderBy method
var parameterExpression = Expression.Parameter(typeof(T));

// Expression representing call to MyGenericStaticMethod
var expression = Expression.Call(genericMethodInfo, parameterExpression);

// To use it as an argument of OrderBy method, we must convert expression to lambda
var lambda = Expression.Lambda(expression, parameterExpression);

You will probably encounter another problem: You cannot simply call myQueryable.OrderBy(lambda), because this doesn't allow compiller to infer it's generic arguments and you cannot provide these generic arguments, because TKey is not known at compile time. So you will need to do another reflection, to actually call an .OrderBy() method:
// OrderBy method has generic parameters and several overloads. It is thus
// difficult to get it's MethodInfo just by typeof(Queryable).GetMethod().
// Although it may seem weird, but it is easier to get it's MethodInfo from
// some arbitrary expression. Generic arguments "<object, object>" does not
// matter for now, we will replace them later
Expression<Func<IQueryable<object>, IQueryable<object>>> orderByExpression =
    x => x.OrderBy<object, object>((o) => null);

// Replace generic parameters of OrderBy method with actual generic arguments
var orderByMethodInfo = (orderByExpression.Body as MethodCallExpression)
    .Method
    .GetGenericMethodDefinition()
    .MakeGenericMethod(new[] { typeof(T), keyType });

// Now we are finally ready to call OrderBy method
var orderedResultQuery = orderByMethodInfo.Invoke(
    null,
    new Object[] { myQueryable, lambda })
    as IQueryable<T>;

// Just for testing purpose, let's materialize result to list
var orderedResult = orderedResultQuery.ToList();


text:
Q: Generate Experimental design Data in R I have a randomized block design experiment in which we d like to test 10 treatments (8 genotypes + 2 controls).
It s structured as follow :
9 sites, within each one, there are 4 blocks (repetitions),
within each block, There are 10 plots,
Within each plot, there are 144 individuals of a given treatment (genotype).
I'd like to generate a dataset as follow :
NB: With a random assignement of treatements to plots within each block.
Site <- LETTERS[1:6]
Block <- LETTERS[1:4] ## For each Site
Plot <- paste(rep("P",10),seq(1,10,1),sep="_") ## For each Block
Trt <- c(LETTERS[1:8],rep("control",2)) ## 10 Treatments within each block
id <- seq(1,144,1) ## for each Plot
observation <- runif(n=144,min=1, max=4) ## repeated for each treatment, each block,and each site.

data.frame(Site,Block,Plot,Trt,id,observation)

Knowing that this code will drop an error, id'like to have,for the same Site, all block levels, for the same block, all plot levels and their coresponding treatments, and for the same plot all id Tags and their corresponding observations.
Many Thanks

A: I think you might be looking for expand.grid :
Site <- LETTERS[1:6]
Block <- LETTERS[1:4] ## For each Site
Plot <- paste(rep("P",10),seq(1,10,1),sep="_") ## For each Block
data <- expand.grid(Site = Site, Block = Block, Plot = Plot)
data$Trt <- sample(c(LETTERS[1:8],paste0("control",1:2)), nrow(data), replace = TRUE)
data


text:
Q: "Turn on" rsubmit as if it were an option I run PC SAS and most of the time I'm sending blocks of code to the server, like
rsubmit;
[code]
endrsubmit;

I'm tired of typing rsubmit and endrsubmit so much.  I wish it were possible to turn on rsubmit as an option, something like
options rsubmit = all;

and then I can run bits and pieces of code while I'm programming without all that extra typing.  Does an option like this exist?

A: Change your key settings (type 'keys' into the Command Box), set CTRL-F3 to rsubmit wait=yes.
You can then press F3 to locally submit code, and CTRL-F3 to remote submit code.

A: It's not exactly what you're asking for, but you could cut out most of the typing by defining an abbreviation under Tools > Add Abbreviation...
I have mine set up as follows:
rs:
rsubmit;
endrsubmit;

sr:
endrsubmit;
rsubmit;

A: RSUBMIT is submitting code to a server.  One way to do this would be to turn over your code to the server, and execute it directly from there.  This is available in some instances and not others (depending on your setup), but many times it's possible.  You can do your development locally, and then use Git or SVN to promote code to the server and execute it there when you want to use the full database or whatever particular reason you are RSUBMITting.

A: You can add a button to your toolbar that can rsubmit your code and you can also bind a hotkey (like the f8 that submits code) to run your rsubmit. You will need to setup the environment for rsubmit just as you would normally or via an autoexec.sas program. Here is a link to a document that talks about other options you can customize your toolbar to use.
http://www2.sas.com/proceedings/sugi28/240-28.pdf

*

*Menu bar : tools | customize

*select the icon you would like to place yours next too

*click the icon second row on the left (little blue star upper left corner of the button) to add new
command = rsubmit

*help text and tip text with whatever makes sense for you.


text:
Q: Trailing Slash tool in CherryPy 3.2 not adding a trailing slash I cannot get the trailing_slash tool to work. I've played around with
the options for the trailing_slash tool and nothing seems to have any effect.
I am using CherryPy 3.2.2 and Routes 1.13. I would like to have a
trailing slash added. There is no errors in the debug output.
If I go to 127.0.0.1:8080/blog/ it works, however if I go
to 127.0.0.1:8080/blog it doesn't.
My Configuration is:
conf = {
'/': {
    'request.dispatch': setup_routes(),
    # This trailing slash stuff has no effect :(
    'tools.trailing_slash.on': True,
    'tools.trailing_slash.missing': True,
    'tools.trailing_slash.status': 301,
},
'/static': {
       'tools.staticdir.on': True,
       'tools.staticdir.root': os.path.dirname(os.path.abspath(__file__)),
       'tools.staticdir.dir': 'static'
   }
}

And the example route is:
routes = [["blog_index", "/blog/", {'controller': BlogController(), 'action': 'index','entry_id': 'index'}],]

Can anybody see what I am doing wrong? Is there a bug or lack of
essential documentation? Does the trailing_slash tool work with the Routes Dispatcher?
The full src: https://bitbucket.org/ddevine/icdy/src

A: The trailing slash Tool doesn't work with the Routes Dispatcher. The trailing slash tool expects that whatever dispatcher is chosen will set cherrypy.request.is_index to True or False, which it looks like the RoutesDispatcher class doesn't do at all. Therefore, is_index is left at None, and the trailing slash Tool does nothing. It might be possible for someone with a good knowledge of Routes to fix that in the CherryPy codebase, or write their own dispatcher which sets is_index, or try to write another Tool which fixes up is_index after the fact.

A: Long time asked, but here is a way to make it work:
def index(index=True):
    cherrypy.request.is_index = index
cherrypy.tools.index = cherrypy.Tool('on_start_resource', index)

config = {
    ...
        'tools.trailing_slash.status': 307,
        'tools.index.on': True,
    ...
}

A: There's no notion of an "index" in Routes because you can define 2 connections of the same path, one with a trailing slash and one without, and have them connected to 2 completely different controllers and/or actions. You won't do this in real life, but it's possible in Routes, so there's really not a good way to change the trailing_slash tool to deal with this.
IMHO, the trailing_slash tool is a bit lacking and it should probably be elevated to the level of a WSGI middleware that sits in front of the default WSGI middle pipeline, like the InternalRedirect middleware is doing in CherryPy now. For example, if you've mounted a RouteDispatcher under a script_name, you can't put the trailing_slash tool anywhere to have CP put a trailing slash after the script_name because all the routes in Routes must start with a slash, and it will throw a RoutesException if the path_info is an empty string when you try to match.


text:
Q: detect pause and 'done' button's click on iphone for jwplayer7 How can I detect pause and 'done' buttons's click on iphone, when video plays within native player ? Need to detect this for jwplayer cause am using this player for videos. I did research, checked this With an HTML5 video element on the iphone, how can I detect the difference between "pause" and "done"? but it doesn't worked for me.

A: There is no event listener for the done button. When the player is not fullscreen and in a paused or idle playback state, the user is no longer watching video:
jwplayer().getFullscreen() // returns false

jwplayer().getState() // returns "paused" or "idle"

You could try listening for the fullscreen event and checking the state:
jwplayer().on('fullscreen', function(e) {
    console.log('fullscreen changed:', e.fullscreen, 'state:', this.getState());
});

For the paused button, prior to version 7.2 jwplayer did not forward paused events from the video tag. This issue has been fixed.
jwplayer().on('pause', function(e) {
    console.log('paused fullscreen:', this.getFullscreen());
});


text:
Q: How to Change the default Application image in android? How to Change the  default Application image in android??we want to distinguish our application to other android application.so we i want to change the default android application image to sepate image.
how this can be done?anyone pls help me?

A: Put an image in your project and reference it in your androidmanifest.xml file with
android:icon="@drawable/icon"

in the <application> part
Random reference with a tiny bit more detail: http://www.connorgarvey.com/blog/?p=97
(a bit offtopic, but this is a great page from the dev-guide for making icons: http://developer.android.com/guide/practices/ui_guidelines/icon_design_launcher.html )


text:
Q: will TLS version support 1.0 and 1.2 work simultaneously? We are supporting SharePoint 2013 onpremises farm.
We need to change the TLS version 1.0 to 1.2 for one specific site collection as per the site owner compliance policy.
If we enable TLS 1.2 in only sharepoint web servers along with existing TLS 1.0 support, will the sites communicated in TLS 1.2 mode in client browsers?
We have workflow manager 1.0 with SSL communication enabled between sharepoint and WFM .
Should i upgrade this WFM communication with SharePoint farm to TLS 1.2 or will it work with existing TLS 1.0?

A: Windows Server 2008 R2 has SSL3.0 and TLS1.0 enabled by default. TLS1.1 & 1.2 have to be enabled manually. The Server will always try to use the newest configured protocol version. But the client (or a man-in-the-middle!) can enforce unsecure protocols like SSL3.0. You can simulate this by disabling TLS 1.2 & 1.1 on your Client (Internet Options -> Advanced -> Security -> Uncheck Enable TLS 1.1 & 1.2). Load your SharePoint Site -> right-klick -> properties.
My thinkings to your situation:

*

*Enabling TLS1.1 & 1.2 will not automatically disable older protocol versions. Your farm will support every protocol from SSL3.0 to TLS1.2 - depending on what the client is willing to accept.

*Disabling older protocol-versions might affect your WFM-Infrastructure. As you already learned in your other post, there is not too much practical experience on this topic. I also lack practical experience on that.

*You cannot disable protocol versions for a SiteCollection. Disabling old versions affects your whole farm.

*Do you have to ensure TLS1.2 ONLY (no older version) for the specific SiteCollection?

*

*If Yes: You seem to be a little stuck here because of WFM. You should try to implement the TLS1.2 only setup in a separate test-environment first.

*If No: Enable TLS 1.1 & 1.2 support in Windows and SharePoint as described here

*You should always try to disable SSL3.0 as it is a known insecure protocol!


text:
Q: No adapter attached; skipping layout kotlin It loads fine at startup but when I navigate to other fragments and go back to Home Fragment, the recycler view doesn't load anymore. It loads fine with other fragments when I navigate back to it, only the recycler view of Home Fragment doesn't show. There is no error showing in the logcat. Only this W/RecyclerView: No adapter attached; skipping layout. Anyone can help me? I don't know what's really wrong here. Thank you in advance guys.
Here is my code of HOME FRAGMENT
class HomeFragment : Fragment() {

private lateinit var homeViewModel: HomeViewModel

var recyclerView:RecyclerView?=null
lateinit var swipeUpToRefresh:SwipeRefreshLayout
private var viewPager:LoopingViewPager?=null

private var layoutAnimationController:LayoutAnimationController?=null

private var _binding: FragmentHomeBinding? = null
private val binding get() = _binding!!

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View {
    homeViewModel =
        ViewModelProvider(this).get(HomeViewModel::class.java)
    _binding = FragmentHomeBinding.inflate(inflater, container, false)
    val root: View = binding.root

    val key = requireArguments().getString("restaurant")

    initView(root)
    refreshPage()
    //bind data
        homeViewModel.getPopularList(key!!).observe(viewLifecycleOwner, {
            val listData = it
            val adapter = MyPopularCategoriesAdapter(requireContext(), listData)
            recyclerView!!.adapter = adapter
            recyclerView!!.layoutAnimation = layoutAnimationController
        })
        homeViewModel.getBestDealList(key).observe(viewLifecycleOwner, {
            val adapter = MyBestDealsAdapter(requireContext(), it, false)
            viewPager!!.adapter = adapter
        })
    return root
}

private fun refreshPage() {
    val key = requireArguments().getString("restaurant")
    swipeUpToRefresh.setOnRefreshListener {
        //bind data
        homeViewModel.getPopularList(key!!).observe(viewLifecycleOwner, {
            val listData = it
            val adapter = MyPopularCategoriesAdapter(requireContext(), listData)
            recyclerView!!.adapter = adapter
            recyclerView!!.layoutAnimation = layoutAnimationController
        })
        homeViewModel.getBestDealList(key).observe(viewLifecycleOwner, {
            val adapter = MyBestDealsAdapter(requireContext(), it, false)
            viewPager!!.adapter = adapter
        })
        swipeUpToRefresh.isRefreshing = false
    }
}

private fun initView(root:View) {
    swipeUpToRefresh = root.findViewById(R.id.refresh) as SwipeRefreshLayout

    layoutAnimationController = AnimationUtils.loadLayoutAnimation(context, R.anim.layout_item_from_left)

    viewPager = root.findViewById(R.id.viewpager) as LoopingViewPager

    recyclerView = root.findViewById(R.id.recycler_popular) as RecyclerView
    recyclerView!!.setHasFixedSize(true)
    recyclerView!!.layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
}

override fun onResume() {
    super.onResume()
    viewPager!!.resumeAutoScroll()
}

override fun onPause() {
    viewPager!!.pauseAutoScroll()
    super.onPause()
}

override fun onDestroyView() {
    super.onDestroyView()
    _binding = null
}}

A: I added this line of code to my HomeActivity in R.id.nav_home
val bundle = Bundle()
bundle.putString("restaurant",Common.currentRestaurant!!.uid)
                    navController.navigate(R.id.nav_home,bundle)

here Is my navView
navView!!.setNavigationItemSelectedListener { p0 ->
            p0.isChecked = true
            drawer!!.closeDrawers()

            if (p0.itemId == R.id.nav_sign_out) {
                signOut()
            } else if (p0.itemId == R.id.nav_restaurant) {
                if (menuItemClick != p0.itemId)
                    navController.popBackStack()
                navController.navigate(R.id.nav_restaurant)
            } else if (p0.itemId == R.id.nav_home) {
                if (menuItemClick != p0.itemId) {
                    EventBus.getDefault().postSticky(MenuInflateEvent(true))
                    navController.popBackStack()
                    val bundle = Bundle()
                    bundle.putString("restaurant",Common.currentRestaurant!!.uid)
                    navController.navigate(R.id.nav_home,bundle)
                }
            } else if (p0.itemId == R.id.nav_cart) {
                if (menuItemClick != p0.itemId) {
                    EventBus.getDefault().postSticky(MenuInflateEvent(true))
                    navController.popBackStack()
                    navController.navigate(R.id.nav_cart)
                }
            } else if (p0.itemId == R.id.nav_menu) {
                if (menuItemClick != p0.itemId) {
                    EventBus.getDefault().postSticky(MenuInflateEvent(true))
                    navController.popBackStack()
                    navController.navigate(R.id.nav_menu)
                }
            } else if (p0.itemId == R.id.nav_view_order) {
                if (menuItemClick != p0.itemId) {
                    EventBus.getDefault().postSticky(MenuInflateEvent(true))
                    navController.popBackStack()
                    navController.navigate(R.id.nav_view_order)
                }
            } else if (p0.itemId == R.id.nav_update_info) {
                showUpdateDialog()
            }

            menuItemClick = p0.itemId

            true
        }

A: Try doing this
private fun initView(root:View) {
    swipeUpToRefresh = root.findViewById(R.id.refresh) as SwipeRefreshLayout

    layoutAnimationController = AnimationUtils.loadLayoutAnimation(context, R.anim.layout_item_from_left)

    viewPager = root.findViewById(R.id.viewpager) as LoopingViewPager

    recyclerView = root.findViewById(R.id.recycler_popular) as RecyclerView
    //Here is where you need to initialize an adapter to the recyclerView
    recylerView!!.adapter = MyPopularCategoriesAdapter(requireContext(), listData) //I'm not sure what is the second argument of your adapter. Feel free to change it as you like.
    recyclerView!!.setHasFixedSize(true)
    recyclerView!!.layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
}


text:
Q: Issues With System.ArgumentOutOfRangeException I have an issue with a program I'm designing around searching for Multi-City flights. For whatever reason, my code is giving an error and I can't figure out for the life of me where this bug is. If you could please lend a hand, you will be my favorite human for the next week, possibly month. Thank you so much!
Code for MultiFactory.cs:
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.IO;

namespace Reservation_Library
{
    public class MultiFactory
    {
        StreamWriter sw;
        XmlSerializer serial;
        List<MultiCityFlight> finalMatches;
        List<FlightRequest> flightList;
        List<Flight> entireList;
        List<Flight> multiCityList;
        const string FLIGHT_REQUEST = @"..\..\flightRequest.xml";
        const string MULTI_FILE = @"..\..\multiFlights.xml";
        const string FLIGHT_FILE = @"..\..\flights.xml";
        const string MATCH_FILE = @"..\..\match.xml";

        DateTime date;
        Random random = new Random();

        public DateTime randomDate()  //Generates a random date for the flight within the provided timeframe
        {
            int month = random.Next(6, 8);
            int day = random.Next(1, 31);
            int Day = random.Next(1, day);

            if (month == 7 && day > 1)
            {
                month = random.Next(6, 7);
                day = random.Next(1, 31);
            }

            date = new DateTime(2017, month, Day);

            return date;
        }

       /*public void SerializeMultiFlight(List<MultiCityFlight> multiFlights) //Simple serializer for writing full list to xml
        {
            serial = new XmlSerializer(finalMatches.GetType());
            sw = new StreamWriter(MULTI_FILE);
            serial.Serialize(sw, multiFlights);
            sw.Close();
        }*/

        public List<MultiCityFlight> findConnections(int choice) //Method for comparing the entire list of flights against the selected flight for matches. All matching flights added to a matchingFlights list
        {
            FlightFactory flight = new FlightFactory();
            entireList = new List<Flight>();
            List<Flight> firstConnections = new List<Flight>(); //Flights on same date as request, must have matching departure point
            List<Flight> secondConnections = new List<Flight>();
            List<FlightRequest> flightList = generateFlightRequests();
            finalMatches = new List<MultiCityFlight>();

            entireList = flight.generateFlightList();
            foreach(Flight f in entireList)
            {
                Console.Write(f.ToString());
            }

            FlightRequest selected = flightList[choice];

            for (int i = 0; i < entireList.Count; i++)
            {

                if (entireList[i].DateAndTime == selected.date &&
                    entireList[i].OrigAirport == selected.origAirport)
                {
                    firstConnections.Add(entireList[i]);
                }
                Console.WriteLine(firstConnections[0]);

                if (entireList[i].DateAndTime == selected.date && entireList[i].DestAirport == selected.destAirport)
                {
                    secondConnections.Add(entireList[i]);
                }

                /*using (var e1 = firstConnections.GetEnumerator())
                using (var e2 = secondConnections.GetEnumerator())
                {
                    while (e1.MoveNext() && e2.MoveNext())
                    {

                        Flight f1 = e1.Current;
                        Console.WriteLine(f1.ToString());
                        Flight f2 = e2.Current;
                        Console.WriteLine(f2.ToString());

                        TimeSpan t = f2.DateAndTime - f1.DateAndTime;
                        int diff = (int)t.Hours;

                        if (diff > 1 && f1.DestAirport == f2.OrigAirport)
                        {
                            finalMatches.Add(new MultiCityFlight(f1, f2));
                        }
                    }
                }*/
            }

            return finalMatches;
        }

        public List<FlightRequest> DeserializeFlightList() //Simple method for deserializing from xml to a list
        {
            flightList = new List<FlightRequest>();
            StreamReader sr = new StreamReader(FLIGHT_REQUEST);
            serial = new XmlSerializer(flightList.GetType());
            flightList = (List<FlightRequest>)serial.Deserialize(sr);
            sr.Close();
            return flightList;

        }

        public List<FlightRequest> generateFlightRequests() //Generating 20 random flights to search for matching flights
        {
            flightList = new List<FlightRequest>();

            FlightRequest f = new FlightRequest("MIA", "SEA", randomDate());
            flightList.Add(f);
            f = new FlightRequest("MIA", "LAX", randomDate());
            flightList.Add(f);
            f = new FlightRequest("MIA", "DEN", randomDate());
            flightList.Add(f);
            f = new FlightRequest("LAX", "MIA", randomDate());
            flightList.Add(f);
            f = new FlightRequest("LAX", "DEN", randomDate());
            flightList.Add(f);
            f = new FlightRequest("LAX", "SEA", randomDate());
            flightList.Add(f);
            f = new FlightRequest("DEN", "LAX", randomDate());
            flightList.Add(f);
            f = new FlightRequest("DEN", "SEA", randomDate());
            flightList.Add(f);
            f = new FlightRequest("DEN", "MIA", randomDate());
            flightList.Add(f);
            f = new FlightRequest("SEA", "MIA", randomDate());
            flightList.Add(f);
            f = new FlightRequest("SEA", "LAX", randomDate());
            flightList.Add(f);
            f = new FlightRequest("SEA", "DEN", randomDate());
            flightList.Add(f);
            f = new FlightRequest("MIA", "LAX", randomDate());
            flightList.Add(f);
            f = new FlightRequest("SEA", "LAX", randomDate());
            flightList.Add(f);
            f = new FlightRequest("DEN", "SEA", randomDate());
            flightList.Add(f);
            f = new FlightRequest("LAX", "DEN", randomDate());
            flightList.Add(f);
            f = new FlightRequest("MIA", "DEN", randomDate());
            flightList.Add(f);
            f = new FlightRequest("SEA", "MIA", randomDate());
            flightList.Add(f);
            f = new FlightRequest("DEN", "MIA", randomDate());
            flightList.Add(f);
            f = new FlightRequest("LAX", "SEA", randomDate());
            flightList.Add(f);

            return flightList;
        }
    }
}

This is the line where the error occurs:
Console.WriteLine(firstConnections[0]);

If you need code from another class or method, please ask. Thanks so much!

A: Obviously you get this error, because the List is empty.
Just debug some code ahead:
Console.WriteLine(entireList[i].DateAndTime + " == "+selected.date+" | "+entireList[i].OrigAirport+" == "+selected.origAirport);

There you should see, that this is not true. So there is nothing added and so you are out of range :D


text:
Q: login form codeigniter form validation show one more login form I have below code for login form with validation,
 public function index(){
            //Check weather session exist or not!
            if(($this->session->userdata('user_email') != ""))
                {
                    if(($this->session->userdata('is_admin') == "Yes"))
                        {
                        redirect('admin/home');
                        }
                        elseif(($this->session->userdata('is_manager') == "Yes"))
                        {
                            redirect('manager/home');
                            }
                    else
                        {
                            redirect('user/home');
                        }
                }
            else
                {
                $this->load->view('view_login');
                }

    //If not exists then get login post request
    if ($this->input->post('login'))
    {
        $this->form_validation->set_rules('username', 'User Name', 'trim|required|xss_clean|valid_email');
        $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');

        if ($this->form_validation->run() == FALSE) {
            $this->load->view('view_login');
            }
            else {

                $username = $this->input->post('username');
                $password = md5($this->input->post('password'));
                $user_count = $this->login_model->user_count($username,$password);

                if($user_count == 1)
                        {
                            // If there is a user, then check enable status
                            $row = $this->login_model->user_data($username,$password);

                                if($row->user_status == "Enable")
                                    {
                                        $_userdata = array(
                                            'user_id' => $row->user_id,
                                            'user_email' => $row->user_email,
                                            'user_firstname' => $row->user_firstname,
                                            'user_lastname' => $row->user_lastname,
                                            'user_image' =>$row->user_image,
                                            'is_admin' => $row->is_admin,
                                            'is_manager' => $row->is_manager,
                                            'user_tz' =>$row->tz_name,
                                            'logged_in' => true
                                            );

                                        $this->session->set_userdata($_userdata);
                                        //Now check user type weather admin or user then move to respected page
                                            if($row->is_admin == "Yes")
                                                {
                                                redirect('admin/home');
                                                }
                                                elseif($row->is_manager == "Yes")
                                                {
                                                    redirect('manager/home');
                                                    }
                                            else
                                                {
                                                redirect('user/home');
                                                }

                                    }
                                    else
                                            {
                                                $error = array(
                                                            'error_message' => 'User Name is Disabled'
                                                            );
                                                $this->load->view('view_login', $error); // Manager Disables

                                            }
                        }
                    else
                        {
                                    $data1 = array(
                                            'error_message' => 'Wrong Username or Password'
                                                );
                                    $this->load->view('view_login', $data1); //Wrong user pw
                        }

                }
        }
}

What i am doing here is when index is load, check weather any session exist or not, and if yes, then simply redirect to home page of user,
If no session exists then load login view page,
Then user enter username and PW then form validation is done,
And if it fails, the loading view page again, this page will show error of CI form validation,
Problem is, when validation fails, i get two login forms on view, means one was already which used for login and another login form with CI validation errors,
How can i get only 1 login form when CI send validation error?
My guess is that i am loading view_login page 2 times, but not sure how can i prevent that!
Thanks,

A: You can remove the load view_login statement from the else part and put as else for the $this->input->post('login') as shown below:
    if ($this->input->post('login'))
    {
          ........
          ........
    } else {
          $this->load->view('view_login');
    }

A: Try this and let me know.
 <?php
     function index(){
                //Check weather session exist or not!
                if(($this->session->userdata('user_email') != ""))
                    {
                        if(($this->session->userdata('is_admin') == "Yes"))
                            {
                            redirect('admin/home');
                            }
                            elseif(($this->session->userdata('is_manager') == "Yes"))
                            {
                                redirect('manager/home');
                                }
                        else
                            {
                                redirect('user/home');
                            }
                    }

        //If not exists then get login post request
        else if ($this->input->post('login'))
        {
            $this->form_validation->set_rules('username', 'User Name', 'trim|required|xss_clean|valid_email');
            $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');

            if ($this->form_validation->run() == FALSE) {
                $this->load->view('view_login');
                }
                else {

                    $username = $this->input->post('username');
                    $password = md5($this->input->post('password'));
                    $user_count = $this->login_model->user_count($username,$password);

                    if($user_count == 1)
                            {
                                // If there is a user, then check enable status
                                $row = $this->login_model->user_data($username,$password);

                                    if($row->user_status == "Enable")
                                        {
                                            $_userdata = array(
                                                'user_id' => $row->user_id,
                                                'user_email' => $row->user_email,
                                                'user_firstname' => $row->user_firstname,
                                                'user_lastname' => $row->user_lastname,
                                                'user_image' =>$row->user_image,
                                                'is_admin' => $row->is_admin,
                                                'is_manager' => $row->is_manager,
                                                'user_tz' =>$row->tz_name,
                                                'logged_in' => true
                                                );

                                            $this->session->set_userdata($_userdata);
                                            //Now check user type weather admin or user then move to respected page
                                                if($row->is_admin == "Yes")
                                                    {
                                                    redirect('admin/home');
                                                    }
                                                    elseif($row->is_manager == "Yes")
                                                    {
                                                        redirect('manager/home');
                                                        }
                                                else
                                                    {
                                                    redirect('user/home');
                                                    }

                                        }
                                        else
                                                {
                                                    $error = array(
                                                                'error_message' => 'User Name is Disabled'
                                                                );
                                                    $this->load->view('view_login', $error); // Manager Disables

                                                }
                            }
                        else
                            {
                                        $data1 = array(
                                                'error_message' => 'Wrong Username or Password'
                                                    );
                                        $this->load->view('view_login', $data1); //Wrong user pw
                            }

                    }
            } else
                    {
                    $this->load->view('view_login');
                    }
    }


text:
Q: Partitioning the range of a function by numbers $a_i$ such that each set $\{x \mid f(x) = a_i\}$ has measure zero Let $f \in C_b(S)$ (set of all bounded and continuous functions) and $\mu$ be a measure on $S$ where $S$ is a complete separable metric space. Then a book (Probability Theory by Borkar) claims that for a given $\epsilon > 0$ there exists $N \geq 1$ and $a_0 < a_1 < a_2<\dots <a_N$ such that
(a) $\|f\| -1 = a_0 < a_1 < a_2<\dots <a_N = \|f\| + 1$
(b) $\mu(\{x | f(x) = a_i\})=0$ for all $i$ and
(c) $a_i - a_{i-1} \leq \epsilon$, $1 \leq i \leq N$ .
I am not understanding how can he claim point (b) for a general $\mu$.
Then he claims $\bigcup_{i=1}^{N} \{x|a_{i-1} \leq f(x) \lt a_i\}=S$.
$\|f\| = \sup_x|f(x)|$

A: I think we established that:

*

*The measure space, being finite, cannot contain an uncountable family of disjoint sets of positive measure. Therefore, there are only countably many values of $a$ that have to be avoided when choosing $a_i$.

*The inequality in (a) should probably be
$$ -\|f\| -1 = a_0 < a_1 < a_2<\dots <a_N = \|f\| + 1$$

*Every value of $f$ falls strictly between  $-\|f\| -1$ and  $\|f\| + 1$, hence the sets $\bigcup_{i=1}^{N} \{x|a_{i-1} \leq f(x) \lt a_i\} $ cover $S$.


text:
Q: UnsupportedOperationException in Android when removing from List First here is the code of the class that is bringing me trouble (its a class defined in a class):
public static class MAbilitiesParseStruct{
    private List<CardView> cards;
    private List<String> abilities;
    private List<Boolean> ask;
    private List<Integer> regtype; //Used for regitering events.
    //private List<Integer> pos;
    private int current = 0;

    //public MAbilitiesParseStruct(List<CardView> cvs, List<String> abs, List<Boolean> asks, List<Integer> p){
    public MAbilitiesParseStruct(List<CardView> cvs, List<String> abs, List<Boolean> asks, List<Integer> regt){
        cards = cvs;
        abilities = abs;
        ask = asks;
        regtype = regt;
        //pos = p;
        current = 0;
    }

    public List<CardView> getCardList(){return cards;}
    public List<String> getAbilities(){return abilities;}
    public List<Boolean> getAsk(){return ask;}
    public List<Integer> getRegTypes(){return regtype;}

    public void addAbility(CardView v, String ability, boolean askq, int rtype){
        cards.add(v);
        abilities.add(ability);
        ask.add(askq);
        regtype.add(rtype);
    }

    public void appendAnotherMaps(MAbilitiesParseStruct another){
        cards.addAll(another.getCardList());
        abilities.addAll(another.getAbilities());
        ask.addAll(another.getAsk());
        regtype.addAll(another.getRegTypes());
    }

    public boolean done(){if (current == cards.size()) return true; else return false;}
    public void next(){ //It is assumed that this is called once current ability has finished being parsed.
        if (cards.size() > 0){
            cards.remove(0);
            abilities.remove(0);
            ask.remove(0);
            regtype.remove(0);
        }
    }

    public void purgeOneShots(){
        int i = 0;
        System.err.println("Purge de 1 shot");
        while (i < cards.size()){
            if (regtype.get(i) == Aux.REG_ONESHOT){
                System.err.println("Purge card");
                cards.remove(i);
                System.err.println("Purge ability");
                abilities.remove(i);
                System.err.println("Purge ask");
                ask.remove(i);
                System.err.println("Purge regtype");
                regtype.remove(i);
            }
            else{
                i++;
            }
        }
    }

    public void purgeTurns(){
        int i = 0;
        while (i < cards.size()){
            if (regtype.get(i) == Aux.REG_TURN){
                cards.remove(i);
                abilities.remove(i);
                ask.remove(i);
                regtype.remove(i);
            }
            else{
                i++;
            }
        }
    }

    public String currentAbility(){return abilities.get(current);}
    public boolean currentAsk(){return ask.get(current);}
    public CardView currentCard(){return cards.get(current);}
    public void reset() {current = 0;}

    public void clearRemainingEvents(){ //This is used for when a certain card cancels an event.
        for (int i = current+1; i < cards.size(); i++){
            cards.remove(i);
            abilities.remove(i);
            ask.remove(i);
            regtype.remove(i);
        }
    }

}

And here is the invocation code that throws the exception (RegisteredAbilities is a SparseIntArray):
    MAbilitiesParseStruct temp = RegisteredAbilities.get(event,null);
    if (temp != null){
        MAPS.appendAnotherMaps(temp);
        RegisteredAbilities.get(event).purgeOneShots();
    }

The code fails with unsupported operation for remove on the last line and I can't undersand why. Is it becuase I'm calling the operation from an SparseIntArray?
Thanks for any help
EDIT:
As requested here is the stack trace.
01-20 18:45:28.010: E/AndroidRuntime(29696): FATAL EXCEPTION: main
01-20 18:45:28.010: E/AndroidRuntime(29696): java.lang.UnsupportedOperationException
01-20 18:45:28.010: E/AndroidRuntime(29696):    at java.util.AbstractList.remove(AbstractList.java:638)
01-20 18:45:28.010: E/AndroidRuntime(29696):    at auxdata.AuxClasses$MAbilitiesParseStruct.purgeOneShots(AuxClasses.java:209)
01-20 18:45:28.010: E/AndroidRuntime(29696):    at legen.dary.GameEngine.LaunchEvent(GameEngine.java:611)
01-20 18:45:28.010: E/AndroidRuntime(29696):    at legen.dary.GameEngine.newVillainEntered(GameEngine.java:319)
01-20 18:45:28.010: E/AndroidRuntime(29696):    at legen.dary.GameEngine.GameTurn(GameEngine.java:193)
01-20 18:45:28.010: E/AndroidRuntime(29696):    at legen.dary.MainActivity.LoadGamePressed(MainActivity.java:290)
01-20 18:45:28.010: E/AndroidRuntime(29696):    at legen.dary.ButtonBlockView$1.onClick(ButtonBlockView.java:54)
01-20 18:45:28.010: E/AndroidRuntime(29696):    at android.view.View.performClick(View.java:4084)
01-20 18:45:28.010: E/AndroidRuntime(29696):    at android.view.View$PerformClick.run(View.java:16966)
01-20 18:45:28.010: E/AndroidRuntime(29696):    at android.os.Handler.handleCallback(Handler.java:615)
01-20 18:45:28.010: E/AndroidRuntime(29696):    at android.os.Handler.dispatchMessage(Handler.java:92)
01-20 18:45:28.010: E/AndroidRuntime(29696):    at android.os.Looper.loop(Looper.java:137)
01-20 18:45:28.010: E/AndroidRuntime(29696):    at android.app.ActivityThread.main(ActivityThread.java:4745)
01-20 18:45:28.010: E/AndroidRuntime(29696):    at java.lang.reflect.Method.invokeNative(Native Method)
01-20 18:45:28.010: E/AndroidRuntime(29696):    at java.lang.reflect.Method.invoke(Method.java:511)
01-20 18:45:28.010: E/AndroidRuntime(29696):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
01-20 18:45:28.010: E/AndroidRuntime(29696):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-20 18:45:28.010: E/AndroidRuntime(29696):    at dalvik.system.NativeStart.main(Native Method)

A: From the API:
Arrays.asList: Returns a fixed-size list backed by the specified array.

You can't add to it; you can't remove from it. You can't structurally modify the List.
Fix
Create a LinkedList, which supports faster remove.
List<String> list = new LinkedList<String>(Arrays.asList(split));


text:
Q: discord roles set gives error when member have booster role im using djs v12 im trying make jail command and im using <member>.roles.set(["id"]) but when member have booster role its gives Missing Permissions error.
I tried
<member>.roles.remove(<member>.roles.cache.filter(x => !x.id == "booster role id"))
await <member>.roles.add("jail role id")

when i trying this bot remove all roles from member but its remove jail role to so then i tried
<member>.roles.remove(<member>.roles.cache.filter(x => !x.id == "booster role id" || !x.id == "jail role id"))
await <member>.roles.add("jail role id")

but still bots take jail role to thats mean member have 0 role
how can i fix that

A: One of the errors is the conditionals  !x.id == "booster role id"
This isn't checking if x.id doesn't equal boost role id, it checks if the opposite of x.id equals the booster role id, simplifying to:
false == "string" which should always be false, so I'm not sure why it removes all the roles, it should remove 0
Another issue is || instead of &&, with the or operator every role will get removed
but anyways to fix:
const roles = <member>.roles;
roles.remove(roles.cache.filter(x => x.id !== "booster role id" && x.id !== "jail role id"));

if(!roles.cache.has("jail role id")) {
  await roles.add("jail role id");
}

But this could be easier with the set method like you stated:
const roles = ["jail role id"];

if(<member>.roles.cache.has("booster role id")) {
  roles[1] = "booster role id";
}

<member>.roles.set(roles);


text:
Q: Not able to publish to Azure Function Apps to Azure Service Environment using VS Code I have created an ASE (Azure Service Environment). Inside that we have a Service Plan and a function app on that plan.
When I try to publish the function app from the visual studio code, it is giving me the error -
Request to https://my-function-service.scm.mydemo.appserviceenvironment.net/api/zipdeploy?isAsync=true&author=VS%20Code failed, reason: getaddrinfo ENOTFOUND my-function-service.scm.mydemo.appserviceenvironment.net

I've tried the push the code from my local machine as well as from Virtual machine hosted on the same Virtual Network as ASE.
Any ideas where I'm doing wrong?
**Note- ** I have changed the service name in above link.

A: Regarding the issue, please check your app service environment type. The app service environment has two types: External ASE and  ILB ASE. The different type has different deployment configurations.
With an External ASE, we can use the same way with normal function app to publish.
With an ILB ASE, the publishing endpoints are only available through the ILB. The ILB is on a private IP in the ASE subnet in the virtual network. If you don't have network access to the ILB, you can't publish any apps on that ASE. Meanwhile, you must configure DNS for the apps in the system. Otherwise, you also cannot publish. For more details, please refer to here and here


text:
Q: Cocoa NSTextField not editable, and disappears with setSelectable I have a programmatically created AppKit/Cocoa NSTextField, within a tab in a popup. I'm creating the control with:
NSTextField *textField = [[NSTextField alloc] init];
[textField setBezeled:YES];
[textField setDrawsBackground:YES];
[textField setEditable:YES];
[textField setSelectable:NO];
[textField setTranslatesAutoresizingMaskIntoConstraints:NO];
return textField;

And then inserting it into the parent NSView (in a tab control in a dialog box) with various layout constraints, and it appears in the correct place. However, the text field is not editable or selectable. If I change the instantiation to
[textField setSelectable:YES];

the control shows up in the tree view in the Debug View Hierarchy tool in XCode, with the same constraints that I'd expect, but the view isn't visible on screen, or in the visual display of the Debug View Hierarchy tool.
And even with [textField setSelectable:NO], I cannot edit the text that I've set in the control.
XCode Version 9.4.1 (9F2000) / macOS High Sierra 10.13.5

A: The problem was that making the field editable removed the minimum width constraint form the control. Adding a width constraint solved the problem:
[parentView addConstraint:[NSLayoutConstraint constraintWithItem:addedControl
                                                       attribute:NSLayoutAttributeWidth
                                                       relatedBy:NSLayoutRelationGreaterThanOrEqual
                                                          toItem:nil // [button superview]
                                                       attribute:NSLayoutAttributeNotAnAttribute
                                                      multiplier:1 constant:40]];

Thank you Willeke for sending me down the right direction with the question about the size.


text:
Q: Parsing file Excel from PHP I have a function PHP to parse file Excel, it read all the number of the rows but it doesn't return all the data in the object.
Number of lines 3247, but it return just 1023 lines.
this following  the parsing function:
 public function parseEquipement($filePath = null) {
        set_time_limit(0);
        $listEquipement = [];
        $count = 0;
        $chunkSize = 8192;
        $objReader = PHPExcel_IOFactory::createReader(PHPExcel_IOFactory::identify($filePath));
        $spreadsheetInfo = $objReader->listWorksheetInfo($filePath);
        $chunkFilter = new \Floose\Parse\ChunkReadFilter();
        $objReader->setReadFilter($chunkFilter);
        $objReader->setReadDataOnly(true);
        $chunkFilter->setRows(0, 1);
        $objPHPExcel = $objReader->load($filePath);
        $totalRows = $spreadsheetInfo[0]['totalRows'];
        for ($startRow = 1; $startRow <= $totalRows; $startRow += $chunkSize) {
            $chunkFilter->setRows($startRow, $chunkSize);
            $objPHPExcel = $objReader->load($filePath);
            $sheetData = $objPHPExcel->getActiveSheet()->toArray(null, null, true, false);
            $startIndex = ($startRow == 1) ? $startRow : $startRow - 1;
            if (!empty($sheetData) && $startRow < $totalRows) {
                $dataToAnalyse = array_slice($sheetData, $startIndex, $chunkSize);
                    if($dataToAnalyse[0][0]==NULL){
                        break;
                }
                for ($i = 0; $i < $chunkSize; $i++) {
                    if ($dataToAnalyse[$i]['0'] != NULL) {
                       $listEquipement[] = new Article($dataToAnalyse[$i]['0'], '', $dataToAnalyse[$i]['1']);
                        $count++;

                    }
                }
            }

        //echo($totalRows); // is best
        //echo($count);  // is wrong
           //print_r($listEquipement);
            $objPHPExcel->disconnectWorksheets();
            unset($objPHPExcel, $sheetData);
        }

        return $listEquipement;

        }

I changed all the code by this following but it doesn't work:
public function parseEquipment($filePath = null) {
    $objReader = PHPExcel_IOFactory::createReader(PHPExcel_IOFactory::identify($filePath));
    $objReader->setReadDataOnly(true);
    $objPHPExcel = $objReader->load($filePath);
    $sheet = $objPHPExcel->getSheet(0);
    $highestRow = $sheet->getHighestRow();
    for ($row = 2; $row <= $highestRow; $row++){
        echo $sheet->getCellByColumnAndRow(3, $row)->getCalculatedValue();
        echo $sheet->getCellByColumnAndRow(4, $row)->getCalculatedValue();
        echo $sheet->getCellByColumnAndRow(2,$row)->getCalculatedValue();
        $listEquipement[] = new Article(
            $sheet->getCellByColumnAndRow(3, $row)->getCalculatedValue(),
            $sheet->getCellByColumnAndRow(4, $row)->getCalculatedValue(),
            $sheet->getCellByColumnAndRow(2, $row)->getCalculatedValue()
);

    }
}

And when I run my code always it display an error of memory size knowing that the size of my file is 81K and it display the number of lines in the same time.
Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted (Tried to allocate 54byte)
Could anyone be kind enough to guide and teach me how I should do my codes or can you suggest me another code to parsing a file Excel ?


text:
Q: My ListView is overlapping on my edittext Why is that my listview is overlapping on my edittext box I think the problem is my XML coding
by the way I am using frameLayout I want my listView to be underneath my edittext how can I do it?
Here is my XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<EditText
            android:id="@+id/editText2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Search Bus Station..."
            android:inputType="textVisiblePassword"
            android:imeOptions="actionDone"
            android:background="@drawable/textinputborder"
            android:ems="10"
            android:padding="5dip"
            android:textSize="18sp" >

        </EditText>

        <ListView
            android:id="@+id/list_view2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/editText2"
            android:layout_alignParentBottom="true"
            android:background="#111"
            android:choiceMode="singleChoice"
            android:divider="@android:color/transparent"
            android:dividerHeight="0dp" >
        </ListView>

A: Add android:layout_below="@+id/editText2" to your ListView so that your ListView is always gonna be below your EditText.
Alternatively, you can add android:layout_marginTop="10dp" to your ListView and set the margin value as per your needs(not recommended though).

A: // try this
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:paddingBottom="@dimen/activity_vertical_margin"
                android:paddingLeft="@dimen/activity_horizontal_margin"
                android:paddingRight="@dimen/activity_horizontal_margin"
                android:paddingTop="@dimen/activity_vertical_margin"
                tools:context=".MainActivity" >

    <EditText
            android:id="@+id/editText2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Search Bus Station..."
            android:inputType="textVisiblePassword"
            android:imeOptions="actionDone"
            android:background="@drawable/textinputborder"
            android:ems="10"
            android:padding="5dip"
            android:textSize="18sp" >

    </EditText>

    <ListView
            android:id="@+id/list_view2"
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:layout_height="0dp"
            android:background="#111"
            android:choiceMode="singleChoice"
            android:divider="@android:color/transparent"
            android:dividerHeight="0dp" >
    </ListView>
    </LinearLayout>

A: use  android:layout_below in your listview for reference to create layout see this.
<EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Search Bus Station..."
        android:inputType="textVisiblePassword"
        android:imeOptions="actionDone"
        android:background="@drawable/textinputborder"
        android:ems="10"
        android:padding="5dip"
        android:textSize="18sp" >

    </EditText>

    <ListView
        android:id="@+id/list_view2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/editText2"
        android:layout_alignParentBottom="true"
        android:background="#111"
        android:layout_below="@+id/editText2"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp" >
    </ListView>

Hope this will help you.

A: Try below code
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/textinputborder"
        android:ems="10"
        android:hint="Search Bus Station..."
        android:imeOptions="actionDone"
        android:inputType="textVisiblePassword"
        android:padding="5dip"
        android:textSize="18sp" >
    </EditText>

    <ListView
        android:id="@+id/list_view2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/editText2"
        android:layout_alignParentBottom="true"
        android:background="#111"
        android:layout_below="@+id/editText2"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp" >
    </ListView>

</RelativeLayout>

A: Use android:layout_below attribute
Add  android:layout_below="@+id/editText2" to your Listview , below is your updated UI
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/textinputborder"
        android:ems="10"
        android:hint="Search Bus Station..."
        android:imeOptions="actionDone"
        android:inputType="textVisiblePassword"
        android:padding="5dip"
        android:textSize="18sp" >
    </EditText>

    <ListView
        android:id="@+id/list_view2"
        android:layout_below="@+id/editText2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/editText2"
        android:layout_alignParentBottom="true"
        android:background="#111"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp" >
    </ListView>

</RelativeLayout>

A: Besides using android:layout_alignBottom="@+id/editText2" try to set the android:layout_below="@+id/editText2" in your ListView So your ListView will be always below to your EditText.


text:
Q: Simulating coin toss In the New York Times yesterday there was a reference to a paper essentially saying that the probability of 'heads' after a 'head' appears is not 0.5 (assuming a fair coin), challenging the "hot hand" myth. I want to prove it to myself.
Thus, I am working on coding a simulation of 7 coin tosses, and counting the number of heads after the first head, provided, naturally, that there is a first head at all.
I came up with the following lines of R code, but I'm still getting NA values, and would appreciate some help:
n <- 7              # number of tosses
p <- 0.5            # probability of heads
sims <- 100         # number of simulations

Freq_post_H <- 0    # frequency of 'head'-s after first 'head'
    for(i in 1:sims){
        z <- rbinom(n, 1, p)
        if(sum(z==1)!=0){
        y <- which(z==1)[1]
        Freq_post_H[i] <- sum(z[(y+1):n])/length((y+1):n)
        }else{
            next()
        }
    Freq_post_H
    }
Freq_post_H

What am I missing?
CONCLUSION: After the initial hiccups of mismatched variable names, both responses solve the question. One of the answers corrects problems in the initial code related to what happens with the last toss (i + 1) by introducing min(y + 1, n), and corrects the basic misunderstanding of next within a loop generating NA for skipped iterations. So thank you (+1).
Critically, and the reason for this appended "conclusion" the second response addresses a more fundamental or conceptual problem: we want to calculate the fraction of H's that are preceded by a H, as opposed to p(H) in whatever number of tosses remain after a head has appeared, which will be 0.5 for a fair coin.

A: This is a simulation of what they did in the newspaper:
nsims <- 10000
k <- 4
set.seed(42)
sims <- replicate(nsims, {
  x <- sample(0:1, k, TRUE)
  #print(x)
  sum( # sum logical values, i.e. 0/1
   diff(x) == 0L & # is difference between consecutive values 0?
     x[-1] == 1L ) / # and are these values heads?
       sum(head(x, -1) == 1L) #divide by number of heads (without last toss)
})

mean(sims, na.rm = TRUE)  #NaN cases are samples without heads, i.e. 0/0
#[1] 0.4054715

k <- 7

sims <- replicate(nsims, {
  x <- sample(0:1, k, TRUE)
  #print(x)
  sum(diff(x) == 0L & x[-1] == 1L) / sum(head(x, -1) == 1L)
})

mean(sims, na.rm = TRUE)
#[1] 0.4289402

A: n <- 7              # number of tosses
p <- 0.5            # probability of heads
sims <- 100         # number of simulations

Prob_post_H <- 0    # frequency of 'head'-s after first 'head'
    for(i in 1:sims){
        z <- rbinom(n, 1, p)
        if(sum(z==1) != 0){
        y <- which(z==1)[1]
        Prob_post_H[i] <- mean(z[min(y+1, n):n], na.rm=TRUE)
        }else{
            next()
        }
    }
mean(Prob_post_H,na.rm=TRUE)
#[1] 0.495068

It looks like it's right around 50%. We can scale up to see more simulations.
sims <- 10000

mean(Prob_post_H,na.rm=TRUE)
#[1] 0.5057866

Still around 50%.

A: This is to simulate 100 fair coin tosses 30,000 times
counter <- 1
coin <- sum(rbinom(100,1,0.5))
while(counter<30000){
  coin <- c(coin, sum(rbinom(100,1,0.5)))
  counter <- counter+1
}

Try these after running above variable
 hist(coin)
 str(coin)
 mean(coin)
 sd(coin)

A: Below is some sample code in R to simulate a fair coin toss in R using the sample function.  You can modify it as you like to simulate any number of flips.  Since the outcome of flipping a coin is independent for each flip, the probability of a head or tail is always 0.5 for any given flip.  Over many coin flips the probability of at least half of the flips being heads (or tails) will converge to 0.5.  The probability that you get exactly half heads and half tails approaches 0.
n <- 7
count_heads <- 0
coin_flip <- sample(c(0,1), n, replace = TRUE)
for(flip_i in 1:n)
{
  if(coin_flip[flip_i] == 1)
  {
    count_heads = count_heads + 1
  }
}
count_heads/n


text:
Q: Scapy: How to access RAW of a custom packet I am trying to access the RAW data of this packet. I am not sure how to extract that and store it in a variable. I have tried using the getlayer method but it does not return the Raw payload.
>>> b.show2()
###[ LSP Object ]###
  \common_object_header\
   |###[ PCEP Common Object Header ]###
   |  oclass= LSP
   |  oType= 1L
   |  resflags=
   |  pflag=
   |  iflag=
   |  obLength= 20
  plspid= 0x1L
  flag= 0L
  Cflag=
  oflag= DOWN
  Aflag=
  Rflag=
  Sflag=
  Dflag= D
  \symbolic_path_name\
   |###[ symbolic_path_name_tlv ]###
   |  tlvType= SYMBOLIC-PATHNAME-TLV
   |  tlvLength= 5
   |  tlvValue= 'lsp12'
   |###[ Raw ]###
   |     load= '000' <---- How to access this field???
>>>

>>> b.symbolic_path_name.getlayer(Raw) <--- This does'nt return anything
>>>
>>>
>>> b.symbolic_path_name.getlayer(Raw).load
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'load'
>>>

A: So I think the Raw object is the last layer and  that represents the payload.
So you would access it directly

last = b.getlayer(Raw)
# Because Raw is last this works as well, e.g. No Padding
last2 = b.lastlayer()
print last.load
print last2.load


text:
Q: xpath locators c# proper technique of finding I'm trying to master my xPath findings but I'm facing a problem. My goal is to get checkbox from the table. Could you please give me any advices how locator should always be set?
Let's imagine that my goal is the input pointing on checkbox which needs to be clicked.
Firstly I tried in really simple way:
By.XPath("//input[@type = 'checkbox'][1]")

I've got two checkboxes so I'm pointing to get the first one. Result - Fail.
Next:
By.XPath("//div[@class = 'receipt-grid-container h-90']//tbody/tr[1]/td[5]/input");

I'm starting from the main class and going "down", through tbody and table elements. As my checkbox is located inside the 5th column I've tried to find it by ending it with /input. Result - Fail also.
And the final approach, I supposed it could be done just by "going down" so:
By.XPath("//div[@class = 'receipt-grid-container h-90']//tbody/tr[1]/td[5]/div/input");

However, I failed also. Can anyone advice me how we can find it? Also, when we're searching for the xpath, is there a need starting "from the top to the bottom" technique like I'm doing above? Or we can start in different way using e.g xPath Axes

                     Name

                     Quantity

                     EUR

                     Refunded

                     Refund

                  Coca-Cola 0,5 l
                  1 pcs
                  3.00
                  0

                        <input type="checkbox" value="on" style="position: absolute; cursor: inherit; pointer-events: all; opacity: 0; width: 100%; height: 100%; z-index: 2; left: 0px; box-sizing: border-box; padding: 0px; margin: 0px;">

                                 <svg viewBox="0 0 24 24" style="display: inline-block; color: rgba(0, 0, 0, 0.87); fill: rgba(0, 0, 0, 0.87); height: 24px; width: 24px; user-select: none; transition: opacity 1000ms cubic-bezier(0.23, 1, 0.32, 1) 200ms; position: absolute; opacity: 1;">
                                    <path d="M19 5v14H5V5h14m0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"></path>
                                 </svg>
                                 <svg viewBox="0 0 24 24" style="display: inline-block; color: rgba(0, 0, 0, 0.87); fill: rgb(0, 188, 212); height: 24px; width: 24px; user-select: none; transition: opacity 450ms cubic-bezier(0.23, 1, 0.32, 1) 0ms, transform 0ms cubic-bezier(0.23, 1, 0.32, 1) 450ms; position: absolute; opacity: 0; transform: scale(0);">
                                    <path d="M19 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.11 0 2-.9 2-2V5c0-1.1-.89-2-2-2zm-9 14l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"></path>
                                 </svg>

                  Fanta Zero 0,5 l
                  1 pcs
                  3.00
                  0

                        <input type="checkbox" value="on" style="position: absolute; cursor: inherit; pointer-events: all; opacity: 0; width: 100%; height: 100%; z-index: 2; left: 0px; box-sizing: border-box; padding: 0px; margin: 0px;">

                                 <svg viewBox="0 0 24 24" style="display: inline-block; color: rgba(0, 0, 0, 0.87); fill: rgba(0, 0, 0, 0.87); height: 24px; width: 24px; user-select: none; transition: opacity 1000ms cubic-bezier(0.23, 1, 0.32, 1) 200ms; position: absolute; opacity: 1;">
                                    <path d="M19 5v14H5V5h14m0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"></path>
                                 </svg>
                                 <svg viewBox="0 0 24 24" style="display: inline-block; color: rgba(0, 0, 0, 0.87); fill: rgb(0, 188, 212); height: 24px; width: 24px; user-select: none; transition: opacity 450ms cubic-bezier(0.23, 1, 0.32, 1) 0ms, transform 0ms cubic-bezier(0.23, 1, 0.32, 1) 450ms; position: absolute; opacity: 0; transform: scale(0);">
                                    <path d="M19 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.11 0 2-.9 2-2V5c0-1.1-.89-2-2-2zm-9 14l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"></path>
                                 </svg>

A: As per the HTML you have shared your usecase might be either to click the checkbox for the item Coca-Cola or the checkbox for the item Fanta Zero. So to click the respective checkbox you can create a function as follows:
public void click_checkbox(string softdrink)
{
    driver.FindElement(By.XPath("//div[contains(@class,'receipt-grid-container')]//table/tbody//td[contains(.,'" + softdrink + "')]//following::input[1]")).Click();
}

Now you can call the function click_checkbox() with the required item which ever you want to click as follows:
click_checkbox("Coca-Cola")
//or
click_checkbox("Fanta Zero")

A: Try using this as your xpath:
By.XPath("(//input[@type = 'checkbox'])[1]")

Generally, try selecting the elements by id (it should be unique, but it isn't always), then name, and after that I would keep them as simple as possible, without using too many numbered elements (e.g. //div[13]/span[9]//td/td[4]/div).


text:
Q: If $p\equiv 1\pmod{8}$, then $-1$ is fourth power? I know that $-1$ is a square modulo $p$ iff $p\equiv 1\pmod{4}$. Curious about this, I'm trying to show that $-1$ is a fourth power if and only if $p\equiv 1\pmod{8}$, for $p$ odd.
I know that if $a^4\equiv -1\pmod{p}$ for some $a$, then
$$
(-1)^{(p-1)/4}\equiv (a^4)^{(p-1)/4}\equiv a^{p-1}\equiv 1\pmod{p}.
$$
So since $p$ is odd, $(-1)^{(p-1)/4}=1$, so $(p-1)/4$ is even, and thus $p\equiv 1\pmod{8}$.
How can the converse be shown? I was trying to break $(p-1)!$ into a power of $4$, by grouping the factors together without success. Thanks.

A: This is a direct consequence of the following more general result.
Theorem: Let $m$ be a positive integer that has a primitive root, and suppose that $\gcd(a,m)=1$. Then the congruence $x^k\equiv a\pmod{m}$ has a solution if and only if
$$a^{\varphi(m)/\gcd(\varphi(m),k)}\equiv 1\pmod {m}.\tag{$1$}$$
To prove the result, let $g$ be a primitive root of $m$, and let $d=\gcd(\varphi(m),k)$. Taking indices with respect to $g$, we see that the congruence $x^k\equiv a\pmod{p}$ holds iff
$$k\,\text{ind}\, x\equiv \text{ind}\,a \pmod{\varphi(m)}.\tag{$2$}$$
The linear congruence $(2)$ has a solution for $\text{ind}\,x$ iff $d$ divides $\text{ind}\, a$.
To complete the proof, we show that $(1)$ holds iff $d$ divides $\text{ind}\,a$.
By taking indices, we can see that $(1)$ is equivalent to $\frac{\varphi(m)}{d}\text{ind}\, a\equiv 0\pmod {\varphi(m)}$. This holds iff $d$ divides $\text{ind}\,a$.

A: You can also use the fact that the multiplicative group of a finite field is cyclic (not difficult to prove directly, but proofs can be found in many textbooks, for example "Topics in Algebra" by Herstein). Let $a$ be an element of (multiplicative) order $p-1$ in the field $\mathbb{Z}/p\mathbb{Z}$. Then if $p \equiv 1 $ (mod 8), we see that $b = a^{\frac{p-1}{8}}$ is an element of (multiplicative) order $8$ in $\mathbb{Z}/p\mathbb{Z}$. Then $c = b^{4}$ satisfies $c^{2} = 1 \neq c,$ and so $c = -1,$ which has also been expressed as the fourth power of $b.$


text:
Q: How to beautifully update a JPA entity in Spring Data? So I have looked at various tutorials about JPA with Spring Data and this has been done different on many occasions and I am no quite sure what the correct approach is.
Assume there is the follwing entity:
package stackoverflowTest.dao;

import javax.persistence.*;

@Entity
@Table(name = "customers")
public class Customer {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private long id;

@Column(name = "name")
private String name;

public Customer(String name) {
    this.name = name;
}

public Customer() {
}

public long getId() {
    return id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}
}

We also have a DTO which is retrieved in the service layer and then handed to the controller/client side.
package stackoverflowTest.dto;

public class CustomerDto {

private long id;
private String name;

public CustomerDto(long id, String name) {
    this.id = id;
    this.name = name;
}

public long getId() {
    return id;
}

public void setId(long id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}
}

So now assume the Customer wants to change his name in the webui - then there will be some controller action, where there will be the updated DTO with the old ID and the new name.
Now I have to save this updated DTO to the database.
Unluckily currently there is no way to update an existing customer (except than deleting the entry in the DB and creating a new Cusomter with a new auto-generated id)
However as this is not feasible (especially considering such an entity could have hundreds of relations potentially) - so there come 2 straight forward solutions to my mind:

*

*make a setter for the id in the Customer class - and thus allow setting of the id and then save the Customer object via the corresponding repository.

or

*add the id field to the constructor and whenever you want to update a customer you always create a new object with the old id, but the new values for the other fields (in this case only the name)

So my question is wether there is a general rule how to do this?
Any maybe what the drawbacks of the 2 methods I explained are?

A: Simple JPA update..
Customer customer = em.find(id, Customer.class); //Consider em as JPA EntityManager
customer.setName(customerDto.getName);
em.merge(customer);

A: Even better then @Tanjim Rahman answer you can using Spring Data JPA use the method T getOne(ID id)
Customer customerToUpdate = customerRepository.getOne(id);
customerToUpdate.setName(customerDto.getName);
customerRepository.save(customerToUpdate);

Is's better because getOne(ID id) gets you only a reference (proxy) object and does not fetch it from the DB. On this reference you can set what you want and on save() it will do just an SQL UPDATE statement like you expect it. In comparsion when you call find() like in @Tanjim Rahmans answer spring data JPA will do an SQL SELECT to physically fetch the entity from the DB, which you dont need, when you are just updating.

A: In Spring Data you simply define an update query if you have the ID
  @Repository
  public interface CustomerRepository extends JpaRepository<Customer , Long> {

     @Query("update Customer c set c.name = :name WHERE c.id = :customerId")
     void setCustomerName(@Param("customerId") Long id, @Param("name") String name);

  }

Some solutions claim to use Spring data and do JPA oldschool (even in a manner with lost updates) instead.

A: This is more  an object initialzation question more than a jpa question, both methods work and you can have both of them at the same time , usually if the data member value is ready before the instantiation you use the constructor parameters, if this value could be updated after the instantiation you should have a setter.

A: If you need to work with DTOs rather than entities directly then you should retrieve the existing Customer instance and map the updated fields from the DTO to that.
Customer entity = //load from DB
//map fields from DTO to entity

A:
So now assume the Customer wants to change his name in the webui -
  then there will be some controller action, where there will be the
  updated DTO with the old ID and the new name.

Normally, you have the following workflow:

*

*User requests his data from server and obtains them in UI;

*User corrects his data and sends it back to server with already present ID;

*On server you obtain DTO with updated data by user, find it in DB by ID (otherwise throw exception) and transform DTO -> Entity with all given data, foreign keys, etc...

*Then you just merge it, or if using Spring Data invoke save(), which in turn will merge it (see this thread);

P.S. This operation will inevitably issue 2 queries: select and update. Again, 2 queries, even if you wanna update a single field. However, if you utilize Hibernate's proprietary @DynamicUpdate annotation on top of entity class, it will help you not to include into update statement all the fields, but only those that actually changed.
P.S. If you do not wanna pay for first select statement and prefer to use Spring Data's @Modifying query, be prepared to lose L2C cache region related to modifiable entity; even worse situation with native update queries (see this thread) and also of course be prepared to write those queries manually, test them and support them in the future.

A: I have encountered this issue!

Luckily, I determine 2 ways and understand some things but the rest is not clear.
 Hope someone discuss or support if you know.

*

*Use RepositoryExtendJPA.save(entity). Example:
List<Person> person = this.PersonRepository.findById(0)
person.setName("Neo");
This.PersonReository.save(person);
this block code updated new name for record which has id = 0;

*Use @Transactional from javax or spring framework.  Let put @Transactional upon your class or specified function, both are ok.  I read at somewhere that this annotation do a "commit" action at the end your function flow. So, every things you modified at entity would be updated to database.

A: There is a method in JpaRepository
getOne

It is deprecated at the moment in favor of
getById

So correct approach would be
Customer customerToUpdate = customerRepository.getById(id);
customerToUpdate.setName(customerDto.getName);
customerRepository.save(customerToUpdate);