If I use array.shift() on this.state.array, should I use setState after?

Question: If I run
this.state={
    myArray: [1,2,3,4]
}

let element = this.state.myArray.shift()

then this.state.myArray will be [2,3,4].
I understand the recommendation is to use setState to avoid race conditions, but since shift() has already done the shifting, it seems unecessary to use setState afterwards.
Is this OK or is there a recommended way to deal with shifting?
Comment: Please show a [mcve] rather than this small stub of pseudocode. What are you trying to achieve? `setState` isn't used to avoid race conditions, it's used to rerender your component. Mutating state directly doesn't trigger a rerender.
Comment: From the title "If I use array.shift() on this.state.array, should I use setState after?" it should be clear it's a question on best practice. Do you really need to reproduce and run an example to comment on best practice?
Answer: It is necessary.
This code is buggy by definition, as you have mutated the state without going through setState -- which is explicitly not allowed in react. That means a re-render will not be triggered, and so anything in render that uses this piece of state will not recalculate, and the DOM displayed to the user will not change.
Use:
this.setState(prev => ({ myArray: prev.myArray.slice(1) }))

Note slice does not modify this.state.myArray directly like shift does, it returns a new copy with the first item removed.
Comment: Use the callback version if you're reading state: `this.setState(prev => ({ myArray: prev.myArray.slice(1) }))`
Comment: If you really wanted to use `shift()` for some reason (I can't see a good reason to do so as picking a method that implicitly mutates in react is just creating more work for yourself for no good reason), you would need to make a shallow clone of the array, and then use it -- assigning it a new var wouldnt work either as that would just create a new reference to that same array and not a copy (calling shift on it would still be mutating the original array).
Comment: OK, so if I use `shift` as per my example, I would simply use `setState(myarray: modifiedArray)` (after storing it as a new variable)?
Comment: @adsy I meant I would run setState on the mutated (original) array, after mutation. I want to remove the first index of the array (other items are being appended to it, I don't currently don't how long the array will get - shift should be faster than slicing if the array gets really long (allegedly).
Comment: Basically, you can't run setState on the mutated version of the array, because its too late, you've already violated react by mutating it without using setState if that makes sense. It has to be immutable in a way that is atomic. At no stage can you mutate `this.state`, even if your intention is to immediately pipe it into `setState`. Doing so may look like its working, but is definitely bad practice, and will lead to hard to find non-deterministic behaviours later.
Comment: To use shift you'd have to do `const newArray = [...this.state.myArray]` and then `newArray.shift()`. But also, the shallow array clone is likely to be a a much bigger perf issue than using slice.
Comment: Also presuming you need to use this array by looping over it anyways in render (?), I wouldnt worry about the perf impact of this. If it really was a problem, you'd likely want a more advanced data structure than an array like a queue or something. But don't optimize too early.
Comment: It makes perfect sense - I'll avoid using splice and shift then. Aappreciate the detailed answers and leave performance optimisation until the end


Customize the toolbar/actionbar in Android?

Question: I have applied MaterialNavigationDrawer component to my app for first activity.
I want to create a custom height toolbar with a background image like:

How can I do that?
Answer: 1) create a layout xml with the layout you need.(as you have shown in image). with name actionbar_custom.
2) write following code in your MainActivity.onCreate
ActionBar actionBar = getActionBar();
LayoutInflater inflater = LayoutInflater.from(this);
View actionView = inflater.inflate(R.layout.actionbar_custom, null);
/*here find your views inside that layout, and make runtime changes. e.g. define onTouch/onClick triggers here..    */

actionBar.setCustomView(actionView);
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);

Answer: you can try toolbar
android.support.v7.widget.Toolbar

A Toolbar is a generalization of action bars for use within application layouts.
Toolbar
Answer:

    <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:srcCompat="@mipmap/back"
          android:layout_centerVertical="true"
            android:paddingLeft="@dimen/_10sdp"
            android:id="@+id/imageView4"/>
    <in.mobilepedia.com.gicgwaliarincubationcentre.util.TextViewNormal
            android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Document Upload"
    android:layout_toRightOf="@+id/imageView4"
            android:id="@+id/txtDocumentUpload"
     android:textColor="@color/white"
     android:layout_marginLeft="@dimen/_10sdp"
    android:textSize="@dimen/_18sdp"
    android:layout_centerVertical="true"/>

    <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:srcCompat="@mipmap/option"
            android:id="@+id/imageView5"
            android:layout_marginRight="@dimen/_10sdp"
            android:layout_alignParentRight="true"
    android:layout_centerVertical="true"/>
    <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:srcCompat="@mipmap/upload_white"
            android:layout_marginRight="@dimen/_10sdp"
            android:id="@+id/imageView6"
            android:layout_toLeftOf="@+id/imageView5"
            android:layout_centerVertical="true"/>

</RelativeLayout>

Comment: make a custom layout and change the layout according to the requirement and include that layout with any xml file.


How to delete a line from a file containing sh extension?

Question: I'm using Ubuntu. I have an fileName.sh file containing 1000 lines and I have to delete the 399 number line is this command is sufficient for the deleting the line.
Command:- sed -i '399d' test.sh
Is there any need to change in this command? And can you please give me more suggestions to delete the line from a file?
Comment: Have you tried running the command and verifying the result manually ? What was the result ?
Comment: IMHO deleting by line number is dangerous, if there is any change in what produces the target file you'll be deleting the wrong line. Deleting by pattern woul be a bit safer (though still dangerous if done on a script).
Comment: yes I tried this command in result it will delete the line from the file @SorenA
Comment: So why the question ?
Comment: @xenoid whatever method you do it all has the same risk. If 1 of the actual arguments is "is has to be line 399" I do not see anything wrong. I would assume someone would 1st verify it is indeed line 399.
Comment: Don't backups work any more?
Comment: Welcome to [ubuntu.se]! If you have some working code you want others to review, please use [codereview.se].
Comment: @SorenA Question I posted because if I'm doing something wrong in this command then you guys guide me that my query is wrong. I also don't is there any impact of this command on other files. There is also a case like it will done what I want but on other side it will effect the other files that's why
Comment: @xenoid Can you tell me the better method
Answer: Better (but stiull unsafe) to remove the line using its contents than using a line number. If you want to delete a line whose contents are known:
sed -i /{contents}/d in.sh

Another solution is to use grep -v:
grep -v '{contents}' <in.sh >out.sh

In both cases {contents} is a regexp that matches the contents you want to remove, knowing that strings with only letters and numbers and a few select special characters are regular expressions for themselves, so:
sed -i /somefile/d in.sh
grep -v 'somefile' <in.sh >out.sh

will remove any line containing somefile from the input. But keep in mind that they could also match more things (for instance somefile2 would also be matched) unless you start using more complete regexps, for instance using ^{contents}$ to match lines that are exactly {contents}, excluding those that contain {contents} and additional things.
Comment: @catter, please also read [What should I do when someone answers my question?](https://askubuntu.com/help/someone-answers). No need to hurry, though. Just take your time.


Is it possible to pass params to an iOS app that can be evaluated immediately after installation?

Question: I want to create a different experience based on where they found the link that took them to the App Store. So when the user opens the app for the first time, I want to parse the params if there are any to display some message that continues the experience. Is this possible?
Comment: Interesting scenario. Unfortunately I am afraid it is not possible to do it.
Answer: It's not possible, your app has no information about where the buyer came from when they found your app or when he bought it.


Send donations to external PayPal account php

Question: My ideal process for this would be...
1) User selects a charity from a list
2) User selects amount to donate
3) pop-up, iframe or new window opens and takes them through paypal preocess
4) user is returned to my site with a callback.
My problem is I don't have access to the paypal acounts as they're charitys, Is this possible?
Answer: Yes, you can do this no problem.  I actually just tested this in the sandbox yesterday.
You can use the Express Checkout API to process the payments, and set the SELLERPAYPALACCOUNTID to the email address of the charity account you want the money to go to.
Take a look at my PHP class library for PayPal, which will make the EC calls very simple for you.  Specifically, you'll be working with SetExpressCheckout, GetExpressCheckoutDetails, and DoExpressCheckoutPayment.
The documentation says SELLERPAYPALACCOUNTID is used with Parallel payments, but it seems to work just fine with a single payment/receiver from the tests I can.


How can I stack more that two numpy arrays of images along third dimension in Python3

Question: Here is what I have tried in Python3. I know the problem is that I can't stack the arrays of different shapes as initially, the stacked_data will be empty. But I have to stack a large amount of dataset of images in ndarray format. And I can't do that by passing a tuple of huge numbers. Thank you.
from numpy import *
from cv2 import *
import glob

folder_path = r'C:\Users\Administrator\Desktop\training\WorkWithMam\TestingImages/*.jpg'

image_path = []
for path in glob.glob(folder_path):
    image_path.append(path)

stacked_data = empty((19, 3024, 4032))
for path in folder_path:
    image = imread(path, 0)
    stack((stacked_data, image))

Comment: you might wana add the python tag as youll get more support from it
Answer: The recommended shape of stacked_data is (3024, 4032, 19), and you can fill frames using the syntax: stacked_data[:, :, i] = image.
The shape of 3D array is illustrated here:

As you can see, the order is: (height, width, depth).
You can use a counter to index the "depth" index in each iteration:
stacked_data = empty((3024, 4032, 19))
i = 0  # Frame counter (index)

for path in folder_path:
    image = imread(path, 0)
    stacked_data[:, :, i] = image
    i += 1

The stacked_data[:, :, i] = image slicing syntax means: Set everything in the first and second dimension of stacked_data (but third dimension index i) to the matching image values.
In Python there are always shortcuts...
You can use the following syntax (using zip function):
stacked_data = empty((3024, 4032, 19))

for path, i in zip(folder_path, range(19)):
    stacked_data[:, :, i] = imread(path, 0)


Selecting specific named elements from XML using XSLT

Question: I got an XML like this on va variable prdxml
  <category numberofproducts="0">
  <id>catering</id>
  <url>/products/kantine</url>
  <name>Kantine</name>
  <category numberofproducts="0">
    <id>madembal</id>
    <url>/products/mad-og-emballage</url>
    <name>Mad og emballage</name>
    <category numberofproducts="9">
      <id>stanniol</id>
      <url>/products/stanniol</url>
      <name>Stanniol</name>
      <category  numberofproducts="9">
        <id>stankd</id>
        <url>/products/stankd</url>
        <name>stankd</name>
      </category>
    </category>
    <category numberofproducts="5">
      <id>termo</id>
      <url>/products/termobakker</url>
      <name>Termobakker</name>
    </category>
  </category>
</category>

Now I want to get all the Id's present in this xml to a string.Tried usual for-each loop but failed,because of the structure of this xml. Now I thinks there may be a smarter way to achieve this ,that i never known.Can any one give me that light.
Answer: If you mean flattening all id's irrespective of their nesting, level, then this should work with a ',' delimiter in between.
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

  <xsl:template match="/">
    <xsl:apply-templates select="//id"/>
  </xsl:template>

  <xsl:template match="id">
    <xsl:value-of select="concat(./text(), ',')"/>
  </xsl:template>

