text:
Q: How to stretch image in canvas? I need to stretch my image to the top and to the bottom in canvas.
How can I do this?
Here's the codepen
HTML
<canvas id="myCanvas" width="240" height="297" style="border:1px solid #d3d3d3;">
</canvas>

JS
window.onload = function() {
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var img = new Image;
    img.src = "http://www.w3schools.com/tags/img_the_scream.jpg"
    ctx.drawImage(img, 10, 10);
}

A: drawImage allows you to pass the width and height as third and fourth parameter.
So your last line should be ctx.drawImage(img, 0, 0,c.width, c.height); in order to fill the entire canvas.

A: Here is a more detailed answer of how to fill or fit a canvas while also keeping the image aspect.
Fill canvas

A: If you just want an image to stretch to fill in the height you can do something like this jsFiddle : https://jsfiddle.net/CanvasCode/92ekrbnz/
javascript
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = new Image;
ctx.fillStyle = "#000";
ctx.fillRect(0,0,c.width,c.height);
img.src = "http://www.w3schools.com/tags/img_the_scream.jpg"
img.onload = function () {
    ctx.drawImage(img, (c.width / 2) - (img.width / 2), 0, img.width, c.height);
}

However the link you provided basically just zooms into the image.
So you can do something like this jsFiddle : https://jsfiddle.net/CanvasCode/92ekrbnz/2/
javascript
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = new Image;

var zoom = 1.0;

img.src = "http://www.w3schools.com/tags/img_the_scream.jpg"

setInterval(function () {
    ctx.fillStyle = "#000";
    ctx.fillRect(0, 0, c.width, c.height);
    ctx.drawImage(img, (c.width / 2) - ((img.width * zoom) / 2), (c.height / 2) - ((img.height * zoom) / 2),
    img.width * zoom,
    img.height * zoom);
}, 1);

document.getElementById("zoomIn").onclick = function () {
    zoom += 0.1;
};
document.getElementById("zoomOut").onclick = function () {
    if (zoom > 0.1) {
        zoom -= 0.1;
    }
};


text:
Q: conditions formation for two colums How can I make the two columns to meet both the conditions then highlight it red? right now is either columns met the condition then it will highlight red.
         If InStr(rcol.Value, "L-Start") > 0 Then
                        With rcol.EntireColumn.Cells
                        .FormatConditions.Add Type:=xlCellValue, Operator:=xlLess, Formula1:="=(today() - 120)"
                        With .FormatConditions(1).Font
                            .Color = RGB(255, 0, 0)
                        End With
                    End With
                    End If

                If InStr(rcol.Value, "L-Type") > 0 Then
                    With rcol.EntireColumn.Cells
                        .FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, Formula1:="=""Q"""

                        With .FormatConditions(1).Font
                            .Color = RGB(255, 0, 0)
                        End With
                    End With
                End If

A: This code will only paint the cells red if both conditions are met
            If InStr(rcol.Value, "L-Start") > 0 And InStr(rcol.Value, "L-Type") > 0 Then
                With rcol.EntireColumn.Cells
                    .FormatConditions.Add Type:=xlCellValue, Operator:=xlLess, Formula1:="=(today() - 120)"
                    .FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, Formula1:="=""Q"""
                    With .FormatConditions(1).Font
                        .Color = RGB(255, 0, 0)
                    End With
                    With .FormatConditions(2).Font
                        .Color = RGB(255, 0, 0)
                    End With
                End With
            End If

I hope this is what you need.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ASP.NET Core: [FromQuery] usage and URL format I am trying to use [FromQuery] in my web api and I am not sure how to use it.
Here's the GetAllBooks() method in the controller:
 [HttpGet]
 [Route("api/v1/ShelfID/{shelfID}/BookCollection")]
 public async Task<IActionResult> GetAllBooks(string shelfID, [FromQuery] Book bookinfo)
            {
               //do something
            }

Here's the Book model class:
 public class Book
    {
        public string ID{ get; set; }
        public string Name{ get; set; }
        public string Author { get; set; }
        public string PublishDate { get; set; }
    }

I am confused about whether it is the correct way to use [FromQuery]. I thought the URL is

https://localhost:xxxxx/api/v1/ShelfID/{shelfID}/BookCollection/IActionResult?ID="123"&Name="HarryPotter"

But the break point is not hitting my controller method, so I was thinking maybe the URL is not correct. Any suggestions? Thanks!

A: The name of the method and return type are completely ignored when you define your route explicitly via attributes like that. IActionResult shouldn't be there.
The correct URL would be: https://localhost:xxxxx/api/v1/ShelfID/{shelfID}/BookCollection?ID="123"&Name="HarryPotter"
Furthermore, query string binding only works out of the box for primitive types (string, int, etc). To bind a class to a query string you'd need a custom modelbinder, which is quite involved.
It would be better to just explicitly declare the properties you want to pass in:
public async Task<IActionResult> GetAllBooks(string shelfID,
                                             [FromQuery] string ID,
                                             [FromQuery] string Name)


text:
Q: July 2013 Breaking Changes, Graph API post search with or without access token on Android My question would be an extension of the question
July 2013 breaking changes: Graph API post search with or without access token?

I have an Android application which uses the Facebook SDK for Android v3.0.
How could I check that all my requests uses the user access token for Graph API post?

In all my requests I check the status of the active session:
Session.getActiveSession() != null && Session.getActiveSession().isOpened()

and pass the active session to the request Constructor (example for a Place request):
Request placeRequest = Request.newGraphPathRequest(
                    Session.getActiveSession(),
                    placeId,
                    requestCallback
);

Is this enough to add the user access token to the request and so being compliant with the July 2013 Breaking Changes?

A: The check for the Session to be not-null and opened grants that each request created using that Session has a valid access token.


text:
Q: Strange React hooks behavior, can't access new state from a function I use the library react-use-modal, and
I'm trying to read the updated value of confirmLoading when inside the handleClick function.
handleClick does read the first value of confirmLoading defined when doing const [ confirmLoading, setConfirmLoading ] = useState(false), but never updates when I setConfirmLoading inside handleOk.
I don't understand what I'm doing wrong
import { Button, Modal as ModalAntd } from 'antd'
import { useModal } from 'react-use-modal'

export interface ModalFormProps {
    form: React.ReactElement
}

export const ModalForm: React.FC = () => {
    const [ confirmLoading, setConfirmLoading ] = useState(false)
    const { showModal, closeModal } = useModal()

    const handleOk = () => {
        setConfirmLoading(true)
        setTimeout(() => {
            setConfirmLoading(false)
            closeModal()
        }, 1000)
    }

    const handleCancel = () => {
        closeModal()
    }

    const handleClick = () => {
        showModal(({ show }) => (
            <ModalAntd
                onCancel={handleCancel}
                onOk={handleOk}
                title='Title'
                visible={show}
            >
                //  the value of confirmLoading is always the one defined
                //  with useState at the beginning of the file.

{confirmLoading ? 'yes' : 'no'}

            </ModalAntd>
        ))
    }

    return (

            <Button onClick={handleClick}>
                Open Modal
            </Button>

    )
}

A: This is happening because of closures. The component that you pass to showModal remembers confirmLoading and when you call function setConfirmLoading your component renders again and function handleClick is recreated. 'Old' handleClick and 'old' component in showModal know nothing about the new value in confirmLoading.
Try to do this:
export const ModalForm: React.FC = () => {
    const { showModal, closeModal } = useModal();

    const handleClick = () => {

        showModal(({ show }) => {
            const [ confirmLoading, setConfirmLoading ] = useState(false);
            const handleOk = () => {
                setConfirmLoading(true)
                setTimeout(() => {
                    setConfirmLoading(false)
                    closeModal()
                }, 1000)
            };

            const handleCancel = () => {
                closeModal()
            };

            return (
                <ModalAntd
                    onCancel={handleCancel}
                    onOk={handleOk}
                    title='Title'
                    visible={show}
                >
                    // the value of confirmLoading is always the one defined
                    // with useState at the beginning of the file.

{confirmLoading ? 'yes' : 'no'}

                </ModalAntd>
            );
        })
    };

    return (

            <Button onClick={handleClick}>
                Open Modal
            </Button>

    )
}


text:
Q: Warning: fwrite(): SSL: Broken pipe when sending mails from Magento messaging queue We have to send multiple emails through Magento 2 messaging queue and for emails, we are using SendGrid SMTP, and the module used within Magento to integrate this is of Mageplaza.
When we start the queue, the first few emails send fine without any issue but after a few we receive:

Sendgrid SMTP connection timed out

After this, we start receiving the following error:

Warning: fwrite(): SSL: Broken pipe in vendor/zendframework/zend-mail/src/Protocol/AbstractProtocol.php on line 260

We have found this fix of the above error and override the Mageplaza SMTP module to apply this fix. This does fix the issue but now again after the first few emails, the emails are getting failed and we are getting the following error:

Cannot issue HELO to existing session

The method used to send emails is following:
public function sendEmail($data = null)
{
    try {
        $this->inlineTranslation->suspend();

        $sender = [
            'name' => $this->escaper->escapeHtml($data['sender_name']),
            'email' => $this->escaper->escapeHtml($data['sender_email']),
        ];

        $transport = $this->transportBuilder
            ->setTemplateIdentifier($data['email_template'])
            ->setTemplateOptions(
                [
                    'area' => \Magento\Framework\App\Area::AREA_FRONTEND,
                    'store' => $this->storeManager->getStore()->getId()
                ]
            )
            ->setTemplateVars($data['template_vars'])
            ->setFromByScope($sender)
            ->addTo($data['customer_email'])
            ->getTransport();

        $transport->sendMessage();

        $this->inlineTranslation->resume();

        return true;
    } catch (\Exception $e) {
        $this->logger->critical($e->getMessage());
    }

    return false;
}

We are using Magento enterprise 2.3.3, any help would be appreciated.

A: The issue has been reported to the Mageplaza side. You can contact them to ask about the latest version and how to fix this problem


text:
Q: how do perf record store assembly code I try to modify perf record to handle assembly code of target process/program. Therefore, I want to know where data structure does perf use to store assembly code and count position of target process/program?
Generally, perf record will write a 'perf.data' when finished and we can use perf record, press 'Enter' and choose 'annotate' to see assembly code of target process/program. By this way, we can get which code line is the reason for counting.

A: perf record does not handle assembly in any way, neither is any assembly or instructions stored in perf.data. perf record records events that contain instruction pointers. During perf report and other analysis tools, these are translated addresses within o DSOs using MMAP information. perf knows the file name to the corresponding binary - note that it may use copies of those binaries  under .debug/.build-id to use the right version if it changed since recording. Perf runs objdump on the file to get the disassembly and show you the annotated view.
This answers your question, but without any further information, it is impossible to really help you achieve what you actually want to do. You can also build your own tool based on  perf_event_open.


text:
Q: Seeking software to visualize and export area selected in OSM format? I have a very large OSM file and I would like to know if there is software that can open the OSM file and then when I select a certain area to be able to export it in OSM file again. I found Maperitive and Marble but both of them can't export area in OSM format.

A: Osmosis can subset by bounding boxes, amongst other capabilities. Its command line though - no visualisation. There are some front ends GUIs, but they tend to be workflow rather than visualising the source data.

A: For splitting OSM files into different geographical regions there are various tools available, for example osmium, osmosis and osmconvert.
For visualization/rendering you can take a look at the client-side GUI applications, for example Kosmtik and Maperitive.


