text:
Q: Where to put generated string-resoures that will be included in R.class generation and can be used in layouts? I'm having a custom JavaExec gradle task
which I currently use for generating several string resource files for android and other platforms.
I found out that when I'm using gradle directly, like this:
buildTypes {
     debug {
         resValue "string", "test", "test-value"
     }
}

Gradle will generate me a

generated.xml

under

/build/generated/resValues/{debug}/values/

depending on my active {buildType}
For the gradle way it works, but I don't want to use gradle directly for generating my resValues. I want to use my custom script instead!
Well, but when my script generates for example a generated-custom.xml it does not work as it should.
It generates the R.class file correctly, but when I want to use my generated string resources in a layout it won't find any of these.
So my question is:
Where do I need to put the generated xml file, so that:

*

*The R.class is generated with these string items

*The string items can be used in layouts aswell (@string/generated_string_key)

Thanks!


text:
Q: Varnish not sending PHPSESSID cookie I am running Varnish 3.0 in front of an Apache2 + PHP 5.3 server. My problem was that Varnish threw many 503 Service Unavailable errors, so I added a workaround, saying something like:
if http_code = 503 and cookie(REDIRECTED) = false
  set-cookie REDIRECTED=true
  header 307 redirect to same page // try again, maybe this time it doesn't fail
else if http_code = 503 and cookie(REDIRECTED) = true
  header 503 // we tried, but the server doesn't want to

This is a sketch in pseudo-code of the main idea what I did. However, when the 307 redirect is being made, the cookies sent by apache in the Set-Cookie header, are not sent. My main concern is that the PHPSESSID cookie isn't being sent. If I don't get an 503 error and Varnish doesn't have to make the redirect, all works fine. Any ideas?

A: Hopefully I understood your question right. I don't really see how PHPSESSID is related to handling the 503 errors, but you don't need to use cookies at all to re-try a request.
You can use restarts in Varnish to accomplish what you are trying to do. For instance to try the request 2 times you could do:
sub vcl_error {
    if (obj.status == 503 && req.restarts < 2) {
        return (restart);
    }
}

This should provide the functionality you are looking for without touching the cookies.
This is obvious, but I will say it anyway: what you really should do is find out what is causing the 503 errors. If they are not coming from the backend, they are caused either by timeouts or a problem with the Varnish configuration. Keep an eye on your Varnish log for "TxStatus     c 503" lines and see what's going on with the requests.
Update regarding the possible cause of 503 errors:
Apparently you are receiving the 503 errors on POST requests (i.e. when a user tries to log in). This can occur if posts are done over slow links or the connection is terminated by the client for some other reason before POST body is completely transferred. However this should not show up as no error recorded in varnishlog. You might want to give the following a shot in any case to see if it fixes your problem.
Varnish defaults to return(pass) for POST requests, but this doesn't work as expected in all cases (see Varnish ticket #849 for more information).
We have opted to pipe all POST requests and append X-Forwarded-For to the requests as well. Here's the relevant VCL:
# PIPE all POST requests

sub vcl_recv {
 if (req.request == "POST") {
   return (pipe);
 }
}

# Set XFF for piped requests

sub vcl_pipe {
  set bereq.http.Connection = "close";
  set bereq.http.X-Forwarded-For = req.http.X-Forwarded-For;
  if (bereq.http.x-forwarded-for) {
    set bereq.http.X-Forwarded-For = bereq.http.X-Forwarded-For + ", " + client.ip;
  } else {
    set bereq.http.X-Forwarded-For = client.ip;
  }
  return (pipe);
}

A: The only way we could fix this, was by installing a varnish module called vmod-headers, which allows you to append headers to other headers.
After that we just appended the cookie we wanted to set, to the already existing cookies which came from the backend.