</xsl:stylesheet>

Returns : catering,madembal,stanniol,stankd,termo,
If you need a more elegant mechanism for handling the last element delimiter, have a look at Dimitre's answer here
Update: To put the result into a variable:
<xsl:variable name="someVar">
  <xsl:apply-templates select="//id"/>
</xsl:variable>
Result: <xsl:value-of select="$someVar"/>

Comment: I am getting the result correctly,But need an extra info.How can I take this values in to a variable.(all comma seperated)
Comment: Now I am getting each one seperately printed


gstreamer: create rtp-stream out of mp4-file without transcoding

Question: I wanted to create a RTP-stream of a mp4-file with gstreamer.
I am using gstreamer 1.18.4 on debian bullseye.
To create a mp4-file I recorded an RTSP-stream from my webcam using the following command:
gst-launch-1.0 -e rtspsrc location="rtsp://192.168.111.146/axis-media/media.amp" port-range=28000-38000 buffer-mode=0 latency=80 ! rtph264depay ! h264parse ! mp4mux ! filesink location=filename.mp4

After recording the file filename.mp4 I tried to stream it using RTP:
gst-launch-1.0 filesrc location=filename.mp4 ! qtdemux ! h264parse ! avdec_h264 ! x264enc ! h264parse ! rtph264pay ! udpsink port=50000 host=127.0.0.1

And the playback of the stream could be started using the following command on the same machine:
gst-launch-1.0 udpsrc address=127.0.0.1 port=50000 auto-multicast=true ! application/x-rtp,encoding-name=H264,payload=96 ! rtph264depay ! avdec_h264 ! autovideosink

Everything works as expected!
But since I don't want to transcode the file, I just wanted to skip the decoding and encoding part. Therefore, I created the following pipelines:
gst-launch-1.0 filesrc location=filename.mp4 ! qtdemux ! h264parse ! rtph264pay ! udpsink port=50000 host=127.0.0.1

and
gst-launch-1.0 filesrc location=filename.mp4 ! qtdemux ! rtph264pay ! udpsink port=50000 host=127.0.0.1

However, if I retry the playback pipeline (the pipeline with udpsrc) on both pipelines the stream is not displayed.
Interestingly, nload shows network traffic on lo.
What is wrong with the streaming pipelines?
Did I miss some magic-plugin in between?
Answer: Meanwhile I found an answer to my question.
Changing the stream-server-pipeline from
gst-launch-1.0 filesrc location=filename.mp4 ! qtdemux ! h264parse ! rtph264pay ! udpsink port=50000 host=127.0.0.1

to
gst-launch-1.0 filesrc location=filename.mp4 ! qtdemux ! h264parse config-interval=-1 ! rtph264pay ! udpsink port=50000 host=127.0.0.1

solves the issue.
Thus, the difference is setting the parameter config-interval=-1 for h264parse.


How to match two columns of logical vectors within a data frame

Question: Here's some dummy code and its pretty obvious output:
xdupe <- as.logical(c("T", "F", "F", "F", "T", "T", "F"))
ydupe <- as.logical(c("T", "F", "F", "F", "F", "T", "T"))
cities <- c("Knox", "Whiteville", "Madison", "York", "Paris", "Corona", "Bakersfield")
df <- data.frame(cities, xdupe, ydupe)
df$cities <- as.character(df$cities)

> df
       cities xdupe ydupe
1        Knox  TRUE  TRUE
2  Whiteville FALSE FALSE
3     Madison FALSE FALSE
4        York FALSE FALSE
5       Paris  TRUE FALSE
6      Corona  TRUE  TRUE
7 Bakersfield FALSE  TRUE

For some context, what xdupe and ydupe represent are logical values for duplicated x and y coordinates (longitude and latitude, respectively).
So what I need to be able to do is see which attributes in the data frame have TRUE values for both xdupe and ydupe. In this particular case, that would be the cities Knox and Corona. How can I compare xdupe and y dupe so that I can pull out all of the cities that have BOTH true values?
Comment: Or ```Reduce(`&`, df[-1])``` or ```do.call(`+`, df[-1]) > 1``` :P Or other silly variations of `do.call` and `Reduce`
Comment: Another code golfing approach would be `pmin(df[2], df[3])` assuming there are only TRUE or FALSE entries
Answer: This can be done in a couple of ways.  One option is &.  It will become TRUE only when all the elements are TRUE.  So, if we use xdupe & ydupe, it will compare the corresponding elements of 'xdupe' and 'ydupe' and get TRUE only when both elements are 'TRUE'.
i1 <- with(df, xdupe & ydupe)

Or another option is rowSums of the subset of dataset that includes only the logical columns.  As the binary representation for TRUE is 1 and FALSE is 0, when there are both TRUE for each corresponding element, it will result in 2.
i1 <- rowSums(df[-1])==2

and then we subset the dataset
Subdf <- df[i1,]
Subdf
#   cities xdupe ydupe
#1   Knox  TRUE  TRUE
#6 Corona  TRUE  TRUE


Category of adjunctions inducing a particular monad