text:
Q: Getting Server Error while calling Servlet from Java Application Here is my Java Class by which I am calling simple servlet and passing the data, I am
using URL and HttpURlConnection class.What should be path of url for the servlet
public class TestJava
{
    public static void main(String[] args)
{
        try
    {
     URL url=new URL("http://localhost:9865/TestingServlet/PushServlet");

    HttpURLConnection http_url =(HttpURLConnection)
                                            url.openConnection();
     http_url.setRequestMethod("POST");
     http_url.setDoOutput(true);
     http_url.setDoInput(true);
     InputStream response = http_url.getInputStream();
     System.out.println(" " +response);
     ObjectOutputStream objOut = new
             ObjectOutputStream(http_url.getOutputStream());
     objOut.writeObject("hello");
     objOut.flush();
     objOut.close();

    }

            catch (IOException e) {

        e.printStackTrace();
    }
       }
   }

Here is the servlet code, I am receiving the object from the java code and displaying
it on the console.
  public class PushServlet extends HttpServlet
   {
        public void doPost(HttpServletRequest request, HttpServletResponse response)
          throws  ServletException, IOException
         {

          try
               {

                    System.out.println("HELLO This is servlet");
                ObjectInputStream objIn = new
                    ObjectInputStream(request.getInputStream());
                TestJava p = null;
                p = (TestJava) objIn.readObject();
                System.out.println("Servlet received p: "+p);
              }
                 catch (Throwable e)
                 {
                    e.printStackTrace(System.out);
             }
    }

My web.xml is like this
 <welcome-file-list>
 <welcome-file>
 Customer_Servlet
  </welcome-file>
  </welcome-file-list>
    <servlet>
    <servlet-name>PushServlet</servlet-name>
    <servlet-class>com.servlet.PushServlet</servlet-class>
   </servlet>
    <servlet-mapping>
     <servlet-name>PushServlet</servlet-name>
     <url-pattern>/PushServlet</url-pattern>
     </servlet-mapping>
     <session-config>
      <session-timeout>50</session-timeout>
      </session-config>
      </web-app>

When i m trying to run the java code on server i.e Apache server, I'm getting
error HTTP Status 404 i am not able to find why i am getting this server error
My code is all about invoking the servlet from java application
 please help me guys .

A: So to answer your question : "What should be path of url for the servlet?" I think you should know the following :
The URL should be something like :
http://localhost:portNumber/nameOfTheContext/MappingOfTheServlet WHERE

portNumber = the port number of the server ( Apache has it by default to 80 but Apache Tomcat has it to 8080, so it's not 9865 unless you changed it from configuration file)
nameOfTheContext = the name of the folder/archive( with .WAR or .EAR extension) which you deployed to the server
MappingOfTheServlet = the mapping of the servlet which you put in web.xml. So if you have <url-pattern>/PushServlet</url-pattern> then the mapping is PushServlet.

So having that said the URL for you should be :
http://localhost:8080/NameOfTheContext/PushServlet

If it's unclear where you can find the NameOfTheContext tell us how did you deployed the servlet , so we may help you.
Later Edit:  the name of the context should be : JavaToServlet because that's the name of your .WAR archive . So your URL should be :
    http://localhost:9865/JavaToServlet/PushServlet

A: From the reference on web for 404 Error WiKi

The web site hosting server will typically generate a "404 Not Found" web page when a user attempts to follow a broken or dead link;

You can more about 404 error from below link
404 Not Found Error (What It Is and How To Fix It) .


text:
Q: Should I return a 204 or a 404 response when a resource is not found? I am developing a simple RESTful service for tournaments and schedules. When a tournament is created through a POST request containing a JSON body, the tournament is inserted in a BiMap, declared as follows in a DAO implementation:
private BiMap<String, Tournament> tournaments = Maps.synchronizedBiMap(HashBiMap.create());

When a tournament is created, its associated string id is returned so the user can have future reference of that tournament. He/she can get information back from the new tournament performing the following request:
GET http://localhost:8080/eventscheduler/c15268ce-474a-49bd-a623-b0b865386f39

But what if no tournament with such id is found? So far, I am returning a 204 response. Well, Jersey is doing it for me when returning null from one of its methods. This is the method that corresponds to the route above:
@Path("/{id}")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Tournament getTournament(@PathParam("id") String id) {
    Optional<Tournament> optTournament = tournamentDao.getTournament(id);
    if (optTournament.isPresent())
        return optTournament.get();
    return null;
}

My question is: is it OK to return a 204: No Content response, or should it be a 404 response instead, since the resource was not found?
If I should change it to a 404, obvious question: I should change the method signature right? Since now a tournament (of type Tournament) might not be returned, the method should look different. Should I use the Response type as the return type instead?

A: HTTP 204 means that something was found, but it's empty. For instance, imagine that you're serving log files through HTTP, with the requests such as http://example.com/logs/[date-goes-here]. On May 18th, 2015:

*

*http://example.com/logs/2015-05-19 would return HTTP 404, which means that there are no logs, because, well, it's difficult to log the future.

*http://example.com/logs/2015-05-18, however, would return either HTTP 200 with the log entries in the content of the response, or HTTP 204 if the log file was created, but there are still no logs recorded yet for this date.
If you provide null to the framework as a response to a request, it assumes that you found an entry, and this entry is empty, thus HTTP 204. Instead, you should throw new NotFoundException(); to indicate to the framework that the entry doesn't exist, so that it would generate a HTTP 404.

If I should change it to a 404, obvious question: I should change the method signature right?

No, you don't. That's the nice thing about throw new NotFoundException();. It will work no matter what is the actual return type of your method.

A: You should return a 404. You can do it by throwing a NotFoundException (https://jersey.java.net/apidocs/2.6/jersey/javax/ws/rs/NotFoundException.html).
Also please look at this SO question if you need to control the returned content type https://stackoverflow.com/questions/23858488/how-i-return-http-404-json-xml-response-in-jax-rs-jersey-on-tomcat

A: Your request is GET http://localhost:8080/eventscheduler/c15268ce-474a-49bd-a623-b0b865386f39.
If http://localhost:8080/eventscheduler/ does not exist as an endpoint, you should return a 404. You are attempting to access a resource (/eventscheduler/) that does not exist. This would indicate to a client that a server exists on localhost:8080, but there's nothing at the eventscheduler endpoint.
If http://localhost:8080/eventscheduler/ exists as an endpoint but required resources are unavailable, a 5xx error is appropriate. A good example of this would be if a database is offline, where you could return a 503. Of course, you may just want to return a generic 500 error instead of a specific instance.
If http://localhost:8080/eventscheduler/ exists but the thing represented by c15268ce-474a-49bd-a623-b0b865386f39 does not exist, I would return a 200 with a body indicating the details. The endpoint exists, the request made was totally valid and could be processed, but there was no match.
If your client's request to the endpoint was not valid, you would look at the other 4xx errors. You can indicate that the client is not authorized to access the endpoint or the item(s) requested with a 401 or 403 or can use a 400 to indicate that the request is invalid. With any of these, additional information can be provided in the response body.


text:
Q: How to substitute a function body in z3py? I have a z3 function, e.g., zero = [else → Epoch!val!2], where Epoch!val!2 is a constant of sort Epoch. I want to get a new function zero(m) = [else -> Epoch!val!2(m)], where I'm basically introducing an argument m as the first parameter in every function in the body.
In SMT-Lib speak, I want to go from the following:
(declare-sort Epoch)
(declare-fun Epoch!val!2 () Epoch)
(define-fun zero () Epoch
  (Epoch!val!2)
)

to the following:
(declare-sort M)
(declare-sort Epoch)
(declare-fun Epoch!val!2 (M) Epoch)
(define-fun zero ((m M)) Epoch
  (Epoch!val!2 m)
)

I tried to use the substitute function, but that only accepts z3 expressions, whereas I have zero from the model, i.e., as a FuncInterp instance. I'm not sure how to convert that into an expression, and couldn't find docs for that.
What should I do?

Edit: Adding more context.
I'm trying to write a CEGIS tool with SAT-based-synthesis (as opposed to enumerated synthesis), but here counter examples are entire models (including uninterpreted functions) rather than simpler entities. So, for example, the generated counter example might be:
(declare-sort Epoch)
(declare-fun Epoch!Val!0 () Epoch)
(declare-fun Epoch!Val!1 () Epoch)
(declare-fun Epoch!Val!2 () Epoch)

(define-fun le ((e1 Epoch) (e2 Epoch)) Bool
   (ite (and (= x!0 Epoch!val!0) (= x!1 Epoch!val!1))
      false
    (ite (and (= x!0 Epoch!val!0) (= x!1 Epoch!val!2))
      false
    (ite (and (= x!0 Epoch!val!2) (= x!1 Epoch!val!1))
      false
      true))))

As you can see, the model declares its universe, and gives the definition of le.
Since this is CEGIS, I will have multiple such models (counter examples). Since this is SAT based synthesis, I am encoding these counter examples into a SAT (well, SMT) query, and asking the solver to synthesize my function. Say, I know the template of the function I'm synthesizing, and it is either le(Epoch, Epoch) or not(le(Epoch, Epoch)). Then I will encode this as an SMT query like below:
<declarations>

(declare-const rev_ord Bool)
(declare-const to_not Bool)

(define-fun inv ((e1 Epoch) (e2 Epoch)) Bool
  (ite (and (not rev_ord) (not to_not))
       (le e1 e2)
  (ite (and (not rev_ord) to_not)
       (not (le e1 e2))
  (ite (and rev_ord (not to_not))
       (le e2 e1)
  (ite (and rev_ord to_not)
       (not (le e2 e1))
  )))))

<constraints??>

(check-sat)
(get-value rev_ord to_not)

Here, encoding the constraints is the tricky part. If I have two counter examples, I want two constraints, each asserting that the synthesized function satisfies the counter example model. To encode the constraints, I've decided that the best approach ahead is to write the SAT query like this:
(declare-sort ModelId)
(declare-sort Epoch)

(declare-fun M0 () ModelId)
(declare-fun M1 () ModelId)

(declare-fun Epoch!val!1 (ModelId) Epoch)
(declare-fun Epoch!val!2 (ModelId) Epoch)
(declare-fun Epoch!val!0 (ModelId) Epoch)

(declare-const rev_ord Bool)
(declare-const to_not Bool)

;;
;; Notice the addition of the model id
;;
(define-fun inv ((m ModelId) (e1 Epoch) (e2 Epoch)) Bool
  (ite (and (not rev_ord) (not to_not))
       (le m e1 e2)
  (ite (and (not rev_ord) to_not)
       (not (le m e1 e2))
  (ite (and rev_ord (not to_not))
       (le m e2 e1)
  (ite (and rev_ord to_not)
       (not (le m e2 e1))
  )))))

; counter example 1.
; Format: (and <model_description> <function_requirements>)

(assert (and
    (and
          (= (le (Epoch!val!0 M0) (Epoch!val!1 M0)) false)
          (= (le (Epoch!val!0 M0) (Epoch!val!2 M0)) false)
          (= (le (Epoch!val!2 M0) (Epoch!val!1 M0))  true)
    )
    (and
         (inv M0 (Epoch!val!0 M0) (Epoch!val!1 M0))
         (inv M0 (Epoch!val!0 M0) (Epoch!val!2 M0))
         (inv M0 (Epoch!val!2 M0) (Epoch!val!1 M0))
    )
))

; similarly, counter example 2

(check-sat)
(get-value rev_ord to_not)

To summarize: I get counter example models, which I want to feed into a synthesis query, but I want to tag the model's uninterpreted functions and constants with that model's "ID", so that the synthesis engine doesn't give me meaningless functions.


text:
Q: Groupmembership powershell I am trying to export Group membership - following is the script , however is it possible to
put a filter based on User ID , like, I want to export all users, prefix with K
$FilePath = "c:/data/ADGroupmembership_09feb.csv"
$OuDomain = "DC=test, DC=abc, DC=com"
Get-QADUser -searchRoot $OuDomain -SizeLimit 0 | Select-Object dn, sAMAccountName, @{Name="Groups";Expression={(Get-QADMemberOf $_ | Select-Object -expandProperty Name) -join ";"}} | export-csv $FilePath | Sort-Object SamAccountName

==================================================
for example
samaccountname=*K*

or
$OuDomain = "CN=*K*,DC=test, DC=abc, DC=com"

Regards
Naveen

A: Try this:
 Get-QADUser -SamAccountName k* -searchRoot $OuDomain -SizeLimit 0 | Select-Object dn, sAMAccountName, @{Name="Groups";Expression={(Get-QADMemberOf $_ | Select-Object -expandProperty Name) -join ";"}} | export-csv $FilePath | Sort-Object SamAccountName


text:
Q: After transmission of text files blank lines appears in them EDIT: Filezilla caused the problem, when i download files back from server it added new lines. I'm sorry for confusion.

This method upload files to ftp server and it's work fine, but in text files uploaded to server blank lines appear after every line("cr lf" appear), for example:
File:
First line
Second line
Third line

Uploaded file:
First line

Second line

Third line

Origin and uploaded files accordingly have different sizes, non-text files are the same.
Code:
private void sendFile(string In, string Out)
{
    FtpWebRequest request = (FtpWebRequest) WebRequest.Create("ftp://domain//" + Out);
    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.Credentials = new NetworkCredential("username", "password");

    FileStream sourceStream = new FileStream(In, FileMode.Open, FileAccess.Read, FileShare.Read);
    byte[] fileContents = new byte[sourceStream.Length];
    sourceStream.Read(fileContents, 0, (int) sourceStream.Length);
    sorceStream.Close();

    request.ContentLength = fileContents.Length;
    Stream requestStream = request.GetRequestStream();
    requestStream.Write(fileContents, 0, fileContents.Length);

    requestStream.Close();
}

How can i fix this?

A: EDIT: As the answer below doesn't seem to have helped (but I'm leaving it there for posterity as it shows better code) here are the next diagnostics steps I'd check:

*

*How are you viewing the files? If at all possible, get onto the server directly rather than fetching the files again via a web browser or whatever.

*What's the type of FTP server you're connecting to? Maybe there's a known issue.

*Have you tried looking at what's actually being sent via Wireshark?

*Have you tried sending the same files via a normal FTP client?

You should set FtpWebRequest.UseBinary to true in order to preserve the exact file contents. Otherwise the two systems will try to figure out line endings themselves, changing line terminators as they see fit. I very rarely think that's a good idea. (EDIT: UseBinary is actually true by default, but this sounds like the kind of problem introduced by using text mode... it certainly does no harm to make this explicit.)
Additionally:

*

*You should be disposing of your FileStream via a using statement

*You should be disposing of the request stream via a using statement

*You should be taking note of the result of Stream.Read - it needn't always read the whole of the requested data in one go

*You can either use File.ReadAllBytes to simply read the complete file data in one go, or use Stream.CopyTo (if you're using .NET 4) to copy the FileStream to the request stream (which won't set the content length, of course; I don't know whether this is a problem)

*You're never calling GetResponse; it's unclear exactly what happens if you never fetch the response of an FtpWebRequest

*Your parameter names don't match .NET naming conventions, and aren't very descriptive

So I would probably use:
private void SendFile(string inputFile, string outputPath)
{
    FtpWebRequest request = (FtpWebRequest) WebRequest.Create
        ("ftp://domain//" + outputPath);
    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.UseBinary = true;
    request.Credentials = new NetworkCredential("username", "password");

    byte[] fileContents = File.ReadAllBytes(inputFile);
    request.ContentLength = fileContents.Length;

    using (Stream requestStream = request.GetRequestStream())
    {
        requestStream.Write(fileContents, 0, fileContents.Length);
    }

    // This *may* be necessary in order to validate that everything has happened
    using (WebResponse response = request.GetResponse())
    {
    }
}

A: Its strange. I face the same problem and I was unable to fix it until I did not provide an extension in file. For Example if my file name was
abcfile
then I make it abcfile.dat and after that it shows me the uploaded file as actual file. I again upload file with abcfile.txt but this time again empty line problem appear in my uploaded file.
I suggest that you must provide extension to your file any except .txt.

A: The system that you're sending to uses different line endings to what your system uses. I can assume, because you get an extra line, that you're on Windows, and it uses CRLF endings. The system you're sending to recognises CR and LF as separate endings, so you get the extra lines.
For text, truncate the LF or the CR, see what happens. I have no clue about the differing file sizes.

A: In the top menu of FileZilla, set:
Transfer menu > Transfer type > binary

A: In the top menu of FileZilla, set:
Transfer menu > Transfer type > binary

It's working for me.


text:
Q: matching across line breaks and multiple line breaks I have a list of two character values, each on its own line in Notepad++. I am trying to eliminate the duplicates, but what I have written is only matching characters that are one line apart.
So if my list looks like this:
ME, <- not matched
OR,   |
ME, <- not matched
RI,
IL,
SD,
NV,
VA,
VA,
NY,
MN,
IL,
CA,
MI,
MO, <- match
MO, <- match

Right now I am using this. How can I modify it so it finds duplicated results more that one line apart as well
((\w{2}).*(\r\n)(\2))+

EDIT
((\w{2}).*(\r\n))(.*\r\n)+\1 This seems to work a bit better.

A: if you check the checkbox "dot matches newline", you will get three matches:
ME, <-  matched
OR,   |
ME, <-  matched
RI,
IL, <-  matched
SD,   |
NV,   |
VA,   |
VA,   |
NY,   |
MN,   |
IL, <-  matched
CA,
MI,
MO, <- matched
MO, <- matched

but this won't help you to remove duplicates..

A: (\w{2}),[^\1]*(\1),

Debuggex Demo
This i believe is the closest you'll ever get it.
EDIT: I LIED, lol this will work.  I'm not sure what language you are using but so ill give you psuedo code.
Essentially,
pattern = "(\w{2}),[^]*(\1),";
compile(pattern);
while(match(pattern, input)){
     //replace input's group 2 with a "" and remove /r/n
}

This will keep running through the code until you have no duplicates left.

A: Maybe that's not the preferred answer, but I would write a small python script to accomplish this task...
my_file = """ME,
OR,
ME,
RI,
IL,
SD,
NV,
VA,
VA,
NY,
MN,
IL,""" #replace by my_file = file("filename.txt", "r")
my_set = set()
for line in my_file.splitlines():
    my_set.add(line)
print my_set #just for demonstartion
out_file = file("C:\\Users\\burgert\\Desktop\\outfile.txt", "w")
for s in my_set:
    s += "\n"
    out_file.writelines(s)
out_file.close()


text:
Q: Confused by output of cat /proc/stat I'm on a university server running Centos 6.10. I'm trying to calculate the amount of time that the system has been in idle task. Im looking at the /proc/stat pseudo file. According to the man page the 4th column in the 1st row is supposed to be the amount of time the system has spent idle in 100ths of a second.
The issue I'm having is that this value is extremely large. When I divide it by 100 to get the seconds, and then divide that result by 60^2*24 (number of seconds in a day) to get the number of days, the resulting answer is longer than the uptime of the system.
In a nutshell this value, the way that I'm calculating it, is telling me that the system has been in idle for longer than it's been up.

A: It's the sum of the idle times on all cpus.
The first cpu line of /proc/stat is followed by cpu0, cpu1 similar lines for each online cpu. This is documented in newer versions of the proc(5) manpage.
Notice that not all cpus may be online, but the idle value from the first/system entry (as its equivalent in seconds from the second field of /proc/uptime) is calculated for all the possible cpus [1].
So you can divide it by the number of cpus to get something like an average.
One way to get the number of present, possible, on and offline cpus, is to look at the files /sys/devices/system/cpu/ directory.

[1] you can have a look at the fs/proc/stat.c in the source:
static int show_stat(struct seq_file *p, void *v)
{
        ...
        for_each_possible_cpu(i) {
                ...
                idle += get_idle_time(kcs, i);
        ...
        seq_put_decimal_ull(p, "cpu  ", nsec_to_clock_t(user));
        ...
        seq_put_decimal_ull(p, " ", nsec_to_clock_t(idle));
        ...
        for_each_online_cpu(i) {
                ...
                seq_printf(p, "cpu%d", i);
                ...
                idle = get_idle_time(kcs, i);
                ...
                seq_put_decimal_ull(p, " ", nsec_to_clock_t(idle));


text:
Q: Add lib dependencies to Axis2 web service when generating aar file I've created an Axis2 Service Project with Developer Studio 3.7.1.
The structure of the project is the following:
ProjectName
-->\src
---->\main
------>\java
-------->Source Code of the web service
------>\resources
-------->\META-INF
---------->services.xml
-->\lib
-->Jar dependencies of the web service

From the Project Explorer, when I right-click in the project and select "Export Project as Deployable Archive" to generate the aar file, it not contains the lib with the dependencies and I have to add them by hand before deploy the aar to the Axis2 server repository.
My question is how can be added those dependencies automatically?

A: Put your lib directory under ProjectName/src/main/resources will package your lib into aar file.


text:
Q: Passing x-ms-routing-name query parameter to app service through app gateway We've deployed our api app on Azure with a private endpoint.  The service is accessible by a custom domain through our app gateway.  We'd like to take advantage of a deployment slot we're calling 'release' but when testing using the x-ms-routing-name query parameter it doesn't work using the custom domain.
This works
https://myservice.azurewebsites.net/path/?x-ms-routing-name=release
But this doesn't
https://example.com/path/?x-ms-routing-name=release
Do we need to looking into rewrite rules in the app gateway or is there other configuration we need to look at first?
After taking a closer look at the cookie it only applies to the azure url

A: In case anyone else is facing this situation we resolved the issue by adding rewrite rules in our app gateway.
Added a condition to check if "x-ms-routing-name=release" is in the url query string
and if it is rewrite the response header and set the following cookie
x-ms-routing-name=release; path=/; HttpOnly; Max-Age=3600; Secure; SameSite=None

Add another rule to handle when x-ms-routing-name=self is in the url


text:
Q: How do I use a boolean operator in a case statement? I just Don't understand how to use a boolean operator inside a switch statement
switch (expression) {
        case > 20:
            statements
            break;
        case < -20:
            statements
            break;
    }

Edit:
I don't want an If () statement.

A: switch ((expression) > 20) {
        case true:
            statements
            break;
        case false:
        default:
            statements
            break;
    }

What.. you want more than 1 boolean in a case?   You could do this
int ii = ((expression) > 20) + 2 * ((expression) < -20);
switch (ii) {
        case 1:
            statements
            break;
        case 2:
            statements
            break;
    }

This, IMO is pretty bad code, but it is what you asked for...
Just use the if statement, you'll be better off in the long run.

A: You can't. Use if() ... else ....
The nearest thing available to what you want uses a GCC extension and is thus non-standard. You can define ranges in case statements instead of just a value:
switch(foo)
{
    case 0 ... 20: // matches when foo is inclusively comprised within 0 and 20
         // do cool stuff
         break;
}

However, you can't use that to match anything under a certain value. It has to be in a precise range. Switches can only be used to replace the comparison operator against a constant, and can't be used for anything more than that.


text:
Q: Android Annotation Processor accessing Annotated classes from different modules I'm having an Android Studio project with 2 modules: A and B. (I do not include here the Annotation Processor and the Annotations module)
B depends on A.
B is an Android Library Module, and A is simple Java library Module. I'm also having an Annotation Processor on module B.
The problem I'm facing is:
I want to generate some code, based on annotated files placed in both modules - A and B. The problem comes from the way the Annotation Processor works - only with source code files *.java - not with compiled *.class ones. Unfortunately, during the compilation of B, the Annotation Processor doesn't have access to those source files from A...
The only thing, I was able to think about as a kind of solution, even an ugly one, was to include the folder with the annotated classes from module A as a source set to module B. This way I give module B access to those files during compilation.
sourceSets {
    main {
        java {
            srcDirs = ['src/main/java', '../module_A/src/main/java/path/to/annotated/classes/folder']
        }
    }
}

That solves the problem - now the Annotation Processor has access to all the annotated classes from both modules, but...
Unfortunately, it introduces another issue... those annotated classes from module A, are now compiled twice. And they are included in the module A's JAR file and in the module B's AAR file.
Question 1: Is there another way to access those source files of module A, from the Annotation Processor running on B??? (From what I was able to find, the answer is NO, but checking...)
Question 2: How can I exclude those compiled files (the repeated ones) from the AAR final package of module B?
Question 3: Maybe... that's an absolutely wrong approach? Any suggestions?
Thanks in advance!

A: Nop, you can not achieve what you want using just java.lang.model API. At least not without some additional tricks.
The issues is not with binary-vs-source. Annotation processors can use Elements#getTypeElement to interospect compiled classes as well as source-defined classes:
Elements elementUtil = processingEnvironment.getElementUtils();
TypeElement integerClass = elementUtil.getTypeElement("java.lang.Integer");
TypeElement myClass = elementUtil.getTypeElement("currently.compiled.Class");

But you still need to have class on compilation classpath to observe it, and the class must be in process of being compiled to be visible to getElementsAnnotatedWith.
You can work around later limitation by using a tool like FastClasspathScanner: it will use it's own mechanisms to find annotations in compiled bytecode, and report them to you separately from compilation process. But you can not work around the classpath issue: if you don't have some dependency in compilation classpath, it can not be processed. So you have to compile modules together — either by merging them into one (as you did) or via declaring one to depend on another. In later case you might not be able to use getElementsAnnotatedWith, but getTypeElement and FastClasspathScanner will work.


text:
Q: Why doesn't MinGW's linker recognise libgslcblas.dll.a? Solution: I can now include libgsl and libgslcblas when I compile minimal code in the /home/HORTICULTIST location in cygwin's directory. Before I set the environment variables in Windows when I should've used export in cygwin's interface.
I'm trying to compile a C/C++ library from github which depends on GSL, using MinGW version 9.2.0 and Cygwin, but we get the error below. I'm unfamiliar with makefiles, and the relevant Stack Overflow sugestion isn't magically fixing the issue in this case.
The error:
C:/cygwin64/lib/libgslcblas.dll.a: file not recognized: file format not recognized

The makefile:
CC = g++
LDFLAGS = -lgsl -lm -lgslcblas

LSOURCE = main.cpp corpus.cpp slda.cpp utils.cpp opt.cpp
LHEADER = corpus.h slda.h utils.h opt.h settings.h

slda: $(LSOURCE) $(HEADER)
      $(CC) $(LSOURCE) -o $@ $(LDFLAGS)

clean:  -rm -f *.o slda

What needs to change?
Thanks~


text:
Q: Custom page margins using print.js I am attempting to print payment receipt using thermal POS printer using Print.js library. I can successfully print the page using the printjs. But the print comes with extra margins as per A4 page.
Is there any way to print it to fit to 58mm with to page margins?
Also it would be very helpful if any alternatives to print using JavaScript are given. Following is my work.
HTML & JS
<button id="print-receipt">print to pos</button>

alpha

                Item
                Qty
                Price

                abc
                1
                120

                pqr
                2
                240

                xyz
                4
            360

A: 1- Instead of using printJS() with the default two arguments, you can pass an object as argument so:
printJS('invoice-print-div', 'html'); should be replaced with:
printJS({printable: 'invoice-print-div', type: 'html',style: ['@page { size: A4; margin: 0mm;} body {margin: 0;} h4 {margin:0}'],  targetStyles: ['*']});
Please note that when it comes to actual printing, the property style in the argument object is where you can pass your custom style that should be applied to the html being printed.
I have made a demo in stackblitz Please do check it out.
For more information you can check PrintJS configuration options
2- As you ask for some alternatives of PrintJS, You can checkout jsPDF Library and here some explanations about it.


text:
Q: New XML node with IXML I'm making a Windows 8 Metro Style test application using XML files. I have the reading of the file and nodes working including editing and deleting them.
The problem I'm facing now and can't figure out how to complete is the adding of a node.
Below here is the code I'm using for reading and saving.
private static async System.Threading.Tasks.Task<XmlDocument> LoadXML()
    {
        StorageFolder storageFolder = ApplicationData.Current.RoamingFolder;
        StorageFile storageFile = await storageFolder.GetFileAsync("Settings.xml");
        var XmlFile = await XmlDocument.LoadFromFileAsync(storageFile);
        return XmlFile;
    }

    private static async System.Threading.Tasks.Task SaveXML(XmlDocument XmlFile)
    {
        StorageFolder storageFolder = ApplicationData.Current.RoamingFolder;
        StorageFile storageFile = await storageFolder.GetFileAsync("Settings.xml");
        await XmlFile.SaveToFileAsync(storageFile);

        MessageDialog Message = new MessageDialog("Data is saved/removed!", "Notification");
        await Message.ShowAsync();
    }

This part below is of an event which refers to the two above. In this part of the code do I need to add a new node based on information from a textbox.
    private async void btnSaveproject_Click(object sender, RoutedEventArgs e)
    {
        var XmlFile = await LoadXML();

        await SaveXML(XmlFile);
    }

For those who wonder how I have done the removing and editing will I also add these part of the code right below here.
    // Removing
    IXmlNode Node = XmlFile.SelectSingleNode("XML").SelectSingleNode("List").SelectSingleNode(lvList.SelectedItem.ToString());
    XmlFile.SelectSingleNode("XML").SelectSingleNode("List").RemoveChild(Node);

    //Saving
    XmlFile.SelectSingleNode("XML").SelectSingleNode("Colors").SelectSingleNode("ColorR").InnerText = tbxColorR.Text;


text:
Q: Goodness of fit test for logistic model I want know what g means and why use Lemeshow goodness of fit (GOF) test in Research ??  and what wrong in "confusion matrix for logistic regression ?
this message :

Error in confusionMatrix(cnfmat) :
    could not find function "confusionMatrix"

# ..Binary Logistic Regression :

install.packages("caTools")
library(caTools)
require(caTools)
sample = sample.split(diabetes$Outcome, SplitRatio=0.80)
train = subset(diabetes, sample==TRUE)
test = subset(diabetes, sample==FALSE)
nrow(diabetes) ##calculationg the total number of rows
nrow(train) ## total number of Train data rows >> 0.80 * 768
nrow(test) ## total number of Test data rows   >> 0.20 * 768
str(train) ## Structure of train set

Logis_mod<- glm(Outcome~Pregnancies+Glucose+BloodPressure+SkinThickness+
                  Insulin+BMI+DiabetesPedigreeFunction+Age,family = binomial,data = train)
summary(Logis_mod)
#AIC .. Akaike information criteria ...
#A good model is the one that has minimum AIC among all the other models.

# Testing the Model
glm_probs <- predict(Logis_mod, newdata = test, type = "response")
summary(glm_probs)
glm_pred <- ifelse(glm_probs > 0.5, 1, 0)
summary(glm_pred)

#Avarge prediction for each of the Two outcomes ..
tapply(glm_pred,train$Outcome,mean)

# Confusion Matrix for logistic regression
install.packages("e1071")
library(e1071)
prdval <-predict(Logis_mod,type = "response")
prdbln <-ifelse(prdval > 0.5, 1, 0)
cnfmat <-table(prd=prdbln,act =train$Outcome)
confusionMatrix(cnfmat)

#Odd Ratio :
exp(cbind("OR"=coef(Logis_mod),confint(Logis_mod)))

A: I'm not sure what "g" you are referring to, but I'm going to assume it's your resulting computed statistic from your Lemeshow test.  If this is the case then values of "g" indicate how well a model explains the variability in the data and can be used to compare models based on the same set of data (better models will have larger "g" values).
More generally, any goodness of fit (GOF) test in research is used to determine how well your model fits the variability in your data.
Additionally, you are receiving your error because the confusionMatrix() function is a part of the caret R package.  Install caret by first running the below line of code in R or RStudio.
install.packages("caret")

Then in your code change
cnfmat <-table(prd=prdbln,act =train$Outcome)
confusionMatrix(cnfmat)

to
cnfmat <-data.frame(prd=prdbln,act =train$Outcome, stringsAsFactors = FALSE)
caret::confusionMatrix(cnfmat)


text:
Q: OpenGL (using SOIL) always loads the same image When I load an image, the next image loaded for something else is the same image.
Basically:
I'm making a Pong replica and there is a texture for the paddle and for the ball (yes I have made sure that they are both different). You can find the source code here. The paddle loads an image fine, but when it comes to the ball it loads the same exact image as the paddle (Paddle = Paddle.cpp , Ball = Ball.cpp).
What could possibly be wrong with it? Am I using SOIL incorrectly?

A: From source:
glBindTexture(PadImg , GL_TEXTURE_2D);
This is way wrong, it should be
glBindTexture(GL_TEXTURE_2D, PadImg);
You should get familiar with glGetError, it will help you find problems like this.
Also, these calls are in the wrong order:
glVertex2f(-w,-10);
glTexCoord2f(0,0);

glVertex should always be the last function called per vertex (normals and texcoords come first).


text:
Q: Let $f : (X, A) → (Y, B)$ be a map such that both $f : X → Y$ and $f : A → B$ are homotopy equivalences. Let $f : (X, A) → (Y, B)$ be a map such that both $f : X → Y$ and $f : A → B$ are
homotopy equivalences. Show that $f_∗ : H_n(X, A) → H_n(Y, B)$ is an isomorphism
for all $n$.
I know that there is a function $g:Y\to X, g:B\to A$ such that $fg\simeq Id_Y, gf\simeq  Id_X$ and that $fg\simeq Id_B$ and $gf\simeq Id_A$. Is it true $g:(Y,B)\to (X,A)$ is the homotopic inverse of $f:(X,A)\to (Y,B)$? Thanks!

A: It is not necessarily true that $f$ is a homotopy equivalence of pairs--the homotopy $fg\simeq Id_Y$ may not map $B$ to itself at all times, for instance.  (We know that there does exist a homotopy $fg\simeq Id_B$ restricted to $B$, but that homotopy need not be the restriction of our homotopy on all of $Y$.)
Instead, you can use the long exact sequence of homology for the pairs.  There is a commutative diagram
$$\require{AMScd}
\begin{CD}
H_n(A) @>{}>> H_n(X) @>>> H_n(X,A) @>>>H_{n-1}(A) @>{}>> H_{n-1}(X)\\
@VVV @VVV @VVV @VVV @VVV\\
H_n(B) @>{}>> H_n(Y) @>>> H_n(Y,B) @>>>H_{n-1}(B) @>{}>> H_{n-1}(Y)
\end{CD}$$
where the rows are exact and the vertical maps are all induced by $f$.  By hypothesis, all the vertical maps except the middle one are isomorphisms, so the middle one is an isomorphism too by the five lemma.

A: The question about homology is answered by Eric.
The question of obtaining a homotopy equivalence of pairs assuming $A \to X, B \to Y$ are cofibrations is answered  by 7.4.2 of Topology and Groupoids,(T&G),  and the Addendum to that result shows how the homotopy inverse to $f$, and the homotopies, may be constructed from the given data. That answers your question on $g$. Here is a slightly transliteratwed version of that Addendum_:
Let $g^{0} :
B  \to A$ be any homotopy inverse of $f^{0}:A \to B$ and let
$H^{0}_{t} : f^{0}g^{0} \simeq 1$, $K^{0}_{t} : g^{0}f^{0} \simeq 1$
be homotopies.  Then $g^{0}$ extends to a homotopy inverse $g':Y  \to X$ of
$f$ such that the homotopy $fg'\simeq 1$ extends $H^{0}_{t}$ while
the homotopy $g'f\simeq 1$ extends the sum
$$
K^{0} + g^{0}H^{0}f^{0} - g^{0}f^{0}K^{0}
$$
of the homotopies
$$
g^{0}f^{0} = g^{0}f^{0}1_{A} \simeq g^{0}f^{0}g^{0}f^{0}
\simeq g^{0}1_{B}f^{0} \simeq 1_{A}
$$
determined by $H^{0}_{t}$ and $K^{0}_{t}$.
I do not know of examples showing that the description of the homotopies cannot be simplified. However the explicit form has useful implications, for example if $H,K$ are constant homotopies, and also to a gluing theorem (7.4.3 of T&G). It is not clear if $g'$ is homotopic to $g$.
These results were found in the 1960s by generalising the well known  result that a homotopy equivalence $f: X \to Y$ induces an isomorphism of homotopy groups  $\pi_n(X,x) \to \pi_n(Y, f(x))$. That proof involves an operation of  fundamental groups on homotopy groups, so the more general result uses a more general operation, as in T&G,  compare  Section 5.2 of tom Dieck's "Algebraic Topology".


text:
Q: Asymptotics of $\sum_{i=0}^{n} \frac{i n^i}{i!}$. How can you calculate the asymptotics of $\sum_{i=0}^{n} \frac{i n^i}{i!}$ ?  This sum looks similar to the power series for $e^n$. I have also seen similar problems solved using Poisson distributions  Limit using Poisson distribution for example. However I cannot see how to handle the extra term.

A: $$\sum_{i=0}^{n} \frac{i n^i}{i!}
= \sum_{i=1}^{n} \frac{n^i}{(i-1)!}
= \sum_{i=0}^{n-1} \frac{ n^{i+1}}{i!}
= n\sum_{i=0}^{n-1} \frac{ n^{i}}{i!}
$$
Since, as shown in the linked problem,
$$e^{-n}\sum_{k=0}^n\frac{n^k}{k!}
=\frac12+O(n^{-1/2})
$$
$$\sum_{i=0}^{n} \frac{i n^i}{i!}
= n(\sum_{i=0}^{n} \frac{ n^{i}}{i!}-\frac{ n^{n}}{n!}),
$$
so
$$\begin{align}
e^{-n}\sum_{i=0}^{n} \frac{i n^i}{i!}
&= e^{-n}n(\sum_{i=0}^{n} \frac{ n^{i}}{i!}-\frac{ n^{n}}{n!})\\
&=n(1/2 +O(n^{-1/2})) - n e^{-n}\frac{ n^{n}}{n!}\\
&= n/2 + O(n^{1/2}) - n \frac{(n/e)^n}{\sqrt{\pi}(1+O(1/n)) n^{n+1/2}/e^n}\\
&= n/2 + O(n^{1/2}) - n (n/e)^n/(\sqrt{\pi}(1+O(1/n)) n^{n+1/2}/e^n)\\
&= n/2 + O(n^{1/2}) - n^{1/2}(1+O(1/n))/\sqrt{\pi}\\
&= n/2 + O(n^{1/2})
\end{align}
$$


text:
Q: Point actions to the same view I have a controller with the following actions...
public ActionResult YellowList()
public ActionResult RedList()
public ActionResult BlueList()
All these actions populate the same viewModel (ListViewModel).
How do I get them all to point to the same view (aspx)?
Thanks,
ETFairfax.

A: In your action use this overload of the view method:
public ActionResult YellowList()
{
    ListViewModel model = GetSomeModel();
    return View("viewName", model);
}

public ActionResult RedList()
{
    ListViewModel model = GetSomeModel();
    return View("viewName", model);
}

public ActionResult BlueList()
{
    ListViewModel model = GetSomeModel();
    return View("viewName", model);
}

A: Here is Controler:
public class ColorsController : Controller
{
    //
    // GET: /Colors/

    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Red()
    {
        ViewData["Color"] = "Red";
        return View("ColorName");
    }

    public ActionResult Green()
    {
        ViewData["Color"] = "Green";
        return View("ColorName");
    }
}

Here is View:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

ColorName

You Selected: <%= ViewData["Color"] %>

</asp:Content>


text:
Q: Issue loading data from csv file - Java As it stands I have a data set in the form of a .csv file which you can find here. Also there is some brief documentation on it which you can find here. What I am attempting to do is to manipulate the data set so that I can work with some machine learning algorithms but as it stands I can't seem to print the outputted data to the console
ImageMatrix.java
import java.util.Arrays;

public class ImageMatrix {
    public static int[] data;
    public int classCode;
    public ImageMatrix(int[] data, int classCode) {
        assert data.length == 64;

    }

    public String toString() {
        return "Class Code: " + classCode + " DataSet:" + Arrays.toString(data) + "\n";
    }

    public int[] getData() {
        return data;
    }

    public int getClassCode() {
        return classCode;
    }

}

ImageMatrixDB.java
import java.io.*;
import java.util.*;

public class ImageMatrixDB implements Iterable<ImageMatrix> {
    List<ImageMatrix> list = new ArrayList<ImageMatrix>();

    public static ImageMatrixDB load(String f) throws IOException {
        ImageMatrixDB result = new ImageMatrixDB();
        try (FileReader fr = new FileReader(f);
             BufferedReader br = new BufferedReader(fr)) {
            for (String line; null != (line = br.readLine()); ) {
                int lastComma = line.lastIndexOf(',');
                int classCode = Integer.parseInt(line.substring(1 + lastComma));
                int[] data = Arrays.stream(line.substring(0, lastComma).split(","))
                                   .mapToInt(Integer::parseInt)
                                   .toArray();
                result.list.add(new ImageMatrix(data, classCode));
            }
            System.out.println(ImageMatrix.data.toString());
        }
        return result;
    }

    public Iterator<ImageMatrix> iterator() {
        return this.list.iterator();
    }
    public static void main(String[] args){
        ImageMatrixDB i = new ImageMatrixDB();
        i.load("dataset1.csv"); // <<< ERROR IS HERE
    }
}

The error is within my main function on the line i.load(... I know I must be missing something or have made a mistake somewhere, I have tried altering the data from static but it just throws more errors and I can't figure it out. Any ideas?

A: Your issue is in the ImageMatrix class.
You never set the int[] data in the constructor. You have:
    public ImageMatrix(int[] data, int classCode) {
        assert data.length == 64;

    }

You need:
    public ImageMatrix(int[] data, int classCode) {
        assert data.length == 64;
        this.data = data;
        this.classCode = classCode;
    }

Here is your updated/complete/working code:
ImageMatrix:
import java.util.*;

public class ImageMatrix {
    private int[] data;
    private int classCode;

public ImageMatrix(int[] data, int classCode) {
    assert data.length == 64;
    this.data = data;
    this.classCode = classCode;
}

    public String toString() {
        return "Class Code: " + classCode + " DataSet:" + Arrays.toString(data) + "\n";
    }

    public int[] getData() {
        return data;
    }

    public int getClassCode() {
        return classCode;
    }

}

ImageMatrixDB:
    import java.util.*;
    import java.io.*;

    public class ImageMatrixDB implements Iterable<ImageMatrix> {
        private List<ImageMatrix> list = new ArrayList<ImageMatrix>();

        public ImageMatrixDB load(String f) throws IOException {
            try (
                FileReader fr = new FileReader(f);
                BufferedReader br = new BufferedReader(fr)) {
                String line = null;

                while((line = br.readLine()) != null) {
                    int lastComma = line.lastIndexOf(',');
                    int classCode = Integer.parseInt(line.substring(1 + lastComma));
                    int[] data = Arrays.stream(line.substring(0, lastComma).split(","))
                                       .mapToInt(Integer::parseInt)
                                       .toArray();
                    ImageMatrix matrix = new ImageMatrix(data, classCode);
                    list.add(matrix);
                }
            }
            return this;
        }

        public void printResults(){
            for(ImageMatrix matrix: list){
                System.out.println(matrix);
            }
        }

        public Iterator<ImageMatrix> iterator() {
            return this.list.iterator();
        }
        public static void main(String[] args){
            ImageMatrixDB i = new ImageMatrixDB();
            try{
                i.load("cw2DataSet1.csv");
                i.printResults();
            }
            catch(Exception ex){
                ex.printStackTrace();
            }
        }

    }

A: Your load method can throw an IOException. You need to catch it in order to successfully compile
public static void main(String[] args){
    ImageMatrixDB i = new ImageMatrixDB();
    try{
        i.load("dataset1.csv"); // <<< ERROR IS HERE
    }
    catch(Exception e){
        System.out.println(e.getMessage());
    }
}


text:
Q: R plot: Print text on margin in top left corner I have the following basic code to plot a grid.
grid <- expand.grid( pi=seq(50, 95, 5) / 100, mu2=seq(5, .5, -.5) )
pi <- seq(44, 100, .5) / 100
par( mai=c(.05, .05, .05, .05), oma=c(2.9, 2.9, 0, 0) ) # Make room for label
plot( grid, cex=.5, xlab="", ylab="", cex.axis=.7 )

How can I plot a text label such as "(A)" in the top left corner as indicated by the red circle?
Edit: The "(A)" should be printed in regular, i.e., horizontal, reading direction; not vertically along with the y-axis.

A: You can use mtext to place text outside of the margins:
##Look at the help page for further details
mtext("A", 2, adj=1, line=2)

##To rotate "A", try
mtext("A", 2, adj=5, las=1, padj=-22)

to get:

A: You may try this:
text(x = 0.44, y = 5, labels = "(A)", xpd = NA)

See also ?par how you can adjust plot margins with mar, if you need more space for the text.


text:
Q: how to mix two digits from URL php I have two variables from URL.
ie, $_GET["pro_id"] and $_GET["pro_page"] and
$_GET["pro_id"] = 1,2,3,4, and
$_GET["pro_page"] = 1,1,1,3,
I have separated these variables as
$pro_id = $_GET["pro_id"];
$pro_id = explode(",", $pro_id);

foreach($pro_id as $key) {
    echo $key.'
';
}

$pro_page = $_GET["pro_page"];
$pro_page = explode(",", $pro_page);

foreach($pro_page as $key) {
    echo $key.'
';
}

and the output for pro_id is
    1
    2
    3
    4
and for pro_page is
    1
    1
    1
    3
and I want to mix the first digit from pro_id and first digit from pro_page.
ie,
select * from db_table where row1=1 and row2=1
select * from db_table where row1=2 and row2=1
select * from db_table where row1=3 and row2=1
select * from db_table where row1=4 and row2=3

how to achieve this. Is there any solution.

A: This should work for you although those are some strange $_GET parameters.
$pro_id = $_GET["pro_id"];
$pro_id = explode(",", $pro_id);

$pro_page = $_GET["pro_page"];
$pro_page = explode(",", $pro_page);

foreach($pro_id as $idx => $value) {
    $proid = $value;
    $propage = $pro_page[$idx];

    //QUERY HERE
    echo $proid." ".$proage;
}

A: To be more reliable, use foreach
foreach($propage as $key => $value)
{
    $sql = "SELECT * FROM db_table WHERE row1 = '".$pro_id[$key]."' AND row2='".$propage[$key]."'";
}


text:
Q: Export embedded media from Apple Numbers to Path AppleScript I want to export embedded media from Apple Numbers to Path with AppleScript. It should only export media like embedded PDF;PNG;JPG;audiorecord from the current Table from the active Sheet. I dont want a package from all media. All media should remain in there specific datatype in one directory.
At this time i can count the media, get there names... but i cant export those

A: I can suggest one possible solution for saved .numbers documents.
-- Choose "numbers" file
set numbersFile to choose file of type "numbers"

-- Choose destination folder
set destinationFolder to (choose folder) as Unicode text

-- Get temporary items folder references
set tempFolder to path to temporary items folder from user domain

-- Unzip to temporary items folder, then Move to destination folder
do shell script "/usr/bin/unzip -o -d " & ¬
    quoted form of (POSIX path of tempFolder) & ¬
    space & ¬
    quoted form of (POSIX path of numbersFile)
try
    tell application "Finder" to ¬
        move files of folder "Data" of folder (tempFolder as Unicode text) to ¬
            folder destinationFolder replacing yes
end try


text:
Q: Google Apps Script [Form Response Data] I have made a form to capture 2 data.
1) Email address.
2) Group which user wants to subscribe to.
Each group has their own spreadsheet.
When a user submits the form, the form should capture the email address, and sends the data to the respective spreadsheet which the user subscribed to.
This is what I've done so far. I'm stuck..
function onFormSubmit() {
  var form = FormApp.getActiveForm();

  var formResponses = form.getResponses();
  for (var i = 0; i < formResponses.length; i++) {
    var formResponse = formResponses[i];
    var itemResponses = formResponse.getItemResponses();
    for (var j = 0; j < itemResponses.length; j++) {
      var itemResponse = itemResponses[j];

      // Checks if it is multiple choice option
      if (itemResponse.getItem().getType() == FormApp.ItemType.MULTIPLE_CHOICE) {

        // If user chooses group 1, open spreadsheet and store user's email in 1st column
        if (itemResponse.getResponse() == "1") {
          var ss = SpreadsheetApp.openById("id goes here");
          var sheet = ss.getSheetByName("Group subscription email");
        }
      }

    }
  }
}

A: What is not happening that you want to happen?  How to match the choice in the form to what spreadsheet to write to?
If so, you can hard code a object of all your spreadsheet IDs and match them to a form choice.
var objOfSpreadsheetIDs = {"1":"oicjo0948t09afoa", "2":"498hnxoiv7r6gahauvgi", "3":"uuiocvgofhgeoyuih"};
Logger.log("Check my object: " + objOfSpreadsheetIDs["3"])

So, your code might look something like this:
var objOfSpreadsheetIDs = {"1":"oicjo0948t09afoa", "2":"498hnxoiv7r6gahauvgi", "3":"uuiocvgofhgeoyuih"};

// If user chooses group 1, open spreadsheet and store user's email in 1st column
var whatGroupUserChoose = itemResponse.getResponse();
var whatSS_ID = objOfSpreadsheetIDs[whatGroupUserChoose];

var ss = SpreadsheetApp.openById(whatSS_ID);
var sheet = ss.getSheetByName("Group subscription email");


text:
Q: How can we export a common global opt out list from Sitecore EXM? I would like to see contacts in a common global opt out list. Is there a way to export the common global opt out list from  Sitecore EXM?
I checked in Dashboard from List Manager, but can not see any default common global opt out list.
Could you please advise me?

A: ManagerRoot class in EXM API has a GlobalSubscription property that contains an object of the GlobalSubscription type. This object can interact with the global opt-out list and using GetAllExcludeCollections() method you can retrieve a collection of all the global opt-out lists. Read more details here.


text:
Q: can't open static page in intellij after run the project(spring mvc) In the beginning, I can view the html just by the IntelliJ button like that

then when I click the button, IntelliJ shows a browser error

then I run tomcat, and click the browser button

I'm a beginner, and I don't know why it happens.

A: You need to run servlet container via Run configuration first.


text:
Q: pivot_longer but for multiple sets of columns I have a data frame as follows:
Z1      Z2      Y1      Y2      smpl
0.451   0.333   0.034   0.173   A
0.491   0.270   0.033   0.207   B

Columns Z1 and Z2 are multiple observations from the same sample. Same goes for Y1 and Y2.
I need to merge columns Z1 and Z2, and columns Y1 and Y2. yielding the following:
Z       Y       smpl
0.451   0.034   A
0.333   0.173   A
0.491   0.033   B
0.270   0.207   B

I am sure the solution is trivial, but... Well, I am a bit of a n00b, and hence I am also stuck. How can I do this?

A: You can use :
tidyr::pivot_longer(df, cols = -smpl,
                        names_to = '.value',
                        names_pattern = '([A-Z])')
# A tibble: 4 x 3
#  smpl    Z     Y
#  <chr> <dbl> <dbl>
#1 A     0.451 0.034
#2 A     0.333 0.173
#3 B     0.491 0.033
#4 B     0.27  0.207

A: you can try
library(tidyverse)
df %>%
  pivot_longer(matches("Z|Y")) %>%
  separate(name, letters[1:2], sep = 1) %>%
  pivot_wider(names_from = a,  values_from = value)
# A tibble: 4 x 4
  smpl  b         Z     Y
  <fct> <chr> <dbl> <dbl>
1 A     1     0.451 0.034
2 A     2     0.333 0.173
3 B     1     0.491 0.033
4 B     2     0.27  0.207

Or easier
df %>%
pivot_longer(matches("Z|Y"),
             names_to = c(".value", "b"),
             names_sep = 1)

if you don't need the information about subgroups of Y and Z you can finish the lines of code using select(-b)


text:
Q: One AVAudioPlayer to play multiple sounds without re-initialising? I'm wanting to use a single instance of an AVAudioPlayer to handle a few different quick sound effects, that could be triggered in any order, etc.
As far as I can see, the only way to change the audio file to be played is to re-initialise the player with initWithContentsOfURL:.
So, two questions: since that's what I'm doing now, is that alright? More overhead in re-allocating, etc. Should I care? And, is there a way to put all four files in there and tell it to just load them one at a time, but NOT sequentially (i.e. by using the AVQueuePlayer)?

A: If the files are short (which it sounds like), I recommend loading them into an AVAudioBuffer and scheduling these buffers to play on the AVAudioPlayer at the correct time.
See the WWDC talk on AVAudioEngine in Practice (transcript).


text:
Q: How to make values from input form not disappear after form is submitted using django I have a html table of variable dimensions in which every cell is
<input type = "number">

After the user has filled every cell and pressed submit, a result of some calculation should be printed in a h2 tag. As predicted every time user presses submit the content that was written inside the table is deleted. Is it possible to somewhat negate that so that after the user has pressed submit he gets the result outputted but his input in the table stays where it was? This is html of the template where all of this is happening:
{% extends "base.html" %}

{% block content %}

 Dimensions: {{ f_number }} X {{ s_number }}

    <form method = "post" action="/calculated/">{% csrf_token %}

        {% for i in range_first %}

            {% for j in range_second %}
                     <input type = "number" name = "{{ i }}{{ j }}">
            {% endfor %}

        {% endfor %}

        <input type = "Submit" value = "Calculate" name = "calc">

        {% if result %}

 The result is: {{ result }}.

        {% endif %}

    </form>

{% endblock content %}

This is my view function:
def calculate(request):
    if request.method == 'POST':

        content = request.POST.dict()
        stuff = calculator.MatrixCalculator(content)

        dimensions = stuff.dimensions_to_normal_form()
        array_numbers = stuff.numbers_to_normal_form()

        range_first = range(dimensions[0] + 1)
        range_second = range(dimensions[1] + 1)

        result = stuff.Rank(array_numbers, dimensions)

        return render(request, 'enter_number.html', {'result': result,
        'f_number': dimensions[0] + 1, 's_number': dimensions[1] + 1,
        'range_first': range_first, 'range_second': range_second})


text:
Q: Equivalent code of hash in .Net to Python 2.7 I have a code in .Net to generate HMAC SHA256 hash. I tried my best to get the equivalent code in Python 2.7 but it differs. Where am I going wrong?
.Net code
using System;
using System.Security.Cryptography;
using System.Text;
public class Program
{
    public static void Main()
    {
        var key = Guid.Parse("7a640e1f-df45-4652-a9d5-4bdc2003deac").ToByteArray();
        var payload = Encoding.UTF8.GetBytes("ab38eadaeb746599f2c1ee90f8267f31f467347462764a24d71ac1843ee77fe3#40011234567890##34567####MitErpNavn#34567#20170719192159");
        Console.WriteLine(key);
        Console.WriteLine(payload);
        for(var i = 0; i < key.Length;i++)
        {
            var b = key[i];
            Console.WriteLine(b);
        }
        using(var ha = new HMACSHA256(key))
        {
           var hash = ha.ComputeHash(payload);
           var result = Convert.ToBase64String(hash);
           Console.WriteLine(result);

        }
    }
}

Output: f0UqIWmJBea+rTixF1jiCNhEt12yPN4R7gJclYMM3mE=

Python 2.7
import hmac
import hashlib
import base64
import uuid

erp_key = '7a640e1f-df45-4652-a9d5-4bdc2003deac'
payload = 'ab38eadaeb746599f2c1ee90f8267f31f467347462764a24d71ac1843ee77fe3#40011234567890##34567####MitErpNavn#34567#20170719192159'
erp_uuid = uuid.UUID(erp_key)
dig = hmac.new(erp_uuid.bytes, msg=payload, digestmod=hashlib.sha256).digest()
hash_key = base64.b64encode(dig).decode()

print hash_key

Output: wI/WinRP4mHfHLnFCSHn6j4VphSOO8CjLqkAVJi1HTQ=

A: Finally I am able to fix the issue. I hope someone else can also get help from this
import hmac
import hashlib
import base64
import uuid
import array

erp_key = '7a640e1f-df45-4652-a9d5-4bdc2003deac'
payload = 'ab38eadaeb746599f2c1ee90f8267f31f467347462764a24d71ac1843ee77fe3#40011234567890##34567####MitErpNavn#34567#20170719192159'

erp_uuid = uuid.UUID(erp_key)
map_arr = array.array('B', erp_uuid.bytes_le)
makeitastring = "".join(chr(x) for x in map_arr)

dig = hmac.new(makeitastring, payload, hashlib.sha256).digest()
hash_key = base64.b64encode(dig).decode()

encodedSignature = base64.encodestring(dig).replace('\n', '')

print encodedSignature

Output: f0UqIWmJBea+rTixF1jiCNhEt12yPN4R7gJclYMM3mE=


text:
Q: Is it possible to create a new account type for OSX Mountain Lion OSX mountain lion provide a lots of account type including twitter, and many service for China(weibo, tudou and so on). But there no default facebook support for ML, I know I can install it.
My question is, is it possibility to make my own Service (Account or something else) for other website? Is there some APIs that can do such thing?


text:
Q: A-Frame grey border around transparent png image A-Frame is adding grey border around the opaque part of png image. Unable to figure out why this is happening. I would be glad to know if anyone has solved this issue.

A: Some artifacts may happen if you won't set the materials property transparency to true:
material="transparent:true; src:myImage.png"

check it out here

Here it's an issue with the image.
Link to your image here.
I've cut out a guy, check out the legs:


text:
Q: MS Teams Webhook ActionCard HttpPost get the user who submitted the post I have a incoming webhook that I sent a messageCard with several actioncards. I know how to post the data and value back to my server endpoint. I need to get the username of the user who pushed the button to submit the httppost. Here is the actioncard part of the code. It works. I just need to also know who submitted it, the MS Teams username.
{
"@type": "ActionCard",
"name": "Skip",
"inputs": [{
"@type": "TextInput",
"id": "skip",
"isMultiline": True,
"title": "Add a skip reason here"
}],
"actions": [{
"@type": "HttpPOST",
"name": "skip",
"target": "",
"body":"{"action":"skip","body":"{{skip.value}}}"}"
}]
}

A: Currently UPN is not sent part of the JSON body/payload, however it can be retrieved by decoding JWT token in Authorization header part of sender verification:
Service can validate the JWT and then extract claims and get the UPN as per below:
Security requirements for actionable messages - Outlook Developer | Microsoft Docs.
Also if you go through the Connector documentation, you'll see that the 'sub' parameter contains the Azure AD object ID. You can then call Get users Graph API to get the user details from AAD Id.


text:
Q: PreferenceActivity action bar background color Dears,
Look at the snapshot:

I use the following code to change the action bar background -same used in normal activities and works fine-:
@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);

    ActionBar actionBar = getActionBar();
    actionBar.setBackgroundDrawable(getResources().getDrawable(R.color.actionbar_background));
    actionBar.setIcon(R.drawable.ic_settings);

    setupSimplePreferencesScreen();
}

the problem is that the action bar background color changed to specified color, but the text and icon background take the activity background color.
What's wrong?

A: Change:
actionBar.setBackgroundDrawable(getResources().getDrawable(R.color.actionbar_background));

To:
actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.actionbar_background)));