A: The default vcl shouldn't remove any cookies nor cache any pages without cache headers.
The reason you get 503 from varnish is because your apache is not responding in time. If you want it to be more forgiving you can change the following settings (awfully high below) for the backend:
backend www {
    .host = "www.example.com";
    .port = "http";
    .connect_timeout = 500s;
    .first_byte_timeout = 500s;
    .between_bytes_timeout =500s;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: how set backcolor to the original color of the custom textbox I'm trying to change the forecolor for the textbox on focus (custom control)
 protected override void OnEnter(EventArgs e)
        {
            base.OnEnter(e);
            BackColor = this.Parent.BackColor;
            ForeColor = _OnFocusForeColor;
        }

but how to back to the original color of the forecolor?
I tried:
protected override void OnLeave(EventArgs e)
        {
            base.OnLeave(e);
            BackColor = Color.WhiteSmoke;
            ForeColor = this.ForeColor;
}

but doesn't work!

A: A couple of ideas:
First option
Set a break point on the line where you change the color, and debug your solution. When it stops at that line, hover over the existing ForeColor to see what the value is called before it is changed. Now you can use that color when you set it back.
Second option
Before setting the new color, save the already existing value in a property which you can then access and reapply later:
protected override void OnEnter(EventArgs e)
{
    base.OnEnter(e);
    BackColor = this.Parent.BackColor;

    // New:
    PreviousColor = ForeColor;
    ForeColor = _OnFocusForeColor;
}

..and then later, obviously:
    ForeColor = PreviousColor;


text:
Q: Where to store images for a website in react js? I am making a react E-comm site where I have 1000+ images to store..
I saw the way myntra stores their images https://assets.myntassets.com/...
How to store images in this way or where can I get more details about this concept?
The same concept is used by algoexpert.io which is a react website and their images are stored like this

A: You can use Cloudinary or Imgur to upload and images through code. You can go through their Documentation. Cloudinary offer 25GB free storage in their free plan.
Documentation Cloudinary


text:
Q: Flutter Gradle task assembleRelease failed with exit code 1 while build apk PS C:\flutter projeleri\firebase> flutter build apk
You are building a fat APK that includes binaries for android-arm, android-arm64, android-x64.
If you are deploying the app to the Play Store, it's recommended to use app bundles or split the APK to reduce the APK size.
    To generate an app bundle, run:
        flutter build appbundle --target-platform android-arm,android-arm64,android-x64
        Learn more on: https://developer.android.com/guide/app-bundle
    To split the APKs per ABI, run:
        flutter build apk --target-platform android-arm,android-arm64,android-x64 --split-per-abi
        Learn more on:  https://developer.android.com/studio/build/configure-apk-splits#configure-abi-split
Running Gradle task 'assembleRelease'...
Parameter format not correct -
Note: C:\src\flutter\.pub-cache\hosted\pub.dartlang.org\firebase_core-0.7.0\android\src\main\java\io\flutter\plugins\firebase\core\FlutterFirebaseCorePlugin.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:lintVitalRelease'.
> Could not delete old C:\flutter projeleri\firebase\build\app\reports\lint-results-release-fatal.html

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BU�LD FAILED in 10m 37s
Running Gradle task 'assembleRelease'...
Running Gradle task 'assembleRelease'... Done                     641,3s (!)
Gradle task assembleRelease failed with exit code 1

what's the problem?

A: first delete your build folder and use this command in terminal
flutter build apk --split-per-abi


text:
Q: From $\frac{dx}{dy} = \frac{1}{y'}$, derive $\frac{d^2x}{dy^2} = -\frac{y''}{(y')^3}$ and $\frac{d^3x}{dy^3} = \frac{3(y'')^2-y'y'''}{(y')^5}$. I am an adult software developer who is trying to do a math reboot. I am working through the exercises in the following book.
Ayres, Frank , Jr. and Elliott Mendelson. 2013. Schaum's Outlines Calculus Sixth Edition (1,105 fully solved problems, 30 problem-solving videos online). New York: McGraw Hill. ISBN 978-0-07-179553-1.
The following question is not consistent with my understanding of the material presented in the chapter.  I may have missed something important.
Chapter 10 Limits, problem 58.
From $\frac{dx}{dy} = \frac{1}{y'}$, derive $\frac{d^2x}{dy^2} = -\frac{y''}{(y')^3}$ and $\frac{d^3x}{dy^3} = \frac{3(y'')^2-y'y'''}{(y')^5}$.
My understanding.
$y'$ implies that $y$ is a function.  This means that I should use the chain rule in conjunction with a special case of the power rule to calculate the second derivative.  Furthermore, the chain rule should be used in conjunction with the quotient rule for the third derivative.  The problem is that my solution is not what the question asks me to derive.
Relevant definitions from the book.
$\frac{dy}{dx}=\frac{dy}{du}\frac{du}{dx}$ (Chain Rule)
$\frac{d}{dx}\big(\frac{u}{v}\big)=\big(v \frac{du}{dx} - u \frac{dv}{dx}\big)\frac{1}{v^2}$ provided $v\ne0$ (Quotient Rule)
$\frac{d}{dx}\big(\frac{1}{x}\big)=-\frac{1}{x^2}$ provided $x\ne0$ (Special Case of Power Rule)
My solution.
$$\frac{d^2x}{dy^2} = \frac{d}{dy}\frac{1}{y'} = -\frac{1}{(y')^2}(y'' )= -\frac{y''}{(y')^2}$$
For what it is worth, WolframAlpha gives the same solution.  I do not know where the extra factor of $y'$ is supposed to come from denominator of the second derivative.  Obviously, the "wrong" second derivative can not be used to calculate the "right" third derivative.
$$\frac{d^3x}{dy^3} = \frac{d}{dy}\frac{-y''}{(y')^2} = \frac{(y')^2(-y''')-(-y'')2(y')(y'')}{((y')^2)^2} = \frac{2(y'')^2(y')-(y')^2(y''')}{(y')^4} = \frac{2(y'')^2-y'y'''}{(y')^3}$$
The above is the second derivative given by WolframAlpha.  If I use the provided second derivative, this is what I get.
$$\frac{d^3x}{dy^3} = \frac{d}{dy}\frac{-y''}{(y')^3} = \frac{(y')^3(-y''')-(-y'')3(y')^2(y'')}{((y')^3)^2} = \frac{3(y')^2(y'')^2-(y')^3(y''')}{(y')^6} = \frac{3(y'')^2-y'y'''}{(y')^4}$$
This is also not what the question expects to be derived.  Yet again, it is consistent with WolframAlpha.  Did I miss something important or simply misunderstand the question?

A: You have
$$ \frac{dx}{dy} = \left(\frac{dy}{dx}\right)^{-1}, $$
so that
\begin{align*}
\frac{d^2x}{dy^2} &= \frac{d}{dy} \left(\frac{dy}{dx}\right)^{-1}\\
&= -\left(\frac{dy}{dx}\right)^{-2} \cdot \frac{d}{dy}\left(\frac{dy}{dx}\right)\\
&= -\left(\frac{dy}{dx}\right)^{-2} \cdot \frac{d^2y}{dx^2} \cdot \frac{dx}{dy}\\
&= -\left(\frac{dy}{dx}\right)^{-2} \cdot \frac{d^2y}{dx^2} \cdot \left(\frac{dy}{dx}\right)^{-1}\\
&= -\left(\frac{dy}{dx}\right)^{-3} \cdot \frac{d^2y}{dx^2}\\
&= -\frac{y''}{(y')^3},
\end{align*}
where we apply the chain rule in the second and the third row.
Can you do the third derivative on your own now?

A: Rephrasing part 1:
$y=f(x)$,  $x=g(y)$ the inverse function .
Then:
$g'(y)=\dfrac{1}{f'(x)}=\dfrac{1}{f'(g(y))}$
$g''(y) =$
$- \dfrac{1}{(f')^2(g(y))}f''(g(y))g'(y)= $
$-\dfrac{1}{(f')^2(g(y))}f''(g(y))\dfrac{1}{f'(g(y))}$.


text:
Q: Multiple markers at this line - Syntax error on tokens, Annotation Name expected Multiple markers at this line
    - position cannot be resolved to a variable
    - Cannot refer to a non-final variable items inside an inner class defined       in a different method
int multiple=0;
ImageView imageView;
TextView tot_calories;
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.items_details);
    Spinner mspin=(Spinner) findViewById(R.id.spinner1);
    Integer[] items = new Integer[]{1,2,3,4};

    ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this,android.R.layout.simple_spinner_item, items);
    mspin.setAdapter(adapter);

    TextView name_select=(TextView)findViewById(R.id.SelectedName);
    name_select.setText(constant.food_items[constant.SelectedIndex]);
    imageView =(ImageView) findViewById(R.id.imagedetail);
    UpdateImage(constant.food_items[constant.SelectedIndex]);
    TextView calories=(TextView)findViewById(R.id.calories111);
    calories.setText(constant.food_calories[constant.index]+"");

    tot_calories=(TextView)findViewById(R.id.caloriestotal);
    mspin.setOnItemSelectedListener(new       AdapterView.OnItemSelectedListener()     {
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            // Your code here
            multiple=items[position]*constant.food_calories[constant.index];
        }
        public void onNothingSelected(AdapterView<?> adapterView) {
            return;
        }
    });
    tot_calories.setText(""+multiple);
}

A: Update this line of code with this:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

public class itemsdetail extends Activity {

int multiple=0;
    ImageView imageView;
    TextView tot_calories;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.items_details);
        Spinner mspin=(Spinner) findViewById(R.id.spinner1);
        Integer[] items = new Integer[]{1,2,3,4};

        ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this,android.R.layout.simple_spinner_item, items);
        mspin.setAdapter(adapter);

        TextView name_select=(TextView)findViewById(R.id.SelectedName);
        name_select.setText(constant.food_items[constant.SelectedIndex]);
        imageView =(ImageView) findViewById(R.id.imagedetail);
        UpdateImage(constant.food_items[constant.SelectedIndex]);
        TextView calories=(TextView)findViewById(R.id.calories111);
        calories.setText(constant.food_calories[constant.index]+"");

        tot_calories=(TextView)findViewById(R.id.caloriestotal);
        mspin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()     {
          public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            // Your code here
            multiple=items[position]*constant.food_calories[constant.index];
          }
          public void onNothingSelected(AdapterView<?> adapterView) {
            return;
          }
        });

        tot_calories.setText(""+multiple);

}
}

Goodluck!


text:
Q: up and down key not firing keypress event textbox in datagridview cell i am tryint to popup one selection box on datagridview cell keypress event .selection box popup working but up and down key not firing i want to move down and up selection box data while pressing up and down key from datagridview cell
these code am using
    private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        DataGridView dttmp = (DataGridView)sender;
        csearch = "";
        var txtbox = e.Control as TextBox;
        if (txtbox != null)
        {
            txtbox.KeyPress -= new KeyPressEventHandler(textBoxPart_TextChanged);
            txtbox.KeyPress += new KeyPressEventHandler(textBoxPart_TextChanged);
            txtbox.Validating -= new CancelEventHandler(txtbox_Validating);
            txtbox.Validating += new CancelEventHandler(txtbox_Validating);
            txtbox.LostFocus += new EventHandler(txtbox_LostFocus);
        }
    }
 private void textBoxPart_TextChanged(object sender, KeyPressEventArgs e)
    {
        if (dataGridView1.CurrentCell.ColumnIndex == 1)
        {
            if (e.KeyChar == Convert.ToChar(Keys.Up))
            {
                if (srchbox.Rows.Count > 1)
                {
                    int curind = srchbox.CurrentRow.Index;
                    //srchbox.Rows[curind - 1].Selected = true;
                    if (curind - 1 >= 0)
                    {
                        srchbox.CurrentCell = srchbox.Rows[curind - 1].Cells[1];
                        srchbox.Refresh();
                    }
                }
                e.Handled = true;
            }

}

A: Use the keydown or keyup events instead.
Control.KeyPress documentation states:

The KeyPress event is not raised by noncharacter keys; however, the noncharacter keys do raise the KeyDown and KeyUp events.

A: Try to use DataGridView.CellEnter event:

Occurs when the current cell changes in the DataGridView control or when the control receives input focus.

or DataGridView.CellLeave event

Occurs when a cell loses input focus and is no longer the current cell.


text:
Q: Networkx with custom cost function for path I have the situation shown below where there is a weighted graph.

I am trying to get the best path from A to D based on a custom function, the total cost is the product of the previous costs.

*

*A - B - D = 0.6 * 30 = 18

*A - C - D = 0.3 * 40 = 12

I want to choose the second path (lower cost).
How can I do this using the networkx library?
thank you

A: One way is to iterate over all paths and select the optimal one using a custom function. This is the rough (pseudo)code:
from networkx import all_simple_paths

paths = all_simple_paths(G, source, target)
costs = []
for p in paths:
    # obtain the edge weights and evaluate the cost using custom function
    cost = custom_function(p)
    costs.append((cost, p))

# sort the costs and pick the one with the smallest cost
lowest_cost, best_path = sorted(costs)[0]


text:
Q: Return an OCR'd PDF File (with text overlay) from Azure Cognitive Services Read I have implemented Azure Cognitive Read service to return extracted/OCR text from a PDF.
However, to make it easier for the user to understand the context/copy and paste data from the PDF i would like to overlay that text data over the PDF. I would then drop that PDF into a viewer.
Does anyone have any ideas on how to proceed. Would also be happy to use AWS. Basically an API that i submit a PDF to and it returns an OCR'd PDF is what i am after. If this is not possible, a library that i can submit the text and the PDF (and return a text searchable PDF) is also ideal.

A: I am looking for something similar and stumbled upon this:
https://learn.microsoft.com/en-us/azure/cognitive-services/form-recognizer/overview?tabs=v2-1
This is the Azure form recogniser.
What is Azure Form Recognizer?
Azure Form Recognizer is a part of Azure Applied AI Services that lets you build automated data processing software using machine learning technology. Identify and extract text, key/value pairs, selection marks, tables, and structure from your documents—the service outputs structured data that includes the relationships in the original file, bounding boxes, confidence and more. You quickly get accurate results that are tailored to your specific content without heavy manual intervention or extensive data science expertise. Use Form Recognizer to automate data entry in your applications and enrich your documents search capabilities.
They have an online example test:
https://fott-2-1.azurewebsites.net/prebuilts-analyze
Create a service in azure for free and test if it fits your needs. From there you will get a json reply and you can use the boundingBox to display. I haven't gone as far as applying the bounding box or something like that to the pdf.
You also have a free development nuget package to do exactly as you want:
https://ironsoftware.com/csharp/ocr/#sample-tesseract-create-searchable-pdf
OCR development is free for testing and see if it works for you.


text:
Q: appsettings.json files or App Service - App Settings in Azure Portal? I have so far used the appsettings.{environment}.json files to keep application level configuration settings. Now I encounter this tab in Azure Portal for an App Service.
What is the difference between using the appsettings.json files and "Application Settings" Tab in the Azure Portal? And which one to use When?

A:
difference between using the appsettings.json files and "Application Settings" Tab in the Azure Portal? And which one to use When?

If you are using more than one environment like Production, Staging and Development for your application. You need specific Environment appsettings i.e., appsettings.{environment}.json.
Or if you don't want to use any specific environment. In this case you are using only production (Default) Environment you can use appsettings.json file.

A: Few reasons to use Azure Application Settings -
1st - Let's assume that in order to avoid leaking configurations in appsettings.json, you aren't committing it to your repo. But you also deploy your web app on Azure AppServices. In this situation Application Settings tab can help you to configure your configurations directly and then Azure will auto create appsettings.json by reading those values.
2nd - This time we are committing appsettings.json and deployed web app on Azure. We also have a property as
{
  "Users": {
     "CanAccessApp": [ "abc@gmail.com", "test@gmail.com" ],
     "CanAccessHangfire": [ "abc@gmail.com", "test@gmail.com" ],
     "CanAccessLog": [ "abc@gmail.com", "test@gmail.com" ]
   }
}

Now, I also want one more user to be able to access logs. How you will do it? Generally, update in your appsettings.json and redeploy.
Or you can create similar property in Application Settings by
Users:CanAccessLog:0 -> vic@gmail.com
Users:CanAccessLog:1 -> abc@gmail.com
Users:CanAccessLog:2 -> test@gmail.com

and so on where 0,1,2 are indexes of the array (Azure style). This one will help us to test quickly without redeploying or modifying appsettings.json.


text:
Q: Can't update values in table TD using AJAX and PHP returned JSON array I have a PHP-AJAX script to delete an existing financial rows from a table. PHP script is working fine and the rows are being deleted. But the problem is inside the success function of AJAX call. First let me show you the table:

Forget about the delete payment button and concentrate on the Delete Project. When clicking on it, I want to delete all the project with the already paid payments and everything is working properly until I need to update the Total, Still to Pay, and Total Paid.
The Total cell is updated properly but when I can't update the others. I will see NaN $ in them.

Here is the script:
    success:function(resp)
    {
      var pay_total = 0;
      row.fadeOut(700);

      //updating the total TD:
      var totalVal = parseInt($("#final_cash").text());
      var NewTotal = totalVal - parseInt(proj_cost);
      $("#final_cash").text(NewTotal +' $');

      //$.each because I have multiple rows returned from PHP
      //and each row represent a payment in a different date.

      $.each(resp, function(key, row)
      {
        $("#"+row.debt_id).fadeOut(600);

        //Updating the still to pay TD:
        var pay_total = parseInt(pay_total) + parseInt(row.payment);
        console.log(pay_total);//The result is NaN
        var still_cash_t = parseInt($("#still_cash").text());
        var sct = pay_total + still_cash_t;
        $("#still_cash").text(sct + ' $');

        //Updating the Total Paid TD:
        var paid_cash_t = parseInt($("#paid_cash").text());
        var pct = paid_cash_t - pay_total;
        $("#paid_cash").text(pct +' $');
      });
    },

A: Remove var in:
var pay_total = parseInt(pay_total) + parseInt(row.payment);

to avoid redeclaration of variable pay_total inside function(key, row) {...}.

A: It seems you adding or may be subtracting into json value, that's why it is showing Nan, it seems it behaving like string value if you convert it into number then this problem can be resolve. convert it into number before adding/subtracting some value


text:
Q: Fetch multiple data on database on Form load I would like to fetch multiple data on my database in form load. But I found the code long and repeating. Can someone make this code a little bit shorter?
This is my code
private void Form1_Load(object sender, EventArgs e)
    {
        string a = label1.Text;
        string connString = "Server=Localhost;Database=this;Uid=root;password=root";
        using (var connection = new MySqlConnection(connString))
        {
            connection.Open();
            using (var command = connection.CreateCommand())
            {
                command.CommandText = ("Select Room_name from firstfloor where Room_no=(?room)");
                command.Parameters.AddWithValue("?room", a);
                command.ExecuteNonQuery();

                MySqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    button1.Text = reader["Room_name"].ToString();
                }
            }
        }
        string b = label2.Text;
        string connString2 = "Server=Localhost;Database=this;Uid=root;password=root";
        using (var connection = new MySqlConnection(connString2))
        {
            connection.Open();
            using (var command = connection.CreateCommand())
            {
                command.CommandText = ("Select Room_name from firstfloor where Room_no=(?room)");
                command.Parameters.AddWithValue("?room", b);
                command.ExecuteNonQuery();

                MySqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    button2.Text = reader["Room_name"].ToString();
                }
            }

        }
    }

