text:
Q: Struts 2 - Pre-populate a form using the Object's Attributes I want to pre-populate a form using Struts 2 tags with the values of attributes of the object that I have received from session.
PromoCode promoCode = (PromoCode) session.getAttribute("PROMOCODE");

I tried with this approach but it did not work.
<s:form action="add">
            <s:select label="Ticket Name " name="ticketName" list="{'PARTY PLATINUM', 'INAUGURATION PREMIUM'}"></s:select>
            <s:textfield label="Promotion Type " value="%{promoCode.promotionType}" name="promotionType"></s:textfield>
            <s:select label="Discount Access " value="promoCode.discountAccess" name="discountAccess" list="{'Choose Your Discount Access', 'Coded Discount', 'Public Discount'}"></s:select>
            <s:textfield label="Name of the Public Discount " name="nameOfPublicDiscount"></s:textfield>
            <s:textfield label="Discount per ticket (%) " value="promoCode.discountPerTicket" name="discountPerTicket"></s:textfield>
            <s:textfield label="Uses per offer " value="promoCode.uses" name="uses"></s:textfield>

            <s:submit id="update" value="UPDATE"></s:submit>
</s:form>

How to fix this ?

A: Create a promoCode class variable with getter and setter. In Struts2 to get http session attributes you should use a session map that is injected to your action bean via interceptor which intercepts SessionAware interface.
public class MyAction extends ActionSupport implements SessionAware {

  private PromoCode promoCode;
  public PromoCode getPromoCode(){ return promoCode; }
  public void setPromoCode(PromoCode promoCode){ this.promoode = promoCode; }
  private Map<String, Object> session;

  @Override
  public void setSession(Map<String, Object> session) {
   this.session = session;
  }
  @Override
  public String execute() throws Exception {
    PromoCode promoCode = (PromoCode) session.get("PROMOCODE");
    setPromoCode(promoCode);
    return SUCCESS;
  }

}

In the JSP you should bind input fields to action bean properties.
<s:form action="add">
    <s:select label="Ticket Name " name="promoCode.ticketName" list="{'PARTY PLATINUM', 'INAUGURATION PREMIUM'}"></s:select>
    <s:textfield label="Promotion Type "  name="promoCode.promotionType"></s:textfield>
    <s:select label="Discount Access "  name="promoCode.discountAccess" list="{'Choose Your Discount Access', 'Coded Discount', 'Public Discount'}"></s:select>
    <s:textfield label="Name of the Public Discount " name="promoCode.nameOfPublicDiscount"></s:textfield>
    <s:textfield label="Discount per ticket (%) "  name="promoCode.discountPerTicket"></s:textfield>
    <s:textfield label="Uses per offer " name="promoCode.uses"></s:textfield>

    <s:submit id="update" value="UPDATE"/>
</s:form>