A: This link help me to figure the problem:
My action bar title is taking the wrong color from theme
The problem was with setting Activity background color, instead of this:
<!-- Settings Activity -->

  <style name="SettingsTheme">
    <item name="android:Background">@color/main_menu_background</item>
    <item name="android:textColor">@color/font_color</item>
  </style>

I use this:
<!-- Settings Activity -->

  <style name="SettingsTheme">
    <item name="android:windowBackground">@color/main_menu_background</item>
    <item name="android:textColor">@color/font_color</item>
  </style>


text:
Q: Google App Engine Launcher not completing loading Good day all. First time stack overflow has not previously answered an issue that I have. My problem is exactly like the one posted here, except I am running windows:
Google App Engine Launcher is not running my hello world for Python Mac
The only thing the log gives me is this

2016-08-18 13:39:13 Running command:
  "['C:\Users\Kesi\Desktop\Documents\Computer
  Science\Udacity\Intro to backend\hello-udacity\main.py',
  'C:\Program Files (x86)\Google\google_appengine\dev_appserver.py',
  '--skip_sdk_update_check=yes', '--port=8080', '--admin_port=8000',
  'C:\Users\Kesi\Desktop\Documents\Computer Science\Udacity\Intro
  to backend\hello-udacity']"

Any suggestions are greatly appreciated.