A: First of all you're connecting to the same database twice.
And you're doing it in the same method (it's obvious you have complete power over the decision whether to connect only once or not).
Secondly you could wrap the actual select execution in a separate method.
That separate method should receive it's connection from the caller (so as that you are able in this particular case to connect only ONCE to the database, but do as many selects as you need).
Third, don't use ExecuteReader, use ExecuteScalar.
Furthemore: You shouldn't do too many things on FormLoad (the UI will freeze).
And why are you querying the database based on the value of a label ?
Was that just a sample you wrote really fast to show us what you mean or is it the actual business logic ?
private string GetRoomName_BasedOn_RoomNumber(string roomNumber, MyConnection connection) {
    using (var command = connection.CreateCommand())
    {
         command.CommandText = ("Select Room_name from firstfloor where Room_no=(?room)");
         command.Parameters.AddWithValue("?room", roomNumber);
         //command.ExecuteNonQuery();

         object response = command.ExecuteScalar();

         return response as string; // consider <null> as a "No such Room Number" signal
    }
}

private void Form1_Load(object sender, EventArgs e)
{
    string a = label1.Text;
    string b = label2.Text;

    string connString = "Server=Localhost;Database=this;Uid=root;password=root";
    using (var connection = new MySqlConnection(connString))
    {
       connection.Open();
       button1.Text = this.GetRoomName_BasedOn_RoomNumber(a, connection);
       button2.Text = this.GetRoomName_BasedOn_RoomNumber(b, connection);
    }
}

A: For example you can refactor your code and extract the following code into a method:
  private void DoSomething(MySqlConnection connection)
{
using (var command = connection.CreateCommand())
        {
            command.CommandText = ("Select Room_name from firstfloor where Room_no=(?room)");
            command.Parameters.AddWithValue("?room", b);
            command.ExecuteNonQuery();

            MySqlDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                button2.Text = reader["Room_name"].ToString();
            }
        }

    }


text:
Q: How do I store values from a single column into a single variable in oracle? The below is my code:
SELECT
      /*+ parallel (sales 8) */
      COUNT(1)
    INTO v_datacount_actualtable
    FROM sales
    WHERE processingunitseq=38
    AND (compensationdate BETWEEN TO_DATE(v_startdate,'DD-MON-YYYY') AND TO_DATE(v_enddate,'DD-MON-YYYY')
    OR eventtypeseq IN
      (SELECT EVENTTYPESEQ FROM EPS_FRS_PAYMENTS
      ));

SELECT EVENTTYPESEQ FROM EPS_FRS_PAYMENTS will return 4 values. So I cannot do a simple SELECT INTO.
I want to store the result of SELECT EVENTTYPESEQ FROM EPS_FRS_PAYMENTS into a variable and make the code something like below, so that the subquery is not executed each time.
SELECT
      /*+ parallel (sales 8) */
      COUNT(1)
    INTO v_datacount_actualtable
    FROM sales
    WHERE processingunitseq=38
    AND (compensationdate BETWEEN TO_DATE(v_startdate,'DD-MON-YYYY') AND TO_DATE(v_enddate,'DD-MON-YYYY')
    OR eventtypeseq = v_frseventpeseqs );

SELECT EVENTTYPESEQ FROM EPS_FRS_PAYMENTS returns four values:
1,
2,
3,
4,

I do not want to hardcode these values in the code as it is a bad practice. Need it in a variable like v_frseventypeseqs.
How can I do that - array/ collection/records/bulk collect into?

A: Create type if it isn't exists
CREATE OR REPLACE
TYPE t_number1 AS TABLE OF NUMBER(8,0)

it's array of number
and using in PL/SQL
declare
v_frseventpeseqs t_number1;
begin
    SELECT EVENTTYPESEQ bulk collect
    into v_frseventpeseqs
    FROM EPS_FRS_PAYMENTS;

    for i in (select t.column_value id from table(v_frseventpeseqs) t)
    loop
        dbms_output.put_line(i.id );
    end loop;

end;

only using statement in (select t.column_value
from table(v_frseventpeseqs) t)

A: You can use the WITH clause. The advantage is that repeated references to a subquery may be more efficient as the data is easily retrieved from a temporary table, rather than being requeried by each reference.
WITH eventtypeseq_query AS
     (SELECT EVENTTYPESEQ
      FROM EPS_FRS_PAYMENTS)
SELECT
       /*+ parallel (sales 8) */
       COUNT(1)
INTO v_datacount_actualtable
FROM sales
WHERE processingunitseq=38
  AND (compensationdate BETWEEN TO_DATE(v_startdate,'DD-MON-YYYY') AND TO_DATE(v_enddate,'DD-MON-YYYY')
        OR eventtypeseq IN eventtypeseq_query);

You can find more information here:
https://oracle-base.com/articles/misc/with-clause

A: Since
SELECT EVENTTYPESEQ FROM EPS_FRS_PAYMENTS

is not correlated you don't need any "optimization" here - Oracle will run this subquery only once.