text:
Q: How to solve this combinatorial problem correctly? Question: Ten different candies are given to three children A, B and C. each child has at least one. How many different ways are there?
I use two different methods to solve this problem:
    f[1, n_] := n;
    f[n_, 1] := 1;
    f[n_, m_] := f[n, m] = m (f[n - 1, m - 1] + f[n - 1, m])

    f[10, 3]

    Select[Tuples[Range[3], 10], Length[Union[#]] == 3 &] // Length

But the result of the first method is not equal to StirlingS2[10, 3] 3!. I want to know how to solve this problem correctly?

A: Here is how I solve it:
1- Use FrobeniusSolve to find all possible solutions (how many candies each kid gets):
FrobeniusSolve[{1, 1, 1}, 10]

(*Out: {{0, 0, 10}, {0, 1, 9}, {0, 2, 8}, {0, 3, 7}, ...} *)
(*Output Length: 66 *)

2- Since each kid should gets at least one candy, filter the possibilities contain zero:
ps = DeleteCases[FrobeniusSolve[{1, 1, 1}, 10], l_ /; MemberQ[l, 0]];

(*Out: {{1, 1, 8}, {1, 2, 7}, {1, 3, 6}, {1, 4, 5}, ...} *)
(*Output Length: 36 *)

*

*To create a list like yours that specify which candy goes to which kid, I use MapIndexed, for example:

Flatten[MapIndexed[ConstantArray[#2, #1] &, {1, 8, 1}]]
(*Out: {1, 2, 2, 2, 2, 2, 2, 2, 2, 3} *)

*

*For finding out how many ways you can distribute in {1,8,1} format, I use Permutations which produces all the tuples without duplicate:

Length[Permutations[Flatten[MapIndexed[ConstantArray[#2, #1] &, {1, 8, 1}]]]]
(*Out: 90 *)

3- Now just apply previous steps to all the possibilities stored in ps and sum it up:
Sum[Length[Permutations[Flatten[MapIndexed[ConstantArray[#2, #1] &, i]]]], {i,ps}]

(*Out: 55980 *)

A: This is the definition of StirlingS2 (not showing conditions of having positive integers):
stirling[n_, m_] := (1/m!) Sum[(-1)^(m - k) Binomial[m, k] k^n, {k, 0, m}]
stirling[10,3]
(* 9330 *)

Removing the factor (1/m!), you get:
f[n_, m_] := Sum[(-1)^(m - k) Binomial[m, k] k^n, {k, 0, m}]
f[10,3]
(* 55980 *)

A: f[1, m_ /; m > 1] = 0;
f[n_ /; n >= 1, 1] = 1;
f[n_, m_] := f[n, m] = m (f[n - 1, m - 1] + f[n - 1, m]); TableForm[
 MapAt[Style[#, Red] &,
  Table[f[m, n], {m, 1, 10}, {n, 1, 10}], {10, 3}],
 TableHeadings -> Automatic]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can I write sub query in KSQL? I am new to ksql and have been using mysql for the longest time.
I would like to know is there anyway to have subqueries in KSQL?
This query works without any problem :
SELECT a.executedate, count(a.pno), sum(a.amount) FROM
tb3_withdraw_record_summary a WHERE a.status='3' GROUP BY
a.executedate;

Whereas this query returns an error message:
SELECT a.executedate, count(a.pno), sum(a.amount), (SELECT COUNT(b.pno)
FROM tb3_withdraw_record_summary b WHERE b.status='5' AND
b.executedate = a.executedate) FROM tb3_withdraw_record_summary a
WHERE a.status='3' GROUP BY a.executedate

'Failed to prepare statement: 'B' is not a valid stream/table name or alias.
  Caused by: 'B' is not a valid stream/table name or alias.'

Anyway for me to make this work? Thanks!

A: nested query feature is not currently supported by Ksql but you can do it in following way -
1) CREATE STREAM B AS SELECT COUNT(b.pno)
FROM tb3_withdraw_record_summary b WHERE b.status='5';
2) SELECT a.executedate, count(a.pno), sum(a.amount) FROM tb3_withdraw_record_summary a JOIN B within 5 hours ON b.executedate = a.executedate WHERE a.status='3' GROUP BY a.executedate

Keep in mind that join is very different meaning then relational database world, here data is being partitioned through keys in multiple buckets and it conceptually a "colocated" join. more details about time-window here.
Hope it will help.

A: SubQuery functionality is not implemented for KSQL.
https://github.com/confluentinc/ksql/issues/745

A: I am not familiar with KSQL, but perhaps this does what you want:
SELECT wrs.executedate,
       SUM(CASE WHEN wrs.status IN ('3') THEN 1 ELSE 0 END),
       SUM(CASE WHEN wrs.status IN ('3') THEN amount ELSE 0 END),
       SUM(CASE WHEN wrs.status IN ('5') THEN 1 ELSE 0 END)
FROM tb3_withdraw_record_summary wrs
WHERE wrs.status IN ('3', '5')
GROUP BY wrs.executedate;


text:
Q: Definition of a 'simple' rules in a combinatorial game I have looked on the internet for this for some time. Unfortunately, when I make a search that includes the words "definition" and "simple", the search engine is certain I am looking for a simple definition rather than a definition of simple.
Apparently Elwyn Berlekamp asked if:

there is a game that has simple, playable rules, an intricate explicit
solution, and is provably NP or harder.

Note I have left words in bold that were bold in the source of the quote (a list of open problems in combinatorial game theory).
So what does simple mean in this context?

A: I agree with the comments that "simple" probably doesn't refer to a precisely defined technical notion - certainly not a standard one.
I think "simple" is intended to mean something like "can be described without to much text, implemented by a human easily, and crucially, doesn't explicitly encode any computationally hard problems". If you make the determination of whether a move is legal require solving an $\mathsf{NP}$-hard problem, that defeats the point.

As an aside, I'm curious/concerned about the "explicit solution" part. Presumably "write out the game tree (easy to do since the rules are simple) and mark every position as a win for the appropriate player" doesn't count as an explicit solution. But then I'd want to define "explicit solution" as something that doesn't take computational power to work through, which seems at odds with the solution being $\mathsf{NP}$-hard.


text:
Q: Variables inside of strings return 1 I was making a test page in which I have a form with the post method and a destination page. The main goal was to output the submitted values to a file called UserInfo.txt.
That worked, but when I looked into the file, all the variables I had put inside the string that was outputted into the file, were 1s.
My code is:
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$age = $_POST['age'];
$email = $_POST['email'];
$emailb = $_POST['emailb'];

$UserInfo = <<<EOT
[NAME] = $fname, $lname
[AGE] = $age
[EMAIL] = $email
EOT;
file_put_contents("UserInfo.txt", $UserInfo, FILE_APPEND);

The file output was:
[NAME] = 1, 1
[AGE] = 1
[EMAIL] = 1

HTML form:
<form action="7_dest.php" method="POST">

First name:<input type="text" name="fname" step=0>

Last name:<input type="text" name="lname" step=0>

Age:<input type="number" name="age">

E-mail:<input type="email" name="email" step=0>

Confirm E-mail:<input type="email" name="emailb" step=0>

<input type="submit">

</form>

A: I have found the culprit after some research and plain testing.
Between the variable assigning bit and the heredoc syntax there was an if statement.
Since if statements use the local variable scope and the values were assigned in the global variable scope the variables were NOT assigned inside of the if statement.
As a  result, the variables were not assigned and could thereby not be used.
I fixed it by copying the assigning bit and pasting it inside the if statement.
Here is what the code looks like now:
<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$age = $_POST['age'];
$email = $_POST['email'];
$emailb = $_POST['emailb'];
if (){ //I had a lot of tests here, removed them for the sake of a nice page
    $fname = $_POST['fname'];
    $lname = $_POST['lname'];
    $age = $_POST['age'];
    $email = $_POST['email'];
    $emailb = $_POST['emailb'];
$UserInfo = <<<EOT
[NAME] = $fname, $lname
[AGE] = $age
[EMAIL] = $email
EOT;
file_put_contents("UserInfo.txt", $UserInfo, FILE_APPEND);
} else {
    echo "Something went wrong";
} ?>


text:
Q: JPA repository Boolean Query - return null pointer exception I have Java springBoot project
With repository that included boolean custom query.
but the system run to null pointer exception apart from return "false".
this is the query:
@Query(value = "select * from customers_vs_coupons where customer_id =? and coupon_id = ?", nativeQuery = true)
    Boolean existsPurchesedCoupon(int customerId, int couponId);

I called the method:
if (customerRepository.customerPurchesedCoupon(customerId, coupon.getId())) {
            throw new PurchaseCouponException("can buy only once.");

and this is the error:
 [Request processing failed; nested exception is java.lang.NullPointerException: Cannot invoke "java.lang.Boolean.booleanValue()" because the return value of "com.chana.repositories.CustomerRepository.customerPurchesedCoupon(int, int)" is null] with root cause   ```

A: Your query
select * from customers_vs_coupons where customer_id =? and coupon_id = ?

is designed to return whatever entity (called CustomersVsCoupons from now on) is mapped to the table customer_vs_coupons, not a Boolean.
If you want to throw an exception whenever a specific customer already has a coupon affected, you should transform the signature of your method to either:

*

*Return a CustomersVsCoupons, and throw an exception if your query did not return null

*Return an Optional<CustomersVsCoupons>, and throw an exception if your query did return a non empty Optional


text:
Q: Can I write SELECT query which returns table name after FROM keyword? I query a table which has another table name in one column. I must get that column value for searching that table. To do that I try something like this;
select cap from (select table_name from table2 where mi_prinx=(select mip1 from table1 where mip1=184425 and startmi1=0 group by mip1,startmi1 having count(*)>=4);

Inner Select statement returns table3 name. But this does not working. Can I write something like that or should I use Pl/Sql for that.
I am using something like this for now;
declare
table_name varchar2(100);
obj_mi_prinx number;
cap varchar2(100);
begin
select table_name,obj_mi_prinx into table_name, obj_mi_prinx from table2 where mi_prinx=(select mip1 from table1 where mip1=184425 and startmi1=0 group by mip1,startmi1 having count(*)>=4);
dbms_output.put_line('table_name: ' || table_name);
if(table_name = 'table3') THEN
select cap into cap from table3 where mi_prinx=obj_mi_prinx;
END IF;
dbms_output.put_line('mi_prinx in yb_ob_boru: ' || obj_mi_prinx);
end;

If I can do this without using IF statement, I prefer it.

A: If you have a somewhat limited number of tables that could be returned by the query, you could have the query select from all of them, but only return results for the one matching the data returned by the table1/table2 query.  That would look something like this:
With TableVariable As (
   SELECT table_name FROM table2
   WHERE mi_prinx=(
      SELECT mip1 FROM table1 WHERE mip1=184425 AND startmi1=0 GROUP BY mip1,startmi1 HAVING count(*)>=4)
   )
SELECT cap FROM TableA WHERE 'TableA' = (SELECT Table_Name FROM TableVariable)
UNION ALL
SELECT cap FROM TableB WHERE 'TableB' = (SELECT Table_Name FROM TableVariable)
UNION ALL
SELECT cap FROM TableC WHERE 'TableC' = (SELECT Table_Name FROM TableVariable)
UNION ALL
SELECT cap FROM TableD WHERE 'TableD' = (SELECT Table_Name FROM TableVariable)
UNION ALL
SELECT cap FROM TableE WHERE 'TableE' = (SELECT Table_Name FROM TableVariable)
UNION ALL
SELECT cap FROM TableF WHERE 'TableF' = (SELECT Table_Name FROM TableVariable)
;

If the number of tables is too long then you'll need to use pl/sql, which may include the dynamic SQL mustaccio mentioned.


text:
Q: Negative voltage PWM? I'm relatively new to EE, sorry if this is newbie territory.
With an Arduino, I am trying to emulate a device that outputs NEGATIVE 3.3v PWM (0V or -3.3V, square wave) at around 500 hz.
Obviously, the PWM out of an arduino is 0V or +5V  (or +3.3v depending on the arduino) but there is no way to output negative voltage.
I've researched feeding the signal through a ICL7660 but it's unclear if the 7660 will produce a clean-enough negative square wave.
I also researched the MAX749, which will produce a negative voltage from a PWM, but it's unclear to me if the MAX749 will actually output a negative PWM square wave, or if it will instead output smooth negative (but variable) voltage output based on the duty cycle of the input PWM'd positive voltage source.
I've also heard that maybe I could accomplish this with a MAX232 since the RS232 standard has negative voltage signals as part of the communication standard but have no clue how to go about this.
Thoughts?

A: You can use the following circuit:

If the microcontroller generates a positive PWM signal, the diode will charge Uc to its maximum value (i.e. a constant value of 3.3 V or 5 V depending on your microcontroller).
Then $$Vout=-Uc + Vin$$ and therefore Vout will swing between 0 and -3.3 (or -5 V) as you want. This assumes a perfect diode with a 0 V drop, I guess that a Schottky diode should be fine for your application.


text:
Q: dompdf - image output I'm using the dompdf library to create PDFs from HTML.
I am having a problem rendering images, as they seem to be appearing as red crosses.
$dompdf = new DOMPDF();

$html = '

';

$dompdf->load_html($html);
$dompdf->set_paper("A4");
$dompdf->render();
$output = $dompdf->output();
$filename = date('dmYHis') . '-lowres.pdf';

file_put_contents('/uploads/pdfs/low-res/' . $filename, $output);

This creates the PDF, but it doesn't seem to find the image.
I've tried to have just , but this also renders the image as a red cross.
I'm using the 0.6.0beta3 version of DomPDF
Thanks

A: Ok, so it seemed having a path such as the full URL doesn't work.
Neither does `
I changed the path to be  which seemed to work


text:
Q: Форматирование строки Есть текстовый файл в котором текст такого вида: X56373Y57483W46373H4747A0.
Можно ли на C# как то из предложенной строки вытянуть по очереди значения, например X56373, потом отдельно Y57483 и W46373?
Если можно, то каким образом ?

A: Вот один из вариантов:
string input = "X56373Y57483W46373H4747A0";
string pattern = @"(X\d+)|(Y\d+)|(W\d+)";
Regex regex = new Regex(pattern);
MatchCollection matches = regex.Matches(input);

foreach (Match match in matches)
{
    Console.WriteLine(match.Value);
}

A: Можно попробовать так:
string text = @"X56373Y57483W46373H4747A0";

Regex regex = new Regex(@"[A-Z]\d+");
var matches = regex.Matches(text);


text:
Q: Program to draw pinouts (and easily visualize pin's multiplexed functions) Documenting an electronics project is also an important task if it will be used by someone else other than the hardware designer(s). Right now I need to draw a diagram for a breakout board in order to show what functions are available on each pin. Something like the following diagram (of mbed):

Can someone recommends me a program that allows me to easily draw such diagrams?

A: *

*Latex + TikZ is popular in academia and you can use it to programmatically create very clean diagrams.

*Illustrator is more user friendly, mass-marketed and has a more shallow learning curves.

*Inkscape is open source software similar to Illustrator.

*Visio is a diagram tool produced by Microsoft.  Widely used in engineering departments.

A: Fritzing is pretty nice for this, there are a bunch of libraries built in and available for download that have a lot of the more popular platforms made, and you can define your own parts using an svg editor like Inkscape. It's particularly nice for having defined pin areas for your lines to connect to so things don't break if you drag it around.
draw.io is good for doing quick block diagrams and simplified wiring and is browser based with nice cloud integration. But I haven't tried to use images of PCBs for pinouts with it so it might not be the right thing for that.
edit 2/22/2020: here is a good video showing how the Adafruit feather diagrams are made: https://youtu.be/ndVs1UvK6AE
Sparkfun also has a repo on github for generating SVG elements that they use for their "graphical datasheet" pinouts. I have not tried it but Sparkfun does a lot of these types of pinouts: https://github.com/sparkfun/Graphical_Datasheets
Someone has taken this further with a python script, which may be a good option for advanced users if you don't mind learning how to use the format: https://github.com/stevenj/GenPinoutSVG
Also adding this link to another GitHub repo to generate nice looking SVG representations of PCB designs from a KiCad board file. I have not used this myself either, but it looks like it would pair really well with the way Fritzing defines parts: https://github.com/yaqwsx/PcbDraw
edit 9/4/2021:  Adding a link to a tool called Pinion, which can create interactive pinout diagrams from KiCAD PCBs: https://yaqwsx.github.io/Pinion/

A: It's probably not the "right" app, but I use Powerpoint for stuff like this.
I also sometimes use the online diagrammer at https://www.lucidchart.com/


text:
Q: Printing the content of a file openFile(argv[1],"r");
while(characterBuff != EOF)
{
    characterBuff = fgetc(examFile);
    memoryAlloc += 1;
    string = expandRealloc(string, memoryAlloc);
    appendString(string, characterBuff);
    printf("%s\n", string);
}
closeFile();
free(string);

In the following code: The output I'm getting from printf gives me ackward values like [somehash]D[somehash]E[somehash]S[somehash]K
I'm getting the output word which is "DESK" but with all kind of random stuff taken from the memory, what Am I doing wrong?
Note: The following has been allocated with malloc(sizeof(char)) and realocates every time a single char is added to the string.
I.e the output I should be getting should be:
D
De
Des
Desk
But instead of that I'm getting the thing i shown u before.
EDIT:
char* expandRealloc(char* ptrS, size_t n)
{
    void *tmp;
    if((tmp = realloc(ptrS, n)) == NULL)
    {
        printf("Error: Memory leak possible; Closing Program");
        exit(EXIT_FAILURE);
    }
    else
    {
        ptrS = tmp;
        return ptrS;
    }
}

I Wrote a wrapper function for realloc. Thank for the help, but it still doesnt solve the problem, i still get [somecrapmemoryhash][letter][somecrapmemoryhash][letter] when trying to printf the result.
APPEND STRING:
void appendString(char* inputString, int inputChar)
{
    int stringLenght = strlen(inputString);
    inputString[stringLenght - 1] = inputChar;
    inputString[stringLenght] = '\0';
}

A: When realloc is called, it may move the allocated memory and so you need to replace the old contents of your pointer with the value returned by realloc.
Try
char *temp_string;
    .
    .
    .
temp_string = realloc(string, memoryAlloc);
if(temp_string != NULL)
  string = temp_string;

EDIT
It strikes me that much of the problem here is the use of user-written functions to do things which have long been part of the standard library. Modifying this code to use standard lib functions without the use of special wrappers, etc, would be no more difficult and would result in greater reliability. As an example, the appendString function seems to have been the source of much of the difficulties encountered here. If the strcat function had been used instead (with minor mods to the source) a great deal of aggravation and hair-pulling could have been avoided.
The standard library is there for excellent reasons. It's consistent, solid, debugged, useful, and - well - it's the STANDARD. If anyone here thinks that they, by themselves, are smarter than the hundreds of people who have contributed to the standard lib, they are very likely wrong. If someone here thinks that they can't POSSIBLY use functions from the standard library to perform basic operations because their needs are so incredibly special, they are very likely wrong. The C language, by itself, is not particularly special - let's face it, curly braces are not such a big deal :-) - the power of C comes directly from the philosophy of "put everything in a function" - i.e. from the use of libraries of functions to accomplish tasks. The standard library is the most basic thing that beginning C programmers need to learn, and its use should be second nature to any experienced C programmer.
Share and enjoy.

A: Your appendString function is wrong - change:
void appendString(char* inputString, int inputChar)
{
    int stringLenght = strlen(inputString);
    inputString[stringLenght - 1] = inputChar;
    inputString[stringLenght] = '\0';
}

to:
void appendString(char* inputString, int inputChar)
{
    int stringLength = strlen(inputString);
    inputString[stringLength] = inputChar;
    inputString[stringLength + 1] = '\0';
}

A: Your string printing problem looks suspiciously like a lack of NULL termination on the end of your string... does appendString take care of adding the terminator?


text:
Q: How to use Curl to make a POST request with Dropwizard I have  Dropwizard backend end and like to use curl to make a POST request with a Json body
I used Postman with the settings on the body tab raw radio button selected and on the drop down menu JSON(applicattion/json).I  entered the body and was able to successfully create a POST request.
However when I used curl I get an error. I used
curl -v  -X POST "localhost:8080/resource"
-H "Content-Type: application/json"
-d '{label1: "words1", label2: "words2"}'

I get the error message
 {"code":400,"message":"Unable to process JSON"}

From my understanding it is curl that has an issue since Postman was able to create the POST request.

A: This
{label1: "words1", label2: "words2"}

is not JSON. Use
{"label1": "words1", "label2": "words2"}


text:
Q: Running a Service in QuickBooks I have written a script that works on its own or when I run it from Automator. But when I add it as a service to QuickBooks I get and error message:
"The action Run AppleScript encountered an error."
This is the script :
activate application "QuickBooks 2016"
set windowtitle to the name of the front window of application "QuickBooks 2016"
tell application "System Events"
    tell process "QuickBooks"
        click button "Print" of toolbar 1 of window windowtitle
        click checkbox "Shrink report to fit page width" of tab group 1 of sheet 1 of window windowtitle
        tell menu button "PDF" of sheet 1 of window windowtitle
            click
            --menu item 2 is "Save as a PDF"
            click menu item 2 of menu 1
        end tell
    end tell
end tell

Any suggestions appreciated.


text:
Q: HTML5 border-bottom is displayed wrong(?) Can't set the border property at the bottom of my html window/viewport...
It's just after the last html element. e.g. div.
Is there a way, so it will be displayed really at the bottom of the window?
Here is my css:
html {
   border-bottom:5px solid rgb(17,17,17);
   border-top:5px solid rgb(17,17,17);
}

Thanks very much!

A: In your html add
html {
    width:100%;
    /*height:99%; Fallback for older browsers*/
    height:calc(100% - 10px);
    border-bottom:5px solid rgb(17,17,17);
    border-top:5px solid rgb(17,17,17);
}

I think this will fix your problem.
Here is the Demo

A: Try setting your body tags margin and padding to 0px.

A: You need to specify width and height.
html{
    border-bottom:5px;
    border-bottom-color:rgb(17, 17, 17);
    border-bottom-style:solid;
    border-top:5px;
    border-top-color:rgb(17, 17, 17);
    border-top-style:solid;
    width:100%;
    height:100%;
}

(here's an imgur album to compare the difference: http://imgur.com/a/Uneo5 notice how in the first image, there's a whitespace under it, which appears to be your issue, whereas with height and width, it reaches the bottom of the document)
Edit: And if you have issues with a scrollbar, try 99%, or 99.5%, etc.


text:
Q: Firestore listener killed when app goes in background for a long time In my app I'm listening for a Firestore query whenever the user signs in. After the app goes in background for some time, the listener gets cancelled and the client doesn't get notified of any new changes.
How do I know if a listener has been cancelled by the SDK? What's the proper way of handling this?

A: On most operating system this is done automatically by the system itself, in order to preserve battery life. Whether it is possible to detect this situation, and how, depends on the OS.
In most cases it is better to depend on another mechanism to deliver updates to an app that is not actively being used, such as Firebase Cloud Messaging - which you can call from for example Cloud Functions to deliver messages to backgrounded apps. For an example of this, see the Firebase documentation on notifying users when something interesting happens.


text:
Q: Open Application from URL with http How to Open URL directly from URL ?
Like in notes if we have URL www.facebook.com then it directly opens Facebook App even if we have internet connection off.
I tried the method where we add URL in Info.plist but in that it detects like this abc://* not for abc.com

A: What are you looking for is Universal Links:

When you support universal links, iOS users can tap a link to your
website and get seamlessly redirected to your installed app without
going through Safari. If your app isn't installed, tapping a link to
  your website opens your website in Safari.

The output after supporting Universal Links:

For supporting Universal Links, I would recommend to check:

*

*Support Universal Links Apple Documentation.

*iOS Universal Links GitHub Repo.


text:
Q: Is there a way to use the Microsoft.Identity.Web for an external login button, without relying on Microsoft authentication? We have a SAAS application, for which we want to add an option to login with Microsoft. We can run the samples perfectly fine, but those samples use Microsoft's [Authorize] attributes to mark pages to automatically require login for.
We have our own authentication and permissions system.
All we want is a button "Login with Microsoft", to initiate the OAuth process, and end up with a fully validated and trusted email address, and continue with our own mechanism from there.
I cannot seem to find any way to do that with Microsoft's code - which handles a lot of situations, but all of them are fully automated.
It's not a lot of code to write to redirect to OAuth and receive the id_token on the other end, but still if we can take advantage of MS' system and perhaps support more authorities in the future with a plug-and-play manner - that would be great.

A: The answer is quite simple:
Option 1
Microsoft fails to properly document this in the right places, but it is in a sample that shows up in the main aspnetcore repo.
It's right here: Microsoft Sample
And the gist is that we can configure the authentication schemes you want like the many samples out there, and then just return a ChallengeResult or call this.Challenge(MicrosoftAccountDefaults.AuthenticationScheme) from the page and return the result.
We can also add events for the authentication lifecycle, like when the authentication completed - to act on it and hook it up to our own authentication system. We do that on each .Add[Whatever] call for a authentication service.
Option 2 - a bit more manual

*

*Generating the authorization urls is simple (and redirect)

*Then we get the JWT (id_token) back

*Use OpenIdConnectConfigurationRetriever from Microsoft.IdentityModel.Protocols.OpenIdConnect to retrive the set of keys from the OIDC endpoint ([authority]/.well-known/openid-configuration)

*Use the JwtSecurityTokenHandler from System.IdentityModel.Tokens.Jwt to read the token, and run the validations with the fetched signatures.

There's no need to use any JWT library, not to validate the timestamps manually, or the signatures.


text:
Q: Unable to build Spring-boot-sample-gae (deploy Spring Boot on GAE) We want to repeat the instruction of  spring-boot-sample-gae  step-by-step, but we are still not able to create the WAR file with the following error message :
[ERROR] Failed to execute goal on project gae-demo: Could not resolve dependencies for project org.demo:gae-demo:war:0.0.1-SNAPSHOT: Could not find artifact org.springframework.boot:spring-boot-legacy:jar:1.1.0.BUILD-SNAPSHOT in spring-snapshots (http://repo.spring.io/snapshot)
Could someone let us know how to tell spring-boot-sample-gae to find this dependency?
(We already have this jar (spring-boot-legacy-1.1.2.BUILD-SNAPSHOT.jar) locally.)
Also, it seems that Spring boot is not compatible to GAE(Google App Engine).
Is there any way to mitigate this issue?
We wish our Spring boot project can be deployed to GAE as soon as possible.
Thanks a lot !!

A: You have Spring Boot Legacy 1.1.2 locally but you're depending on 1.1.0. You need to update your POM to depend on 1.1.2:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-legacy</artifactId>
    <version>1.1.2.BUILD-SNAPSHOT</version>
</dependency>

You say that you have 1.1.2 "locally", but it's not clear if you mean that it's in your local Maven cache. That's where it needs to be. The easiest way to get it there is:
git clone https://github.com/scratches/spring-boot-legacy
cd spring-boot-legacy
mvn clean install


text:
Q: C# Avoid file lock when Assembly.Load My situation is;
I am designing a plugin application, based on dynamically loading plugin assemblies more than one user may run the application that's hosted on a server machine. Application is auto-updating plugin assemblies from my live update server on its startup. So plugin files (and its satellite dlls should not be locked on file system.
 byte[] assemblyBytes = File.ReadAllBytes("asm-path");
 var assembly = Assembly.Load(assemblyBytes);

as expected not locking the dll file. but what if the dll I am loading has static reference dlls itself? they are locked on file system now.
to name files, lets say;

*

*APP.Exe is my base application;

*PL1.dll is my first plugin, APP.exe loads it in a new Appdomain

*PL2.dll is my second plugin, APP.exe loads it in a new Appdomain

*PL1_S.dll is a static reference dll for PL1.dll plugin, loaded in PL1 AppDomain

*PL_COMMON is a static reference dll for both PL1 and PL2 plugins, loaded by PL1 and PL2 AppDomains

PL1_S and PL_COMMON also should not be locked in file like PL1 and PL2 assemblies
Any idea on how to solve that?

A: There is functionality already built in to do this, as used by e.g. ASP.Net. See Shadow Copying Assemblies:

Shadow copying enables assemblies that are used in an application domain to be updated without unloading the application domain. This is particularly useful for applications that must be available continuously, such as ASP.NET sites.

So just turn that on via the AppDomainSetup.ShadowCopyFiles when creating your AppDomains


text: Q: Spring Boot Admin Console 2.0.4 How to have the wallboard unsecured? I'm using Spring Boot Admin Console 2.0.4 (with Spring Boot 2.0.6) with security setup based on that provided in the reference guide http://codecentric.github.io/spring-boot-admin/2.0.4/#_securing_spring_boot_admin_server.  I can't see how to unsecure the wallboard page so that this is publicly accessible whilst securing the remaining pages.  Has anyone experience of doing this?


text:
Q: How to use the list index in a for loop?
Possible Duplicate:
Finding the index of a list in a loop

Assume you have a list, where not just the values have meaning, the index has, too.
counts = [3,4,5,3,1]

Let's say that means "we have 3 objects of type zero, 4 objects of type 1 and so on".
You want to create a list of objects from that and give these objects both information details:
[CountObject(amount=a,type=???) for a in counts]

How would you do that?

A: Use the enumerate() function:
[CountObject(amount=a, type=i) for i, a in enumerate(counts)]

where i is then the index.

A: Something like:
[CountObject(amount=counts[a],type=a) for a in range(len(counts))]

would do what you want i guess .

A: beside enumerate() you can also try range(), use xrange() if you're on python 2.x:
[CountObject(amount=counts[i],type=i) for i in range(len(counts))]


text:
Q: How can I get correct typing on handleSubmitWithRedirect when making custom SaveButton? I need a save button that is visually so different from the normal one, that I opted to build my own based on the SaveButton source code (as suggested in [1]).
However, just an import of the component cause the handleSubmitWithRedirect prop to protest that handleSubmit (I'm also going the customized form road, so handleSubmit here comes from the render property of react-final-form's Form component.) does not match the typing of handleSubmitWithRedirect. This is not a problem when using the SaveButton from the library (although according to WebStorm hswr has no type on SaveButton).
Since handleSubmit works when used with SaveButton.handleSubmitWithRedirect, I assume that there may not be an actual incompatability, just an issue with the type specifications.
I would appreciate help on both how to fix this issue, and/or help to understand exactly what is the issue. I'm quite far from being anywhere good at typescript.
I have tried with typescript 3.6.4 and 3.9.2.
Here is the typescript compiler error:

TS2322: Type '(event?: Partial, "preventDefault" | "stopPropagation">> | undefined) => Promise | undefined' is not assignable to type '(redirect?: string | boolean | RedirectToFunction | undefined) => void'.
    Types of parameters 'event' and 'redirect' are incompatible.
      Type 'string | boolean | RedirectToFunction | undefined' is not assignable to type 'Partial, "preventDefault" | "stopPropagation">> | undefined'.
        Type 'string' is not assignable to type 'Partial, "preventDefault" | "stopPropagation">> | undefined'.

handleSubmit has the type:

(event?: (Partial, "preventDefault" | "stopPropagation">> | undefined)) => (Promise | undefined)

handleSubmitWithRedirect (when SaveButton is imported into my tree) has the type:

((redirect?: (string | boolean | RedirectToFunction | undefined)) => void) | undefined

[1] How to change SaveButton icon in React-Admin

A: I ignored this for a while, but I did a react-admin update today, the latest version now being 3.9.5, and checked the SaveButton. Turned out that handleSubmitWithRedirect had had its type amended to
handleSubmitWithRedirect?:
    | HandleSubmitWithRedirect
    | FormRenderProps['handleSubmit'];

This allowed the suggested assignment of handleSubmit to work also from a TypeScript perspective.


text:
Q: COM/ActiveX and Downloading url I am have an ActiveX that asks a server for a URL and downloads / reads the data and ask for a new buffer of data until completion. The data gets read correctly, but if I watch the task manager the memory and the handles for IE go up and never come down. Process explorer shows that the handles are to the cache files.
int AXGetUrl(char*     url,
             void*     buffer,
             int       buffer_size,
             void*     pUnk)
{
char                    buffer2[256];
int                     rc;
HRESULT                 rc2;
ULONG                   buffer_len;
ULONG                   buffer_len2;
IStream*                pStream;
char                    newurl[1024];
ULONG64                 RequestBytes;
CURLCallBack            UCB;

    //Initialize
    rc = 0;
    rc2 = 0;
    memset(newurl,
           0x00,
           sizeof(newurl));
    buffer_len = 0;
    pStream = NULL;
    RequestBytes = 0;
    strcpy(newurl,
           url);

    rc = URLOpenBlockingStream((IUnknown *)pUnk,
                               url,
                               &pStream,
                               0,
                               &UCB);
    while (rc == 0)
        {
        if  (pStream != NULL)
            {
            rc2 = pStream->Read(buffer,
                                buffer_size,
                                &buffer_len);
            RequestBytes = RequestBytes + buffer_len;

            pStream->Release();
            pStream = NULL;

            buildnewurl(newurl,
                        RequestBytes);
            rc = URLOpenBlockingStream((IUnknown *)pUnk,
                                       newurl,
                                       &pStream,
                                       0,
                                       &UCB);
            }
        else
            {
            rc = 1;
            }
        }

    return (rc);
}

UPDATE:
#include "stdafx.h"
#include "Test.h"

Test::Test()
{
}
Test::~Test()
{
}

HRESULT Test::FinalConstruct()
{
void*       pUnk = NULL;
void*       buffer = NULL;
int         buffer_size = 131072;
ULONG       buffer_len = 0;
HRESULT     rc = 0;
HRESULT     rc2 = 0;
IStream*    pStream = NULL;
int         counter = 0;
char        url[1024];

    rc = QueryInterface(IID_IUnknown, &pUnk);
    buffer = malloc(buffer_size);
    if  (buffer != NULL)
        {
        //Get URL
        sprintf(url,
                "http://search.yahoo.com/search?p=%d",
                counter);
        rc = URLOpenBlockingStream((IUnknown *)pUnk,
                                    url,
                                    &pStream,
                                    0,
                                    NULL);
        while (rc == 0)
            {
            if  (pStream != NULL)
                {
                rc2 = pStream->Read(buffer,
                                    buffer_size,
                                    &buffer_len);
                pStream->Release();
                pStream = NULL;

                counter++;
                if (counter == 15)
                    {
                    break;
                    }
                sprintf(url,
                        "http://search.yahoo.com/search?p=%d",
                        counter);
                rc = URLOpenBlockingStream((IUnknown *)pUnk,
                                           url,
                                           &pStream,
                                           0,
                                           NULL);
                }
            else
                {
                rc = 1;
                }
            }
        free(buffer);
        }

    return (S_OK);
}

void Test::FinalRelease()
{
    return;
}

A: You are making a call to 'URLOpenBlockingStream' to retrieve a stream object but the stream it returns is never deleted. Assuming that IStream is a COM object you need to call Release() once you are done with pStream...
rc = URLOpenBlockingStream((IUnknown *)pUnk,
                           url,
                           &pStream,
                           0,
                           &UCB);
while (rc == 0)
{
    // ... your code here...
}

if(pStream != NULL)
{
    pStream->Release();
}


text:
Q: Django rewrites URL as IP address in browser - why? I am using django, nginx and apache. When I access my site with a URL (e.g., http://www.foo.com/) what appears in my browser address is the IP address with admin appended (e.g., http://123.45.67.890/admin/). When I access the site by IP, it is redirected as expected by django's urls.py (e.g., http://123.45.67.890/ -> http://123.45.67.890/accounts/login/?next=/)
I would like to have the name URL act the same way as the IP. That is, if the URL goes to a new view, the host in the browser address should remain the same and not change to the IP address. Where should I be looking to fix this?
My files:
; cpa.com (apache)
NameVirtualHost *:8080

<VirtualHost *:8080>

AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript application/javascript application/x-javascript
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/htm

DocumentRoot /path/to/root
ServerName www.foo.com

<IfModule mod_rpaf.c>
    RPAFenable On
    RPAFsethostname On
    RPAFproxy_ips 127.0.0.1
</IfModule>

<Directory /public/static>
    AllowOverride None
    AddHandler mod_python .py
    PythonHandler mod_python.publisher
</Directory>

Alias / /dj
<Location />
    SetHandler python-program
      PythonPath "['/usr/lib/python2.5/site-packages/django', '/usr/lib/python2.5/site-packages/django/forms'] + sys.path"
    PythonHandler django.core.handlers.modpython
    SetEnv DJANGO_SETTINGS_MODULE dj.settings
    PythonDebug On
</Location>

</VirtualHost>

;
; ports.conf (apache)
Listen 127.0.0.1:8080

;
; cpa.conf (nginx)
server {

listen       80;
server_name  www.foo.com;

location /static {
    root   /var/public;
    index  index.html;
}

location /cpa/js {
    root   /var/public/js;
}

location /cpa/css {
    root   /var/public/css;
}

location /djmedia {
    alias "/usr/lib/python2.5/site-packages/django/contrib/admin/media/";
}

location / {
include /etc/nginx/proxy.conf;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass   http://127.0.0.1:8080;
}
}

;
; proxy.conf (nginx)

proxy_redirect          off;
proxy_set_header        Host            $host;
proxy_set_header        X-Real-IP       $remote_addr;
proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size    10m;
client_body_buffer_size 128k;
proxy_connect_timeout   90;
proxy_send_timeout      90;
proxy_read_timeout      500;
proxy_buffers           32 4k;

A: Its probably your mod_rpaf config, I'm guessing the "RPAFsethostname On" line in particular.
I'm not fully confident because after googling for 10 minutes its clear that there is little to no documentation anywhere on mod_rpaf. It seems to be the kind of thing you would only ever hear about in a handful of "me and my fancy stack" blog posts.   It solves a problem that you can just as easily solve in your django layer and not run some mystery apache module by some guy you read about on some blog post.
Its actually covered in the middleware chapter of the book: http://www.djangobook.com/en/2.0/chapter17/

A: Why even use nginx+apache+mod_python? Your stack is crazy and mod_python is horribly slow. Look into removing apache and running a wsgi server: I recommend uwsgi. I use it with nginx and django and it is wonderful!
http://projects.unbit.it/uwsgi/
I think you are just over complicating things.


text:
Q: Dynamic HTML with Javascript in JavaFX Webview I will try to ask my Question as precise as I can. At the moment I cannot post any example Code as I'm not allowed to post code of my work. In my next free time I will lookup that I will code some example to be more precise.
Here is my Question:
I'm developing some project where I built some HTML and Javascript code dynamically with Java and load it into a Webview of JavaFX. The Html has to be generated dynamically because there are lots of Information in it that come up from a central database. Then I try to run it via a ChangeListener that is set on LoadWorker for the WebEngine of the Webview to ensure that the Webpage is loaded. The page is loaded correctly but when I try to use some javascript function the Application crashes.
The whole thing is working with a local written html document. In the Html are lots of Javascript-Libraries like Jquery and others. But my project crashes because the libraries and its functions cannot be used. I think that the http-Request of loading a local written html sets up these javascript when the webpage is loaded.
Am I correct with this?
And is there anything I can fix this Problem with dynamic generated htmls loaded in a Webview.
Thanks for any help!


text:
Q: How can I unmask the first name and email address on Microsoft clarity of people who visit my checkout page I linked my Wordpress website to Microsoft clarity in order to manage and see how users are interacting with my website. Now when users insert their first name and username in the input boxes field of the checkout (the plug-in that I'm using for checkout is cart flow, its responsible for managing the form fields) the information that they have added is masked when viewing it through "recording feature" of Microsoft clarity, even though I tried a variety solutions that I mentioned in the bottom to unmask the information they provided
**For anyone asking why i want to unmask, its just to give me a more in depth analysis of users who are facing difficulties signing up or buying a specific product **
Things I've done to unmask form input fields:
1- Added a parent CSS class selector for the the form. (doesn't work)
2- Added input & select selectors as umasked (doesn't' work)
3- Added data-clarity-unmask="true" to a parent div of the form (doesn't work)
The only think I haven't tried is adding data-clarity-unmask="true" to each individual form input. I'd have to modify the form plugin's code so I was trying to avoid that.
Any possible solutions to this problem ?


text:
Q: Where does map-reduce/hadoop come in in machine learning training? Map-reduce/hadoop is perfect in gathering insights from piles of data from various resources, and organize them in a way we want it to be.
But when it comes to training, my impression is that we have to dump all the training data into algorithm (be it SVN, Logistic regression, or random forest) all at once so that the algorithm is able to come up with a model that has it all. Can map-reduce/hadoop help in the training part? If yes, how in general?

A: Yes. There are many MapReduce implementations such as hadoop streaming and even some easy tools like Pig, which can be used for learning. In addition, there are distributed learning toolset built upon Map/Reduce such as vowpal wabbit (https://github.com/JohnLangford/vowpal_wabbit/wiki/Tutorial). The big idea of this kind of methods is to do training on small portion of data (split by HDFS) and then averaging the models and commutation with each nodes. So the model get updates directly from submodels built on part of the data.


text:
Q: Proving pointwise convergence given that $f$ is bounded and cont Given $f:X\to\mathbb{R}$ be a bounded function such that $\exists M$ s.t $|f(x)|\leq M$ and $f_k:X\to\mathbb{R}$ where $f_k=\inf_{y\in X}(f(y)+kd(x,y))$ Let $k\in\mathbb{N}$ and $X=\mathbb{R}$ and $d(x,y)$ be the usual metric. Let $(X,d)$ and $f$ be arbitary metric space and bounded function.

Show that if $f$ is both continuous and bounded then $f_k\to f$ pointwise as $k\to\infty$

How would I go on about proving this?
What I know so far is that.
Let $M>0$ using the contounity of $f$. Then for $x\in X$ and $\epsilon >0$, let $\delta >0$ and $f_k=\min{(T_1(x),T_2(x))}$, where
$$T_1(x) =\inf_{y\in B(x;\delta)}\{f(y)+kd(x,y)\},\qquad T_2(x) =T_1(x) =\inf_{y\notin B(x;\delta)}\{f(y)+kd(x,y)\} $$
How would I go on to prove that $T_1(x)\leq M$ and $T_2(x)\geq -M +k\delta$

A: First, $f_k$ is an increasing sequence as $f_k\leq f_{k+1}$
Also for $y=x$ we get that $f_k(x)=\underset{x\in X }{inf}(f(x)+kd(x,x))=\underset{x\in X}{inf}(f(x))\leq f(x)$
So $f_k$ is bounded as $f$ is so. This means that $f_k$ converges pointwisely.
Recall that in general if $inf A$ exists, then $\forall \epsilon >0$ $\exists x_0\in A$ such that $x_0\leq infA+\epsilon $
Applying this on $f_k(x)$, there exists a sequence $(y_k)$ of $X$ such that  $f(y_k)+kd(x,y_k)\leq \frac{1}{k} + f_k(x)$ (took $\epsilon=\frac{1}{k}$)
Then $d(x,y_k)\leq \frac{f_k(x)+\frac{1}{k}-f(y_k)}{k}$. Notice that the right side converges to zero as both $f$ and $f_k$ are bounded, which means that $d(x,y_k)$ goes to zero that is $y_k$ converges to $x$.
So now that we already have $f(y_k)+kd(x,y_k)-\frac{1}{k} \leq f_k(x)\leq f(x)$ , take the limit on all sides.
We get  $f(\lim_{k \to \infty }y_k)+0-0\leq \lim_{k \to \infty  }f_k(x)\leq f(x)$.
(As $f$ is continuous, $\lim_{k \to \infty }f(y_k)=f(\lim_{k \to \infty }y_k)$)
Therefore we get, $f(x)\leq \lim_{k \to \infty  }f_k(x)\leq f(x)$, hence the result.


text:
Q: Backend script passing data to client-side script Say that I have a Python Flask server running which has a backend script that produces a number and a string.
How can I pass the number and string from the backend to a script that runs of client-side so that the user can run it rather than the server?
Example:
backend script data_producer.py produces "asdaslkdjasdlksja" and 18 from its functions
I want to pass "asdaslkdjasdlksja" and 18 to a Brython or JavaScript HTML embed ( tag) so that it can be processed in the browser and the results be sent back to my server.
Edit: I realized that I can just use Jinja2's "{{ }}" when rendering a template so that I can use data in an HTML script embed

A: The question you asked is too broad. It's almost equivalent to asking, how you can connect two computers. Since you haven't even specified any data type, the first thing that comes to my mind is using sockets which is as low level as you can get.
A more high level and appropriate approach would be to use an HTTP REST server (with flask-RESTful), since you already have a flask server running.
However, there's another million ways to transfer data between two Python scripts, from WebSockets, WebRTCs, sshing, the new IPFS to even emails. Now most of them would probably be overkill, so I would suggest you to make a simple REST server and make the client send GET or POST requests to it.
After looking at the new edit, I still think a REST api is the best option. Since you can easily make a GET or POST request using the fetch api in Javascript. In Brython you can use ajax to do the same thing.


text:
Q: Django - Assign default value to field in ModelForm In my application I have a CreateView that must initialize some fields of the model with a default value, different from the default defined inside the model.
I do not want the user to edit the value, thus I put the field in the exclude list
class AForm(ModelForm):
    class Meta:
        model = AModel
        exclude = ['a_field']

class AView(CreateView):
    form_class = AForm

The question is: where do I set the value of a_field?
I tried to define clean methods inside AForm, like thus
class AForm(ModelForm):
    [...]
    def clean(self):
        d = super(AForm, self).clean()
        d['a_field'] = 10
        return d

however a_field is set to whatever its default value defined in the model is, rather than 10. I also tried defining clean_a_field, but that is simply not executed.
If I remove a_field from the exclude list, then the clean and clean_a_field will work, but the form won't validate unless I render some <input name="a_field"> inside the template, which is not optimal.

A: I managed to solve the issue in a way that makes me satisfied, although I'm still not 100% happy with the code.
a_field is a required (by the model) field, thus it is necessary to render an <input name="a_field"> inside the template. The trick was to make a_field non-required:
class AForm(ModelForm):
    a_field = Field(required=False,
                    widget=forms.HiddenInput)
    class Meta:
        model = AModel

    def clean_a_field(self):
        return 10

This way I can avoid rendering the field in my template, and the form will still validate. And even if the form is rendered with {{ form.as_p }}, widget=forms.HiddenInput saves my day.

A: Exclude the field from the form, then in the view you can set the value before you save the form:
form = AForm(request.POST)
if form.is_valid():
    new_record = form.save(commit=False)
    new_record.a_field = 10
    new_record.save()

You also might want to avoid the exclude list and specify which fields you'd like to include with the fields attr of the form definition. See the first paragraph here in the docs.

A: You set a default value in the model. From the official document,
a_field = models.CharField(max_length=7, default=''), for example

A: I have a way to Face this situation. Follow the following process:

*

*Remove 'a_field' from the excludes in AForm.

*Do not expose 'a_field' in HTML template. i.e. Don't give the user option to change the value via Form in Template. This would ensure that normal user's wont modify the value.

*To prevent completely, over-ride get_form_kwargs in the View.
This would provide or over-ride your desired value to 'a_field' and save that
e.g.

class AView(CreateView):
    form_class = AForm

    def get_form_kwargs(self):
        kwargs = super(AView, self).get_form_kwargs()
        if self.request.method in {'POST', 'PUT'}:
            # Change post data to over-ride or provide value of 'a_field'
            data = self.request.POST.copy()
            data.update({
                'a_field': 'value'
            })
            kwargs['data'] = data
        return kwargs


text:
Q: How to keep command line open when error occurs when running a program through an executable (.exe) I created an executable program using PyInstaller (Python 3.6). When you click on the .exe file it runs through the command line. This is intended as I haven't created a GUI interface yet.
My issue is if there are any errors the command line immediately closes. It's impossible to catch what the error was, which is frustrating. It's not an issue for me as developer, as I can run my program through an IDE. However, I'd like other people on my team (They are not developers or programmers) to try it out and give feedback including any errors that come up that I may have missed. They will not be able to let me know of any bugs if it shuts down that quickly.
I've tried creating a .bat file and using os.system('pause'). I couldn't get the .bat file to work when I'm not running a .py script, but an .exe instead as show here Keep Windows Console open after a Python Error. I also couldn't figure out how incorporate the .bat file when I'm using PyInstaller to create an executable from a .py file.The pause function in the os module does work, however it pauses in only where the code is located.
Ideally, I would like the user to take as long as they want to be able to read the error before closing the console and let me know what it is so I can fix what I need to. Right now, as mentioned earlier, the console closes almost instantly.

A: Can you please try this .BAT file? Maybe it can help.
CALL MyExeFile.exe
PAUSE

An other possible solution can be
cmd /c "MyExeFile.exe"

Please let me know, if one of the workarounds is successful.


text:
Q: How do I fix CLIENT_MISSING_INTENTS error? I started learning about discord.js, but now I am facing this issue.
I tried some googling, but I couldn't manage to fix it.
const Discord = require('discord.js');
// const Discord = require('discord.js');

// Using Intents class
const client = new Discord.Client();

client.on('message', (msg) => {
  // Send back a reply when the specific command has been written by a user.
  if (msg.content === '!hello') {
    msg.reply('Hello, World!');
  }
});

client.login('my_token');

This is the error I am getting:

A: You can instead just degrade the discord.js version by typing this into the shell:
npm i discord.js@12.5.3

The latest discord.js version doesn't function very well, so I use v12. It isn't a complicated script.

A: You need to specify the events which you want your bot to receive using gateway intents.
Instead of
const client = new Discord.Client();
Use
const client = new Discord.Client({ intents: [Enter intents here] })
For example
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] })
Here's another useful page: Gateways

*

*Intents help you control which events your bot receives. See Privileged Intents for more information.

*You need node.js 16.6 or higher to use discord.js13. npm install node@16 in shell.

*The list of events are under the events tab at Client.

A: Add Intents.
const { Client, Intents } = require('discord.js');
// Create a new client instance
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });

You can also use the template available in the discord.js documentation.
Documentation

A: client = new Discord.Client({intents: 32767})


text:
Q: How to write a simple C# script to copy file to directory one level up? Trying to write a simple C# script to copy file to directory one level up. Here is what I have, but it is sending an error,

"Script.OnActivate()" not all code paths return a value.

and my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Windows.Forms;
using System.Globalization;

    class Script : CopyFile {

        public static bool OnActivate() {
            CopyDataFile("script/file.js", "../file.js");
        }

    }

SOLVED!
using System;
using System.IO;

class Script : CopyFile {

    public static void OnActivate() {
        FileInfo myFile = new FileInfo("script/file.js");
        myFile.CopyTo(myFile.Directory.Parent.FullName + "\\" + myFile.Name);
    }

}

This moves file.js into the directory one level up from "script/"

A: The description is as it is described. You need to change your OnActive to be void, or return a boolean (ie. If CopyDataFile returns a boolean, then return CopyDataFile(...))

A: The error occurs because you do not return a bool
   public static bool OnActivate() {
        CopyDataFile("script/file.js", "../file.js");
        return true;
    }

If you dont want to return something change you method to return void, do the following
   public static void OnActivate() {
        CopyDataFile("script/file.js", "../file.js");
    }

MSDN The void operator evaluates its expression, and returns undefined. It is most useful in situations where you want an expression evaluated but do not want the results visible to the remainder of the script.


text:
Q: Component will not delete I'm doing a bit tidy of the Content Manager and have a component that won't delete (not the same as my other question).
When I try to delete the component in question I get the following error
(8004032D) This item is in use.
Unable to delete Component (tcm:4-65020).

UtilitiesBL.AssertItemCanBeDeleted
UtilitiesBL.AssertItemCanBeDeleted
ComponentBL.Delete
Component.Delete
Request.Delete

When I use the Where Used tool on the component I get no results in the "Used In" tab, one result in the "Uses" tab, the "Blueprint Hierachy" shows it is not localized in any of my three child publications and no results in the "Published To" tab.
I have had a look in the Content Manager database to see if I can spot what is going wrong but not really found anything.
Any ideas?
Thanks in advance.

A: It looks like the Where Used tool in R5.3 isn't working correctly. The component in question is used in 15000 other components. I found this by using the TOM API directly.
var componentID = "tcm:4-65020";
TDS.TDSE tdse = new TDS.TDSE();
var component = (TDS.Component)tdse.GetObject(componentID, TDSDefines.EnumOpenMode.OpenModeView);
var whereUsedString = component .Info.GetListUsingItems();

Now comes the task of deleting all these links...


text:
Q: Mirror number of unread mails in title bar Is there a way to show the exact number of unread mails from the Mail.app icon also in the title bar? Note that this is not the same as showing the number of unread mails in inbox, since I can change the folder to something else like a smart mailbox.
(A script which outputs this number would also be okay; I could write a menu bar item around this myself.)
Update: Alternatively, a script which outputs the number of unread mails for a user-definable smart mailbox is also okay. All example code I've seen so far only works for non-smart mailboxes.

A: You can obtain the number of unread items with the following AppleScript:
tell application "Mail" to get the count of messages of mailbox "INBOX" of account "Me"

As you mentioned you could write a menu bar item, you could use this AppleScript for it.
Alternatively, you can do this with Mail Unread Menu.
However, I'm not sure if it works with Mavericks.

A: Try this:
set unreadNumber to 0
set i to 1
tell application "Mail"
activate
get message viewer 1's selected mailboxes
repeat with thisBox in result
    repeat until ((message number is i) exists) is false
        if read status of (message number i of thisBox) is true then set unreadNumber to (unreadNumber + 1)
        set i to i + 1
    end repeat
end repeat
display dialog "You have " & unreadNumber & " unread messages."
end tell


text:
Q: Laurent Series On Multiple Domains Find the laurent series for the function $ \frac {1} {(z-1)(z-2)} $ in each of the following domains:
a) $|z|<1$
b) $1<|z|<2$
c)$|z|>2$

I understand all the maths in doing these problems, my main issue is how do we know when to write the terms in geometric series on a certain domain?
For example in problem (a) on the domain $|z|< 1 $ we expand using partial fraction decomposition and get $$ \frac {1} {(z-1)(z-2)} = \frac {1} {z-2}-\frac{1}{z-1},$$
Then we proceed to find the expansion for each term here:
$$ \frac {1} {z-2} = -\frac 1 2 \frac{1}{1-\frac z 2}=-\frac 1 2\sum_{j=0}^\infty (\frac z 2)^{j}=-\sum_{j=0}^{\infty}\frac{z^j}{2^{j+1}}$$
$$\frac {1} {z-1}=-\frac{1}{1-z}=-\sum_{j=0}^\infty z^j $$
Now this all makes sense to me, my issue comes in problem (b) on the domain $ 1<|z|<2$. The domain still doesn't include the singularities 1, or 2, but they still change the expansion for $\frac {1}{z-1} $ by finding the geometric series another way.
$$ \frac {1} {z-1}=\frac 1 z \frac{1}{1-\frac 1 z}=\frac 1 z\sum_{j=0}^\infty \frac {1} {z^j}= \sum_{j=0}^\infty \frac {1} {z^{j+1}}$$
I don't understand what is different in this domain that doesn't allow us to use the old expansion for $\frac{1}{z-1}$ that we used in problem (a).


text:
Q: Deriving the stress-energy tensor from the Einstein-Hilbert action I'm a mathematician who knows very little physics and is trying to learn relativity theory from a mathematical perspective.
Let $M$ be a compact, orientable manifold. In the vacuum, the Einstein-Hilbert functional is
 \begin{equation}
  S(g) = \frac{1}{2\kappa} \int_M R_g \, v_g
 \end{equation}
 where $g$ is any semi-Riemannian metric on $M$ and we denote by $R_g$ and $v_g$ the scalar curvature  and volume form of $g$ respectively,
 and $\kappa = \frac{8\pi G}{c^4} = 8\pi$ is a constant. The Euler-Lagrange equation for this functional is the Einstein equation $\mathrm{Ric}_g -\frac{1}{2} R_g \, g= 0$. I understand this and know how to prove it, so far so good.
What about the non vacuum case? From what I understand from Wikipedia, the presence of matter is encoded by a smooth function $\mathcal{L}_g  = \mathcal{L}(g, \cdot) \colon M \to \mathbb{R}$. In this case the functional is
  \begin{equation}
  S(g) =  \int_M \left[ \frac{1}{2\kappa}(R_g - 2\Lambda) + \mathcal{L}_g \right] \, v_g~.
 \end{equation}
Now, they say, the Euler-Lagrange equation is
 \begin{equation}
  \mathrm{Ric}_g -\frac{1}{2} R_g \, g= \kappa T
 \end{equation}
 where $$T := -2 \frac{\delta \mathcal{L}_g}{\delta g^{\mu \nu}} + \mathcal{L}_g g_{\mu \nu}$$ is the stress-energy tensor (by definition).
I am puzzled by this because:

*

*For starters, it looks like the stress-energy tensor $T$ does not only depend on $g$, but also on its first variation $\delta g$. Therefore the Einstein equation is not properly speaking an equation on $g$. Isn't that unacceptable?

Edit: I mean, my understanding from the vacuum case is that Einstein's equation is an equation where the unknown is the metric $g$, and
$g$ solving the equation is equivalent to being a critical point of the EH functional. Now this interpretation fails. Am I supposed to understand that now a solution is a $1$-parameter family of metrics? What would the parameter represent? (I thought that "time" is already part of $M$).

*What is $\mathcal{L}$ supposed to be, say in terms of a mass distribution or something? I mean, if we say nothing about $\mathcal{L}$ other than it's a function of both $g$ and $x\in M$, that's the most general thing we can imagine to integrate. We might as well throw $\frac{1}{2\kappa}(R_g - 2\Lambda) $ in $\mathcal{L}$ then, why not? It seems a little silly.


text:
Q: Is Heap sort is an in-place sorting algorithm when we use recursive version of heapify? I understand that we are constructing a max-heap using the same array (which we have to sort) so there is no extra memory required there (from here).
But my question is what about heapify function (which is recursive when I follow Introduction to Algorithms, CLRS) which we use while building the heap (and also during swapping the first element of heap - that is the biggest and the last element of the heap and then again re-heapifying the array).
The call to this recursive function can, in worst case take O(log(n)) because of storing the stack pointer on each recursive call.
So, my question is that when this wiki article says that heapsort is an inplace sorting algorithm, does it implicitly mean that the heapify function that it is assuming is non-recursive one (which will not take any (non-constant) extra space). Or is there something that I'm missing?
Will the space complexity of heapsort, which uses a recursive heapify function, be O(log(n))?


text:
Q: Html5 input type number formatting I have this page where i use the input type number. so that it will show the numeric keyboard on wp, android and ios device .
But my problem is that if the user use a culture info on the device for. lets say Denmark. the numeric keyboard shown use , instead of .
But the input number won't accept , only .
Anyone got a idea how this can be done?
Thanks for your time.

A: Try setting the lang attribute to en in the  element or the <input> element itself to force decimal point as input syntax. For example:
<input type="number" name="myNum" id="myNum" lang="en">

However the user's environment may even override this, in which case the only alternative would be to include a message requiring decimal point rather than comma.
This is a good write-up of locale handling for the number input type:
https://www.aeyoun.com/posts/html5-input-number-localization.html
UPDATE:
Another alternative would be to stop the form from validating the input by using the novalidate attribute in a <form> element, like so:
<form novalidate>
  <input type="number" name="myNum" id="myNum">
  <button id="submit">Submit</button>
</form>

This would allow anything, even non-numbers, so you'd have to set up the JavaScript code to check and handle the value.
UPDATE AGAIN:
Just thought of one more alternative — use the pattern attribute to do a regular expression check and use the plain old text input type. For example:
<input type="text" name="myNum" id="myNum" pattern="[0-9.]*">

Advantage: You get to control exactly what users can input.
Disadvantage: The keyboard on mobile devices will not be the numeric keypad.
Note that HTML input types can be spoofed so you still need to do server-side validation.

A: When retrieving the value with jquery it is returned with a . decimal separator. Try this:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>JS Bin</title>

  <input type="number" name="myNum" id="myNum">
  <button id="submit">Submit</button>

http://output.jsbin.com/xixunewowe


text:
Q: Allow comments for all users; create comments review queue Low-rep users can't leave comments. This leads to many users posting their comments as answers.
While the rationale behind this limitation is understandable, seen from the outside, it looks  inane and bureaucratic. New users often have useful information to bring to the table. That information is often enough destroyed through deletion,  or has to be manually converted to a comment by a moderator.
How about, experimentally for a month or so, removing the limitation, allowing comments from (registered) new users, and countering the threat of garbage comments with

*

*A comment review queue for low-rep users' comments

*A lowered flagging threshold for low-rep users' comments (say, 2 flags instead of 3 or whatever is required right now)
After all, features like anonymous feedback show that there's value to be gained from the input of the countless visitors who end up on Stack Overflow through Google, but are never going to become active members of the community. So why not use it?

A: I think there is value in the idea, and now that we have review queues (which didn't exist when the comment feature was devised) you can have a multitude of users reviewing comments for appropriateness, and flagging ones that aren't.  Maybe you can even consider a short term "comment" ban for low-rep users who have a high rate of comment deletions due to inappropriate comments.
But I am concerned removing the limit for just a month is just going to cause confusion, because if we decide that the rep-less commenting is causing more harm than good, and we roll it back, you are going to have a lot of lower rep users get used to the ability when we take it away.
A longer period of time for the test would solve this problem as most of the affected users would hopefully achieve the 50 rep limit and won't miss it, but another alternative would be graduated test over several weeks (or months).  Initially, we can start by dropping it to 25 rep, then 15, 10 and eventually 0.  We can assess the "damage" at each step and make a decision if to move forward with the next step or if we need to stop and watch it for a while longer, but unless there was serious damage, we don't roll back to the previous rep level,

A: Not to be a broken record, but the main reason for keeping new users from commenting is that their comments are vanishingly unlikely to be useful. In order to comment (as opposed to answer) you need to establish:

*

*is information missing? For example, I've seen comments asking for information, such as what programming language this is, that is clearly in the tags

*is this in fact a duplicate question that requires neither comment nor answer, just directing the asker to a beautiful canonical Q/A pair?

*is the question hopelessly off topic and about to be closed, making any request for further clarification or details irrelevant?

*is this the kind of tag where 10 people will post an answer while you're posting your "have you tried debugging yet I often find that yields a lot of insight" comment?

New users (those with less than 50 rep) tend not to know this. They don't know about tagging, they don't know about dupes, they don't know how quickly or slowly things move on a particular site or in a particular tag. Yes, you may know a counter example who read for weeks or months and came to learn our entire system without ever asking or answering anything, but rules are not made for counterexamples, and that learner could have tossed off 25 edits during the journey and would be comment-ready by so doing. Folks who Googled for their problem, then followed a few links and are now wondering if they could possibly answer a question, but want to comment first for clarification, are simply not comment-ready. Telling me they really want to comment changes nothing.
I've said this before and I'll continue to say it every chance I get. And as I have said before, the complaint that no questions exist that can just be answered without commenting is utterly and obviously untrue. We all found some didn't we?

A: I'm strongly against this idea. (At least not without comments aging away with no interaction which hasn't been popular previously).
Even if there's a limited trial and the outcome isn't just pain, Stack Overflow is about Questions and Answers. The bottom line is we want good questions and good answers not comments and that's a message we rightly emphasize from day one.

*

*We can't clear a review queue of questions where the quality has been called into doubt and some of the other review queues are far too lenient.

*We don't have search tools for comments

*Mod tools for comments are somewhat painful except the nuclear "purge all option" (To be precise it's hard to handle the flags and see the context of the comment simultaneously, it's hard to bulk delete comments by specific troublesome users).

*New users can't vote. (For good reasons). If we shift the barrier for "out of band" interactions then comments will be come a proxy for voting through "+1 same here but I couldn't vote" comments. At best it just shifts the problem elsewhere.

Let's not spend dev time when there are other cool feature requests begging for it and not waste reviewer time when it's clearly in great demand already.
Please, let's stick to doing Q&A well, not descend into the quagmire of awful "me too" and "same here" comments which say less than the original post that the rest of the Internet is drowning in --- that's part of what makes this format so great.

A: I'm still concerned about the potential of a massive backlog in the proposed comment review queue.
The last time an idea like this came up we had approximately 1,642,000 users with less than 50 rep. and I still think if each one of them posted one comment that went into a review queue we would have a massive problem.

I'm guessing that if we opened up commenting to new users and dumped
all of those comments into a review queue, the queue would fill up
fast, really fast, faster than reviewers would likely be able to keep
up with.
If the backlog grew well into the thousands, and I wouldn't be
surprised if it did, it would take quite a while for a comment to
reach its intended destination and with comments being transient in
nature, I doubt that many of the comments would still be relevant days
or weeks later.

For those that have doubts about the number of comments creating a significant backlog, here's some data:

That's just comments from users with less than 50 rep commenting on their own posts each week... Imagine how big that number could get if we opened the flood gate.
SE tries to optimize for pearls not sand. A review queue for comments would seem to ask users to sift through sand, and look for better and worse qualities of sand.

A: One of the main arguments that has been made against this so far is that comments wouldn't be reviewed quickly on sites which already have review backlogs. But as far as I can see, this applies only to Stack Overflow and a few others. Thus, why not leave things on those sites as they are and test this feature somewhere else? (Moreover, since empty review queues correlate with the effort required from users to reach 50 reputation.)
Apart from the workload of implementing this, the only potential negative side I acknowledge is the risk of "teaching" users to use Stack Exchange the wrong way. On the other hand, one could argue that the current system teaches users to post comments as answers or more generally to misplace content. And let's not forget that a proper review can teach users what is an appropriate comment – something that we hardly teach users right now. Moreover, there is little incentive for leaving useless comments.
As with the proposed triage system, one could think about letting comments go live only after review.
So, why is this worth the effort?

*

*The current system scares away potential contributors: If you are new to something, you usually want to start at a low level, which would be commenting on Stack Exchange. If you cannot do this, this alone might keep you from contributing on a higher level. If you decide to go against the rules to post a constructive comment as an answer, this may be a disappointing experience due to the lack of a comment-conversion option in the low-quality-posts review queue, as I elaborated here.

*This might actually reduce the workload of admins and reviewers. Evaluating whether a comment is appropriate as such is done relatively quickly in most cases. On the other hand, the current system causes a lot of comments-as-answers in the low-quality-posts review queue which require a more thorough evaluation as to whether there is some hint of an actual answer left in them. Also, admins have the workload of performing comment conversion right now.

*We get some constructive comments.
As a bonus, the same queue could also be used to allow users reviewing comment flags, something that is restricted to admins right now. This might drastically help keeping the comment sections clean.

A: I am in favor of status quo (commenting is a 50 rep privilege).
Mainly for these simple points

*

*1 rep users could spam comments easily. Even if this went into a queue it would be a hassle to deal with.

*Using a queue is counter intuitive for a comment which is supposed to show up instantly. It could cause a lot of duplication to occur.

*New users do not understand the system and many times consider it to be a forum or a social network which results in poor comments.

A: As a new user I think something should be done with the reputation cap for commenting. I mean, yea you run the risk of a bunch of new users commenting the pointless "me too" thing. I've been on this site a week now, and I've run into questions where I can't give a complete answer, but I do have some info that might help, which is what I have seen comments used for, for the most part. Yea the site wants quality questions and answers, however comments do have their place in that system.
It's part of the basic functionality of the site. Personally I think it should be a privilege you can lose, and not one you have to earn. My thought process for fixing it is to start users out with enough rep to comment, maybe coupled with a lower comment reputation requirement. However that leads to other balance issues, like proxy voting. Hell, even just matching the up/down voting requirement would make a lot more sense in my mind.
I usually hang out on the philosophy board, and they are pretty understanding of that fact, and usually don't downvote the newbie who is just trying to contribute. As long as I give that warning of a partial answer. Also a good number of times people will have already answered the crap out of a question, and you just want to throw this little tidbit out there to add to their answers.
There is my two cents as a new user. The devs will do what they think is best for the site.

A: I think we need the opposite: we need to make it harder for newer users to leave comments. Most comments left by new users on their own questions,  which do not require 50 reputation,  should instead be edits of their question.


text:
Q: Select arbitrary single value for GROUP BY: What's the fastest option? I have a query that I use to indicate locations in a map where there are overlapping points:
select
    min(objectid) as min_objectid,
    longitudex,
    latitudey,
    count(1) as count,
    min(shape) as min_shape
from
    workorders
group by
    longitudex,
    latitudey
having
    count(1) > 1

In the mapping software that I use, I need to include columns like objectid and shape. For those columns, it doesn't matter which of the grouped-by rows the values come from, just as long as there is a value.
Presently, I'm using min() to get an arbitrary value for those columns. However, I don't know if that's the fastest option since finding the minimum value would require calculation — and I wonder if that time spent is unnecessary.
What is the fastest option for getting an arbitrary/single value for GROUP BY in an Oracle query?

A: Your query does return the duplicate locations, but does not return the individual points (work orders) with the same location.
This returns those locations again (same as your query, just reformatted in a more compact notation):
select longitudex, latitudey, count(*)
from workorders
group by longitudex, latitudey
having count(*) > 1;

Then this returns the individual work orders that share the same location:
select objectid, longitudex, latitudey, shape
from workorders
where (longitudex, latitudey) in (
  select longitudex, latitudey
  from workorders
  group by longitudex, latitudey
  having count(*) > 1
);

That obviously only works if the geographical coordinates are exactly the same for work orders at the same location, down to all decimals. If not then you need to use spatial operators to compare the locations. Those are available with databases like Oracle (out of the box) or PostgreSQL (with the PostGis extension).

A: With Oracle 12.1 or later, add this to the end of the query:
fetch first row only

By the way, count(*) is the standard expression across all SQL variants as far as I'm aware.
For your example, that would be:
select
    min(objectid) as min_objectid,
    longitudex,
    latitudey,
    count(*) as count,
    min(shape) as min_shape
from
    workorders
group by
    longitudex,
    latitudey
having
    count(*) > 1
fetch first 1 row only


text:
Q: using java priorityQueue remove method I was looking for dijkstra algorithm with java.
Below code works normally.
public static void computePaths(Vertex source, Subway p, int broken)
    {
        //set the source vertex distance to 0 (as distance source->source=0)
        source.minDistance=0;
        //init queue , add source to keep track of nodes visited (cloud)
        PriorityQueue<Vertex> vertexQueue = new PriorityQueue<Vertex>();
        vertexQueue.add(source);

        //keep track of total vertices tracked so as not to go in circles
        List<Integer> l=new LinkedList<Integer>();

    // while the cloud is not empty
    while (!vertexQueue.isEmpty()) {
        // take the head as u and...
        Vertex u = vertexQueue.poll();
        //(add position of u to the tracking list)
        l.add(new Integer(u.pos));

            // ...Visit each edge exiting u
            Iterator<Edge> it=(p.subwayNetwork.getEdges(u.pos)).iterator();
            while (it.hasNext())
            {

                Edge e= it.next();
                Vertex v = e.dest;
                Double weight = e.weight;
                // calculate the distance from u to the node v
                Double distanceThroughU = u.minDistance + weight;

                // if the distance is less then the min. distance, and not already visited, and  neither
                // the vertice and edge are broken
                if (distanceThroughU < v.minDistance && !l.contains(v.pos) && v.pos!=broken && !e.broken) {
                    //remove the node form the queue and update the distance and prev. value
                    vertexQueue.remove(v);
                    //update the distance
                    v.minDistance=distanceThroughU;
                    //update the path visited till now
                    v.previous = u;
                    //reenter the node with the new distance
                    vertexQueue.add(v);

                }
            }

        }
    }

why that vertexQueue.remove(v); occurs no error?
since we init the queue, we add something then poll.
so queue might be empty.
I thought remove operation occurs NoSuchElementException error.
but it operates normally.
and advice would be appreciated

A: The remove()-method has bool as its return value.
It returns "true" if the queue changed as a result of the call, otherwise, it returns "false", but no exception!
Source: https://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html#remove(java.lang.Object)


text:
Q: If $x = 0$, then $x/x$ is undefined, right? It's been a while since I worked with math, but I stumbled upon a rather 'simple' equation and the ways of solving it had me thinking for a bit.
Consider this equation:
$$x(1-x) = x(2 - \sqrt{1-x})$$
Any normal person would consider making the problem easier by dividing both left and right side of the equal sign by $x$, but bear in mind that one of the solutions might be $0$, so this is what makes me wonder, why would it be allowed to even divide by $x$ here, if one of its solutions might be $0$ then that is that $0/0$ is undefined... right?
Kindly refresh my memory.

A: Dividing by $x$ is permissible, but this reduces the equation into two cases where $x$ may or may not be $0$.
Let's go with a basic, almost trivial, example:
$$x^2 + x = x^3 - x^2$$
Now, at a glance, we can divide this by $x$, and get
$$x + 1 = x^2 - x$$
However, the caveats abound:

*

*Yes, if $x=0$, we can't divide by it. We treat this case separately.

*This is especially pertinent since $x=0$ is clearly a solution of the original.

So really we have that
$$x^2 + x = x^3 - x^2 \implies \begin{cases}
x^2 + x = x^3 - x^2, & \text{if } x=0 \text{  (we'll see what happens here)} \\
x+1 = x^2 - x, & \text{if } x \ne 0\end{cases}$$
Well, the second case can be solved as usual via whatever means you prefer, e.g. quadratic formula after rearranging. This will give you some set of solutions (namely, $x = 1 \pm \sqrt{2}$).
The first equation is more simple: if $x=0$, the equation reduces to the true statement $0=0$. We conclude that $x=0$ is a solution. (If it resulted in something false, like $1=0$, then it would not be a solution.)
So the solution set of the original equation is the combination of both solution sets: $0, 1 + \sqrt 2, 1 - \sqrt 2$.

In your case, you divided by $x$.
If $x=0$, then you get something undefined in just $x/x$. BUT if you plug $x=0$ into the original equation you have, you get $0=0$: $0$ is thus a solution.
If $x \ne 0$, it becomes $1$. And then your equation simplifies and you can find some nonzero solutions.

A: You can divide both sides by $x$, but you must bear in mind that you are considering $x\neq 0$. Having said that, you can split the equation's solution into two steps. Firstly, consider $x = 0$ and notice if it is a solution or not (in the present case, it is). Secondly, you can consider that $x\neq 0$ in order to divide both sides by it so that you get the equation $1 - x = 2 - \sqrt{1 - x}$.
Additional Comments
With the purpose to solve such equation, there is no need to divide by $x$. Indeed, you can factor it as:
\begin{align*}
x(1 - x) = x(2 - \sqrt{1 - x}) & \Longleftrightarrow x(1 - x) - x(2 - \sqrt{1 - x}) = 0\\\\
& \Longleftrightarrow x(\sqrt{1 - x} - 1 - x) = 0
\end{align*}
Can you take it from here?


text:
Q: Firefox open new tab behaviour When I open a new tab the cursor focuses on the address bar. Is it possible to focus on the search bar by default?

A: If you go to
about:config

you can change the setting below (default is false, set to true.)
browser.search.openintab

Then you can just press CTRL + K to focus on the search box, and then when you hit enter, the search results will open in a new tab.

A: While I'm not sure of the exact answer to your question, you can change the default search engine that the address bar uses.  This tutorial explains how:

*

*At Firefox address bar, enter about:config and press ENTER.

*At Filter: field, type keyword.url

*You should see a Preference name of keyword.URL in the list. Double click it, a Enter String Value input box will appear.

*Replace the string with: http://www.google.com.my/search?q=

*Click OK button and done!

A: While not default, the Search Box is one TAB away from the Awesome Bar in Firefox.
I often Ctrl+L, TAB to get to the search bar.
Or Ctrl+T, TAB to get to the search box when opening a new tab.

A: You might be interested in the New Tab Searchbar addon, which solves exactly this problem. New tabs have focus redirected to the search bar.
https://addons.mozilla.org/en-US/firefox/addon/new-tab-searchbar/

A: This is not an exact answer either, but you can define short keywords to use in the address bar in order to use different search engines. E.g. su to search in Super User (through Google) and w for Wikipedia (through Google or directly).
To search for UltraEdit on Super User enter in the address bar:
su UltraEdit

How to install:
Bookmark a Google search where you have used site:superuser.com,
e.g. CPU site:superuser.com.
Then edit the bookmark (menu Bookmarks/Organize Bookmarks.../Bookmarks Menu/<select the bookmark - it is at the end>):

*

*Fill out the keyword field. E.g. with "su".

*Replace the word you used in the original search (CPU in the example above) with %s.

Now searches in Super User can be done directly from the address bar, e.g.:
su firefox installer

(F6 toggles focus to the address bar.)

A: Finally found the answer to this
http://www.howtogeek.com/howto/15127/make-firefox-show-google-results-for-default-address-bar-searches/
So now when I open a new tab I can just type the phrase I want to search in the address bar and get the results.


text:
Q: How to resolve python thread error 'too many arguments' on my created web crawler? I get an error when i run my code.

It gives a thread error:

too many arguments

I am trying to get it to go through every link it finds, it's a webcrawler.
I don't know what I did wrong. Please let me know if you have an idea.
    def run(links):
    try:
        try:
            import random
            z = str(links[random.randint(0,len(links))]).replace("(","")
            q = z.replace(")","")
            m = q.replace(", 'http'","")
            m = m[1:len(m)-1]
            line = m
        except:
            with open("sites.txt", "r") as file:
                import random
                line = random.choice(file.readlines())
                print(line)
        with urllib.request.urlopen(line) as response:
            html = response.read()

        #use re.findall to get all the links
        links = re.findall('"((http|ftp)s?://.*?)"', str(html))
        a = 0
        print(links)
        with open("sites.txt", "a") as file:
            while a != len(links):
                z = str(links[a]).replace("(","")
                q = z.replace(")","")
                m = q.replace(", 'http'","")
                m = m[1:len(m)-1]
                l = m
                t = threading.Thread(target=run, args=l)
                t.start()
                file.write(m + "\n")
                a += 1
    except:
        traceback.print_exc()
        pass
import urllib.request
import re
import traceback
import threading
go = False
l = None
t = threading.Thread(target=run, args=l)
while go != True:
    afd = input()
    try:
        with urllib.request.urlopen(afd) as response:
            html = response.read()
            go = True
    except:
        print("Error\nmake sure your using \nhttp://www.\nor https://www.\nor the ip")
with open("sites.txt", "a") as file:
    file.write(afd + "\n")

#use re.findall to get all the links
links = re.findall('"((http|ftp)s?://.*?)"', str(html))
a = 0
print(links)
with open("sites.txt", "a") as file:
    while a != len(links):
        z = str(links[a]).replace("(","")
        q = z.replace(")","")
        m = q.replace(", 'http'","")
        m = m[1:len(m)-1]
        file.write(m + "\n")
        a += 1
while True:
    try:
        try:
            import random
            z = str(links[random.randint(0,len(links))]).replace("(","")
            q = z.replace(")","")
            m = q.replace(", 'http'","")
            m = m[1:len(m)-1]
            line = m
        except:
            with open("sites.txt", "r") as file:
                import random
                line = random.choice(file.readlines())
                print(line)
        with urllib.request.urlopen(line) as response:
            html = response.read()

        #use re.findall to get all the links
        links = re.findall('"((http|ftp)s?://.*?)"', str(html))
        a = 0
        print(links)
        with open("sites.txt", "a") as file:
            while a != len(links):
                z = str(links[a]).replace("(","")
                q = z.replace(")","")
                m = q.replace(", 'http'","")
                m = m[1:len(m)-1]
                l = m
                t = threading.Thread(target=run, args=l)
                t.start()
                file.write(m + "\n")
                a += 1
    except:
        traceback.print_exc()
        pass

A: when creating the Thread object you shuold pass the arguments not as a list. but as a tuple.
like this:
t = threading.Thread(target=run, args=(l,))
t.start()

this will solve your error.
BTW - since you are using python to crawl webpages. I would strongly recommend using scrapy


text:
Q: Override multiple sqoop properties while executing sqoop job I am finding that when overriding sqoop job properties at runtime, I am able to override only one property.
example 1: if i submit
sqoop job --exec test123 -- --query "select * from test where update_batch_id between 4 and 10 and \$CONDITIONS" -- --last-value 3

It overrides only query property
example 2: if i submit
sqoop job --exec test123 -- --last-value 3 -- --query "select * from test where update_batch_id between 4 and 10 and \$CONDITIONS"

It overrides only query property last-value property.

*

*Is it possible to override multiple sqoop properties while executing a sqoop job? If not, is there a workaround available for this?

*Can I update a Sqoop Job without running it?

A: Use -- once to specify that you are overriding arguments like this:
sqoop job --exec test123 -- --query "select * from test" --last-value 3

Currently there is no way to edit a saved job from command line.


text:
Q: Flutter.h not found Hello all: I am working on a Flutter App with a team, and the App uses Firebase. When I try to run the App in Xcode, I get an error: Flutter/Flutter.h file not found from FLTFirebaseCorePlugin.h (error messages pasted at the bottom of this post). The steps I followed to bring the project over to the Mac from the PC are:
Copied the entire directory for the project
Open the project on the Mac in Android Studio
Run flutter pub get
Open a terminal, cd to the iOS folder
run pod install
but no joy. Can anyone offer any advice? I did have to set the paths to the Dart and Flutter SDKs on the Mac explicitly, and flutter doctor says all is OK, so stuck.
Thanks for any and all input.
/Users/johnstraumann/Development/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_crashlytics-1.0.0/ios/Classes/FLTFirebaseCrashlyticsPlugin.h:8:9: 'Flutter/Flutter.h' file not found
/Users/johnstraumann/Development/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_crashlytics-1.0.0/ios/Classes/FLTFirebaseCrashlyticsPlugin.m:5:9: In file included from /Users/johnstraumann/Development/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_crashlytics-1.0.0/ios/Classes/FLTFirebaseCrashlyticsPlugin.m:5:
/Users/johnstraumann/Development/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_core-1.0.3/ios/Classes/FLTFirebaseCorePlugin.h:8:9: 'Flutter/Flutter.h' file not found
/Users/johnstraumann/Development/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_crashlytics-1.0.0/ios/Classes/FLTFirebaseCrashlyticsPlugin.h:12:9: While building module 'firebase_core' imported from /Users/johnstraumann/Development/flutter/.pub-cache/hosted/pub.dartlang.org/firebase_crashlytics-1.0.0/ios/Classes/FLTFirebaseCrashlyticsPlugin.h:12:

A: I got this error when I update flutter 1.0 to flutter 2.0;
I find just remove next line in Podfile, then pod install again, it got fixed;
:generate_multiple_pod_projects => true;

A: I had the same issue a week ago.
Updating Firebase Crashlytics to the latest version fixed the issue for me.
After upgrading in pubspec.yaml to the latest version, don't forget to run

*

*flutter clean

*flutter pub get

*pod install

*pod update


text:
Q: Customized sharepoint 2010 dispform cannot be found I would like to modify a customized dispform, however, i cannot find. I checked in All files > List > mylist but because this list contains a lot of data SP designer gives an error and I cannot load it.
Please help.

A: Instead of going to All files > List, Try the below alternative way to edit your Form List:

*

*In the browser, Open your site > Open your list > from the above ribbon > Click on Edit List In SharePoint Designer.

*

*On Forms Section > Righ click on your custom Form > Select Edit File in Advanced Mode.


text:
Q: Constructor not defined: [pagereference].(String) public PageReference requestCode(){
        String endpoint='https://login.salesforce.com/services/oauth2/authorize';
        endpoint=endpoint+'?response_type=code&client_id='+clientId;
        endpoint=endpoint+'&redirect_uri='+redirectUri;
        PageReference p=new PageReference(endpoint);
        return p;
    }

A: If PageReference was the Salesforce class, the message would include this:
[System.PageReference]

rather than:
[pagereference]

so it is likely that you have a local pagereference class that is hiding the Salesforce class. Generally best not to use the same names to avoid this problem, but a quick workaround is to qualify the class name:
System.PageReference p = new System.PageReference(endpoint);


text:
Q: Shucked WD Easystore works on PC but not on MyCLoud EX4100 I recently shucked a 14tb EasyStore from BestBuy and taped the third pin. This drive now shows up on my PC. When I plug it into a WD My Cloud EX4100, the LED indicator glows solid red.
The drive shows up in the "Disk Status" under Storage Menu and indicates its 14tb available space.
But when I go to "Shares" to create a Share, it shows me all the drives except this one. Same under format menu. I see all drives except this one.
Its formated as NTFS if that helps.
Any ideas what I could be doing wrong ?