A: Converting comments to an answer.
The 1st argument in the command list from your message is 'C:\Users\Kesi\Desktop\Documents\Computer Science\Udacity\Intro to backend\hello-udacity\main.py', preceeding the dev_appserver.py suggests a configuration problem.
In the google app engine preferences section there is a place to specify the path to executable python file. That should not be set to your app's python file (as you have it), but to the actual python executable (from your python installation) - which executes dev_appserver.py (the 2nd arg in the command list) which in turn loads the subsequent command list args including one which is the one specifying your app code's location - the last one in your case.
The python executable could be a python.exe or pythonw.exe according to the Executing scripts section of Using Python on Windows doc:

Python scripts (files with the extension .py) will be executed by
  python.exe by default. This executable opens a terminal, which stays open even if the program uses a GUI. If you do not want this to
  happen, use the extension .pyw which will cause the script to be
  executed by pythonw.exe by default (both executables are located
  in the top-level of your Python installation directory). This
  suppresses the terminal window on startup.


text:
Q: Symfony nginx virtual host I have a virtual server with nginx, with my Symfony project installed in /var/www/test. In /etc/nginx/site-avalible/test.conf I create this config:
server {
server_name test.dev www.test.dev;
root /var/www/test/web;

location / {
    # try to serve file directly, fallback to app.php
    try_files $uri /app.php$is_args$args;
}

location ~ ^/(app_dev|config)\.php(/|$) {
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_split_path_info ^(.+\.php)(/.*)$;
    include fastcgi_params;

    fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
    fastcgi_param DOCUMENT_ROOT $realpath_root;
}

location ~ ^/app\.php(/|$) {
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_split_path_info ^(.+\.php)(/.*)$;
    include fastcgi_params;

    fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
    fastcgi_param DOCUMENT_ROOT $realpath_root;

    internal;
}

location ~ \.php$ {
    return 404;
}

error_log /var/log/nginx/test_error.log;
access_log /var/log/nginx/test_access.log;
}