A: Using EXISTS is always better in terms of performance as compared to using IN.
Also, if you are writing this query to run regularly in LIVE environment, it is suggested not to use HINTs like /*+ parallel */. HINTs should be used only for ad-hoc queries.
I have re-written your query below using EXISTS:
SELECT
    /*+ parallel (sales 8) */
    COUNT(1)
    INTO v_datacount_actualtable
    FROM sales sl
    WHERE processingunitseq=38
    AND (compensationdate BETWEEN TO_DATE(v_startdate,'DD-MON-YYYY') AND TO_DATE(v_enddate,'DD-MON-YYYY')
    OR EXISTS ( SELECT 1 from EPS_FRS_PAYMENTS efp where s.eventtypeseq = efp.eventtypeseq);


text:
Q: Why can't I use the async library from pub.dev? Um.. yeah... so I wanted to use a Timer in a flutter app, and realized I needed to import the async library in order to do so.
So, per the installation instructions on pub.dev, I added the dependency to pubspec.yaml:
async: ^2.5.0

But when I run pub-get, the following text shows up in the messages tab:

Because every version of flutter_test from sdk depends on async
2.5.0-nullsafety.1 and flutter_app depends on async ^2.5.0, flutter_test from sdk is forbidden. So, because flutter_app depends on
flutter_test any from sdk, version solving failed. pub get failed (1;
So, because flutter_app depends on flutter_test any from sdk, version
solving failed.)

I'm trying to decipher this.  Can you decipher this complex boolean algebraic word problem?


text:
Q: mysql query dynamic date range I've created a website showing the prices of the fruits and vegetables of my province. These prices are updated every day (aprox. +250 rows each day).
For that reason I created a MySql table to speed up the access to this information.
On the table showed on my Web site I want to limit the date showed up to 1 week and not all the dates available on the database. Taking in consideration that the database is increased daily I need a query for this dynamic date request.
They query I'm using right now is:
 SELECT base_beta.Tipo,
    base_beta.fecha_numero,
    base_beta.Variedad,
    base_beta.Fecha,
    base_beta.alhondiga,
    base_beta.corte_uno,
    base_beta.corte_dos,
    base_beta.corte_tres,
    base_beta.corte_cuatro,
    base_beta.corte_cinco,
    base_beta.corte_seis,
    base_beta.corte_siete,
    base_beta.corte_ocho,
    base_beta.corte_nueve,
    base_beta.corte_diez,
    base_beta.corte_once,
    base_beta.corte_doce,
    base_beta.corte_trece,
    base_beta.corte_catorce,
    base_beta.corte_quince
 FROM base_beta
 WHERE 1=1
 AND base_beta.Tipo = 'pi'
 ORDER BY base_beta.fecha_numero DESC

There are serveral columns with corte (aka prices) because every item has a random number of prices, since the fruits and vegetables has a bid system where prices decrease on every round.
For example, a tomato may start at 0,80€ and then its prices decrease to 0.76, 0.74, 0.69 and so on.
What code do I have to add to show the data of the current day and the next 6 days to complete a week?
Here are a photo of the: database content and format
Thanks, Jose.

A: If this defines your table schema
CREATE TABLE prices (item INT UNSIGNED, price DECIMAL(5,2), date DATETIME);

the following query will retrieve prices up to 7 days back in time
SELECT * FROM prices WHERE date > SUBDATE(CURDATE(),7) AND date <= CURDATE();

See also https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
Hope this helps.


text:
Q: How to reinstall High Sierra if pressing Option key did not bring bootable disk on boot As my MacBook Pro a1278 13" High Sierra always gets into Safe Mode, though the Shift key is normal, I plan to reinstall High Sierra from bootable USB (external), but pressing Opt did not bring up the bootable disk option on boot.
Please inform/guide me on how to reinstall High Sierra considering my condition.


text:
Q: Setting up Google Protocol Buffer(C++) in Visual Studio 2015 I am a newbie to C++. I tried setting up Google Protocol Buffers to Visual Studio 2015 and find it real hard to execute a very simple program. It would be great, If someone could guide me on how to set up google protocol buffers on Visual Studio 2015.
I followed the steps in http://forums.4fips.com/viewtopic.php?f=3&t=807. But still it is not successful.


text:
Q: linq to EF, how to use 'top` method I want to use linq to Entities to bring the top record ordered by descending column Value1.
I know I ca write like:
MyCollection.OrderByDescending(item => item.Value1).FirstOrDefault();
But how do I use the folloing method Top ?
System.Data.Objects.ObjectQuery.Top(string, params System.Data.Objects.ObjectParameter[])

A: EDIT: This answer was written when the question was specifically about LINQ to SQL.
System.Data.Objects is used for Entity Framework rather than LINQ to SQL as far as I can tell - but to find the top N values in either LINQ to SQL or even LINQ to Objects, you'd usually just use Take:
var query = db.Customers
              .OrderByDescending(c => c.Value1)
              .Take(10);

(I'd really encourage you to try to use more meaningful names than Value1 though...)
EDIT: Even in Entity Framework, I'd usually use Take in LINQ queries - it's "the LINQ way" of representing the first N results. If you really, really want to use Top, the documentation provides examples - but you should consider why you want to use Top rather than Take. (You've given us no context to work with.)

A: Please look at MSDN for an example http://msdn.microsoft.com/en-GB/library/bb155995.aspx
using (AdventureWorksEntities context =
    new AdventureWorksEntities())
{
    string queryString =
        @"SELECT VALUE product FROM AdventureWorksEntities.Products AS product";

    ObjectQuery<Product> productQuery1 =
        new ObjectQuery<Product>(queryString, context, MergeOption.NoTracking);

    ObjectQuery<Product> productQuery2 = productQuery1.Top("2");

    // Iterate through the collection of Product items.
    foreach (Product result in productQuery2)
        Console.WriteLine("{0}", result.Name);
}

Or if you just have a List<T> consider using the Take() extension.
List<string> strs = new List<strs>() { "1", "2", "3", "4" };
var firstTwo = strs.Take(2);


text:
Q: using python cassandra driver in multithread to write to db I'm writing a small Python script to async the data into Cassandra but need some help in adjusting the code.
Right now I have this which works:
from cassandra.cluster import Cluster
cluster = Cluster(['111.111.111.111'])

session = cluster.connect('testingKeyspace')

with open('dataImport.txt') as f:
    for line in f:
        session.execute (
            """
            INSERT INTO tstTable (id, accts, info)
            VALUES (%s)
            """ $ (line)
        )

but when i run it in async like this:
from cassandra.cluster import Cluster
cluster = Cluster(['111.111.111.111'])

session = cluster.connect('testingKeyspace')

with open('dataImport.txt') as f:
    for line in f:
        session.execute_async (
            """
            INSERT INTO tstTable (id, accts, info)
            VALUES (%s)
            """ $ (line)
        )

I get this error:
", consistency=Not Set>' request_id=187 result=(no result yet) exception=None host=10.205.111.43>
<ResponseFuture: query='<SimpleStatement query="

why is async giving me that error back and not sure single executes.
fair warning...my first time using python so in learning mode here...

A: got it working:
with open('dataImport.txt') as f:
    for line in f:
        query = SimpleStatement (
            "INSERT INTO tstTable (id, accts, info) VALUES (%s) " %(line),
            consistency_level=ConsistencyLevel.ONE)
        session.execute_async (query)


text:
Q: 500 error when asp.net session variable times out I have an aspx.cs file where I check if the user's session variable is still good, if it is, do some stuff, if it isn't, write out a response with a div tag back to the page that made the ajax request to it so that the receiving page knows it needs to redirect to the login page.
if (Session["AccountID"].ToString() != "" && Session["AccountID"] != null)
    {...do something }
else{Response.Write("

)}

I thought that I could check if something exists without getting an error, but it gives me an error on the if statement. The error is:
"[NullReferenceException: Object reference not set to an instance of an object.]
   editOwner.Page_Load(Object sender, EventArgs e) in c:\Users\Administrator\Documents\Visual Studio 2013\WebSites\BlippohAdminSvn\editOwner.aspx.cs:13 ......"
Line 13 is the if statement

A: I would check only if the session is null. You are attempting a ToString() on a possibly null value which would give you a NullReferenceException.
if (Session["AccountID"] != null)
{...do something }
else{Response.Write("

)}


text:
Q: M365 Dev Program E5 Subscription Errors My institution has recently signed up to the MSLE (Microsoft Learn for Educators) program. We are currently trialing MS-900 with one of our 2nd year IT groups.
We are trying to set all students up with a M365 E5 Developer Subscription, but students are unable to create this. We have had a couple of students successfully create their dev subscription, but the others get an error saying 'Sandbox provisioning has been disabled, please try again in a few days'.
Could someone shed some light on getting my students set up please?
We have tried multiple browsers.
Thanks
Chris


text:
Q: List Method exposing WCF service in MVC 4 I am working on MVC 4 and WCF Class Library I had added method that is return List and I have added reference of WCF services.
now I am creating proxy of ServiceReference1 then I am not able to get this ServiceReference1 object.
if I changed return type to string then it working..
I had tried changing all collection type but I dint get ServiceReference1 object.!
where I am wrong or what is the solution.?
My WCF code is here
public class BuildTrackerService : IBuildTrackerService
{
    public List<Property> DoWork()
    {
        DataTable dt = new DataTable();
        List<Property> objProperty = new List<Property>();
        SqlConnection conn = DbConnection.GetConnection();
        SqlDataAdapter adpt = new SqlDataAdapter("[GetPropertyDetail]", conn);
        adpt.SelectCommand.CommandType = CommandType.StoredProcedure;
        try
        {
            conn.Open();
            adpt.Fill(dt);
        }
        catch (Exception) { throw; }
        finally
        {
            conn.Close();
            adpt.Dispose();
        }
        objProperty = DataTableHelper.ConvertTo<Property>(dt);
        return objProperty;
    }
}

MY MVC 4 ActionResult is like
public ActionResult Index()
{
    ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

    /*
        ==> this ServiceReference1 is not accessible here....!
        var obj = new ServiceReference1.BuildTrackerServiceClient();
    */

    var objct = obj.DoWork();
    return View();
}

I had tried with !

A: With a WCF web service you can transport only primitive types. Changes your list to an array and try it again.


text:
Q: reducing data that are very close to one another in matlab to get one set of data I am trying to perform image analysis to get the boundary of an image.  The problem is, there is an overlap of more than one point on the data. The problem occurs due to the pixel width of the boundary. ie, my algorithm reads the image, and because the boundary is thick, I get multiple ( sometimes 2 or 3) data points that represent the boundary .As you can see in the image, I have analysed an image and have the scatter plot showing the coordinates.  The boundary has more than one element representing it. I need to reduce my vectors (of coordinates) such that a boundary is represented by only one line. I attach the code along with the question for your reference. I am doing this so as to get one single data that can represent the whole image.
clc;close all;
clear all;
folder = 'C:\Users\Adi\Desktop'; % image folder
baseFileName = 'part8.jpg';
% Get the full filename, with path prepended.
fullFileName = fullfile(folder, baseFileName);
rgbImage = imread(fullFileName); % read the image
% Get the dimensions of the image.  numberOfColorBands should be = 3.
[rows, columns, numberOfColorBands] = size(rgbImage);
figure;
greenChannel = rgbImage(:, :, 2);
   binaryImage = greenChannel < 200; % convert image to BW
   imshow(binaryImage);
i=1;
j=1;
data=zeros(rows,columns);
n=1;% sample every n rows or col of the image
img2=zeros(rows/n,columns/n);
for col=1:n:columns                  %reducing the size of the image
    for row=1:n:rows
        if(binaryImage(row,col)==1)
%         data(row,col)=1;
        x(i)=row;
        y(i)=col;           % locate where the image is present
       img2(x(i),y(i))=1;
       i=i+1;
        end
      end
end
figure;
scatter(x,y);
figure;
imshow(img2);
blankImage=zeros(length(1:rows),length(1:columns));
m=1; % counter variable
for k=2:rows-1
    for l=2:columns-1
        if((binaryImage(k+1,l)==0)&&(binaryImage(k,l+1)==0)&&(binaryImage(k-1,l)==0)&&(binaryImage(k,l-1)==0)&&(binaryImage(k,l)==0))
%             % if all surrounding pixels are black, ignore them
            blankImage(k,l)=0;
            elseif((binaryImage(k+1,l)==1)&&(binaryImage(k,l+1)==1)&&(binaryImage(k-1,l)==1)&&(binaryImage(k,l-1)==1)&&(binaryImage(k,l)==1))
            %if all surrounding pix are white ,ignore them
            blankImage(k,l)=0;
           else
            blankImage(k,l)=1; % get the boundary elements
            x_brep(m)=k;
            y_brep(m)=l;
              m=m+1;
          end
      end
  end
  figure;
  imshow(blankImage);
    figure;
    scatter(x_brep,y_brep);

Sample image and output:

A: If you have the image processing toolbox, you can take your original image, and use bwmorph - for example, thin or skel, to reduce it to a single pixel line.  Note that you may need to invert your image (so that it is a white line on a black background).
Presuming your original image as shown is already binary and is stored in BW (but with line as black on white), it should be as simple as (~BW just inverts the image).
BW2 = bwmorph(~BW,'thin', Inf);

If your image is not already binary you will need to convert it to binary first.


text:
Q: Can I use Amazon ELB instead of nginx as load balancer for my Node.Js app? I have a Node.js app and I've seen a lot of posts here in SO that it needs to be behind a nginx as load balancer. Since I'm already accustomed to Amazon's services, thus my question.

A: Yes, but there are a few gotcha to keep in mind:

*

*If you have a single server, ensure you don't return anything except 200 to the page that ELB uses to check health. We had a 301 from our non-www to www site, and that made ELB not send anything to our server because of it.

*You'll get the ELB's IP instead of the client's in your logs. There is an ngx_real_ip module, but it takes from config hacking to get it to work.

A: ELB works great in front of a basic Node.js application. If you want WebSockets, you need to configure it for TCP balancing. TCP balancing doesn't support sticky sessions though, so you get one or the other.


text:
Q: Avoid repetition in Angular controller I'm an angular newbie and I'm writing an Ionic app.
I finished my app and am trying to refactor my controller avoiding code repetition.
I have this piece of code that manages my modal:
 angular.module('starter')
  .controller('NewsCtrl', function($scope, content, $cordovaSocialSharing, $timeout, $sce, $ionicModal){
    $scope.news = content;

    content.getList('comments').then(function (comments) {
      $scope.comments = comments;
    });

    $scope.addComment = function() {

    };

    $scope.shareAnywhere = function() {
        $cordovaSocialSharing.share("Guarda questo articolo pubblicato da DDay", "Ti stanno segnalando questo articolo", content.thumbnail, "http://blog.nraboy.com");
    };

    $ionicModal.fromTemplateUrl('templates/comments.html', {
      scope: $scope,
      animation: 'slide-in-up'
    }).then(function(modal) {
      $scope.modal = modal;
    });

    $scope.showComment = function() {
      $scope.modal.show();
    };

    // Triggered in the login modal to close it
    $scope.closeComment = function() {
      $scope.modal.hide();
    };

    $scope.$on('modal.shown', function() {
      var footerBar;
      var scroller;
      var txtInput;

      $timeout(function() {
        footerBar = document.body.querySelector('#commentView .bar-footer');
        scroller = document.body.querySelector('#commentView .scroll-content');
        txtInput = angular.element(footerBar.querySelector('textarea'));
      }, 0);

      $scope.$on('taResize', function(e, ta) {
        if (!ta) return;
        var taHeight = ta[0].offsetHeight;
        if (!footerBar) return;
        var newFooterHeight = taHeight + 10;
        newFooterHeight = (newFooterHeight > 44) ? newFooterHeight : 44;

        footerBar.style.height = newFooterHeight + 'px';
        scroller.style.bottom = newFooterHeight + 'px';
      });

    });

  });

I have added this same code in 6 controllers.
Is there a way to avoid the repetition?

A: Probably what you are looking for is an angular service. This component is a singleton object, that you inject in every controller you need to execute this code.
Angular Services
Regards,

A: Below is an example of a service I created to retrieve address data from a Json file. Here is the working Plunk. http://plnkr.co/edit/RRPv2p4ryQgDEcFqRHHz?p=preview
  angular.module('myApp')
    .factory('addressService', addressService);

  addressService.$inject = ['$q', '$timeout', '$http'];

  function addressService($q, $timeout, $http) {
    var addresses = [];

    //console.log("Number of table entries is: " + orders.length);

    var promise = $http.get('address.data.json');
    promise.then(function(response) {
      addresses = response.data;
      //  console.log("Number of table entries is now: " + orders.length);
    });

    return {
      GetAddresses: getAddresses
    };

    function getAddresses() {

      return $q(function(resolve, reject) {
        $timeout(function() {
          resolve(addresses);
        }, 2000);

      });

    }
  }

Here's an example of how I added dependencies for it and another service to my controller  (This is NOT the only way to do dependency injection, but is my favorite way as it is easier to read).  I then called my addressService.GetAddresses() from within my controller.
var app = angular.module('myApp', ['smart-table']);

app.controller('TableController', TableController);

TableController.$inject = [ "orderService",  "addressService"];

function TableController( orderService, addressService) {

 addressService.GetAddresses()
  .then(function(results) {
      me.addresses = results;
     // console.log(me.addresses.length + " addresses");
    },
    function(error) {})
  .finally(function() {
    me.loadingAddresses = false;
});
  });}

I also had to include my .js tag in a script element on my index.html.
<script src="addressdata.service.js"></script>


text:
Q: Find a parameterisation for $(x-8)^2 + y^2 = 16$ starting at the point $(4,0)$ and moving clockwise once around the circle. Find a parameterisation for $(x-8)^2 + y^2 = 16$ starting at the point $(4,0)$ and moving clockwise once around the circle.

My work
We can describe the circle using polar coordinates:
$x(\theta) = \rho\cos(\theta)$, $y(\theta) = \rho\sin(\theta).$
$(x-8)^2 + y^2 = 16$ is a circle with radius of $4$.
$\therefore \rho = 4$
Let $t = \theta \ \forall \ t \in [0, 2\pi]$ be our parameter.
$\therefore (x(t), y(t)) = (4\cos(t), 4\sin(t))$
$(x(t), y(t)) = (4\cos(\pi-t), 4\sin(\pi-t))$ represents the circle of radius $4$ and starting at $\pi$ and moving clockwise.
However, this circle is still centred at $(0, 0)$. To centre the circle at $(8,0)$, we must have the parameterisation $(x(t), y(t)) = (8 + 4\cos(\pi - t), 4\sin(\pi-t)) \ \forall \ t \in [0, 2\pi]$.
We can test values some values to get an indication of any errors in our parameterisation.
$(x(0), y(0)) = (4, 0)$
$(x(\pi/2), y(\pi/2)) = (8, 4)$
$(x(\pi), y(\pi)) = (12, 0)$
$(x(3\pi/2), y(3\pi/2)) = (8, -4)$
$(x(2\pi), y(2\pi)) = (4, 0)$

I would greatly appreciate it if people could please take the time to review my reasoning and solution for correctness.

A: Yes, the work is correct.
Below is a parametric plot of $\left\{8 + 4 \cos \left( \pi - t \right), 4 \sin \left(t\right)\right\}$ for $0\le t < 2\pi$.

To show that your parameterization starts at $(4,0)$ and proceeds in a clockwise manner, a sequence of values was created:
$$
\begin{array}{cccc}
 k & t & x(t) & y(t) \\\hline
 1 & 0 & 4 & 0 \\
 2 & \frac{\pi }{6} & 8-2 \sqrt{3} & 2 \\
 3 & \frac{\pi }{3} & 6 & 2 \sqrt{3} \\
 4 & \frac{\pi }{2} & 8 & 4 \\
 5 & \frac{2 \pi }{3} & 10 & 2 \sqrt{3} \\
 6 & \frac{5 \pi }{6} & 8+2 \sqrt{3} & 2 \\
 7 & \pi  & 12 & 0 \\
 8 & \frac{7 \pi }{6} & 8+2 \sqrt{3} & -2 \\
 9 & \frac{4 \pi }{3} & 10 & -2 \sqrt{3} \\
 10 & \frac{3 \pi }{2} & 8 & -4 \\
 11 & \frac{5 \pi }{3} & 6 & -2 \sqrt{3} \\
 12 & \frac{11 \pi }{6} & 8-2 \sqrt{3} & -2 \\
 1 & 0 & 4 & 0 \\
 2 & \frac{\pi }{6} & 8-2 \sqrt{3} & 2 \\
 3 & \frac{\pi }{3} & 6 & 2 \sqrt{3} \\
 4 & \frac{\pi }{2} & 8 & 4 \\
 5 & \frac{2 \pi }{3} & 10 & 2 \sqrt{3} \\
 6 & \frac{5 \pi }{6} & 8+2 \sqrt{3} & 2 \\
 7 & \pi  & 12 & 0 \\
 8 & \frac{7 \pi }{6} & 8+2 \sqrt{3} & -2 \\
 9 & \frac{4 \pi }{3} & 10 & -2 \sqrt{3} \\
 10 & \frac{3 \pi }{2} & 8 & -4 \\
 11 & \frac{5 \pi }{3} & 6 & -2 \sqrt{3} \\
 12 & \frac{11 \pi }{6} & 8-2 \sqrt{3} & -2 \\
\end{array}
$$
The $k$ values are plotted against the circle.


text:
Q: crash on UIPageViewController, trying to add new pages to Model I would like to add a new page to the page-based project in xcode, the DataViewController takes the whole screen, so I could not add any button on the RootVC. So when I add a IBAction on the DataVC, there is a crash, I don't understand why, the exception just says

thread 1, breakpoint 1.1

Here is the code :
//in DataVC, not sure if it is ok to create the DataVC inside itself
- (IBAction)addOne:(id)sender {
    DataViewController *dvc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"DataViewController"];
    [[ModelController sharedModelController] addOneToModel:dvc];
}