Question: Every pair $F \dashv G$ of adjoint functors $F: \mathcal C \to \mathcal D$, $G: \mathcal D  \to \mathcal C$ induces a monad $\mathbb T = (T,\eta,\mu)$ on $\mathcal C$. Given a  monad $\mathbb T = (T,\eta,\mu)$ on $\mathcal C$, we define $\operatorname{Adj}(\mathbb T)$ to be the category of adjunctions inducing $\mathbb T$. Its objects are adjoint pairs of functors $F \dashv G$ between $\mathcal C$ and some category $\mathcal D$ such that the monad induced by the adjunction is $\mathbb T$, i.e. $GF = T$, the unit is $\eta$, and $G\varepsilon F = \mu$ where $\varepsilon$ is the counit. The morphisms between two such adjunctions $F \dashv G$, $F' \dashv G'$ are functors $H: \mathcal D \to \mathcal D'$ such that $HF=F'$ and $G' H = G$.
I am now worried whether this is really a category. Consider the example where $\mathcal C$ is a one-object category with only the identity morphism and $\mathbb T = (T,\eta,\mu)$ is the trivial monad. For every category $\mathcal D$ which has an initial object $I$, we get an adjunction $F \dashv G$, where $F: \mathcal C \to \mathcal D$ sends the one object of $\mathcal C$ to $I$, and $G: \mathcal D \to \mathcal C$ sends everything to the one object (it's easy to check that this is really an adjunction). Its induced monad on $\mathcal C$ is necessarily $\mathbb T$. So $\operatorname{Adj}(\mathbb T)$ contains at least one object for each category having an initial object. However, $\operatorname{Adj}(\mathbb T)$ itself has an initial object, namely the Kleisli adjunction, which in this case is just $1_{\mathcal C} \dashv 1_{\mathcal C}$. If $\operatorname{Adj}(\mathbb T)$ is a category, it seems that in a way it contains itself, in the form of the adjunction $\mathcal C \rightleftarrows \operatorname{Adj}(\mathbb T)$ defined by the Kleisli adjunction. (How) Is that possible?
Answer: Well, either one works in a framework where self-containing categories are permitted (but I do not know of any), or else one works more carefully. So I would say something like, fix a universe $\mathbf{U}$ such that $\mathcal{C}$ is a $\mathbf{U}$-small category, and let $\mathbf{Adj}(\mathcal{C})$ be the category of $\mathbf{U}$-small categories equipped with an adjunction etc.; then $\mathbf{Adj}(\mathcal{C})$ will not be $\mathbf{U}$-small, and so will not member of itself.


MySQL (Workbench) group by operation on large dataset (30GB)

Question: I have a large dataset, wim.tr_2012, with columns Year, Month, Day, and Lane. I'm trying to group by Year, Month, and Day and count number of rows for each group. I used:
SELECT `Station Number`, Month, Day, Year, COUNT(`Lane`)
FROM wim.tr_2012
GROUP BY `Station Number`, Month, Day, Year

The message says:

Error Code 2013. Lost connection to MySQL server during query.

Could anyone tell me what happened? I tried some simple queries such as select * From wim.tr_2012, and it works just fine.
Thank you
Comment: its because your size of database ...
Comment: It's usually not a good idea to split a date into 3 separate columns.
Comment: The simple `SELECT *...` is faster because Workbench delivers the first few rows, then quits.  With the `GROUP BY`, it must read the entire table before it can start delivering output.
Answer: increase mysql session time by going through following
steps
edit > preference >sql editor > mysql session


Multiple Contact Us forms and how to handle them

Question: What is the best approach to organize multiple forms? Simple websites might only have 1 contact form for any type of questions.
However, some sites have contact forms for difference users. For example, Media Inquiries, Business vs Customer issues, Charity Program causes, Careers applications, etc.
How do you organize all these contact forms?
Answer: Most Fields are the Same
I'm assuming all the contact forms share the same fields (like Name, Email, etc.) except for the destination (like Media Inq, Business Inq, etc.)
If this is the case, I'd recommend using the same form and one of the fields would be something like "In Regards To" and it'd be a selection of the different departments or categories.
The basic form could live on a generic page where the user would have to select where to direct the inquiry. If a "Contact Us" link was clicked on a Media page, for example, the form would load with the "In Regards To" field pre-filled with Media.
Unique Fields Per Form
If the fields are different for each destination, I'd recommend using a multi-step form. The first question would be something like "In Regards To" and that would determine the fields shown in the second step.
Of note, if you go this route you may also consider putting Name/Email in the first step as well. That way if users jump ship after filling out Step 1, you can at least capture their Name and Email for retargeting. (Be kind with retargeting though)
Comment: I like the multi-step approach and unifying forms into one page. However, I've seen many many sites dedicating distinct pages per form type. For example, a job position with embedded application form, a news&press with embedded media contact form, etc... It can certainly be helpful to have the correct form when needed and targeted to right audience. Have you seen any studies comparing this approach vs unifying all in one page?
Comment: For sure, a unique form with only what is needed and nothing of what is not needed would be preferred. My answer was primarily from a UX + Dev perspective (i.e. biggest bang for the buck). And no, unfortunately I don't know of any studies specifically about this question.
Answer: What's the main goal of your site?
If you want to get users to take a specific action, then designing persuasive call-to-action buttons is critical.
Whether you're using them on pricing pages, product pages, landing pages, or your blog, well-designed CTA buttons are going to help you get more people to do what you want them to do.
If you need to offer multiple CTAs
Sometimes you'll have to include more than one CTA button on a webpage. For example, your homepage might have one button for signing up, and another button for signing in.
If you need to offer the user multiple things they can do, you should still guide them to the thing they should do — the most important task on the page.
Persuasive CTA buttons are prioritized. Use visual hierarchy to give weight to the most important conversion pathway. Your main CTA should always be the most visually striking while the others should be less attention grabbing.
Answer: Typeform seems to have perfected many facets of form filling usage, including multi-especially the transitions between steps. I believe trying out their design may provide you with inspiration.
https://www.typeform.com/
I am not affiliated with them.


the method in the type is not applicable for the arguments java

Question: I have 2 methods in one class. from first i contains strings and return index. In 2nd I try to use this index to find element. But I have error in eclipse "the method containsStatsName() in the type SettingsPage is not applicable for the arguments java" What i have to do to work correctly??
SettingPage.class
public int containsStatsName(String statusName){
    int statListPos =0;
    int statsNumber = getStatusList.size();
     for(int i=0;i<statsNumber;i++){
         if(getStatusList.get(i).getText().toLowerCase().contains(statusName)){
             statListPos = i+1;
         }

         }
     return statListPos;
}

public void editStatsName(){
    int leadNewPos = containsStatsName();
    int buttonNumber = getButtonList.size();
    int couterNew = 0;
    for(int i=0;i<buttonNumber;i++){
        if(couterNew == leadNewPos){
            getButtonList.get(i).click();
            break;
        }else{
            couterNew++;
        }
    }
}

MainPage.class
 SettingsPage sp = new SettingsPage(driver);

    sp.gotoLeadStat();

    sp.containsStatsName("new");

    sp.editStatsName();

Comment: int leadNewPos = containsStatsName(); requires String parameter.
Comment: but i want there use return statListPos;
so what i should do?
Comment: Not sure what you mean. Take pen & paper and work through, it's easy to understand.
Comment: But i dont know how to solve it, im begginer, and I not the best in java. Can u tell mi what i should do to work it?
Comment: Nambari answered the question, the error is due to `containsStatsName()` since you didn't provide a String as a parameter. That function will return your `statListPos` if you provide any string for `statusName`... This is an **error that will not help future readers** (caused by "a simple typographical error"), therefore I'm flagging to close this question.
Answer: You can nest the method containsStatsName as parameter of the 2nd method...
sp.gotoLeadStat();

sp.editStatsName(sp.containsStatsName("new"));

and modify the editStatsName Method.
public void editStatsName(int leadPosition){
int leadNewPos = leadPosition;
int buttonNumber = getButtonList.size();
int couterNew = 0;
for(int i=0;i<buttonNumber;i++){
    if(couterNew == leadNewPos){
        getButtonList.get(i).click();
        break;
    }else{
        couterNew++;
    }
}

Answer: Your problem lies here:
public void editStatsName(){
        int leadNewPos = containsStatsName();

Your containsStatsName method takes a String parameter, there is no method with that name defined that takes no parameter, so the compiler tells you there is a problem.
You can modify your editStatsName method by giving it the parameter statusName:
public void editStatsName(String statusName){
        int leadNewPos = containsStatsName(statusName);

with that you give your containsStatsName method the parameter it needs.
But since the parameter that your editStatsName method really needs is the index and not the statusName - I would throw the containsStatsName method out of editStatsName, as you already call it in your main method:
public void editStatsName(int leadNewPos){
    int buttonNumber = getButtonList.size();
    int couterNew = 0;
    for(int i=0;i<buttonNumber;i++){
        if(couterNew == leadNewPos){
            getButtonList.get(i).click();
            break;
        }else{
            couterNew++;
        }
    }

and call both methods in your main method like that:
int statListPos = sp.containsStatsName("new");

sp.editStatsName(statListPos);


What is the purpose of the "Death Clock" during boss fights?

Question: When everyone dies in a party during a boss fight, a red timer starting at 1 minute appears near their corpse and counts down. What is the purpose of this timer?

I imagine that is how long a party has to do something before the boss resets, but what can be done? There is no way to revive during a boss fight without another player's help.
Comment: I do not have any experience, but, besides the dots and followers, maybe if another player joins the party, and the timer is still running he can teleport trough banner to your location and the figth follows normally. But It's just a wild guess
Comment: @NunoFreitas If your party members are in a boss fight you can not teleport to them.
Answer: Damage over time spells could still be on the boss, if it is a close fight it might be enough to take him out. I have not had it happen vs a boss but i have seen champion packs die due to my WD dots after I died my self.
Comment: You forgot the (possibly still) living DoT: your follower.
Comment: Me and my friend had this happen to us the first time we killed the butcher his Hydra finished him off as we died.


Regex to find State and Zip from Address

Question: Trying to make regex that can get state from address
1- 1234 Bellaire Blvd, Suite 123, Houston, TX 77036
2- 1234 BELLAIRE BL #123, HOUSTON, TX  77036
I have this for state

\w{2}(?=\s\d{1,5})

And this for Zip

(?<=\w{2}\s)\d{5}

FOR STATE
In 1st case above regex is returning "te" from "Suite" and TX for state which is correct
However, in 2nd case it is returning nothing
FOR ZIP
77036 is returned in 1st case and null is returned in 2nd case
Answer: I don't think regular expressions are the best way to do this. Rather I'd use an API to parse the address into it's components. You will need state_abbreviation and you're sorted. Example response:
<code>[
    {
        "input_index": 0,
        "candidate_index": 0,
        "delivery_line_1": "1 Santa Claus Ln",
        "last_line": "North Pole AK 99705-9901",
        "delivery_point_barcode": "997059901010",
        "components": {
            "primary_number": "1",
            "street_name": "Santa Claus",
            "street_suffix": "Ln",
            "city_name": "North Pole",
            "state_abbreviation": "AK",
            "zipcode": "99705",
            "plus4_code": "9901",
            "delivery_point": "01",
            "delivery_point_check_digit": "0"
        },
        "metadata": {
            "record_type": "S",
            "zip_type": "Standard",
            "county_fips": "02090",
            "county_name": "Fairbanks North Star",
            "carrier_route": "C004",
            "congressional_district": "AL",
            "rdi": "Commercial",
            "elot_sequence": "0001",
            "elot_sort": "A",
            "latitude": 64.75233,
            "longitude": -147.35297,
            "precision": "Zip8",
            "time_zone": "Alaska",
            "utc_offset": -9,
            "dst": true
        },
        "analysis": {
            "dpv_match_code": "Y",
            "dpv_footnotes": "AABB",
            "dpv_cmra": "N",
            "dpv_vacant": "N",
            "active": "Y",
            "footnotes": "L#"
        }
    },

    {
        "input_index": 1,
        "candidate_index": 0,
        "addressee": "Apple Inc",
        "delivery_line_1": "1 Infinite Loop",
        // truncated for brevity
    }
]
</code>
Hope that helped.
Answer: You can match against ', ([A-Z]{2}) ' the state will then be the subpattern matched by the parentheses. In python it would look like this.
<code>import re

s1 = "1- 1234 Bellaire Blvd, Suite 123, Houston, TX 77036"

s2 = "2- 1234 BELLAIRE BL #123, HOUSTON, TX 77036"

m = re.search(', ([A-Z]{2}) ', s1)

print(m.group(1))
</code>


YouTube embed that scales up when played - how did Google do this?

Question: See this Google support page for reference. They have an embedded YouTube video that is responsive and when you click it it expands to a comfortable viewing size (704x396?). But in its default state it is nice and compact (400x230px), not hogging real estate for viewers who are focused on the text content. In its expanded state there is an X button to exit the expanded state and pause the video.
This is an awesome way to present embedded video content for obvious reasons, but no such configuration options are offered by YouTube when you generate an embed link. This is something unique to Google's support pages. I want to do the same for a page I have with an embedded video, but I don't really understand which div(s) are responsible for this or how they're doing it.
The relevant HTML is somewhere in here:

<video class="video-stream html5-main-video" style="width: 400px; height: 230px; left: 0px; top: -230px; transform: none;"></video>

<svg width="60" height="60"><g><circle class="countdowntimer-background-circle" cx="30" cy="30" r="15"></circle><path class="countdowntimer-diminishing-pieslice" d="M30,30 z"></path><circle class="countdowntimer-middle-dot" cx="30" cy="30" r="4"></circle></g></svg>

<canvas width="60" height="60" class="html5-video-loader html5-center-overlay ytp-scalable-icon-grow" style="display: none; transform: scale(0.5);" aria-hidden="true"></canvas>

<svg><path fill-rule="evenodd" clip-rule="evenodd" fill="#1F1F1F" class="ytp-large-play-button-svg" d="M84.15,26.4v6.35c0,2.833-0.15,5.967-0.45,9.4c-0.133,1.7-0.267,3.117-0.4,4.25l-0.15,0.95c-0.167,0.767-0.367,1.517-0.6,2.25c-0.667,2.367-1.533,4.083-2.6,5.15c-1.367,1.4-2.967,2.383-4.8,2.95c-0.633,0.2-1.316,0.333-2.05,0.4c-0.767,0.1-1.3,0.167-1.6,0.2c-4.9,0.367-11.283,0.617-19.15,0.75c-2.434,0.034-4.883,0.067-7.35,0.1h-2.95C38.417,59.117,34.5,59.067,30.3,59c-8.433-0.167-14.05-0.383-16.85-0.65c-0.067-0.033-0.667-0.117-1.8-0.25c-0.9-0.133-1.683-0.283-2.35-0.45c-2.066-0.533-3.783-1.5-5.15-2.9c-1.033-1.067-1.9-2.783-2.6-5.15C1.317,48.867,1.133,48.117,1,47.35L0.8,46.4c-0.133-1.133-0.267-2.55-0.4-4.25C0.133,38.717,0,35.583,0,32.75V26.4c0-2.833,0.133-5.95,0.4-9.35l0.4-4.25c0.167-0.966,0.417-2.05,0.75-3.25c0.7-2.333,1.567-4.033,2.6-5.1c1.367-1.434,2.967-2.434,4.8-3c0.633-0.167,1.333-0.3,2.1-0.4c0.4-0.066,0.917-0.133,1.55-0.2c4.9-0.333,11.283-0.567,19.15-0.7C35.65,0.05,39.083,0,42.05,0L45,0.05c2.467,0,4.933,0.034,7.4,0.1c7.833,0.133,14.2,0.367,19.1,0.7c0.3,0.033,0.833,0.1,1.6,0.2c0.733,0.1,1.417,0.233,2.05,0.4c1.833,0.566,3.434,1.566,4.8,3c1.066,1.066,1.933,2.767,2.6,5.1c0.367,1.2,0.617,2.284,0.75,3.25l0.4,4.25C84,20.45,84.15,23.567,84.15,26.4z M33.3,41.4L56,29.6L33.3,17.75V41.4z"></path><polygon fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" points="33.3,41.4 33.3,17.75 56,29.6"></polygon></svg>

The CSS and javascript I'm not sure about.
Answer: None of the HTML you posted really does what you think. YouTube's HTML that is inside the embedded iframe is designed to proportionally fit inside the iframe node.
To answer your question though, they simply just use JavaScript to change embedded iframe's height and width. Inside the reference link you posted, inspect the youtube player, and find the iframe node, and watch the inline styling as you play/close the youtube player.
Comment: Sorry I forgot to accept your answer for so long. And thank you!


How can I put a knob on a threaded rod?

Question: I need to create a "thumb screw" or "hand wheel" out of a 1/2-20 UNF threaded rod to serve as fine linear adjustment screw for a heavy load.  (I can't find ready-made knobs with this thread, nor thumb screws in any reasonable length.)
I have hex nuts matching the threads, so I can use two nuts to "thread-lock" the cut end of the rod.  But how can I attach an extended knob or handle to the nuts so that I can easily turn the rod when it's under a load?
Comment: Or, [something that bypasses threads altogether](https://www.amazon.com/Spoked-Polished-Aluminum-Dished-Diameter/dp/B006M70BM2/ref=sr_1_4?s=industrial&ie=UTF8&qid=1500751171&sr=1-4&keywords=1%2F2%22) might work. You could tap it for set screws or simply drill a pin through everything.
Comment: Most hardware stores have knobs that fit the heads of hex bolts in the 1/4" to 3/8" range. A 1/2" bolt is quite large, though, and I doubt you'll find them there. Have you searched?
Comment: Mcmaster-Carr has everything you could possibly want.  Grainger has a smaller selection but has local warehouses.
Answer: There are many variations on this answer, allowing you to fine tune the results to your liking.
If you have a disk cut from thin plywood or similarly flat material and tighten your locking nuts on each side, you have a knob of sorts. The larger the diameter of the disk, the greater control you will have, as the resulting lever become longer.
You didn't note that the nuts are at the end of the threaded rod, but the above method will work regardless of the location.
If you need a knobby knob, just about any dome or spherical shape will suffice.
Instead of a disk, you could use a hexagon or octagon shape, or a pointed star shape. At the simplest form, a single flat rod with a hole at one end, locked into the nuts provides a lever for adjustment, somewhat like the lever on a ball valve assembly. If a balanced control is required, a longer flat bar with a hole in the center would also work.
In all of the above designs, the force with which you secure the locking nuts will determine how much load the system will handle when you want to make an adjustment. If the load is high, your lever or disk may slip if the nuts cannot apply sufficient force.
Comment: All of these variations boil down to: "Find a solid piece of material, cut it to a shape you like, drill a hole so rod can pass through it, then sandwich it between two nuts," right?
Comment: That's a pretty good summary, yes.
Answer: If you want a nice clean solution then you want to check out a selection of hand wheels. Some types even have a crank built into them. Many even have a provision for a set screw to lock it to the shaft to which they mount. There are styles made of various types of materials. Those shown here are made of aluminum.
Answer: If you cannot find s suitable knob, take some nuts and short pieces of solid rod to a weld shop and have them weld the rod to the sides of the nuts.
This makes an improvised wing nut.
Good luck!

How can I put a knob on a threaded rod?


Atheros Wifi works on one desktop computer but not another

Question: My Wifi card worked on my old desktop fine but is not working whe I moved it to my new one.
Here is the output of sudo lshw -C network
-network UNCLAIMED
       description: Ethernet controller
       product: Atheros Communications Inc.
       vendor: Atheros Communications Inc.
       physical id: 0
       bus info: pci@0000:04:00.0
       version: 01
       width: 32 bits
       clock: 33MHz
       capabilities: pm bus_master cap_list
       configuration: latency=32
       resources: memory:fb200000-fb20ffff

and sudo lspci
00:00.0 Host bridge: Intel Corporation Sandy Bridge DRAM Controller (rev 09)
00:01.0 PCI bridge: Intel Corporation Sandy Bridge PCI Express Root Port (rev 09)
00:16.0 Communication controller: Intel Corporation Cougar Point HECI Controller #1 (rev 04)
00:1a.0 USB Controller: Intel Corporation Cougar Point USB Enhanced Host Controller #2 (rev 05)
00:1b.0 Audio device: Intel Corporation Cougar Point High Definition Audio Controller (rev 05)
00:1c.0 PCI bridge: Intel Corporation Cougar Point PCI Express Root Port 1 (rev b5)
00:1c.2 PCI bridge: Intel Corporation 82801 PCI Bridge (rev b5)
00:1c.3 PCI bridge: Intel Corporation Cougar Point PCI Express Root Port 4 (rev b5)
00:1c.4 PCI bridge: Intel Corporation Cougar Point PCI Express Root Port 5 (rev b5)
00:1d.0 USB Controller: Intel Corporation Cougar Point USB Enhanced Host Controller #1 (rev 05)
00:1f.0 ISA bridge: Intel Corporation Cougar Point LPC Controller (rev 05)
00:1f.2 IDE interface: Intel Corporation Cougar Point 4 port SATA IDE Controller (rev 05)
00:1f.3 SMBus: Intel Corporation Cougar Point SMBus Controller (rev 05)
00:1f.5 IDE interface: Intel Corporation Cougar Point 2 port SATA IDE Controller (rev 05)
01:00.0 VGA compatible controller: nVidia Corporation Device 0de1 (rev a1)
01:00.1 Audio device: nVidia Corporation Device 0bea (rev a1)
03:00.0 PCI bridge: Device 1b21:1080 (rev 01)
04:00.0 Ethernet controller: Atheros Communications Inc. Device ff1a (rev 01)
05:00.0 USB Controller: NEC Corporation uPD720200 USB 3.0 Host Controller (rev 03)
06:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168B PCI Express Gigabit Ethernet controller (rev 06)

and sudo iwconfig
lo        no wireless extensions.

eth0      no wireless extensions.

and sudo ifconfig
eth0      Link encap:Ethernet  HWaddr 6c:62:6d:e6:8f:6f
          inet addr:192.168.0.143  Bcast:192.168.0.255  Mask:255.255.255.0
          inet6 addr: fe80::6e62:6dff:fee6:8f6f/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:5772951 errors:0 dropped:0 overruns:0 frame:0
          TX packets:5587811 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:996414964 (996.4 MB)  TX bytes:1604420754 (1.6 GB)
          Interrupt:44 Base address:0x2000

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:60498 errors:0 dropped:0 overruns:0 frame:0
          TX packets:60498 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:9892064 (9.8 MB)  TX bytes:9892064 (9.8 MB)

I totally have no idea what to do, or even what most of this means, any help at all to get my wifi working again would be appreciated.
Thanks!
Ash
Comment: What version of Ubuntu are you using?
Comment: Just stop using madwifi.  Ath5k works fine and you can do almost everything through ath5k now.  Try an lsmod if you have issues getting ath5k working to make sure it loads.
Comment: version 10.10 ans as I say it was working on the old desktop, also running 10.10
Answer: Look into your logfiles:
 dmesg | grep ath
 grep ath /var/log/*.log* | egrep -iv path

Maybe issues with an interrupt. I could heal such a thing in the bios, but with intel-IPW2100. Maybe some other idea can be found.
update after comment:
On my older laptop, ubuntu 9.04, I get:
locate ath_pci
/etc/modprobe.d/blacklist-ath_pci.conf
/lib/linux-restricted-modules/2.6.27-14-generic/ath_pci
/lib/linux-restricted-modules/2.6.27-14-generic/ath_pci/ath_pci.mod.o
/lib/linux-restricted-modules/2.6.27-14-generic/ath_pci/if_ath.o
/lib/linux-restricted-modules/2.6.27-14-generic/ath_pci/if_ath_pci.o
/lib/linux-restricted-modules/2.6.28-16-generic/ath_pci
/lib/linux-restricted-modules/2.6.28-16-generic/ath_pci/ath_pci.mod.o
/lib/linux-restricted-modules/2.6.28-16-generic/ath_pci/if_ath.o
/lib/linux-restricted-modules/2.6.28-16-generic/ath_pci/if_ath_pci.o
/lib/modules/2.6.24-24-generic/madwifi/ath_pci.ko
/usr/share/linux-restricted-modules/2.6.27-14-generic/modules.alias.override/ath_pci
/usr/share/linux-restricted-modules/2.6.28-16-generic/modules.alias.override/ath_pci

On the newer one (10.04) only line 1, modprobe-blacklist.
But on both a lot of ath5k-files, mainly .ko-related (Kernel object, alias: driver).
Comment: Here is the output:

http://pastebin.com/fSp9FSuE
Answer: I believe these cards should work out the box on the newest kernels but unless you want to upgrade your version of Ubuntu, this particular chipset is known to misbehave and forcing it onto the ath5k driver should work.
In older versions of Ubuntu, especially where the madwidi driver is involved, the ath5k driver ends up blacklisted by other drivers. To fix this, you need to find out where it's blocked. Fire this off into a terminal:
grep -R 'ath5k' /etc/modprobe.d/

If that comes back with any lines that start with blacklist, you need to edit that file and comment the line out. grep will output the name of the file so just run sudo nano the_filename, stick a # in front of the applicable line (control+w in nano to search) and then control+x to save. Reboot and hopefully you'll have a wireless card.
Comment: here is the output: /etc/modprobe.d/blacklist-ath_pci.conf:# which ath5k cannot recover. To prevent this condition, stop
Comment: ok, so i did sudo nano and here is what it said:

# For some Atheros 5K RF MACs, the madwifi driver loads buts fails to
# correctly initialize the hardware, leaving it in a state from
# which ath5k cannot recover. To prevent this condition, stop
# madwifi from loading by default. Use Jockey to select one driver
# or the other. (Ubuntu: #315056, #323830)
blacklist ath_pci

ok, so I guess I have to install Jockey and stop madwifi from loading, but what do I load in its place?
Comment: ok, ran jockey and it doesn't say anything about anything other than Nvidea drivers, nothing to do with wifi whatsoever. I tried commenting out the  "blacklist ath_pci" line and rebooted as you suggested and it did nothing, so i uncommented it again


Symfony Routing Component not routing url

Question: I have mvc php cms like this folder structure:
application
---admin
--------controller
--------model
--------view
--------language
---catalog
--------controller
------------------IndexController.php
--------model
--------view
--------language
core
--------controller.php
//...more
public
--------index.php
vendor

I install symfony/router component for help my route url using composer json:
{
  "autoload": {
    "psr-4": {"App\\": "application/"}
  },
  "require-dev":{
    "symfony/routing" : "*"
  }
}

Now with route documents I add this code for routing in index.php:
require '../vendor/autoload.php';
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;

$route = new Route('/index', array('_controller' => 'App\Catalog\Controller\IndexController\index'));
$routes = new RouteCollection();
$routes->add('route_name', $route);

$context = new RequestContext('/');

$matcher = new UrlMatcher($routes, $context);

$parameters = $matcher->match('/index');

In My IndexController I have :
namespace App\Catalog\Controller;

class IndexController {

    public function __construct()
    {
        echo 'Construct';
    }

    public function index(){
        echo'Im here';
    }
}

Now in Action I work in this url: localhost:8888/mvc/index and can't see result : Im here IndexController.
How do symfony routing url work and find controller in my mvc structure? thank for any practice And Help.
Answer: The request context should be populated with the actual URI that's hitting the application. Instead of trying to do this yourself you can use the HTTP Foundation package from symfony to populate this:
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\RequestContext;

$context = new RequestContext();
$context->fromRequest(Request::createFromGlobals());

It's also documented here: https://symfony.com/doc/current/components/routing.html#components-routing-http-foundation
After the matching ($parameters = $matcher->match('/index');) you can use the _controller key of the parameters to instantiate the controller and dispatch the action. My suggestion would be to replace the last \ with a different symbol for easy splitting, like App\Controller\Something::index.
You can then do the following:
list($controllerClassName, $action) = explode($parameters['_controller']);
$controller = new $controllerClassName();
$controller->{$action}();

Which should echo the response you have in your controller class.
Comment: I add `"symfony/http-foundation": "*"` using composer json and add your code But I cant see reaction!
Comment: You should add it using `composer require symfony/http-foundation`. Did you check if the package was actually installed? And maybe paste the full example.
Comment: Ok so, I think I know what else is going on. You're not actually dispatching the action. I'll update my answer.
Comment: @NewCod3r I've updated the instructions which should fix your issue. If I'm honest I would suggest you to just use Symfony as a whole or something like Laravel which provides more convenience in terms of simple dispatching of http-related actions.


Simple Checkbox values to SQL database

Question: Sorry for asking something that seems to have been asked many times, but is because I'd not found anything so... simple as my case, so I'm not so sure about that path to follow.
The thing is, I have a form, in the page "estimate.php" with most of its input types as Text, and some checkboxes. Its action is set to "insert.php", where is the code that sends the e-mail, and sends the data to the database, and on the end of it, an alert and a redirection to the form page.
When I fill the form without checking anything on the checkboxes, everything works just fine, the database columns are filled perfectly, and the e-mail is correctly sent, the fields that were supposed to receive the checkboxes values are blank, as it was supposed to be, since I've not filled them. But once I try to use the checkboxes, when I hit Submit, I get a empty page, and the address freezes on insert.php. I'm not sure what is happening, but since I haven't worked with Checkbox to SQL before, and I'm pretty newbie on coding, I think it has something to do with the way I'm trying to process the data from the checkboxes to send it to the db. I understood that, setting values to each checkbox, it would post them as text.
Here are the codes (the most important parts of if, to try to summarize. [...] are in place of parts I took away, to make it more simple for you to help me.)
-
FORM:
<form id="contact-form" action="../painel/insert.php" method="POST">
//[...]

Quantidade de pares por numeração

SANDÁLIAS INFANTIS

Numeração
Quantidade
Alça

25/26
<input type="text"  name="i2526_quant">

<input type="checkbox" name="i2526_a" value="Slim"> Slim

<input type="checkbox" name="i2526_a" value="Tradicional"> Tradicional

27/28
<input type="text" name="i2728_quant">

<input type="checkbox" name="i2728_a" value="Slim"> Slim

<input type="checkbox" name="i2728_a" value="Tradicional"> Tradicional

29/30
<input type="text" name="i2930_quant">

<input type="checkbox" name="i2930_a" value="Slim"> Slim

<input type="checkbox" name="i2930_a" value="Tradicional"> Tradicional

31/32
<input type="text" name="i3132_quant">

<input type="checkbox" name="i3132_a" value="Slim"> Slim

<input type="checkbox" name="i3132_a" value="Tradicional"> Tradicional

//[...]
<input type="submit" class="submit no-margin-bottom"  value="Enviar" style="font-size:20 px; padding: 10px; border: 3px solid #555555;"/>
</form>

-
THE CODE, on Insert.php:
<?php
include "conexao.php";
//[...]
$i2526_quant = $_POST['i2526_quant'];
$i2526_a = $_POST['i2526_a'];
$i2728_quant = $_POST['i2728_quant'];
$i2728_a = $_POST['i2728_a'];
$i2930_quant = $_POST['i2930_quant'];
$i2930_a = $_POST['i2930_a'];
$i3132_quant = $_POST['i3132_quant'];
$i3132_a = $_POST['i3132_a'];
//[...]

$inserir = "INSERT INTO orcamento VALUES([...],'$i2526_quant','$i2526_a','$i2728_quant','$i2728_a','$i2930_quant','$i2930_a','$i3132_quant','$i3132_a',[...])";

//[...](here is the part of the code that sends the e-mail. As I said, everything is working fine, except for the checkboxes (actually, I took away the part from the code that would send the checkbox values to the e-mail and tested it again, and it didn't work. Since the code is pretty long, I decided not to post it (if you need to, I will).

$enviado = $mail->Send();

if ($enviado) {
//$envia =  mail($recipient, $subject, $message, $headers);
echo '';
}else{
echo '';
            } }

?>

--
Thank you very much in advance. I'm sorry for the poor english, and for being such a newbie, as I'm pretty sure this is a simple thing to solve, but hey, here I am trying to learn from the bests (:
Answer: Try to add [] after the checkbox name in your HTML file. This will post them as an array to your PHP file. If you don't do that there is no possibility to have several checked values.
Not sure if this solves your error. You should be able to get more information though by adding the following to the top of your insert.php file:
error_reporting = E_ALL;
ini_set('display_errors', 'On');

This enables error reporting for the file and should output what's going wrong. Make sure to remove that after fixing your error.
Comment: Thank you for anwering! I added the [] on the names of the checkboxes on form, and on the code

(i.e.
    $i2728_quant = $_POST['i2728_quant'];
    $i2728_a = $_POST['i2728_a[]'];
)

but it didn't work yet. I've got the same error (a blank page.). I'm sorry, but what did you mean by putting error_reporting on the top of insert.php? I tried to put it after the opening <?php, but DW returned an syntax error message, and when I put it before the opening <?php, the code simply appeared written on the blank page.
Comment: I meant after the <?php. What does the syntax error message say? This could be the reason for your white page.
Comment: I meant an error like "There is a syntax error on line [...]. Code hinting may not work...". But hey, I fixed it! Well, not quite as I wanted though. I substituted the checkbox type for radio (a friend of mine told me checkbox processess datas as Arrays. I don't undertand much about it, but I knew I'd have to add a lot of code, I found it simply to substitute.) I'll still wait for someone (who undertands more than my friend, who actually don't know much either, and wouldn't know how to teach me) to explain everything perfectly, but for now, the form is working. Thank you so much for replying!

Simple Checkbox values to SQL database


How to turn off PS4 controller?

Question: I'm trying to figure out if its possible to turn off the PS4 controller without turning off the system because it pretty much stays on the whole time I'm not gaming and obviously drains the battery pretty quickly.
On the PS3 there was always an option to turn off the controller itself so I'm wondering if I'm missing something. Anyone know if this is possible?
Answer: To turn it off manually, you can hold the PS button for 10 seconds. Good for if your screen is off, if it's indefinitely stuck in searching mode, or if you're using it with PC.
Comment: thanks. after you pair your device with windows this is how i turn off my controller when not using it.
Comment: This is much easier than going through all the menus.
Comment: This is the correct answer and should have been chosen as the best.
Comment: is there a faster way to do this for PC? 10 seconds is a long time when Im in a workflow or trying to get out the door.
Answer:
Hold PS button
Go to adjust devices
Select turn off device
Pick dualshock 4.
Comment: Amazing. Reminds me of Windows 8 and the hidden Power Off button.
Comment: No probblem! Glad to help
Comment: there you go! lol, i wouldve never found it!. thanks
Comment: Yeah, not under "power" where you would naturally look...
Answer: To have it turn off automatically after not being used for a while:

choose the settings option from the menu on the top of the main screen (far right, next to the power symbol, toolbox icon)
scroll down and choose 'Power Save Settings'
choose 'Turn Off DUALSHOCK 4 Automatically'
select 10, 30, or 60 minutes as the idle time before the controller is turned off automatically (selecting off will return it to always-on)

How to turn off PS4 controller?


Can you still get and use Auriel's bow when you join the Dawn Guard?

Question: Just got the Dawn Guard DLC and noticed the achievement to use Auriel's bow, but I was I want to be with the Dawn Guard.
Do you still get Auriel's bow if your sided with the Dawn Guard or do you have to be a vampire?
The bow is supposed to help the vampires and also leads to an achievement using it (and I'm all about the achievements) and I don't want to start a new character and complete the main quest and Dawn Guard because it takes too long
Answer: The bow itself doesn't change, so yes, you can use it.  It's still a powerful sun-damage weapon. What changes is whether or not you use your companion's blood to make the arrows that blot out the sun.
Bethesda games often have their story splits early for achievement purposes, but if you're achievement farming, the best choice is to make a hard save right before a point of no return on the decision. Then you can play through each branch, make a hard save at the end of that branch, reload the first save, and once you've obtained all of the achievements, load and keep the branch with the outcome you wanted.
Comment: If you're not achievement farming then go through as the Dawnguard as per your playthrough and, whenever you want, start a new playthough with a character that will follow the Volkihar Vampire clan as opposed to the Dawnguard. This way you still get the achievements whilst enjoying all the gameplay available. Plus, being a Vampire Lord is quite fun and you get a lot of power out of it, and you get a nice big castle! FYI you can be a Vampire Lord and side with the Dawnguard, but what fun is that?!
Comment: -1 for not addressing the question, which is about the achievement related to Auriel's Bow.
Answer: If you sided with the Dawn Guard, you get neither the bow now the Shield.
HOWEVER, if you are on PC, just console command it.
If you don't know the ID number, jus' type, "help Auriel," and everything associated with that name will come up
Comment: Wrong.  The differences between the two quest lines are trivial.  You get both bow & shield either way.


show the equality $f(\bar{z})=\overline{f(z)}$ for entire function $f(z)$

Question: i am struggling with this proof.
Do you have some ideas?
Let $f(z)$ be entire function.
Show that, if $f$ maps $\mathbb{R}$ into $\mathbb{R}$, then equality $f(\bar{z})=\overline{f(z)}$ holds for all $z \in \mathbb{C}.$
Thanks for help.
Comment: Check out H. Cartan's book (it's thin).
Answer: If $f$ maps reals to reals, the coefficients of the power series expansion are real.
Then $\overline{f(z)} = \sum_n \overline{a_n} \overline{z^n} = \sum_n a_n \overline{z}^n  = f(\overline{z})$.
To see why the $a_n$ are real, note that $a_0$ must be real since $f(0) = a_0$.
Suppose $s$ is real, then since $f'(s) = \lim_{t \to 0, t \text{ real}} {f(s+t)-f(s) \over t}$ we see that $f'(s)$ must be real, and hence
$f'$ maps reals to reals, and so $a_1$ is real. It follows that all the $a_n$ are real.
Comment: Cooper.hat, your explanation is oustandingly clear and beautiful, thank you very much....if you would have time, could you please look at my  second problem http://math.stackexchange.com/questions/1985161/show-that-function-fz-z23z-ez-1-can-be-expressed-as-a-power-series ...cause some guys was trying to help, but your explanation are really clear. Thanks so much.
Answer: Hint: $f^{(k)}(0)$ exists for any $k\geq 0$ and differentiability in the complex sense implies differentiability in the real sense, so
$$ f^{(k)}(0)=\lim_{h\to 0^+}\frac{1}{h^k}\sum_{j=0}^{k}\binom{k}{j}(-1)^j f(jh) \tag{1}$$
where every term in the sum appearing in the RHS is real. That implies $f^{(k)}(0)\in\mathbb{R}$ for any $k\geq 0$, hence
$$ f(z) = \sum_{n\geq 0}c_n z^n = \sum_{n\geq 0}\frac{f^{(k)}(0)}{k!}\,z^n \tag{2}$$
trivially fulfills $f(\overline{z})=\overline{f(z)}$.


Where is the Red/Green Bar for unit-testing in IntelliJ 2018?

Question: The manual for IntelliJ 2018 shows the usual Red/Green bar in the Run panel, as seen in this shot:

But in my IntelliJ Ultimate Edition version 2018.3.4, I see no such green or red bar, as seen in this screenshot from my computer:
Answer: New feature: Red/Green bar disappears
I am working with IntelliJ IDEA 2018.3.3 Ultimate Edition (Build 183.5153.38) on a Windows 10. I would expect 2018.3.4 turn out the same considering the bar design.
The bar design and behavior is changed and the documentation seems not updated yet. It is shown just a brief moment before it is gone, as you can see in the following pictures.
Those unhappy with this new feature can vote for issue ticket # IDEA-200548: Keep showing the red / green bar when tests execution is finished.
green

red

And I see the checkmark icon after the test is ok

or a warning icon if the tests failed

Althoug I noticed, that sometimes the checkmark/warning icons are not shown.
After rerun of the tests they appear again.
Comment: Please see/follow/comment usability problem issue already created at YouTrack: https://youtrack.jetbrains.com/issue/IDEA-200548
Comment: Hi @OlgaKlisho, Thanks for pointing out this issue on YouTrack. Good to know.


How to access Attribute data from within a method

Question: I have a PostSharp class like this:
[Serializable]
public sealed class TraceAspect : OnMethodBoundaryAspect
{
    public override void OnException(MethodExecutionArgs args)
    {
        public Dictionary<string, object> tt
             = new Dictionary<string, object>();

        tt.Add("WebServiceName", args.Method.DeclaringType.Namespace);

        for (int x = 0; x < args.Arguments.Count; x++)
        {
           // ignore ref parameters
           if (!args.Method.GetParameters()[x].ParameterType.IsByRef)
               tt.Add(args.Method.GetParameters()[x].Name, args.Arguments.GetArgument(x));
        }

        // call to my custom logging with parameter name and values in tt
        // …

        args.FlowBehavior = FlowBehavior.Continue;

        base.OnException(args);
     }
}

And this is used by my code in this way in a web service:
[WebMethod,Trace]
public int TestFunction(string Param1, string Param2, string ref error)
{
    try
    {
        bool test = true;
        if (test)
        {
             error =  "this is a test exction";

             throw new Exception (error);
        }

        return 1;
     }
     catch (Exception ex)
     {
         error = ex.Message;

         throw ex;
     }

     return 2;
}

The problem I have is that my test method never returns 2. How can this be done?
Regards
Answer: To better understand the issue, you can visualize how the OnException aspect is weaved into your method's code. It basically wraps the whole method body into a try-catch block. So, the result looks similar to the following:
[WebMethod,Trace]
public int TestFunction(string Param1, string Param2, string ref error)
{
    try
    {
        try
        {
            bool test = true;
            if (test)
            {
                 error =  "this is a test exction";

                 throw new Exception (error);
            }

            return 1;
        }
        catch (Exception ex)
        {
            error = ex.Message;

            throw ex;
        }

        return 2;
    }
    catch (Exception e)
    {
        // Call to TraceAspect.OnException
    }
    // The execution will continue here
}

As you can see, the exception is caught and re-thrown in the first catch. After that, it is caught again in the second catch. At this point the return 2; statement is already skipped.
You can set the new return value of the method in the aspect by setting args.ReturnValue whenever you set args.FlowBehavior to Continue or Return (these two values are equivalent in case of the exception flow behavior, see FlowBehavior Enumeration).
For example:
[Serializable]
public sealed class TraceAspect : OnMethodBoundaryAspect
{
    private object returnValue;

    public TraceAspect(object returnValue)
    {
        this.returnValue = returnValue;
    }

    public override void OnException(MethodExecutionArgs args)
    {
        public Dictionary<string, object> tt
             = new Dictionary<string, object>();

        tt.Add("WebServiceName", args.Method.DeclaringType.Namespace);

        for (int x = 0; x < args.Arguments.Count; x++)
        {
           // ignore ref parameters
           if (!args.Method.GetParameters()[x].ParameterType.IsByRef)
               tt.Add(args.Method.GetParameters()[x].Name, args.Arguments.GetArgument(x));
        }

        // call to my custom logging with parameter name and values in tt
        // …

        args.FlowBehavior = FlowBehavior.Continue;
        args.ReturnValue = this.returnValue;

        base.OnException(args);
     }
}

Comment: Ok, this is fine. But how can I get the exception type in OnException ? The value is always null ?


Django Rest Framework, can I use ViewSet to generate a json from django view function?

Question: I know I can use drf serializer from django views, but queryset, pagination setting is all duplicated in drf viewset and django view.
Can I reuse viewset to generate json data and include it in regular django response?
Update:
ie, Can I call ViewSet.as_view()(self.request) from django view?
it's not documented way, so I'm wondering the downsides of this approach .. and if it's doable..
Answer: Yes, you can call YourViewSet.as_view()(self.request) in your Django view.
Make sure you call the ViewSet like below:

YourViewSet.as_view({'get': 'list'})(self.request)

Else it will raise an exception

The actions argument must be provided when calling .as_view() on a ViewSet. For example .as_view({'get': 'list'})


Start multiple Processes and wait till they are finished

Question: I'm trying to start multiple Task which will start a process on a remote maschine. After they concluded a mail should be send.
What should my Code do?: I have multiple Bots running on VMs/Remoteclients to simulate some traffic and im doing some research on their behavior after manipulating the machine and it takes hours to finish. This is done by my main machine that use ps tools to run scripts remotely on them. Basically I start one psexe to start my bot and a psexe to "watch" over the output of the bot. Until now I used 4 programs to let the script run on the 4 machines and one program that was looking after those 4 task if they have finish so it may send me a mail that the task have completed and if it had some errors or smth like that. And tbh its annoying to change always the code in 4 solutions^^ so I though I could make it run asynchrony but in class we only talked about the concept how smth like this may work and now I'm struggling with the different concepts of .net how to implement it. Below I provided a mockup of my code.
void mainClass(){
   doWithThreads(); // this works
   doWithTasks(); // this dosnt work
   doWithTaskAndWait(); // this works again
}

void doWithThreads(){
   Thread t1 = new Thread(() => startBot("Bot1"));
   t1.start();
   Thread t2 = new Thread(() => startBot("Bot2"));
   t2.start();
   t1.join();
   t2.join();
   sendMail();
}

void async doWithTasks(){
   List<Task> tl = new List<Task>();
   tl.add(Task.Factory.Startnew(() => startBot("Bot3"));
   tl.add(Task.Factory.Startnew(() => startBot("Bot4"));
   await Task.WhenAll(tl); // jumps instantly to sendMail and Task in TL are never started
   sendMail();
}

void doWithTaskAndWait(){
   List<Task> tl = new List<Task>();
   tl.add(Task.Factory.Startnew(() => startBot("Bot5"));
   tl.add(Task.Factory.Startnew(() => startBot("Bot6"));
   Task.WhenAll(tl).Wait(); //I think this works bc its again busy waiting
   sendMail();
}

void startBot(string x){
   Process a = ... //pstoolsconfig
   Process check = ... //pstoolsconfig
   a.start();
   check.start() // this one checks the logfile of process a
   while(!check.StandardError.ReadToEnd().Contains(x + " has finished")){
      check.start(); //should simulate busy waiting
      thread.sleep(1000) //wait a sec
   }//as soon it finds the phrases "BotX has finished" in the logfile it should be done with his job

}

Unluckily I don't have anyone who I can ask about it and I don't have any idea why the async/await method doesn't work. My Idea is that the startBot method returns void and bc of this it never can "confirm" that it has finished to run. And the I think that the thread.join and the task.whenall.wait are like busy waiting operations that blocks everything else on the scheduler. But maybe I'm just lucky that those methods find very fast a spot on the scheduler and are executed "faster" then the sendmail.
I hope someone can help me to figure out what I'm doing wrong.
//Update 1:Thats the behavior of doWithTask
List<Task> tl = new List<Task>();
tl.add(Task.Factory.Startnew(() => startBot("Bot3"));
Console.WriteLine(tl.elementat(0).status)); // running
Task.WhenAll (tl).ContineWith(t => sendMail());
Console.WriteLine(tl.elementat(0).status)); // running
//end of code exe closed

Comment: Possible duplicate of [Why exactly is void async bad?](https://stackoverflow.com/questions/45447955/why-exactly-is-void-async-bad)
Comment: [`Task.WaitAll(tl.ToArray())`](https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.waitall?view=netframework-4.7.2#System_Threading_Tasks_Task_WaitAll_System_Threading_Tasks_Task___)
Answer: Lets have a look why it works like it does at the moment:
Thread.Join Doc

Blocks the calling thread until the thread represented by this instance terminates ...

It 'waits' for the threads (t1, t2) to terminate before continuing with sendMail().
Task.WhenAll Doc

Creates a task that will complete when all of the supplied tasks have completed.

This one does not wait. It is creating another Task an continues on as usual.
Task.WhenAll.Wait Doc

Waits for the Task to complete execution.

This one takes the Task create above and waits for its termination. (Task.WaitAll would have achived the same)
What you can do:
If you want to block the current thread until completion:
Task.WaitAll(tl.ToArray());

If you dont want to block the current thread:
Task.WhenAll(tl).ContinueWith(t => sendMail());

ContinueWith Creates a continuation that executes asynchronously
  when the target Task completes.
Comment: This is a great answer but it doesn't help me. My problem is that startBot() is never finished befor the end of the code is reached. As example:
    List tl = new List();
    tl.add(Task.Factory.Startnew(() => startBot("Bot3"));
    Console.WriteLine(tl.elementat(0).status)); // running
    Task.WhenAll(tl).ContineWith(t => sendMail());
    Console.WriteLine(tl.elementat(0).status)); // running
Comment: @Kleisophabo if you want to wait for startBot() to finish you need to use `Task.WaitAll(tl.ToArray()); sendMail(); Console.WriteLine(tl.elementat(0).status));` or keep extending with ContinueWith `Task.WhenAll(tl).ContinueWith(t => sendMail()).ContinueWith(t => Console.WriteLine(t.status)));`
Comment: If this does not help you might to want to add your startBot() function. Maybe it is async itself?
Comment: Well thank you for your help but the only different between the startBot here and mine is a lot of strings to define the parameter to start pstools.
Answer: Thank you all for your help. I figured it out during the weekend.
I changed the design from my startBot to let it return a Task and then the await did work.


How to validate location path in Firebase Rules?

Question: I would like to validate $username length to be longer than 5 character and shorter than 24 character
{
    "rules": {
        "user": {
            "$username": {
                ".write": "auth != null",
                "uid": {},
                "created": {},
                "lastlogin": {}
            }
        }
    }
}

(if it's possible) How can i do that?
Answer: Yes it is possible:
{
    "rules": {
        "user": {
            "$username": {
                ".write": "auth != null",
                ".validate":"newData.hasChildren(['validate_username'])",
                "validate_username":{
                    ".validate":"
                        newData.val() == $username
                        && newData.val().length > 5
                        && newData.val().length < 24
                    "
                },
                "uid": {},
                "created": {},
                "lastlogin": {}
            }
        }
    }
}

Answer: you can validate the $username with a regex

{
    "rules": {
        "user": {
            "$username": {
                ".write": "auth != null",
                ".validate": "$username.matches(/^.{6,23}$/)"
            }
        }
    }
}


Firepit burner safety limitations indoor

Question: I wanted to put a high BTU burner into a fireplace that only has a "log lighter" burner in it now, but one brand I had reached out to said "our burners aren't approved for indoor use, due to the high BTU output"
This is a vented fireplace which is rated to be able to burn wood. Are there any considerations I should be aware of when finding a high powered burner to swap into here?
I wouldn't think exhaust would be an issue since wood can be burned, and I also wouldn't think heat output would matter since with coals and logs burning, the heat could be quite intense, but I'm asking to be safe given the comment made by that manufacturer.
Comment: You ought to be checking with the manufacturers making the burners. They would know better than us.  Plus, if you install a unit that isn't approved, say good bye to any homeowner's insurance coverage in case of fire or damage.
Comment: Can google for the numbers, but I think gas has a much higher BTU output than wood/coal in a limited space.
Comment: At least part of the reason gas has replaced wood & coal in furnaces.
Answer: TL;DR
Google for "indoor gas fireplace insert". Preferably get one with a blower so that you're not strictly wasting heat up the flue.
You need to make sure your flue can handle the BTU.

I wanted to put a high BTU burner into a fireplace that only has a "log lighter" burner in it now, but one brand I had reached out to said "our burners aren't approved for indoor use, due to the high BTU output"

Okay, a picture of the current situation would be nice. What brand did you reach out to? What model number did you inquire about?

This is a vented fireplace which is rated to be able to burn wood. Are there any considerations I should be aware of when finding a high powered burner to swap into here?

Yes, consult a chimney/fireplace company. At minimum you'll want it inspected and cleaned. If you get someone nice then you can inquire about your gas fireplace plans and they might provide some insight into way to not burn down your house.

I wouldn't think exhaust would be an issue since wood can be burned, and I also wouldn't think heat output would matter since with coals and logs burning, the heat could be quite intense, but I'm asking to be safe given the comment made by that manufacturer.

Sorry to be blunt but your opinion does not matter and neither does mine when it involves a fireplace. Consult a chimney/fireplace company.
The manufacturer has zero clue about the health of your existing fireplace and they'd rather lose your business as a customer than face the legal woes of you burning your house down due to their guidance.
Comment: Glad I asked - thanks


Dynamic Memory Allocation inside Class

Question: How do i dynamically allocate memory inside a class?
To clearify my question i made up an example. I would construct an instance a of A and copy it into b. After usage a and b would be destructed and the allocated memory would be freed twice in the destructor.
So how would i handle this situation?
<code>#include <stdlib.h>

class A {
public:
    char * allocatedMemory;
    A(int length) {
        allocatedMemory = (char *) malloc(sizeof(char) * length);
    }

    ~A(){
        free(allocatedMemory);
    }
};

int main() {
    A a = A(50);
    A b = a;
    return 0;
}
</code>
PS: To understand the Context: I am trying to figure out by example how std::string allocates and frees memory. Only the basic allocation of course.
Comment: Search for "the rule of three" (and "five" and "zero").
Comment: Hi the problem you are facing is due to shallow copy. If you wont provide the copy constuctor explicitly then the default copy constructor will be provided by compiler to inialize one object using exising object. The default copy constructor does the bit wise copying. I.e. just copy the address stored in pointer of one object to another. To avoid such double free problem, you need to do deep copy. Write your own copy constructor, inside that copy constructor explicitly allocate memory for your character pointer using new then using memcpy() copy the actual content. Hope this will help.
Comment: Why not just use something that already has the semantics you want, like `std::vector`?
Comment: Have you considered overloading the assignment operator?
Comment: Thanks guys. The copy constructor was all i needed!
Comment: Hi if my comment solved your problem. Will you please accept my answer and vote my comment. Thanks.
Comment: As described, i designed an example for clarification purposes. So mostly for gathering knowledge on how this could be done in background, which could be useful for more complex situations.
Answer: Hi the problem you are facing is due to shallow copy. If you wont provide the copy constuctor explicitly then the default copy constructor will be provided by compiler to inialize one object using exising object. The default copy constructor does the bit wise copying. I.e. just copy the address stored in pointer of one object to another. To avoid such double free problem, you need to do deep copy. Write your own copy constructor, inside that copy constructor explicitly allocate memory for your character pointer using new then using memcpy() copy the actual content. Hope this will help.
<code> #include <stdlib.h>
 class A
 {
    public:
    char * allocatedMemory;
    int length;
    A(int length):length(length)
    {
          // i am ignoring exception due to failure in new to keep code simple
          this->allocatedMemory = new char[length];
    }
    A(const A& obj)
    {
        this->allocatedMemory = new char[obj.length];
        memcpy(this->allocatedMemory, obj.allocatedMemory, obj.length);
        this->length = obj.length;

    }
    A& operator=(const A& obj)
    {
         if(this != &obj)
         {
             if(this->length == obj.length)
             {
                 memcpy(this->allocatedMemory, obj.memory, obj.length);
             }
             else
             {
                 delete[] this->allocatedMemory;
                 this->allocatedMemory = NULL;
                 this->allocatedMemory = new char[obj.length];
                 memcpy(this->alocatedMemory, obj.allocatedMemory, obj.length);
                 this->length = obj.length;
             }
        }
        return *this;
     }

    ~A()
   {
        if(allocatedMemory)
            delete[] allocatedMemory;
   }
};

int main()
{
    A a = A(50);
    A b = a;
    return 0;
}
</code>
Comment: `memcpy` needs a length parameter, and the `operator=` has a lot of mistakes. For getting started I'd suggest using copy-and-swap for `operator=`.
Comment: `if(allocatedMemory)` is redundant, it is safe to `delete` a null pointer. Also you are correctly handling allocation failure in the constructor -- it's good practice for the constructor to throw when it was unable to create an object
Comment: Start again, and think about what you are doing. You forgot to set both the length and the allocated sinze in the current object. See [what is the copy and swap algorithm](http://stackoverflow.com/questions/3279543/what-is-the-copy-and-swap-idiom)
Comment: You still fail to handle the case of `obj.length > length`
Comment: @M.M hi thanks for the coments. Will you please let me know what are the mistakes in operator= here. I will improve those errors.
Comment: @M.M  yes i missed to inirialize length in current object.Edited the answer.
Comment: Actually i assumed that identical objects where lentgh represents the amount of memory to be allocated. But you are right the length case issue still exists here.

Dynamic Memory Allocation inside Class


How to average across excel rows for multiple rows using Openpyxl in Python?

Question: I am currently trying to average 3 excel columns(Col C to E) into and new 4th column (Col F). When I look up how to do this with openpyxl the code looks like this:
from openpyxl import load_workbook

wb = load_workbook('PythontestAvg.xlsx')
sheet1 = wb['full trace']
sheet2 = wb['full trace Copy']

sheet2["F1"] = '=AVERAGE(C1:E1)'
sheet2["F2"] = '=AVERAGE(C2:E2)'

However, doing this is very tedious for 1500 cells from F1 to F1501. Is there a way to write a code that will let me average each of the rows for the 3 columns and paste in Column F? Basically a code that will give the same result as:
sheet2["F1"] = '=AVERAGE(C1:E1)'
sheet2["F2"] = '=AVERAGE(C2:E2)'
sheet2["F3"] = '=AVERAGE(C3:E3)'
\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/
sheet2["F1501"] = '=AVERAGE(C1501:E1501)'

Please let me know if any more clarification is needed. Thanks in advance
Answer: Seems like you are looking for a for loop similar to this:
for i in range(1, 1502):
    sheet2["F" + str(i)] = '=AVERAGE(C%s:E%s)' % (i,i)

Comment: yes exactly! thank you so much. Sorry for the basic question this is my first time coding and trying to use openpyxl.
Comment: @HoumanQadir No problem, if the question is solved feel free to accept my answer so others can quickly see it.


ValueError: The shape of the input to "Flatten" is not fully defined (Neural Networks)

Question: I try to using Flatten for my LSTM model, but it doesn't work and getting this error:

ValueError: The shape of the input to "Flatten" is not fully defined (got (None, 450) Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.

Model:
<code>input_vector_size = kwargs.get('input_vector_size', 128)
dense_size = kwargs.get('dense_size', 20)
timesteps = None
xav_init = tf.contrib.layers.xavier_initializer()
##########

model = Sequential()
model.add(LSTM(int(input_vector_size), input_shape=timesteps,int(input_vector_size)), return_sequences=True))
model.add(SeqSelfAttention(attention_activation='softmax'))
model.add(Flatten())
model.add(Dense(dense_size, activation='sigmoid', kernel_initializer=xav_init))
model.add(Dense(kwargs.get('label_size', 2), activation='sigmoid'))
</code>
How do I solve this problem?
Comment: You need another bracket: `input_shape=(timesteps, int(input_vector_size))`, otherwise the `input_shape=timesteps=None`
Comment: Yes i forgot the bracket anw i fixed the code. I should change the timesteps to 1 if i want to use Flatten() @JimmyOnThePage
Answer: Just for anyone want to know the answer. You should change the input_shape to (1,int(input_vector_size)) to use Flatten


Using the cosine law

Question: We have a triangle $ABC$ with $AB = 6.5$ , $BC=3.5$ and $AC = \sqrt{61}$. Can we calculate $\angle A$ using the law of cosines? I tried it but I kept getting wrong answers, so I'm wondering if it's possible?
I tried:
$c^2=a^2+b^2-2ab\cos\gamma$
$(3.5)^2= (6.5)^2 + 61 -6.5\sqrt{61}\cos\gamma$
$91 = 6.5\sqrt{61}\cos\gamma$
$\cos\gamma = 1...$ which is impossible
Comment: Of course it's possible. Show us your working, and we'll try to help.
Comment: Can you use the second bullet ($\gamma$) with the graphic under [**Applications**](http://en.wikipedia.org/wiki/Law_of_cosines#Applications) and follow the logic to find $\angle A$?
Answer: You just forgot to multiply the term $ab\cos\gamma$ by $2$.

Using the cosine law


Number issue with single and double digit

Question: I'm having an issue with some numbers. Currently, I have an input box that displays the result of an equation. If the numbers are between "-25" and "-55", they display green. If the numbers are from "-55" to "-65", they are orange. Anything else outside of those ranges are red. The problem that I am having is that numbers "-3", "-4" and "-5" are all outside of that range, but they display as green. "-6" displays as orange. Those numbers should be red. Am I missing something from my code that would fix that?
Thank you!
var tb = (num1 * num2) + num3 + num4 + num5 + num6 + num7 + num8 + num9 + num10 + num11 + num13 + num12 + num14;

    if (tb > 0) {
        document.calcForm.resist.value = "+" + Math.floor(tb* 100)/100 + " dBm";
    }
    else
    {
        document.calcForm.resist.value = Math.floor(tb* 100)/100 + " dBm";
    }

       document.calcForm.resist.style.color = "green";

   if (document.calcForm.resist.value < "-26" || document.calcForm.resist.value > "-65") {
        document.calcForm.resist.style.color = "red";
   }
   else { if (document.calcForm.resist.value > "-55") {
        document.calcForm.resist.style.color = "orange";
   }}

num1 - num14 are different fields for the equation.
Comment: Because `"-26 dBm" !== -26` Also, `"-26" !== -26`
Comment: you're comparing them as strings. Try `parseFloat(document.calcForm.resist.value) < -26`
Comment: bad coding use some varaibles
Answer: You were comparing strings to strings, which compares alphabetically, not by value. So, you need to convert document.calcForm.resist.value to a number – parseInt(resist.value) (see code):
var tb = (num1 * num2) + num3 + num4 + num5 + num6 + num7 + num8 + num9 + num10 + num11 + num13 + num12 + num14;
var resist = document.calcForm.resist;
if (tb > 0) {
    resist.value = "+" + Math.floor(tb* 100)/100 + " dBm";
}
else
{
    resist.value = Math.floor(tb* 100)/100 + " dBm";
}
resist.style.color = "green";
if (parseInt(resist.value) < -26 ||
    parseInt(resist.value) > -65) {
    resist.style.color = "red";
}
else if (parseInt(resist.value) > -55) {
    resist.style.color = "orange";
}

Comment: Worked perfectly. Thank you.
Answer: You are trying to compare values with string type variables. You should not be using quotes for numeric data type.While using numeric comparisons you should use parseInt:
if (parseInt(document.calcForm.resist.value) < -26 || parseInt(document.calcForm.resist.value) > -65) {
        document.calcForm.resist.style.color = "red";
   }

Answer: That happens due to the fact that document.calcForm.resist.value is being
treated as string/text because you add "+" and + " dBm" to it
document.calcForm.resist.value = "+" + Math.floor(tb* 100)/100 + " dBm";

That's why "-3" > "-26", and "-3" < "-65".
Likewise for the rest.
Think of string comparison as: "-1" > "-10" > "-11"
whereas numerical: -1 < -10 < -11
In addition, you should remove the quotes from the numbers at:
if (document.calcForm.resist.value < "-26" || document.calcForm.resist.value > "-65")

to avoid invoking a string a comparison instead.


Basic tile map in winforms

Question: I am making a program where you bassicly move from tile to tile in windows forms.
So in order to do that, I wanted to use panels each panel has a tag. To detect collision.
So I have an image of my map. and I divided into multiple tiles. However now I have to drag 900 tiles onto panels.
This isn't very effective in 2 ways. First loading 900 textures isn't really a smart idea. Also it would take ages. So i wanted to use a spritesheet or tilemap. But how would I do that in winforms. I believe I have seen some people use a grid view or whatever. However im not sure how to do what I want to do.
What would be the best solution?
Thanks in advance!
Comment: @HighCore Well, the answer can be solved with code. Winforms is indeed not suitable. Altough that doesn't mean it can't be done. I am not trying to create the best application out there. I am just learning myself OOP in a way I enjoy doing it. Winforms is decent.
Answer: For any serious gaming project WinForms is not the best platform. Either WPF or XNA or Unity are able to deliver high performance use of DirectX.
But since you want to do it in Winforms here is a way to do it.
It creates a whopping number of 900 PictureBoxes and loads each with a fraction of an source image:
private void Form1_Load(object sender, EventArgs e)
{
    int tileWidth = 30;
    int tileHeight = 30;
    int tileRows = 30;
    int tileCols = 30;

    using (Bitmap sourceBmp = new Bitmap("D:\\900x900.jpg"))
    {
        Size s = new Size(tileWidth, tileHeight);
        Rectangle destRect = new Rectangle(Point.Empty, s);
        for (int row = 0; row < tileRows; row++)
            for (int col = 0; col < tileCols; col++)
            {
                PictureBox p = new PictureBox();
                p.Size = s;
                Point loc = new Point(tileWidth * col, tileHeight * row);
                Rectangle srcRect = new Rectangle(loc, s);
                Bitmap tile = new Bitmap(tileWidth, tileHeight);
                Graphics G = Graphics.FromImage(tile);
                G.DrawImage(sourceBmp, destRect, srcRect, GraphicsUnit.Pixel);
                p.Image = tile;
                p.Location = loc;
                p.Tag = loc;
                p.Name = String.Format("Col={0:00}-Row={1:00}", col, row);
                // p.MouseDown += p_MouseDown;
                // p.MouseUp += p_MouseUp;
                // p.MouseMove += p_MouseMove;
                this.Controls.Add(p);
            }
    }

}

When I tried it I was a bit worried about perfomance, but..

This takes under 1 second to load on my machine.
Starting the programm adds 10MB to VS memory usage. That is like nothing.

For a fun project this will do; for best performance one might use Panels but these will have to be filled and refilled in the Paint event. This solution saves you the hassle and since you don't change the tile picture all the time this works well enough.
Pleae note: I have added a Name and a Tag to each PictureBox, so you can later refer to it. These both contain info about the original position of the Picturebox. The Name looks like this: Col=23-Row=02 and the Tag is the original Location object.
Also: Dynamically added controls take a little extra to script since you can't create their method bodies in the designer. Instead you add them like above. In doing so Intellisense and the Tab key are your best friends..
I have added three event handlers for a few mouse events. When you uncomment them you will have to add the methods like e.g. this:
void p_MouseMove(object sender, MouseEventArgs e)
{
    throw new NotImplementedException();
}

But maybe you want to use other events to play like Drag&Drop or keyboard events..
There are two ways to refer to these tiles. Maybe you want to try and/or use both of them: You can loop over the form's controls with a
    foreach (Control ctl in this.Controls)
    { if (ctl is PictureBox ) this.Text = ((PictureBox)ctl).Name ; }

It tests for the right type and then casts to PictureBox. As an example it displays the name of the tile in the window title.
Or you can have a variable and set it in the MouseDown event:
PictureBox currentTile;
void p_MouseDown(object sender, MouseEventArgs e)
{
    currentTile = (PictureBox ) sender;
}

Comment: Thanks for the helping me out here you saved me alot of work. I also do understand how it works now and i had thaught of this before. However I face one big problem now. How would I detect if the user could enter the tile. I was thinking about tagging it but the problem here is that winforms doesn't allow me to just look for a tag i need to specify what control holds the tag. Do you know of a way to do this?
Comment: try:  this.Controls.Find(String.Format("Col={0:00}-Row={1:00}", col, row), true); to find the control

Basic tile map in winforms


MVC3 using EF4.3 and Dependancy Injection issues

Question: I have recently been learning MVC3 using Entity Framework 4.3 and Dependancy Injection so I can implement unit tests at a later date. I am now trying to implement some functions I have seen in various examples however I have hit a few issues that seem to stem from my use of dependancy injection and therefore I would like someone to point out where I am going wrong.
My first question is pretty simple; In most MVC3 examples I have seen, the access to the database is done in controllers, but when using dependancy injection I seem to need to refactor this code out to the implemented repository. Is this normal and correct?
My second more indepth issue is dealing with this simple example:
I have this method in my repository class which is pretty much copied from an online example (here). However I get an error regarding the Include part, and the intellisense does say that the variable needs to be a string. I have tried the original code from the link I mentioned earlier and that works fine, the only major difference between the project is that I am using dependancy injection.
public ExampleUser GetStruContractUser(int id)
{
    ExampleUser user = context.ExampleUsers
        .Include(i => i.ExampleRoles)
        .Where(i => i.UserID == id)
        .Single();

    return user;
}

Changing the Include parameter to the following works fine.
public ExampleUser GetStruContractUser(int id)
{
    ExampleUser user = context.ExampleUsers
        .Include("ExampleRoles")
        .Where(i => i.UserID == id)
        .Single();

    return user;
}

For reference this is my DbContext class that I am using:
public class EFDbContext : DbContext
{
    public DbSet<ExampleUser> ExampleUsers { get; set; }
    public DbSet<ExampleRole> ExampleRoles { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Entity<ExampleUser>().ToTable("User", "MySchema");
        modelBuilder.Entity<ExampleRole>().ToTable("Role", "MySchema");

        modelBuilder.Entity<ExampleUser>()
            .HasMany(m => m.ExampleRoles)
            .WithMany(t => t.ExampleUsers)
            .Map(a =>
            {
                a.MapLeftKey("UserID");  // your PK column name in user table
                a.MapRightKey("RoleID"); // your PK column name in role table
                a.ToTable("UserRole", "MySchema");  // your join table name
            });
        }
    }

Is this an issue due to my use of dependancy injection or is there something else going on that I am misunderstanding?
If you need more information, please ask and I will try and provide it.
Thanks very much.
Answer: Question 1:
Using DI doesn't force you to use a repository pattern, in fact they are not related. It's just a nice way to avoid tightly coupling your controller classes to the database context class, and being able to thus test those classes more easily. Repository gives you the ability to hide the implementation details of how you're accessing the DB, and allows you to switch ORM:s if that were to happen (and it never ever does). Repository relies on you to provide interfaces for your DbContext, and so does using DI.
What you want to do is use your DB through an interface nevertheless, and seeing as you're using DI, you could just inject the reference to the DbContext class in the constructor of your controllers, and let the DI controller do the work for you.
The reason it is preferable to pass in an interface that defines the repository to the Controller over passing an interface that defines your DbContext, is because making an interface of the latter can easily become overly complex, whereas sticking to a repository is much simpler. For simplicity though, I'd start with just using DbContext directly, and then expanding from there.
Question 2:
Include needs to contain the name of the table as a string. So your latter use of Include is correct, and the former isn't.
If I remember correctly, you can do this tho: ".Include(i => i.ExampleRoles.Name)" to achieve the same thing.
Answer: Yes, extracting your database layer (repositories / context) and then injecting it into your business layer (controllers) is very normal and a good way future proof your application.  What if you ever wanted to change your database ORM from Entity Framework to something else?  Having it tightly coupled with your controllers would create a huge headache.
Your second issue, with include, is unrelated to the dependancy injection.
Include on a dbset using lambdas an extension in System.Data.Entity.  You'll need to include that reference if you want to use it.