and then create symlink:
ln -s /etc/nginx/sites-available/test.conf /etc/nginx/sites-enabled/test.conf

and add rules to /etc/hosts:
127.0.0.1       test.dev

this is all done in the server. Then I know the IP of my virtual server and I create in my local computer in /etc/hosts:
82.91.183.61    test.dev

and then try to open in my browser but have a 502 error, why? And how can I correct the virtual host config for nginx and how do I open my project in my local computer if I know the IP and can create a virtual host?


text:
Q: extra double quotes is added when i get value from propertis file in Java When i am printing value of browserName from child class its showing    "chrome" not chrome.(I am reading value from properties file"
public WebDriver initializeDriver() throws IOException
{
Properties prop=new Properties();
FileInputStream fs=new FileInputStream("D:\\data.properties");
prop.load(fs);
String browserName=prop.getProperty("browser");
System.out.println(browserName);
}

data.propeties
browser=chrome


text:
Q: Info.plist may not contain the UIRequiredDeviceCapabilities key When I try to upload my iOS + apple watch app to iTunes using Application Loader, I get the error message

ERROR ITMS-90595: "Unsupported Key. The Info.plist of bundle Watchless.app/Watch/WatchlessWatchApp.app/PlugIns/WatchlessWatchApp Extension.appex may not contain the UIRequiredDeviceCapabilities key."

Info.plist contains
<key>UIRequiredDeviceCapabilities</key>
<array>
    <string>healthkit</string>
</array>

which I think is absolutely necessary because both, watch app and iOS app depend heavily on HealthKit.
The entry is generated when I turn on the HealthKit capability of the watch extension target.
I am running out of ideas what to change.
Using XCode 7.2, Application Loader 3.4

A: UIRequiredDeviceCapabilities are just your way of saying "I don't want to be installed on device without this functionality".
Removing this will not affect your Watch extension using HealthKit.
Just remove the UIRequiredDeviceCapabilities from the plist in your extension and it should be fine.


text:
Q: FOSUserBundle authenticate user with multiple fields I'm trying to implement user authentication based on 3 fields ( a string, a boolean value and an email ). Following Symfony2 and Fos documentation I've started to create a custom User Provider, but it seems that the interface I have to implement ( UserProviderInterface ) at lower level needs the "loadUserByUsername" method.
My question is: Which is the best way to implement login with multiple fields?
Thank you very much!

A: Assuming you are using FOSUserBundle and that you don't use the username field I think the easier way is to "compose" your 3 fields and use them as username
To do this you need:

*

*Customize the login form. Hide the username field and add your 3.

*Create a kernel.request listener that read your 3 fields and add the username fields to the request object. Once you have done this you are in the "normal" flow

Let's say I've these data:

*

*me@mymail.com

*MyRandomString

*1 <- This is your booleand value

In the DB my username would be my@mymail.com|MyRandomString|1 (You can compose the username as you like)
Here an example for the listener
My\PersonBundle\Listener\MyLoginFieldFormatterListener
namespace My\AwesomeBundle\Listener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;

class MyLoginFieldFormatterListener {

    public function onKernelRequest(GetResponseEvent $event)
    {
        // This is you request object.
        // http://api.symfony.com/2.5/Symfony/Component/HttpFoundation/Request.html
        $request   = $event->getRequest();

        // Add a condition to execute code only when route login data are submitted is required
        if ($request->get('_route') != 'fos_user_security_check')
                return;

        // You can access POST values via `request` property
        $yourField1 = $request->request->get('yourField1');

        // Get the other fields and compose your username

        // The field name MUST be _username as long as you didn't overwrite it in the conf
        $request->request->set('_username', $yourComposedUsername);

    }

}

And the configuration
services.yml
services:
  listener.compose_username_listener:
    class: My\PersonBundle\Listener\MyLoginFieldFormatterListener
    tags:
      - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest, priority: 255 }