//in ModelController
-(void) addOneToModel:(DataViewController*)dvc{
    [self.pageData addObject:dvc];//ERROR HERE: not much details : "thread 1, breakpoint 1.1"
}

//the sharedMOdelController
+(instancetype)sharedModelController{
    static dispatch_once_t once;
    static ModelController *sharedInstance;
    dispatch_once(&once, ^{
        sharedInstance = [[ModelController alloc] init];
    });
    return sharedInstance;
}

A: You are going to have to do more detective work. Log your newly created DataViewController to make sure it isn't nil, and is the kind of object you think it is.
It is also possible that you have a breakpoint at that line and can't see it. The Xcode IDE and the debugger command line maintain separate lists of breakpoints, and I have seen a breakpoint disappear from the IDE but still show up in the debugger command line. Have you tried continuing?
You might also want to disable all breakpoints and see what happens.
You might also want to try adding an exception breakpoint for all Objective-C exceptions. Sometimes that provides more information when an exception occurs.


text:
Q: How can I display my meta value in a textarea? I have this saved:
$description = get_post_meta( $postID, 'video_desc', true );

and then have used this in my form in textarea:
value="<?php echo $description; ?>"

When I check the console it is there as the value but it is not displaying in the textarea. I am wanting this to show the text as it is in a edit-post.php page/file.
I have been searching for hours!! Any help would be much appreciated.

A: The value of the textarea must be printed between the opening and the closing tag:
<form action="/">
    <textarea name="whatever"><?php echo esc_textarea( $description ); ?></textarea>
</form>

Note the usage of the function esc_textarea() here. It prevents any possible character inside the variable $description from being interpreted as HTML. It's an important step to avoid possibly XSS vulnerabilities.
There are many more escaping functions like esc_attr(), esc_html() or esc_url(). You should know about them and how they are meant to be used: https://codex.wordpress.org/Data_Validation


text:
Q: What is the appropriate directory for sites and apps when setting up public multi-purpose home server? I'm still very new and green to the Linux world. I'm doing this as a learning experience. I've seen a lot of tutorials that walk you through setting up a multi-purpose home server.
They all seem to fall short as far as giving examples or suggestions on how to structure a multi-site web server or multiple web applications and dump everything into the default web root /var/www/html/.
Is this the appropriate directory to install or configure multiple site document folders or web-based apps? I've worked with web-based apps and sites in a shared host environment which points to /home/~johndoe/public_html or something similar. Keep in mind; I would like to have this "home server" public-facing for file-sharing with friends, not just family.
As far as the machine, I'm working with, it's a custom built box with an Intel I5 processor and 16gb of ram, 500gb SSD primary drive, and two 1TB WD drives set up in RAID1 (if I remember correctly).
I've edited the above questions, etc in hopes to clarify what I'm asking. Another example of what I'd like to do in Linux similar to how I have my test site structure; since posting this I've been using XAMPP on Windows 10. In my htdocs folder, I've created virtual hosts with a public_html folder in each such as "site1.local/public_html", "site2.local/public_html", etc. I'm not sure if this is typical, however, it seems to work in my case.
Please let me know if this needs further clarification.


text:
Q: SDL_TTF and runtime missing entry point ScriptFreeCache with GDI32.dll (Windows 7 - SDL - SDL_TTF - Mingw64 - Codeblocks) I'm trying to understand Simple DirectMedia Layer (SDL) for my own projects and I've encountered an issue I'm not able to solve. The issue arises with Windows 7, but not with Windows 10 (both 64bit machines). The project compiles fine on both OS without warnings, but during runtime (at the beginning) on Windows 7 a popup window appear stating that it's not possible to find the entry point for ScriptFreeCache procedure in GDI32.dll.
The original message in Italian states: "Impossibile trovare il punto di ingresso ScriptFreeCache della procedura nella libreria di collegamento dinamico GDI32.dll"
The issue is related to sdl_tff. Commenting those lines, the program runs fine.
The gdi32.dll is present in both system32 and in sysWOW64 folders (windows 7).
On Windows 10 there is also a dll named gdifull.dll.
I've tried to put all the libraries from the two machine system folders, and others from internet (different versions and both 32 and 64bit), in the execution folder.
No change, same error during runtime.
The setup on the two machine is (should be) the same.
Mingw 64 bit
SDL2 64 bit
SDL_Image 64 bit
SDL_TTF 64 bit
Developer SDL libraries correclty installed

Here the minimal source code that reproduces the error
#include <exception>
#include <string>
#include <iostream>
#include <SDL2\SDL.h>
#include <SDL2\SDL_image.h>
#include <SDL2\SDL_ttf.h>