Do not forget priority so this listener is the first one executed.

A: @Hpatoio thank you, your solution works perfectly :) there's only a detail that has to be fixed: listener priority must be set at 31
according to documentation (http://symfony.com/doc/current/reference/dic_tags.html#kernel-request), RouteListener has priority 32
the custom listener has to be executed after RouteListener (to have the correct routing info) and before the validation system
so the correct configuration is:
services:
  listener.compose_username_listener:
    class: My\PersonBundle\Listener\MyLoginFieldFormatterListener
    tags:
      - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest, priority: 31 }


text:
Q: WPF: How can I adjust the style of disabled text boxes? If I want to change the background color of all disabled text boxes -- to make it more obvious that they are disabled -- how would I do this? I would like to change them to a darker grey color in particular, but an answer about styling of DISABLED inputs in general would be fine.

A: If you want a quick solution without having to re-template the entire control:-
<Style TargetType="TextBox">
  <Style.Triggers>
    <Trigger Property="IsEnabled" Value="false">
      <Setter Property="Template">
        <Setter.Value>
          <ControlTemplate TargetType="TextBox">
            <Border Background="LightGray" BorderBrush="Gray" BorderThickness="1">
              <TextBlock Text="{TemplateBinding Text}" Padding="2" />
            </Border>
          </ControlTemplate>
        </Setter.Value>
      </Setter>
    </Trigger>
  </Style.Triggers>
</Style>

A: There is no style property exposed for the disabled color -- so you will have to modify the default ControlTemplate.  To change the background color, it looks like you should be able to just copy-paste, and modify the one brush:
<Color x:Key="DisabledControlLightColor">#FFE8EDF9</Color>

Edit by "copy-paste", I mean you have to copy-paste the whole style into your resources:
<!--Control colors.-->
<Color x:Key="DisabledControlLightColor">Pink</Color> <!-- #FFE8EDF9-->

<Color x:Key="WindowColor">#FFE8EDF9</Color>
<Color x:Key="ContentAreaColorLight">#FFC5CBF9</Color>
<Color x:Key="ContentAreaColorDark">#FF7381F9</Color>

<Color x:Key="DisabledControlDarkColor">#FFC5CBF9</Color>
<Color x:Key="DisabledForegroundColor">#FF888888</Color>

<Color x:Key="SelectedBackgroundColor">#FFC5CBF9</Color>
<Color x:Key="SelectedUnfocusedColor">#FFDDDDDD</Color>

<Color x:Key="ControlLightColor">White</Color>
<Color x:Key="ControlMediumColor">#FF7381F9</Color>
<Color x:Key="ControlDarkColor">#FF211AA9</Color>

<Color x:Key="ControlMouseOverColor">#FF3843C4</Color>
<Color x:Key="ControlPressedColor">#FF211AA9</Color>