int main(int argc, char* argv[]){
    /* Create a window */
    SDL_Window* window=nullptr;

    /* Grab the window surface */
    SDL_Surface* screen;

    /* Initialize the video subsystem */
    if(SDL_Init(SDL_INIT_VIDEO) < 0)
    {
        std::cout << "SDL could not be initialized: " << SDL_GetError();
    }
    else
    {
        std::cout << "SDL video system ready" << std::endl;
    }

    /* Allocate Window pointer */
    window = SDL_CreateWindow("SDL2 Window", 200, 200, 640, 480, SDL_WINDOW_SHOWN);
    screen = SDL_GetWindowSurface(window);

    SDL_Surface* image;
    image = SDL_LoadBMP("Test.bmp");
    /* Check loaded image */
    if (!image)
    {
        std::cout << "Failed to load image: Test.bmp" << std::endl;
    }

    SDL_BlitSurface(image,NULL,screen,NULL);
    SDL_FreeSurface(image);
    SDL_UpdateWindowSurface(window);

    /* Delay for splash screen. */
    SDL_Delay(1000);

    /* Printing on screen some information */
    TTF_Font *font = NULL;
    SDL_Color color={0,255,0};

    if(TTF_Init()==-1) {
        printf("TTF_Init: %s\n", TTF_GetError());
        exit(2);
    }

    font = TTF_OpenFont(".\\calibri.ttf", 14);
    if(font == NULL)
       std::cout << "Failed to load font" << std::endl;

    // Render some text
    SDL_Surface *text_surface;
    if(!(text_surface=TTF_RenderText_Solid(font,"Hello World!\n",color)))
    {
        std::cout << "Error writing text on surface" << std::endl;
    }
    else
    {
        SDL_BlitSurface(text_surface,NULL,screen,NULL);
        SDL_FreeSurface(text_surface);
    }

    SDL_UpdateWindowSurface(window);

    SDL_FreeSurface(screen);

    /* Delay for screen. */
    SDL_Delay(1000);

    // Destroy the window.
    SDL_DestroyWindow(window);

    SDL_Quit();
    return 0;
}

Here the Codeblocks project
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<CodeBlocks_project_file>
    <FileVersion major="1" minor="6" />
    <Project>
        <Option title="SDL_TTF_gdi_issue" />
        <Option pch_mode="2" />
        <Option compiler="gnu_gcc_compiler_x64_64bit" />
        <Build>
            <Target title="Debug">
                <Option output="../Test/GDI_Issue" prefix_auto="1" extension_auto="1" />
                <Option working_dir="../Test/" />
                <Option object_output="obj/Debug/" />
                <Option type="1" />
                <Option compiler="gnu_gcc_compiler_x64_64bit" />
                <Compiler>
                    <Add option="-g" />
                </Compiler>
            </Target>
            <Target title="Release">
                <Option output="../Test/GDI_Issue" prefix_auto="1" extension_auto="1" />
                <Option object_output="obj/Release/" />
                <Option type="0" />
                <Option compiler="gnu_gcc_compiler_x64_64bit" />
                <Compiler>
                    <Add option="-O2" />
                </Compiler>
                <Linker>
                    <Add option="-s" />
                </Linker>
            </Target>
        </Build>
        <Compiler>
            <Add option="-Wall" />
            <Add directory="C:/x86_64-w64-mingw32/include" />
        </Compiler>
        <Linker>
            <Add library="mingw32" />
            <Add library="SDL2main" />
            <Add library="SDL2.dll" />
            <Add library="user32" />
            <Add library="gdi32" />
            <Add library="winmm" />
            <Add library="dxguid" />
            <Add directory="C:/x86_64-w64-mingw32/lib" />
        </Linker>
        <ExtraCommands>
            <Add after="XCOPY $(#sdl2)\bin\*.dll $(TARGET_OUTPUT_DIR) /D /Y" />
        </ExtraCommands>
        <Unit filename="main.cpp" />
        <Extensions>
            <code_completion />
            <envvars />
            <debugger />
            <lib_finder disable_auto="1" />
        </Extensions>
    </Project>
</CodeBlocks_project_file>

What am I doing wrong?


text:
Q: UITableViewCell accessoryType.Checkmark messes with my .Center textAlignment As the title says. I have a tableview filled with some cells which have a textAlignment = .Center. Whenever I select a cell, the checkmark is showing up as it should be, but at the same time it messes my alignment of the text so the text is pushed by a small offset to the left. Any solutions?

A: The problem is that by adding an accessory view, the size of the cell used to calculate center is reduced by that much, as there are now 2 separate views being rendered in that cell. Without seeing your cell (and/or code) and how your labels are laid out, I can't comment on a specific solution.


text:
Q: Laravel/Lighthouse - Resolve to an external API I have a setup that uses laravel and lighthouse to create a graphql setup. I've gone through the tutorials on lighthouses page and it's worked great. In my use case, however, i'm looking to simplify the use of an xml Soap API using it.
I can't find in the documentation how to do this other than creating "resolvers", which i've managed to do. However these are set to fields..? So in order to return the correct information from the other api i'd have to do one for each field?
I'm getting a little lost.
Simply put, i just need to ask:
How do i plug in an external api so when i make a call with graphql it returns information from the api?

A: So i ended up using lighthouses built-in artisan function to create a custom resolver:
php artisan lighthouse:query

The file that is created from this in the graphql folder in the root of laravel allows me to input and output what i need correctly. I'll basically be using this file to do the calls and returning the response.
Thank you for the help :)


text:
Q: How to get the Record id of a pageblocktable individual row? I am displaying a list of all Case records in a pageblocktable. The Case object has a relationship to Asset. On click of a related field (Asset), I want to get the record details. How to do this?
<apex:pageBlockTable value="{!openList}" var="a" id="theTable1" styleClass="mytable" >
    <apex:column value="{!a.CaseNumber}" headerValue="CaseNumber"/>
    <apex:column value="{!a.Reason}" headerValue="Reason"/>
    <apex:column value="{!a.Status}" headerValue="Status"/>
    <apex:column value="{!a.Service_For__c}" headerValue="Service For"/>
    <apex:column value="{!a.Assigned_To__c}" headerValue="Assigned To"/>
</apex:pageBlockTable>

A:  <apex:column headerValue="CaseNumber">
    <apex:outputLink value="{!URLFOR($Action.Asset.View, a.id)}">{!a.CaseNumber}</apex:outputLink>
</apex:column>

If you want to redirect to asset view page, above code may work.


text:
Q: 'Learn Ruby on Rails' tutorial: Can't submit contact form I am getting the error below following the tutorial in the book Learn Ruby on Rails.
I am able to launch my app manually by typing the URL into my browser but am wondering why Heroku open does not work.
Any idea what is happening here?
Heroku open error...
$ heroku open
Opening peaks-app... failed
 !    Heroku client internal error.
 !    Search for help at: https://help.heroku.com
 !    Or report a bug at: https://github.com/heroku/heroku/issues/new

    Error:       Unable to find a browser command. If this is unexpected, Please rerun with environment variable LAUNCHY_DEBUG=true or the '-d' commandline option and file a bug at
 https://github.com/copiousfreetime/launchy/issues/new (Launchy::CommandNotFoundError)
    Backtrace:   /home/action/.heroku/client/vendor/gems/launchy-2.4.2/lib/launchy/applications/browser.rb:63:in `browser_cmdline'
                 /home/action/.heroku/client/vendor/gems/launchy-2.4.2/lib/launchy/applications/browser.rb:67:in `cmd_and_args'
                 /home/action/.heroku/client/vendor/gems/launchy-2.4.2/lib/launchy/applications/browser.rb:78:in `open'
                 /home/action/.heroku/client/vendor/gems/launchy-2.4.2/lib/launchy.rb:29:in `open'
                 /home/action/.heroku/client/lib/heroku/helpers.rb:328:in `block in launchy'
                 /home/action/.heroku/client/lib/heroku/helpers.rb:227:in `action'
                 /home/action/.heroku/client/lib/heroku/helpers.rb:326:in `launchy'
                 /home/action/.heroku/client/lib/heroku/command/apps.rb:342:in `open'
                 /home/action/.heroku/client/lib/heroku/command.rb:217:in `run'
                 /home/action/.heroku/client/lib/heroku/cli.rb:33:in `start'
                 /home/action/.parts/bin/heroku:24:in `<main>'

    Command:     heroku open
    Version:     heroku-toolbelt/3.12.1 (x86_64-linux) ruby/2.1.1

A: The short answer is that Heroku uses Launchy to launch my app and Launchy is looking for my browser. Since I am using Nitrous.io, I do not have a browser installed, so Launchy does not know what to do.
The author of Launchy explains that "...launching a browser from within the virtual box would do nothing if there was no browser installed." https://github.com/copiousfreetime/launchy/issues/78
Launching manually appears to be my only option at this point.


text:
Q: Websocket connection failed with nginx and faye I'm trying to introduce chatting to my Rails app. For this purpose I used gem private_pub and it works perfectly in development mode.
In production I was using Apache + Passenger, but I couldn't configure Faye with it, so I changed Apache to Nginx. My main app is still on Apache server, and this demo on Nginx with port 8080 (just for test).
I'm able to connect to faye.js by entering http://chat.mysite.com:8080/faye.js, but the connection from app throws an error (browser console).

WebSocket connection to 'ws://localhost:9292/faye' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

After this error, another error appears every 5 seconds.

faye.js:2 GET http://localhost:9292/faye?message=%5B%7B%22channel%22%3A%22%2Fmeta%2Fhands…22%2C%22callback-polling%22%5D%2C%22id%22%3A%221%22%7D%5D&jsonp=jsonp2 net::ERR_CONNECTION_REFUSED

My private_pub.yml
production:
  server: "http://localhost:9292/faye"
  secret_token: "mysecret"
  signature_expiration: 3600 # one hour

My private_pub.ru
require "bundler/setup"
require "yaml"
require "faye"
require "private_pub"

Faye::WebSocket.load_adapter('thin')
PrivatePub.load_config(File.expand_path("../config/private_pub.yml", __FILE__), ENV["RAILS_ENV"] || "development")
run PrivatePub.faye_app

My nginx site.conf
  server {
  listen 8080;
  server_name www.chat.mysite.com;
  passenger_enabled on;
  passenger_app_env production;

  root /var/www/mysite/public;

  location ^~ /faye {
     proxy_pass http://127.0.0.1:9292;
     proxy_http_version 1.1;
     proxy_set_header Host $host;
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
     proxy_set_header X-Real-IP $remote_addr;
     proxy_set_header Upgrade $http_upgrade;
     proxy_set_header Connection "Upgrade";
     proxy_buffering off;
     proxy_redirect off;
     proxy_connect_timeout      90;
     proxy_send_timeout         90;
     proxy_read_timeout         90;
     #proxy_set_header X-Forwarded-Proto https;
     proxy_cache_bypass $http_pragma $http_authorization;
     proxy_no_cache     $http_pragma $http_authorization;
     break;
    }
 }

If I change private_pub.yml to http://localhost:9292/faye/faye, I saw error like "can't load resource /faye/faye.js".
How should I change my Nginx conf or app yml to resolve websocket error?

A: I see private_pub is quite similar to ActionCable in its design. Before you go too far down the road, you may want read my blog post on "ActionAcable - The good and bad parts" as it addresses suitable use cases when a system like private_pub is good, and when it's not.
If of course you are aware of the shortcomings already, then good luck!

A: I tried to configure my private_pub.yml as @niceman said. Now all is working good.
production:
  server: "http://my-ip:8080/faye"


text:
Q: Newton's third law (action and reaction) and work done with a wheel I'm aware of the common misunderstanding about action and reaction canceling each other; they don't because they don't act on the same object. This is about a more subtle issue: exactly where is the work being done? Consider a bicycle wheel:

The bike wheel pushes the earth backwards (action force $F_A$) and the reaction force $F_R$ is in the opposite direction on the bike wheel (ignoring gravity). But the point of the wheel that touches the ground is not moving relative to the ground; therefore, neither the reaction force nor the action force does any work; therefore, this force cannot be what causes the bike to accerelate from a standstill. (If you account for the displacement of the earth, there would be on the order of $10^{-20}$ W of work, which is small enough to ignore.)
The chain of the bike definitely does work on the sprocket on the back axle (teeth and chain are moving with a force). Presumably, the axle does work on the bike frame; the frame and rider are pushed from the axle. Something tricky happens between the axle and the tire.
The question is: what is a clean way to describe the forces (especially those acting on the wheel) so that this is all consistent? Is it possible to draw the relevant force vectors in a free body diagram?
Edit: to make the problem more well-defined: the bike is accelerating, ignore air resistance, and ignore gravity (you can pretend that it's a rack and pinion construction that works without vertical force.
Here is a diagram with the forces around the sprocket/chain and the forces around the road contact point (arrows not on scale). How do you describe acceleration?

A:
But the point of the wheel that touches the ground is not moving
relative to the ground; therefore, neither the reaction force nor the
action force does any work; therefore, this force cannot be what
causes the bike to accelerate from a standstill.

That is not correct. If the wheel is not slipping on the ground, then the static friction force will cause the bicycle, as well as the earth, to accelerate, though the latter would be imperceptible.
Per Newton's third law $F_R$= $F_A$=$F$.
Per Newton's second law the friction force $F$ that the earth exerts on the bicycle causes the bicycle to accelerate
$$a_{b}=\frac{F}{m_b}$$
where $a_b$ is the acceleration of the bicycle and $m_b$ is the mass of the bicycle
The force $F$ that the bicycle exerts on the earth causes the earth to accelerate
$$a_{E}=\frac{F}{M_E}$$
where $a_E$ is the acceleration of the earth and $M_E$ is the mass of the earth.
Clearly since $M_{E}>>>>m_b$, then $a_{E}<<<<a_b$ . The acceleration of the earth would be too small to measure, but it would theoretically exist nonetheless.

The chain of the bike definitely does work on the sprocket on the back
axle (teeth and chain are moving with a force). Presumably, the axle
does work on the bike frame; the frame and rider are pushed from the
axle. Something tricky happens between the axle and the tire.

Ultimately the energy that causes work to be done on the bicycle comes from the conversion of chemical potential energy of the body to mechanical energy doing work pushing on the pedals. If we can ignore any dissipative forces in the chain of events from the force on the bike pedal to the torque applied to the wheel, then all of these forces can be considered internal to the bike/cyclist system. If we can exclude all external dissipative forces (air resistance, tire rolling resistance, etc.), then the only external force acting on the bike/cyclist system is the static friction force exerted by the earth, which is then responsible for the acceleration of the bike.
Hope this helps.

A:
These are the steps through which i believe the bicycle accelerates from rest.

*

*You push the pedal .

2.The back wheel moves to rotate (clockwise) to stop that relative motion  $f_1$ acts forward , now the whole bicycle  will accelerate forward due to $f1$.
3 .  Now come to rear wheel  . Since the whole bike along with rear wheel moves forward , the point of contact of rear whiles tries to skid and to oppose that , friction ($f_2$) at rear wheel acts backwards. This also creates a torque.
Translation Motion of bicycle : $f_1-f_2=M_{bicycle}a_{com}$
To answer your work done question :

*

*Your muscle energy get converted into kinetic energy .If we include the friction between the gears . Your energy spent = $KE\ _{bicycle}+ Friction\ _{gears} $


text:
Q: Opencart v2 Worldpay relay response error Any guidance/advice would be great.
We have WorldPay installed with Opencart 2.0.1.1
All online orders/transactions work fine, everything processes.
However, at the end of the transaction the relay response does not work.
Customers are not re-directed back to the website.
WorldPay have confirmed this should be working (all settings are correct)
It must be a problem with the worldpay.php itself.
Complete shot in the dark, but has anybody experienced this? Opencart forums are usless.
Really appreciate your help!
<?php
class ControllerPaymentWorldPay extends Controller {
private $error = array();

public function index() {
    $this->load->language('payment/worldpay');

    $this->document->setTitle($this->language->get('heading_title'));

    $this->load->model('setting/setting');

    if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
        $this->model_setting_setting->editSetting('worldpay', $this->request->post);

        $this->session->data['success'] = $this->language->get('text_success');

        $this->response->redirect($this->url->link('extension/payment', 'token=' . $this->session->data['token'], 'SSL'));
    }

    $data['heading_title'] = $this->language->get('heading_title');

    $data['text_edit'] = $this->language->get('text_edit');
    $data['text_enabled'] = $this->language->get('text_enabled');
    $data['text_disabled'] = $this->language->get('text_disabled');
    $data['text_all_zones'] = $this->language->get('text_all_zones');
    $data['text_yes'] = $this->language->get('text_yes');
    $data['text_no'] = $this->language->get('text_no');
    $data['text_successful'] = $this->language->get('text_successful');
    $data['text_declined'] = $this->language->get('text_declined');
    $data['text_off'] = $this->language->get('text_off');

    $data['entry_merchant'] = $this->language->get('entry_merchant');
    $data['entry_password'] = $this->language->get('entry_password');
    $data['entry_callback'] = $this->language->get('entry_callback');
    $data['entry_test'] = $this->language->get('entry_test');
    $data['entry_total'] = $this->language->get('entry_total');
    $data['entry_order_status'] = $this->language->get('entry_order_status');
    $data['entry_geo_zone'] = $this->language->get('entry_geo_zone');
    $data['entry_status'] = $this->language->get('entry_status');
    $data['entry_sort_order'] = $this->language->get('entry_sort_order');

    $data['help_password'] = $this->language->get('help_password');
    $data['help_callback'] = $this->language->get('help_callback');
    $data['help_total'] = $this->language->get('help_total');

    $data['button_save'] = $this->language->get('button_save');
    $data['button_cancel'] = $this->language->get('button_cancel');

    if (isset($this->error['warning'])) {
        $data['error_warning'] = $this->error['warning'];
    } else {
        $data['error_warning'] = '';
    }

    if (isset($this->error['merchant'])) {
        $data['error_merchant'] = $this->error['merchant'];
    } else {
        $data['error_merchant'] = '';
    }

    if (isset($this->error['password'])) {
        $data['error_password'] = $this->error['password'];
    } else {
        $data['error_password'] = '';
    }

    $data['breadcrumbs'] = array();

    $data['breadcrumbs'][] = array(
        'text' => $this->language->get('text_home'),
        'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
    );

    $data['breadcrumbs'][] = array(
        'text' => $this->language->get('text_payment'),
        'href' => $this->url->link('extension/payment', 'token=' . $this->session->data['token'], 'SSL')
    );

    $data['breadcrumbs'][] = array(
        'text' => $this->language->get('heading_title'),
        'href' => $this->url->link('payment/worldpay', 'token=' . $this->session->data['token'], 'SSL')
    );

    $data['action'] = $this->url->link('payment/worldpay', 'token=' . $this->session->data['token'], 'SSL');

    $data['cancel'] = $this->url->link('extension/payment', 'token=' . $this->session->data['token'], 'SSL');

    if (isset($this->request->post['worldpay_merchant'])) {
        $data['worldpay_merchant'] = $this->request->post['worldpay_merchant'];
    } else {
        $data['worldpay_merchant'] = $this->config->get('worldpay_merchant');
    }

    if (isset($this->request->post['worldpay_password'])) {
        $data['worldpay_password'] = $this->request->post['worldpay_password'];
    } else {
        $data['worldpay_password'] = $this->config->get('worldpay_password');
    }

    $data['callback'] = HTTP_CATALOG . 'index.php?route=payment/worldpay/callback';

    if (isset($this->request->post['worldpay_test'])) {
        $data['worldpay_test'] = $this->request->post['worldpay_test'];
    } else {
        $data['worldpay_test'] = $this->config->get('worldpay_test');
    }

    if (isset($this->request->post['worldpay_total'])) {
        $data['worldpay_total'] = $this->request->post['worldpay_total'];
    } else {
        $data['worldpay_total'] = $this->config->get('worldpay_total');
    }

    if (isset($this->request->post['worldpay_order_status_id'])) {
        $data['worldpay_order_status_id'] = $this->request->post['worldpay_order_status_id'];
    } else {
        $data['worldpay_order_status_id'] = $this->config->get('worldpay_order_status_id');
    }

    $this->load->model('localisation/order_status');

    $data['order_statuses'] = $this->model_localisation_order_status->getOrderStatuses();

    if (isset($this->request->post['worldpay_geo_zone_id'])) {
        $data['worldpay_geo_zone_id'] = $this->request->post['worldpay_geo_zone_id'];
    } else {
        $data['worldpay_geo_zone_id'] = $this->config->get('worldpay_geo_zone_id');
    }

    $this->load->model('localisation/geo_zone');

    $data['geo_zones'] = $this->model_localisation_geo_zone->getGeoZones();

    if (isset($this->request->post['worldpay_status'])) {
        $data['worldpay_status'] = $this->request->post['worldpay_status'];
    } else {
        $data['worldpay_status'] = $this->config->get('worldpay_status');
    }

    if (isset($this->request->post['worldpay_sort_order'])) {
        $data['worldpay_sort_order'] = $this->request->post['worldpay_sort_order'];
    } else {
        $data['worldpay_sort_order'] = $this->config->get('worldpay_sort_order');
    }

    $data['header'] = $this->load->controller('common/header');
    $data['column_left'] = $this->load->controller('common/column_left');
    $data['footer'] = $this->load->controller('common/footer');

    $this->response->setOutput($this->load->view('payment/worldpay.tpl', $data));
}

protected function validate() {
    if (!$this->user->hasPermission('modify', 'payment/worldpay')) {
        $this->error['warning'] = $this->language->get('error_permission');
    }

    if (!$this->request->post['worldpay_merchant']) {
        $this->error['merchant'] = $this->language->get('error_merchant');
    }

    if (!$this->request->post['worldpay_password']) {
        $this->error['password'] = $this->language->get('error_password');
    }

    return !$this->error;
}
}


text:
Q: Can service workers detect if the tab that registered it has closed? Is there a reliable way for service workers to detect if the tab that registered it has closed? The use case I'm concerned about is trying to get the service worker to run specific code after a tab is closed?
The way I'm doing this currently is by sending healthcheck messages to the service worker, and once these messages stop, we can assume that the tab has been closed. However, this is not completely reliable because browsers throttle tabs that are not in focus, which leads to healthcheck messages being sent inconsistently.
Anyone have any other ideas?


text:
Q: Hyperlink Transferring from worksheet to worksheet I am creating an excel file management platform for my staff. I have a master list created that houses all of the files that we are currently working on. Within the master list, I have the client's name hyperlinked to a specific folder on our public drive.
I have other tabs within the workbook that is employee specific. I am trying to get the client name hyperlink to automatically transfer to the specific employee tab and be active. I have used =hyperlink('Master List'!16), but the hyperlink is not active on the corresponding tab and returns an error Cannot open the specified file. It is still able to be opened from the master list, but not the employee specific tab.
Is there a way that I can get the hyperlink to transfer to another worksheet and be an active hyperlink? I am using the paste link feature so that if it is every updated, it will update on each tab as well.
Thank you,


text:
Q: Tempdata session expires after browser close in codeigniter I'm creating login functionality for my site. I'm using CI Sessions. I've two sessions created in my login model.The first one is for the temp. user while the second is for the permanent user (Remember me functionality). For the first one, I've the tempdata() & for the second one, i've the userdata(). The problem i'm facing is that the session expires after the browser closes.
My login model code looks like this:
public function logger($email, $pass, $check)
        {
            $q = $this->DB->get_where('users', array('email' => $email, 'pass' => $pass));
            if($q->num_rows() == 1)
            {
                if(isset($check))
                {
                    $this->session->set_tempdata('per_ue', $email, 86400*30);
                    $this->session->set_tempdata('per_up', $pass, 86400*30);
                    return redirect('uhome');
                } else {
                    $this->session->set_userdata('tmp_ue', $email);
                    $this->session->set_userdata('tmp_up', $pass);
                    return redirect('uhome');
                }
            } else {
                $login_error = '
Login credentials are incorrect
';
                $this->load->view('coders-community/login', compact('login_error'));
            }

        }

My config setting for session:
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 0;
$config['sess_save_path'] = NULL;
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;

Could anyone tell me why tempdata ttl (time-to-live) not working & destrying tempdata session after browser closes?

A: Try like this.Just set $config['sess_expiration'] with certain amount of time.
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;//sets session for 2 hours
$config['sess_save_path'] = NULL;
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;


text:
Q: Symfony 5 - Filter some entities from DB for a collectionType I have a form based on a collection. I would like that form to be set with a part of the data I have in my entity (not all).
I have search but haven't find the answer I'm looking for.
I tought using PRE_SET_DATA but the way I understand it doesn't work.
Can someone help me to do that?
I have an entity Service
<?php

namespace App\Entity;

use App\Repository\ServiceRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass=ServiceRepository::class)
 */
class Service
{
    //[...]

    /**
     * @ORM\ManyToOne(targetEntity=User::class, inversedBy="services")
     */
    private $performer;

    /**
     * @ORM\ManyToOne(targetEntity=User::class, inversedBy="performer_services")
     */
    private $service_performer;

    //[...]

    public function getPerformer(): ?user
    {
        return $this->performer;
    }

    public function setPerformer(?user $performer): self
    {
        $this->performer = $performer;

        return $this;
    }

    public function getServicePerformer(): ?User
    {
        return $this->service_performer;
    }

    public function setServicePerformer(?User $service_performer): self
    {
        $this->service_performer = $service_performer;

        return $this;
    }
}

My Collection Form
<?php

namespace App\Form;

use App\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class PerformerServiceType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('performer_services',CollectionType::class,[
                'entry_type' => ServicePerformerNoMoneyUnitType::class,
                'entry_options' => ['label' => false],
                'allow_add' => true,
                'allow_delete' => true,
            ])
            ->add('enregistrer', SubmitType::class)
        ;
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => User::class,
        ]);
    }
}

My Entity Form (based on Service)
<?php

namespace App\Form;

use App\Entity\Service;
use App\Repository\UserRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\MoneyType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Security\Core\Security;
use App\Entity\User;

class ServicePerformerNoMoneyUnitType extends AbstractType
{
    public function __construct(Security $security)
    {
        $this->security = $security;
    }
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('price', MoneyType::class, [
                'currency' => false])
            ->add('servicePerformer', EntityType::class, [
                'class' => 'App\Entity\User',
                'query_builder' => function (UserRepository $er) {
                    return $er->findByPartners($this->security->getUser());
                },
            ])
            ->add('description')
        ;
        $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
            $service = $event->getData();
            $userService = new User;
            $performerService = new User;
            if ($service <> null)
            {
                $userService = $service->getPerformer();
                dump($userService);
                $performerService = $service->getServicePerformer();
                dump($performerService);
            }

            $form = $event->getForm();

            // checks if the Product object is "new"
            // If no data is passed to the form, the data is "null".
            // This should be considered a new "Product"
            if ($userService == $performerService) {
                $form->removeElement();
            }
        });
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Service::class,
        ]);
    }
}

What I would like to do is not show rows where Performer = Service Performer.


text:
Q: Validate Gmail account and retrieve basic profile info Is there a way to validate account existence and retrieve basic gmail account info such as name and photo url using only email ?
Previously it was possible to get account photoUrl using the following endpoint:
http://picasaweb.google.com/data/entry/api/user/<hereYourUserIdOrYourEmail>?alt=json

but it was shut down.

A: You can't access that information with the gmail-api. If you are the admin of a g suite domain, you could use the directory API to obtain that info.
If the application is not intended for a specific domain, you can implement google oauth2 with JavaScript in the front-end, the user would have to authenticate and this way you'll be able to access the basic information. You need to create a project in cloud.google.com and get credentials (a clientID is needed in the code). More explanation here:
https://developers.google.com/identity/sign-in/web/sign-in
Implementation example (only clientID missing):
 <!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="google-signin-client_id" content="#clientId">
    <title>Oauth2 web</title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

<button type="button" class="btn btn-danger" onclick="signOut();">Sign out</button>


text:
Q: C# How to force focus to be on my form When my form on c# net3.5 is started and I don't click anywhere, focus remains on my form. But if at the time of loading of a form I click for example on an empty seat of the screen, then focus runs away from my form.
In windows 7 it works, but in windows server 2008 isn't present.
private void LoginDialog_Shown(object sender, EventArgs e)
{
    this.Activate();
}

How to force focus to be on my form?


text:
Q: Will you lose games you got with xbox game pass ultimate? I am thinking about cancelling my xbox game pass ultimate subscription. I have Forza Horizon 4 which was included with the pass. If I cancel now, will I have to pay for the game to keep playing?

A: After your game pass is up you will have to buy the game to continue playing. All of your game data will still be there if you do purchase the game so you can pick up where you left off.


text:
Q: Update leaflet-map when user clicks on map and new data is added I am developing a React app on my Ubuntu 20.4 VM machine in a chrome Version 100.0.4896.127 (Official Build) (64-bit) browser.
For creating the polygons I use "h3-js". h3-js can only be added via npm as the the core library is transpiled from C using emscripten.
I want to implement the following: When I set a marker I would like to show the hexagon that are in the data array.
Setting the marker works fine. Also adding the data.
I do this the following way:
Setting the marker
 <MapContainer
        // center={[40.0151, -105.2921]}
        center={[40.7579747, -73.9877313]}
        // @ts-ignore
        // onClick={addMarker}
        zoom={15}
        style={{ height: "90%" }}
        // @ts-ignore
        onZoomEnd={console.log}
      >
        <SetMarker />

        <TileLayer
          url="https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png"
          maxZoom={19}
        />

        {Object.entries(groups).map(([weight, polygons]) => {
          const color = getColor(weight);
          return (
            <Polygon
              key={weight}
              positions={polygons}
              pathOptions={{
                ...baseStyle,
                fillColor: color,
                color: color, // stroke color
                weight: 0 // stroke weight
              }}
            />
          );
        })}
      </MapContainer>

The functional component <SetMarker />, sets my marker the following:
function SetMarker() {
  console.log("set marker");
  const [position, setPosition] = useState(null);

  const map = useMapEvents({
    click(e) {
      setPosition(e.latlng);
    }
  });

  // render hexagon
  if (position !== null) {
    data.pop(); // delete the last element that was added before the click
    data.push([position.lat, position.lng]); // add new element
  }

  return position === null ? null : (
    <div>
      <Marker position={position}>
        <Popup>You are here</Popup>
      </Marker>
    </div>
  );
}

In the data array are all my coordinates stores that create my hexagons.
However, when clicking the map the marker is set, but the map does not re-render.
I have created the following app:
https://codesandbox.io/s/react-leaflet-map-with-marker-forked-0uexf6
Sorry that I do not use the inbuilt stackoverflow editor as h3-js has to be installed via npm and cannot added via a cdn.
How can I update my leaflet map and show the polygon on the location where the user clicked.
Any suggestions what I am doing wrong?
I appreciate your replies!

A: The component doesn't rerender because react is not tracking the data that you're importing. You can use that data to initialize a react state and use it to render your hexagons.
const [mapData, setMapData] = useState(data);
[...mapData].forEach((point) => {

and add a new item to that state every time the position changes inside your SetMarker component
function SetMarker({ setMapData }) {
  ...
  useEffect(() => {
    if (position !== null) {
      setMapData((prevMapData) => [
        ...prevMapData,
        [position.lat, position.lng]
      ]);
    }
  }, [position, setMapData]);
  // render hexagon
  ...
}

and don't forget to pass the setter in the component props
<SetMarker setMapData={setMapData} />

You can see it working here https://codesandbox.io/s/react-leaflet-map-with-marker-answer-ycm2u0?file=/Map.js
As an additional note, your code generally does not follow react's good practices about immutability. I'd recommend you revisit the official documentation and adjust your code accordingly. Every time you use an imperative js function like pop, push, or set is a red flag. Personally, learning redux helped me to understand more immutability; Dan's courses in egghead are a good start https://egghead.io/q/resources-by-dan-abramov


text:
Q: getting past ReadTimeout from Python Requests I'm trying to scrape the Home Depot website using Python and requests. Selenium Webdriver works fine, but takes way too much time, as the goal is to make a time-sensitive price comparison tool between local paint shops and power tool shops.
When I send a request to any other website, it works like normal. If I use any browser to navigate manually to the website, it also works fine (with or without session data/cookie data). I tried adding randomized headers into the request, but it does not seem to help the issue. From what I can see, it's not an issue of sending too many requests per time-period, (considering that selenium and manual browsing still works at any time.) I am confident that this specific issue is NOT because of a rate limitation.
my code:
from random import choice
import requests
import traceback

list_desktopagents = ['Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36']
def random_headers():
    return {'User-Agent': choice(list_desktopagents),
        'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'}

response = requests.get(
    'https://www.homedepot.com/p/BEHR-1-gal-White-Alkyd-Semi-Gloss-Enamel-Alkyd-
     Interior-Exterior-Paint-390001/300831629',
     headers=myheaders,
     timeout=10)

my error:
raise ReadTimeout(e, request=request)
requests.exceptions.ReadTimeout: HTTPSConnectionPool(host='www.homedepot.com', port=443): Read timed out. (read timeout=10)

Does anyone have a suggestion on what else I could do to successfully receive my response? I would prefer to use Requests, but anything that runs fast unlike selenium will be suitable. I understand that im being blocked, my question is not so much 'whats happening to stop me from scraping?', but rather, 'what can i do to further humanize my scraper so it allows me to continue?'

A: The error is coming from the User Agent. The reason why Selenium is working and not request is because Selenium is using a web driver to make the request, so it is more humanlike while request is much easier to be detected as a script. From Home Depot's robots.txt page it doesn't look like products are allowed for scraping. I just used this code and got a response by using this code:
headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'}
response = requests.get('https://www.homedepot.com/p/BEHR-1-gal-White-Alkyd-Semi-Gloss-Enamel-Alkyd-Interior-Exterior-Paint-390001/300831629', headers=headers)

print(response.content)

By using these user agents you can "trick" the site into thinking you are an actual person, which is what the web driver with Selenium does.