<Color x:Key="GlyphColor">#FF444444</Color>
<Color x:Key="GlyphMouseOver">sc#1, 0.004391443, 0.002428215, 0.242281124</Color>

<!--Border colors-->
<Color x:Key="BorderLightColor">#FFCCCCCC</Color>
<Color x:Key="BorderMediumColor">#FF888888</Color>
<Color x:Key="BorderDarkColor">#FF444444</Color>

<Color x:Key="PressedBorderLightColor">#FF888888</Color>
<Color x:Key="PressedBorderDarkColor">#FF444444</Color>

<Color x:Key="DisabledBorderLightColor">#FFAAAAAA</Color>
<Color x:Key="DisabledBorderDarkColor">#FF888888</Color>

<Color x:Key="DefaultBorderBrushDarkColor">Black</Color>

<!--Control-specific resources.-->
<Color x:Key="HeaderTopColor">#FFC5CBF9</Color>
<Color x:Key="DatagridCurrentCellBorderColor">Black</Color>
<Color x:Key="SliderTrackDarkColor">#FFC5CBF9</Color>

<Color x:Key="NavButtonFrameColor">#FF3843C4</Color>

<LinearGradientBrush x:Key="MenuPopupBrush"
                 EndPoint="0.5,1"
                 StartPoint="0.5,0">
    <GradientStop Color="{DynamicResource ControlLightColor}"
            Offset="0" />
    <GradientStop Color="{DynamicResource ControlMediumColor}"
            Offset="0.5" />
    <GradientStop Color="{DynamicResource ControlLightColor}"
            Offset="1" />
</LinearGradientBrush>

<LinearGradientBrush x:Key="ProgressBarIndicatorAnimatedFill"
                 StartPoint="0,0"
                 EndPoint="1,0">
    <LinearGradientBrush.GradientStops>
        <GradientStopCollection>
            <GradientStop Color="#000000FF"
                Offset="0" />
            <GradientStop Color="#600000FF"
                Offset="0.4" />
            <GradientStop Color="#600000FF"
                Offset="0.6" />
            <GradientStop Color="#000000FF"
                Offset="1" />
        </GradientStopCollection>
    </LinearGradientBrush.GradientStops>
</LinearGradientBrush>

<Style TargetType="{x:Type TextBox}">
    <Setter Property="SnapsToDevicePixels"
      Value="True" />
    <Setter Property="OverridesDefaultStyle"
      Value="True" />
    <Setter Property="KeyboardNavigation.TabNavigation"
      Value="None" />
    <Setter Property="FocusVisualStyle"
      Value="{x:Null}" />
    <Setter Property="MinWidth"
      Value="120" />
    <Setter Property="MinHeight"
      Value="20" />
    <Setter Property="AllowDrop"
      Value="true" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type TextBoxBase}">
                <Border Name="Border"
            CornerRadius="2"
            Padding="2"
            BorderThickness="1">
                    <Border.Background>
                        <SolidColorBrush Color="{DynamicResource ControlLightColor}" />
                    </Border.Background>
                    <Border.BorderBrush>
                        <SolidColorBrush Color="{DynamicResource BorderMediumColor}" />
                    </Border.BorderBrush>
                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup x:Name="CommonStates">
                            <VisualState x:Name="Normal" />
                            <VisualState x:Name="Disabled">
                                <Storyboard>
                                    <ColorAnimationUsingKeyFrames Storyboard.TargetName="Border"
                                            Storyboard.TargetProperty="(Panel.Background).
                (SolidColorBrush.Color)">
                                        <EasingColorKeyFrame KeyTime="0"
                                     Value="{StaticResource DisabledControlLightColor}" />
                                    </ColorAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="ReadOnly">
                                <Storyboard>
                                    <ColorAnimationUsingKeyFrames Storyboard.TargetName="Border"
                                            Storyboard.TargetProperty="(Panel.Background).
                (SolidColorBrush.Color)">
                                        <EasingColorKeyFrame KeyTime="0"
                                     Value="{StaticResource DisabledControlDarkColor}" />
                                    </ColorAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="MouseOver" />
                        </VisualStateGroup>
                    </VisualStateManager.VisualStateGroups>
                    <ScrollViewer Margin="0"
                    x:Name="PART_ContentHost" />
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>


text:
Q: cURL and Digest Auth I'm making a DIGEST AUTH using cURL and it's working perfect. The problem is, I need the browser to keep those Digest Credentials made on the login page, in all other pages without having to resend the user:pass again.
Example:
I'm in login.php, I write my user and password, I make a cURL request to authenticate, servers responds with OK, so I redirect to index.php, which requires to be authenticated, but it will ask for username and password again, it didn't keep it from login.php. How do I fix this?

A: You need to use Cookie Jar for that, eg:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
/* more cURL options */
curl_setopt($ch, CURLOPT_COOKIEJAR, '/tmp/cookies.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, '/tmp/cookies.txt');

$output = curl_exec($ch);
curl_close($ch);


text:
Q: Print VBA Userform as PDF I created a long userform that contains alot of information and I had like the user to have option to print if ones he clicks the "print_button".
I have found the following code:
private Sub CommandButton1_Click()
    Application.ScreenUpdating = False
    Path = "C:\Users\" &
    Environ("USERNAME") & "\Desktop\"
    Application.SendKeys "(%{1068})"
    DoEvents
    Workbooks.Add
    ActiveSheet.PasteSpecial Format:="Bitmap"
    ActiveSheet.Range("A1").Select
    ActiveSheet.ExportAsFixedFormat
    Type:=xlTypePDF, Filename:=Path & Me.Name & ".pdf"
    UserForm1.Hide
    ActiveWorkbook.Close False
    Application.ScreenUpdating = True
End Sub

This code works great and copies the userform as picture to another excel that can be printed
However, It snaps only the shown part of the userform, and since my userform contains scrollbar, it does not print all the information that is in the remaining of the userform.
Is there some option to make it possible to print/snap the whole userform and long page when it contains scrollbar?
thank you


text:
Q: How can I destroy the buttons generated using a for loop (after been clicked...) I already generated the buttons which their name is based on the list output1.
So, This program will create 4 buttons respectively from 'key1' to 'key4'
, whenever I click the button key1, the search box B will be replaced by "key1"
,similarly, button key 2,key3,key4 will replace "key2","key3","key4" respectively in search box B...
My objective is once I click one of these buttons, It will insert the word in the seach box B, and these 4 buttons will automatically be deleted
root = Tk()

def setTextInput(text):
    B.delete(0,"end")
    B.insert(0, text)
    for k in Autput1:
        Autput1[k].destroy()

j=0

if j==0:

    output1 = ['key1','key2','key3','key4']

    global Autput1
    Autput1 = []

    k=0

    for e in output1:
        Autput1.append(Button(root,text=e,command=lambda e=e:setTextInput(str(e))))
        Autput1[k].grid()
        print(Autput1)
        k+=1

A = Label(root,text="Search your song here",font=('Roboto',10),bg='#c4302b')
A.grid(row=0,column=0,columnspan=2,padx=10,pady=10)

B = Entry(root,font=('Roboto',20))
B.grid(row=1,column=0,columnspan=2,padx=10,pady=10)

C= Button(root,image=img,command=getsong)
C.grid(row=1,column=2,padx=10,pady=10)

root.mainloop()

This is the part of how I try to destroy the button which appends inside the list Autput1.
  for k in Autput1:
    Autput1[k].destroy()

and This is the error and the only problem I try to fix
 TypeError: list indices must be integers or slices, not Button

You might be wondering what is the value Autput1
   [<tkinter.Button object .!button2>, <tkinter.Button object .!button3>, <tkinter.Button object
   .!button4>, <tkinter.Button object .!button5>]

A: As you are iterating over Autput, so k is each button and don't index:
for k in Autput1:
    k.destroy()

If you are using range(len()) then it will work, because then you will be iterating using index:
for k in range(len(Autput1)):
    Autput1[k].destroy()


text: Q: Child_Process Multiple Commands I want to execute multiple commands in one spawn function without using the shell parameter, as it breaks my code. Let's say I wanted to run this command using the spawn function: ls && node app.js, how would I do this?


text:
Q: поиск совпадений из двух массивов Как мне найти совпадения в двух массивах?
задача такая: есть массив из jsona,
[{
  "id": 112,
    "name": "Standart Room",
    "img": "rooms_img_1.jpg",
    "price": 126,
    "category": "single",
    "roomType": "room",
    "adults": 1,
    "children": 0,
    "bed": "King",
    "facilities": "Closet with hangers, HD flat-screen TV, Telephone",
    "area": 20,
    "breakfast": false,
    "reservedFrom": "2020-02-01T23:28:56.782Z",
    "reservedTo": "2020-02-05T23:28:56.782Z"
},  {
    "id": 313,
    "name": "Double Room",
    "img": "rooms_img_3.jpg",
    "price": 320,
    "category": "double",
    "roomType": "room",
    "adults": 2,
    "children": 1,
    "bed": "Twin",
    "facilities": "Closet with hangers, HD flat-screen TV, Telephone",
    "area": 20,
    "breakfast": false,
    "reservedFrom": "2020-03-07T23:28:56.782Z",
    "reservedTo": "2020-03-091T23:28:56.782Z"
}]

и так далее. И другой массив, с перечнем типов комнат:
const roomCategories = ["single", "standart", "double", "family", "vip", "suite"];
Мне нужно пройтись по первому массиву искать по категориям и перебрать все типы комнат по одному из массива и создать новый по 1 типу комнат из каждой категории.
Я только начинаю учить JS и есть сложности(
Заранее спасибо!

A:

let mas1 = [{
  "id": 112,
    "name": "Standart Room",
    "img": "rooms_img_1.jpg",
    "price": 126,
    "category": "single",
    "roomType": "room",
    "adults": 1,
    "children": 0,
    "bed": "King",
    "facilities": "Closet with hangers, HD flat-screen TV, Telephone",
    "area": 20,
    "breakfast": false,
    "reservedFrom": "2020-02-01T23:28:56.782Z",
    "reservedTo": "2020-02-05T23:28:56.782Z"
}, {"id": 113,
    "name": "Standart Room",
    "img": "rooms_img_1.jpg",
    "price": 126,
    "category": "single",
    "roomType": "room",
    "adults": 1,
    "children": 0,
    "bed": "King",
    "facilities": "Closet with hangers, HD flat-screen TV, Telephone",
    "area": 20,
    "breakfast": false,
    "reservedFrom": "2020-02-01T23:28:56.782Z",
    "reservedTo": "2020-02-05T23:28:56.782Z"
}, {
    "id": 313,
    "name": "Double Room",
    "img": "rooms_img_3.jpg",
    "price": 320,
    "category": "double",
    "roomType": "room",
    "adults": 2,
    "children": 1,
    "bed": "Twin",
    "facilities": "Closet with hangers, HD flat-screen TV, Telephone",
    "area": 20,
    "breakfast": false,
    "reservedFrom": "2020-03-07T23:28:56.782Z",
    "reservedTo": "2020-03-091T23:28:56.782Z"
}];

const roomCategories = ["single", "standart", "double", "family", "vip", "suite"];

// console.log(mas1)

let result = {};

roomCategories.forEach(category => {
  result[category] = mas1.filter(f => f.category === category);
});

console.log(result);

использую filter - он отбирает коллекцию по предикату.
foreach - цикл (перебор) массива.