text:
Q: Bring Column Contents Up Why are the contents of the right-column not at the top? And how do I put them there? I'm trying to show the correspondence between graphical transformations and the values of a, b, c, and d in y=af(b(x-c))+d.
\documentclass{article}

\usepackage[margin=1.5cm]{geometry}
\usepackage{tikz}

\pagestyle{empty}

\newcommand{\mygrid}
{
\begin{tikzpicture}[scale=0.3]
\node at (0,14) {\LARGE{Graph}};
\draw[gray] (-12,-12) grid (12,12); % faint grid lines
\draw[very thick] (0,-12)--(0,12); % x-axis
\draw[very thick] (-12,0)--(12,0); % y-axis
\end{tikzpicture}
}

\newcommand{\mytable}
{%
\LARGE Variables \& Words \par
\vspace{0.2cm}
\begin{tabular}{|l|p{3cm}|p{3cm}|} \hline
& Vertical & Horizontal \\ \hline
$\times$& $a=$ & $b=$ \\ \hline
$+$ &$c=$ &$d=$\\ \hline
\end{tabular}
}

\begin{document}

\begin{tabular}{p{9.5cm}p{9.5cm}}
\mygrid & \mytable \\    % WHY IS \MYTABLE SO LOW IN ITS CELL?
\end{tabular}

\end{document}

A:
\documentclass{article}

\usepackage[margin=1.5cm]{geometry}
\usepackage{tikz,array}

\pagestyle{empty}

\newcommand{\mygrid}
{
\begin{tikzpicture}[scale=0.3]
\node at (0,14) {\LARGE{Graph}};
\draw[gray] (-12,-12) grid (12,12); % faint grid lines
\draw[very thick] (0,-12)--(0,12); % x-axis
\draw[very thick] (-12,0)--(12,0); % y-axis
\end{tikzpicture}
}

\newcommand{\mytable}
{%
\LARGE Variables \& Words \par
\vspace{0.2cm}
\begin{tabular}{|l|p{3cm}|p{3cm}|} \hline
& Vertical & Horizontal \\ \hline
$\times$& $a=$ & $b=$ \\ \hline
$+$ &$c=$ &$d=$\\ \hline
\end{tabular}
}

\begin{document}

\begin{tabular}{m{9.5cm}m{9.5cm}}
\mygrid & \mytable \\    % WHY IS \MYTABLE SO LOW IN ITS CELL?
\end{tabular}

\end{document}

A: It is the bottom of a graphic file that is laid on the base line of a row, so if you want the columns to be top-aligned, you need to use \raisebox{-\height}(plus some adjustment) in the first column. In other words: you don't have to bring the 2nd column up, but to bring the 1st column down.
\documentclass{article}

\usepackage[margin=1.5cm]{geometry}
\usepackage{tikz}

\pagestyle{empty}

\newcommand{\mygrid}
{
\begin{tikzpicture}[scale=0.3]
\node at (0,14) {\LARGE{Graph}};
\draw[gray] (-12,-12) grid (12,12); % faint grid lines
\draw[very thick] (0,-12)--(0,12); % x-axis
\draw[very thick] (-12,0)--(12,0); % y-axis
\end{tikzpicture}
}

\newcommand{\mytable}
{%
\LARGE Variables \& Words \par
\vspace{-0.3cm}
\begin{tabular}[t]{|l|p{3cm}|p{3cm}|}
 \hline
& Vertical & Horizontal \\ \hline
$\times$& $a=$ & $b=$ \\ \hline
$+$ &$c=$ &$d=$\\ \hline
\end{tabular}
}

\begin{document}

\begin{tabular}{p{9.5cm}p{9.5cm}}
\raisebox{\dimexpr-\height+3.4ex}{\mygrid} & \mytable \\ % WHY IS \MYTABLE SO LOW IN ITS CELL?
\end{tabular}

\end{document}


text:
Q: Should it step 2 registration / onboarding be a method or a new controller? So I'm working on an app. Registration of user is through omniauth, and using Twitter.
What I'd like to do is after that registration is complete, ask that you add your email.
Should I create a new controller called say setups, or should I create a method called setup under the users_controller?

A: Technically either is fine, I would however just drop them on their show action and prompt them there to enter their email address.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use CoreMotion for getting device orientation in space I am having a thinking and searching problem here and can't find the good direction to look at...
I am looking to develop an algorithm to move in a 360 image (sphere like) by using the device motion.
So if the user point the device in front of him he get the determined origin point of the image. As he moves the device around him the panoramic image moves according to it.
Any idea or source I can look into ?
Thanks and good luck to everyone with Swift :)

A: Thanks to Kay I could be on the right track to achieved this effect.
I am making this answer just to provide more details for those looking for the same thing.
First you need to create a CMMotionManager object.
Then use startDeviceMotionUpdatesToQueue to handle motion events.
[self.motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMDeviceMotion *motion, NSError *error) {
    [self processMotion];
}];

In processMotion you just need to get the attitude based on the previous one:
// Get attitude difference with previous one
CMAttitude *currentAttitude = self.motionManager.deviceMotion.attitude;
[currentAttitude multiplyByInverseOfAttitude:self.referenceAttitude];

Thanks to this you know the new angle made by the user since the last update.
Then where you handle your view you convert the new Euler angle into the amount of pixels you need to move your image.
Just be careful Euler angle varies between -180, 180 and are given in rad by Apple. This could be handy:
#define RADIANS_TO_DEGREES(radians) ((radians) * (180.0 / M_PI))

So in my case I just calculate the new x offset because I am just moving on the x axis.
Hope this helps.

A: I see two easy ways to implement this without to much math hassle:

*

*Use Euler Angles i.e. the roll property of CMAttitude. Define a mapping between the width of the image and the measured angle and take care of the singularity at 180° / -180°. Drawback of this approach:

*

*Possible danger of Gimbal Lock when users start to move their devices in a chaotic way.

*The same applies to extensibility regarding a full 3D view.

*Use the magnetic field from CMDeviceMotion which is robust against Gimbal Lock. The magnetometer is a little bit slower than accelerometer / gyro, but I think the CoreMotion's  fusion algorithm will provide a reasonable estimation so that this won't be the point. Drawbacks here:

*

*Magnetic field is not always available or tends to be slighlty imprecise.

*Extending it to 3D view might be a hassle.

Both approaches should be pretty easy to implement and thus I would start with one of them. If you then want to have a more sophisticated solution, you will need to dive a little bit deeper into the maths. In this case a ppossible solution can be to use the current device normal (s. for example Finding normal vector to iOS device), project it onto the earth suface plane and take the angles' delta for the cylindric panorama.
The sphere projection is even easier in this case as you can use the nomal vector directly.


text:
Q: How to convert image from  and AJAX POST data to the specific server My question in topic. Some details:
Server - node.js
Convert for image - child process with image magick (script for convert - works)
URL for uploading image - specific url from VK.API (RU) I need to attach input file=type and name=photo. How I can do it with $.ajax ? What variable I need put to data field? Or another way?
I have a form with 2 fields: text and <input type="file" name="photo">. After submit - data sends to express. And now: how i can work with uploaded image? Convert script waiting for correct way/to/img.
After success with convert, I receive file on my hard disk. How I can $.post to specific url with correctly (again) way/to/img and name=photo ?
Thank you!
p.s. Server side - node.js + express, convert tool - image magick


text:
Q: Very nested JSON with optional fields into pandas dataframe I have a JSON with the following structure. I want to extract some data to different lists so that I will be able to transform them into a pandas dataframe.
{
    "ratings": {
        "like": {
            "average": null,
            "counts": {
                "1": {
                    "total": 0,
                    "users": []
                }
            }
        }
    },
    "sharefile_vault_url": null,
    "last_event_on": "2021-02-03 00:00:01",
    ],
    "fields": [
        {
            "type": "text",
            "field_id": 130987800,
            "label": "Name and Surname",
            "values": [
                {
                    "value": "John Smith"
                }
            ],
        {
            "type": "category",
            "field_id": 139057651,
            "label": "Gender",
            "values": [
                {
                    "value": {
                        "status": "active",
                        "text": "Male",
                        "id": 1,
                        "color": "DCEBD8"
                    }
                }
            ],
        {
            "type": "category",
            "field_id": 151333010,
            "label": "Field of Studies",
            "values": [
                {
                    "value": {
                        "status": "active",
                        "text": "Languages",
                        "id": 3,
                        "color": "DCEBD8"
                    }
                }
            ],
       }
}

For example, I create a list
names = []

where if "label" in the "fields" list is "Name and Surname" I append ["values"][0]["value"] so names now contains "John Smith". I do exactly the same for the "Gender" label and append the value to the list genders.
The above dictionary is contained in a list of dictionaries so I just have to loop though the list and extract the relevant fields like this:
names = []
genders = []

for r in range(len(users)):
    for i in range(len(users[r].json()["items"])):
        for field in users[r].json()["items"][i]["fields"]:
            if field["label"] == "Name and Surname":
                names.append(field["values"][0]["value"])
            elif field["label"] == "Gender":
                genders.append(field["values"][0]["value"]["text"])
            else:
                 # Something else

where users is a list of responses from the API, each JSON of which has the items is a list of dictionaries where I can find the field key which has as the value a list of dictionaries of different fields (like Name and Surname and Gender).
The problem is that the dictionary with "label: Field of Studies" is optional and is not always present in the list of fields.
How can I manage to check for its presence, and if so append its value to a list, and None otherwise?

A: To me it seems that the data you have is not valid JSON. However if I were you I would try using pandas.json_normalize. According to the documentation this function will put None if it encounters an object with a label not inside it.


text:
Q: react navigation: Navigate to screen from specific screen My navigation structure looks something like this:
    TabNavigator
    |
    |- StackNavigator
    |  |
    |  |- ListA
    |  |
    |  |- ShowA
    |
    |- StackNavigator
    |  |
    |  |- ListB
    |  |
    |  |- ShowB

ListA shows, as you might expect, a list of resources (type A). Pressing on one sets the state and navigates you to ShowA where you are viewing details about that specific resource.
ListB shows a list of resources (type B), and ShowB also shows a list of resources, however the resources are of type A. When pressing on one of these resources, you should be navigated to ShowA.
If on ListA I press and navigate to ShowA, that works perfectly.
If on ShowB I press and navigate to ShowA, that also works as expected.
However, if I first go to ListA, navigate to ShowA, then (without pressing 'Back' on ShowA) use the TabNavigator and go to ListB, then to ShowB, pressing on a resource opens ShowA but it's another instance of the screen placed on top of the stack. So when I press 'Back', instead of taking me to ListA as would be expected, it takes me to the previously opened ShowA.
I'm sorry if the formatting or explanation of this is inadequate. If anyone can help or if anyone needs more information please let me know and I'll do whatever I can.

A: You should register two screens using the same component under different screen names. The structure should look something like this:
Tab:
  Stack
    "Tab1List"
    "Tab1Show"
  Stack
    "Tab2List"
    "Tab2Show"


text:
Q: Removing characters from 1st textbox that are contained in 2nd textbox in vb.net I am not talking about :
if textbox1.text.contains(textbox2.text) then
textbox1.text = ""
end if

But this:
If textbox1 contains any char that exists in textbox2 also,is automatically removed at button click.
Thanks,

A: You could use something like
textbox1.Text = new String(textbox1.Text.Except(textbox2.Text).ToArray())

or a simple For Each loop.

A:   ' btn click event
  Dim unique As List(of String)
  For i As Integer = 0 to textbox2.text.length - 1
    Dim c As String = textbox2.text.substring(i,1)
    If not unique.contains(c)
      textbox1.text = textbox1.text.replace(c, "")
      unique.add(c)
    End If
  Next For

A: You could also use a Regex:
textbox1.Text = Regex.Replace(textbox1.Text, _
    "[" & Regex.Escape(textbox2.Text).Replace("-", "\-")  & "]", "")


text:
Q: Implement a simple many-to-many relation in a Form in OpenOffice.org's Base I'm doing a small relational database, to be used by one person on a single computer. I chose OpenOffice.org's Base (version 3.1.1) because it's free and should be more than enough for this case. The simplified version of my problem is:
I have an Articles table, with columns: ID, Title, Content, etc....
I have a Keywords table with columns: ID, Keyword.
I have a Relations table with columns: ID, ArticleID, KeywordID
Just a basic, classic, example of a many-to-many relation.
Then I created a form (for the user using the database) using the 'Design view' in Base and linked to the Articles table, which works fine, and allows me to view, edit and created rows in the Articles table.
My problem is how to include the relation to Keywords in that same form. That is, I want the user to be able to view and choose which keyword(s) belongs to the article currently being viewed in the form.
The number of keywords is finite (probably 5-15) if that matters. A preferred setup would be a list of keywords (dynamically linked to the Keywords table of course) in the previously  mentioned form I've already created with a check box in front of each keywords
I've tried Google'ing all possible keywords and I've come up with nothing applicable to my case. I belive the answer is somehow using SubForms, or maybe some SQL syntax I'm not familiar with. Any help appreciated.

A: To answer this in a little more detail, as it comes up early on Google search, please refer to the following video of creating the movies.odb file from scratch:
http://www.youtube.com/watch?v=GYawYO8u3_s
Some further notes on creating this:
Setting up the tables

*

*The principle tables must have an integer primary key that is set to AutoValue

*The linking table must have a multi-column primary key, and both columns must be integers

*The table relationships must be set in the Relationships... dialog

*The relationships disappear if Update options not changed from No action

Setting up the subform

*

*The subform Data >> Content must be set to the mapping table

*The subform Data >> Link master fields and Link slave fields must be set to the related fields (as per the Relationships... dialog discussed above)

*A table control should be draw (focus must be on the subform at the time, such that the table control sits below the subform in the Form Navigator

*A column should be inserted into the table control

*The column Data >> Data field should be set to the ID of the related data (i.e. not that of the main form)

*The column Data >> Type of list contents should be set to "sql"

*The column Date >> List content should be set to "SELECT "Genre Name", "GenreID" FROM "Genre"" (where Genre Name is the relevant field from the related table, the GenreID is the primary key of that table, and Genre is the related table)

A: I did some more searching and finally found a solution.
A thread explaining this very issues (among other issues), creating form for a database containing many-to-many relation in Base using a middle table, can be found at:
http://user.services.openoffice.org/en/forum/viewtopic.php?p=16159#p16159
A sample database with a functional form by one of the above thread's posters (DrewJensen) can be found and downloaded at page 2 of the above posted thread. (named movies_2.odb)
A brief description of the solution using my example tables and columns from orginial post:
The trick lies in creating a sub-form linked to the Relations table within the form I had created. That sub-form should contain a Table Control. Then a column should be created in that Table Control. The column should be asigned to the KeywordID column. The "List content" field for that column should then contain: SELECT "Keyword", "ID" FROM "Relations".
(just check out the above link if my instructions are cryptic)


text:
Q: Download webpage as Word document (docx) I have a wordpress page with some custom features in JS that people can save in a pdf format. Is there a way to allow people to download the page in docx (MS Word) as well? I tried searching for a solution but couldn't find much.
I'd like to have a button 'Download as docx' that generates a similar looking version as the pdf format.
Ideally, I'd like to do it in JS or find a WP plugin that offers the functionality.
Thanks for the help
Thomas

A: You can do this with JavaScript.  There's a repository for it on Github html-docx-js.  There's also a jquery plugin googoose.
You can also do it with a WP plugin that uses googoose.

A: There is also this plugin, FileSaver.js. You are able to export to .doc using jQuery


text:
Q: UITableViewCell contentView insets and Auto Layout My problem is, that I want to inset the cell's contentView by 10 for each top, bottom, left, right. I want to use this space as a separator and disable the default table view separator. It looks like this without the insets:

Now there are two issues:

*

*Issue: Ambiguous height constraints (in the view debugger)

*No separator

1.

*I can change this by overriding layoutSubviews for my table view cell:
override func layoutSubviews() {
   super.layoutSubviews()

   let contentViewFrame = self.contentView.frame
   let insetContentViewFrame = contentViewFrame.inset(by: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10))
   self.contentView.frame = insetContentViewFrame
   self.selectedBackgroundView?.frame = insetContentViewFrame
}

However this causes issue number 3:

Now the description label has issues:
Here is my Table View Cell (which uses autolayout so the labels define the cell height):
class NewsTableViewCell : UITableViewCell {

public private(set) var titleLabel: UILabel!
public private(set) var descriptionLabel: UILabel!

override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)

    self.tintColor = UIColor.white

    self.contentView.backgroundColor = UIColor.barTintColor
    self.contentView.layer.masksToBounds = false
    self.contentView.layer.cornerRadius = 10.0

    self.backgroundColor = UIColor.clear

    let layoutGuide = self.contentView.layoutMarginsGuide

    self.titleLabel = UILabel(frame: .zero)
    self.titleLabel.numberOfLines = 0
    self.titleLabel.font = UIFont.preferredFont(forTextStyle: .headline)
    self.titleLabel.textColor = UIColor.white
    self.titleLabel.adjustsFontSizeToFitWidth = false
    self.titleLabel.translatesAutoresizingMaskIntoConstraints = false
    self.titleLabel.textAlignment = .left
    self.contentView.addSubview(self.titleLabel)

    self.titleLabel.setContentCompressionResistancePriority(.required, for: .vertical)

    self.titleLabel.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor).isActive = true
    self.titleLabel.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor).isActive = true
    self.titleLabel.topAnchor.constraint(equalTo: layoutGuide.topAnchor).isActive = true

    self.descriptionLabel = UILabel(frame: .zero)
    self.descriptionLabel.numberOfLines = 0
    self.descriptionLabel.font = UIFont.preferredFont(forTextStyle: .subheadline)
    self.descriptionLabel.textColor = UIColor.lightGray
    self.descriptionLabel.adjustsFontSizeToFitWidth = false
    self.descriptionLabel.translatesAutoresizingMaskIntoConstraints = false
    self.descriptionLabel.textAlignment = .left
    self.contentView.addSubview(self.descriptionLabel)

    self.descriptionLabel.setContentCompressionResistancePriority(.required, for: .vertical)

    self.descriptionLabel.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor).isActive = true
    self.descriptionLabel.trailingAnchor.constraint(equalTo: layoutGuide.trailingAnchor).isActive = true
    self.descriptionLabel.topAnchor.constraint(equalTo: self.titleLabel.bottomAnchor, constant: 5.0).isActive = true
    self.descriptionLabel.bottomAnchor.constraint(equalTo: layoutGuide.bottomAnchor).isActive = true

    let selectedView: UIView = UIView(frame: .zero)
    selectedView.backgroundColor = UIColor.gray
    selectedView.layer.cornerRadius = 10.0
    selectedView.layer.masksToBounds = false
    self.selectedBackgroundView = selectedView
}

That is my table view controller code:
self.tableView.rowHeight = UITableView.automaticDimension
self.tableView.estimatedRowHeight = 200.0
self.tableView.register(NewsTableViewCell.self, forCellReuseIdentifier: "NewsCell")
self.tableView.separatorStyle = .none

Is there any way I can both inset my contentView and have dynamically sizing labels (that define the cell height)?
Thanks!

A: 1- Add constant paramter
 self.titleLabel.leadingAnchor.constraint(equalTo: layoutGuide.leadingAnchor,constant:10).isActive = true

for leading , trailing , top and bottom
2-
lower descriptionLabel bottom constraint's priority to 999

A: Your issue
1 ) You want two label to grow dynamically.
2) You want your cell resize with your content
To do this you need to give constraint at all side (left,lead, trail,bottom) otherwise Automatic dimension  won't work
but auto layout engine won't allow this. because it needs some specific idea that which label will grow so it may calculate internally. and . you are getting error to change content hugging priority
Solution is also simple
Suppose from bottom you need 8px space then apply greater than equal to(  >=) Relation with 8 value
and reset your content hugging priority to default they don't required now :)


text:
Q: Reusing a global array in a function in a threadsafe way in C I want to use some temporary storage in a function and not have to reallocate it at each call.  This works fine for a single thread, but how do I extend the idea to multi-threaded programs (a subject I'm only familiar with in the abstract).
For example,
int *foo_array;
int foo_array_size;//global initalises to 0
void foo(int *A, int n){
  int i;
  if(n>foo_array_size && foo_array) free(foo_array);
  if(n>foo_array_size){
    foo_array=malloc(2*n*sizeof(int));
    foo_array_size=2*n;
  }
  for(i=0;i<n;i++){
    foo_array[i]=A[i];
  }
  for(i=0;i<n;i++){
    A[i]=foo_array[i];
  }
}

As I understand it, foo_array points to the same place in memory for every thread, so if foo() is called at the same time in two threads, we could end up with unexpected behaviour (correct?).
So how would I, at an abstract level, perhaps, ensure that foo_array points to different memory for use in each thread?

A: You don't say with thread library you are using. The C11 thread library has the qualifier _Thread_local that creates a variable that has a different incarnation per thread.
If you don't have C11 threads, some compiler extensions may provide a similar feature. E.g gcc has __thread.
According to the thread library that you are using there may also be a set of functions that simulate such a thing. C11 threads have the tss_t type (thread specific storage) and functions tss_create etc to deal with them.


text:
Q: How to upload profile picture with blobID during signup in QuickBlox? I have problem image uploading during signup.There is a blobID property.can you tell me how we can generate blobid uniquely to new user.I checked with dummy integer value. I found error this blobid not associate with this userid. Please provide me better solution for this.

A: You should do next tasks:

*

*Sign Up user

*Sign In user

*Create blob and Upload file - you will receive blobID of new file

*Update user's blobID field - just set blobID from step 3

A: Using SWIFT. The popUp function lets the user know they have been successfully added.
func addUser() {

    // add new user

    let newUser:QBUUser = QBUUser()

    newUser.password = pwTxt.text
    newUser.fullName = unTxt.text
    newUser.email = emTxt.text

    QBRequest.signUp(newUser, successBlock: { (response) in

        self.popUp("Signup Success!", msg:"You are now signed up!", button1: "OK!")

        // You must be logged in to upload an avatar/image file
        QBRequest.logIn(withUserEmail: self.emTxt.text!, password: self.pwTxt.text!, successBlock: { (response: QBResponse, user) in

            QBRequest.tUploadFile(imgData, fileName: "image.png", contentType: "image/png", isPublic: true, successBlock: { (response, blob) in

             }, statusBlock: { (request, status) in
                        print("Upload Succcess!")

             }, errorBlock: { (response) in
                        print("Upload Failure!")
             })

         }, errorBlock: { (response: QBResponse) in
                    print("Sign In Failed")
         })

         }, errorBlock: { (response) in
                    print("Error in SignUp")

         })
 }

func popUp (_ title: String, msg: String, button1: String){

    print("\(title)")
    print("\(msg)")

    let alert = UIAlertController(title: "\(title)", message: "\(msg)", preferredStyle: UIAlertControllerStyle.alert)

    self.present(alert, animated: true, completion: nil)

    alert.addAction(UIAlertAction(title: "\(button1)", style: .default, handler: {
        action in
        alert.dismiss(animated: true, completion: nil)
    }))

}


text:
Q: Возможен ли переход по якорям на странице без ссылок а? У меня кнопка "вверх" http://joxi.ru/Y2LqlnGu3P0wA6 сделана ссылкой:

    Наверх

Я оптимизирую страницу для SEO продвижения, и хотелось бы убрать все пустые ссылки.
Вот чего хотелось бы:

    Наверх

A:

for(const el of document.querySelectorAll('*[data-target]')){
    const target = document.querySelector(`*[data-ankor="${el.dataset.target}"]`);
    el.addEventListener('click', e => target.scrollIntoView(true));
}

    Туда

    Сюда

A: Спасибо комментаторам за ответы, на основе их я нарыл хороший пример той прокрутке, которую я желал:
$(function(){
    $('#to-top-btn').on('click', function(e){
        $('html,body').stop().animate({ scrollTop: $('body').offset().top }, 1000);
        e.preventDefault();
    });
});


text:
Q: Getting an error in C: passing argument 1 of function from incompatible pointer type The function signature is
void abort(context_t **ctx);

, where ctx is a property of another struct.
After I have created a pointer to the main struct ( server_t *server ), I can pass the pointer to the pointer to the main struct ( **server ) around with no problem, using the pointers to its properties like this: (*server)->ctx or (*server)->addr, etc.
But I cannot figure out how to pass the **ctx to a function directly, without passing the **server. If I try it as abort(&server->ctx), I get an error:
error: passing argument 1 of 'abort' from incompatible pointer type: abort(&server->ctx);

note: expected 'context_t ** {aka struct context_t **}' but argument is of type 'struct context_t *'

void abort(context_t **ctx);

A:
note: expected 'context_t ** {aka struct context_t **}' but argument is of type 'struct context_t *'

It seems you try to assign pointer to double pointer. You can try:
context_t * temp_ctx = &server->ctx;
abort(&temp_ctx);

A: The compiler error can be fixed by the following lines of codes:
/* declare context_t* pointer variable on the appropriate scope */
/* based on how **ctx is used by abort() */
context_t *pContext;

/* .... */

/* assign the pointer */
pContext = &server->ctx;

/* now pass the context_t** or "the address of pContext" to abort() */
abort(&pContext);


text:
Q: Create a download button in WCFM frontend manager I've created a product custom field in WCFM frontend manager, In that field I selected Html type and then I added the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <style>
        .download{
            width: auto;
            background-color: royalblue;
            color: white;
            font-size: 20px;
            border:none;
            padding-left: 30px;
            padding-right: 30px;
            padding-bottom: 5px;
            padding-top: 5px;
        }

        .download:hover{

            background-color:turquoise
        }
    </style>

    <a href="wptbox/mouaz/socks-setup-template.rar" download>

      <button type="submit" class="download">Download</button>
    </a>

</body>
</html>

That code is for create a button to download .rar file when clicking on it, but the code not working, where is the problem here?


text:
Q: How to use soap in javascript I am trying to use SOAP in javascript but i am not getting how to start it.
Here is the code sample i write in PHP and it works fine. I want to write this code in Javascript. In following code i call one api from a www.example.com and for calling certain api we require to pass some parameters.
    $soapClient = new SoapClient("https://www.example.com/WSDL");
    $param_sh = array( );
    $header = new SoapHeader('http://somesite.com/action/', 'user_credential', $param_sh);
    $soapClient->__setSoapHeaders(array($header))
    $param = array("with some parameter");
    $contents = $soapClient->__call("name_of_method",array($param));

    print($contents);

A: Now, after more than 5 years since this question was asked, lots of stuff has happened to Javascript and web in general, so:

*

*you can send cross-origin requests and modern browsers are 100% OK with that (if the server you're sending them to allows CORS, of course)

*there are lots of libraries both for server and client side javascript.

*there are lots of questions on the topic on StackOverflow.

A: Assuming you're talking about in-browser Javascript, you won't be able to use SOAP.  Browsers obey something called the Same Origin Policy, which says (loosely) that you can't make cross domain requests from javascript.  That means you can only make requests to a SOAP service (or any HTTP request) if it's on the same domain that the browser page is currently on.  Because of this limitation/feature, no one ever went to a lot of trouble to implement a SOAP client in Javascript (although they probably do exist).
Your best bet is to make your SOAP calls via PHP, and then make AJAX requests from your web page (via javascript) to the PHP pages that make the actual SOAP request.

A: JavaScript doesn't have a SOAP library out of the box, though you can google around and find them, e.g., here. Not that this won't do anything to work around the limitations @Alan cites. The web services still need to be on the origin server.


text:
Q: Python Resources Is there anyway to incorporate a "resources" folder with .exe's inside of it, with my python program?? I basically want to bundle .exe's with my .py file... My python program depends on these executables... If this isn't possible, would it be possible to convert .exe to .py???

A: For the first one, yes. Just put it in a known subdirectory and manipulate __file__ with os.path to get the path to pass to subprocess.
For the second... no. Just no.


text:
Q: sorting the column of csv file through an element (scores) without using pandas I'm having trouble sorting the scores on my data without using pandas. Here's my code below:
def loadData():
    fileHandle = open('Leaderboard.csv', 'r')
    player = {}
    for line in fileHandle:
        data = line[0:-1].split(",")
        playerName = data[0]
        playerScore = data[1]
        playerPattern = data[2]
        playerData = {}
        playerData["Score"] = playerScore
        playerData["Pattern"] = playerPattern
        player[playerName] = playerData
    fileHandle.close()
    return player

    def leaderboard(player):
        print("=========================================")
        print("              LEADERBOARD")
        for k in player:
            playerData = player[k]
            playerScore = playerData["Score"]
            playerPattern = playerData["Pattern"]
            print(k + " - " + playerScore + " - " + playerPattern)
        print("\n")

player = loadData()
leaderboard(player)

Sample CSV file:
Eman,30,kerf
Hans,10,ie
John,55,okelf
Gian,40,jfue

I want my output to be like this:
John - 55 - okelf
Gian - 40 - jfue
Eman - 30 - kerf
Hans - 10 - ie

Would really appreciate your help. Thank you!

A: I amended your code in a more pythonic way, feel free to use the code snippet below as you like.
The main change that I made is in the leaderboard function, from this:
for k in player:

to this:
for player_name in sorted(
    all_players.keys(),
    key=lambda x: all_players[x]['Score'],
    reverse=True
):

def loadData(filename):
    with open(filename, 'r') as f:
        all_players = {}
        for line in f:
            data = line[0:-1].split(",")
            player_name = data[0]
            player_score = data[1]
            player_pattern = data[2]

            player = {}
            player['Score'] = player_score
            player['Pattern'] = player_pattern

            all_players[player_name] = player
    return all_players

def leaderboard(all_players):
    print('=========================================')
    print('              LEADERBOARD')
    for player_name in sorted(
        all_players.keys(),
        key=lambda x: all_players[x]['Score'],
        reverse=True
    ):
        player = all_players[player_name]
        player_score = player['Score']
        player_pattern = player['Pattern']
        print(f'{player_name} - {player_score} - {player_pattern}')
    print()

filename = 'Leaderboard.csv'
all_players = loadData(filename)
leaderboard(all_players)


text:
Q: Validation routine not working Every time I click submit when the correct information is not filled in, there is suppoesed to be an alert message for each section and the text is supposed to turn red but it is linking staight to the linked file. If someone could help with this the I would be really greatful.

<title>Exam Entry</title>

Exam Entry Form

<form name="ExamEntry" method="post" action="success.html">

Name
<input type="text" name="Name" />

Subject
<input type="text" name="Subject" />

ExamNumber
<input type="text" name="ExamNumber" Length="4"/>
<front size="1">(Maximum characters: 4)

Exam Level
<input type="radio" name="age" value="GCSE">GCSE

<input type="radio" name="Exam Level" value="AS">AS

<input type="radio" name="Exam Level" value="A2">A2

<input type="submit" name="Submit" value="Submit" onclick="return validateForm();" />
<input type="reset" name="Reset" value="Reset" />

</form>

This is the file It links to...

<title>Success message</title>

 You entered all the data required

A: This line:
if ( ( Examentry.Exam Level[0].checked == false ) && ( Examentry.Exam Level[1].checked == false )  && ( Examentry.Exam Level[2].checked == false ))

contains syntax errors (space between "Exam" and "Level" ) that are preventing your script from running.
If you remove the spaces between "Exam" and "Level" , it will work:
 if ( ( Examentry.ExamLevel[0].checked == false ) && ( Examentry.ExamLevel[1].checked == false )  && ( Examentry.ExamLevel[2].checked == false ))

Update:You will also need to modify the id tags of the actual HTML elements themselves to remove the spaces. e.g  becomes
I would recommend keeping your browser dev. tools (F12 in most browsers) open when testing things like this, as script synatx errors will normally be flagged right away.

A: This might be your problem.  Remove ;
function validateForm(); { //-----> Remove ;
//rest of your code
}

Also you should take a look at validationEngine plugin or jQuery validate.


text:
Q: Displaying data from multiple entities in a single NSTableView (Core-Data) I have an entity called Pupil, and an entity called Loan.
The Pupil entity has the attributes: firstName, lastName, address, postCode, telephoneNumber.
The Loan entity has the attribute: loanID,  and the relationship: pupilID, which is a relationship to the entity Pupil.
I wish to display the loanID, with the pupil (if any) related to the loanID in a table.
e.g.:
LoanID | firstName | lastName | address     | postCode | telephoneNumber
   1   |    bob    |  smith   | 98 Any Road |  N1 1QW  | 0123456789

How would I go about this? I am currently using the bindings for my other tables.
Thank you!

A: You can do this assuming that you have set the reverse relationship for pupilID (i.e. a relationship from Pupil to the Loan). If you call that relationship loan, and have an NSArrayController, PupilsController bound to the collection of Pupils, then your first table could be bound to PupilsController.arrangedObjects.loan.loadID and your other columns bound as you'd expect.
On a purely stylistic side note, the pupilID property would more appropriately be named pupil. Core Data is no an ORM and you're not in SQL JOIN land any more. Name the properties what they are, not how they're implemented under the hood by Core Data.


text:
Q: accessing data from structure in flash I am using an Atmel AVR and am trying to access data from a structure which is stored in flash (program) memory.
The structure is:
typedef struct {
    uint8_t width;
    uint8_t height; // row number 0 to 5
    uint8_t images; // how many frames does this bitmap have
    uint8_t data[]; // the actual pixel data
} bitmap_t;

the data is:
    __flash   static const bitmap_t bmp_stereo2  = {14,1,1,{126,129,60,66,24,36,60,60,36,24,66,60,129,126}};

I'm trying to access the data with (partial code shown)...
void lcd_bitmap2(const bitmap_t *bit, uint8_t id, uint8_t posx, uint8_t posy) {
    uint8_t x;
    uint8_t y;

    const uint8_t bw  = pgm_read_byte(&bit->width);   // this works -- I can print out to serial
    const uint8_t bh  = pgm_read_byte(&bit->height);  //this also works -- I can print out to serial
    // this doesn't work
    const uint8_t  *data = pgm_read_word(&bit->data); // I get: - initialization makes pointer from integer without a cast [enabled by default]

    const uint8_t  *data = (uint8_t *)pgm_read_word(&bit->data); // this also doen't work (no warning, but wrong data read out)

    //rest of function...

So I can access the width, height and image variable, but not the data part of the structure.
It all works if I don't store in flash - It's my retrieval and only has a problem with the data array part of the structure (width, height and image are read ok)

A: TL;DR: you cannot safely do that in standard C.
Given this definition ...

typedef struct {
    uint8_t width;
    uint8_t height; // row number 0 to 5
    uint8_t images; // how many frames does this bitmap have
    uint8_t data[]; // the actual pixel data
} bitmap_t;

... bitmap_t.data is a "flexible array member":

As a special case, the last element of a structure with more than one
  named member may have an incomplete array type; this is called a
  flexible array member. In most situations, the flexible array member
  is ignored. In particular, the size of the structure is as if the
  flexible array member were omitted except that it may have more
  trailing padding than the omission would imply. However, when a . (or
  ->) operator has a left operand that is (a pointer to) a structure with a flexible array member and the right operand names that member,
  it behaves as if that member were replaced with the longest array
  (with the same element type) that would not make the structure larger
  than the object being accessed [...].

[C2011 6.7.2.1/18; emphasis added]
Examples in the standard clarify that it is invalid to provide an initializer for a flexible array member, as your code attempts to do.  Moreover, there is no reason to expect that any space at all will be allocated for the contents of a flexible array member of an object with static or automatic storage duration, such as yours.  Flexible array members are useful only in conjunction with dynamically allocated objects, unless in an implementation that makes promises in this area beyond those required by the standard.
Accessing the flexible array member of your statically allocated object therefore produces undefined behavior.  This is not directly related to the actual location of the storage, though it is possible that the UB manifests differently when it is in flash.  (After all, the behavior is undefined.)  To use objects of type bitmap_t in the way you are trying to do, you will need to modify that type so that its data member has a complete type (i.e. fixed dimension(s)).

A: (independently of John Bollinger answer)
You incorrectly use pgm_read_word to ->data member of bitmap_t here and the code would not work even if the structure will be defined with, say, data[14].
Let XXX is an byte-size object in flash memory.
You can read it with pgm_read_byte(& XXX)
So that, one can read pixel at position pixel_number (data[pixel_number] object) this way:
// just address of first byte in data[]
const uint8_t  *data = bit->data;

uint8_t  pixel = pgm_read_byte(&data[pixel_number]);

The same result gets from direct structure access
uint8_t  pixel = pgm_read_byte(&bit->data[pixel_number]);

At last, modern avr-gcc compilers (those with the keyword __flash) can do this automatically.
Just declare all pointers with __flash modifier (<avr/pgmspace.h> can be omitted):
void lcd_bitmap2(__flash const bitmap_t *bit, uint8_t id,
                 uint8_t posx, uint8_t posy)
{
    uint8_t x;
    uint8_t y;

    const uint8_t bw  = bit->width;
    const uint8_t bh  = bit->height;
    __flash const uint8_t *data = bit->data;

    uint8_t pixel_number; // make calculations with id, bw, bh and positions

    uint8_t pixel = data[pixel_number];

    // or ditectly pixel = bit->data[pixel_number];

p.s. From my experience, avr-gcc process incomplete array initialization (also in flash) and access in the way you expected.


text:
Q: EJB Scheduler doesn't run every hour? I have an EJB Scheduler. I want that the Method runs every hour. But the Method only runs one Time. I don't know why.
This is my EJB Class:
@Singleton
public class DBTimeout {

  @PersistenceContext
  private EntityManager em;

  @Inject
  private Logger logger;

  @Schedule(second = "0", minute = "0", hour = "*/1", info = "Every 1 hour", persistent = false)
  public void refreshDBConnectionPool() {
    em.createNativeQuery("SELECT 1");
    logger.info("successfully executed cronejob for refreshing Database Connection Pool.");
  }

}

A: With Wildfly, make sure you're using standalone-full.xml as your configuration.  The default standalone.xml does not have support for EJB schedules.

A: hey can you try code from bellow?
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.ScheduleExpression;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.Timeout;
import javax.ejb.TimerService;

@Singleton
@Startup
public class DBTimeout {

    @PersistenceContext
    private EntityManager em;

    @Inject
    private Logger logger;

    @Resource
    private TimerService timerService;

    @Timeout
    public void timeOut() {
        refreshDBConnectionPool();
    }

    @PostConstruct
    public void initTimer() {
        System.out.println("INIT-CALLED");
        ScheduleExpression exp = new ScheduleExpression();
        exp.hour("*/1").minute("*");
        timerService.createCalendarTimer(exp);
    }

    public void refreshDBConnectionPool() {
        em.createNativeQuery("SELECT 1");
        logger.info("successfully executed cronejob for refreshing Database Connection Pool.");
   }
}


text:
Q: Bounded ration of functions If $f(x)$ is a continuous function on $\mathbb R$, and $f$ is doesn't vanish on $\mathbb R$, does this imply that the function $\frac{f\,'(x)}{f(x)}$ be bounded on $\mathbb R$?
The function $1/f(x)$ will be bounded because $f$ doesn't vanish, and I guess that the derivative will reduce the growth of the function $f$, so that the ration will be bounded, is this explanation correct!?

A: Take $f(x)=e^{x^2}$ then
$$\frac{f'(x)}{f(x)}= 2x$$ which is not bounded on $\mathbb{R}$
Also if $f(x)$ does not vanish it does not mean that $\frac{1}{f(x)}$ is bounded
for example take $e^{-x}$.

A: In fact for any positive continuous function $g(x)$ on $\mathbb R$ and any $y_0 \ne 0$, the differential equation $\dfrac{dy}{dx} = g(x) y$ with initial condition  $y(0) = y_0$ has a
unique solution $y = f(x) = y_0 \exp\left(\int_0^x g(t)\ dt\right)$, and this is a nonvanishing continuous function with $f'(x)/f(x) = g(x)$.    So $f'/f$ can do anything
a continuous function can.


text:
Q: PhoneGap/Cordova platform commands won't work Whether trying to update or add (after removing, which DID work), I get errors about missing directories/files, but it is looking in places where it shouldn't (and unsurprisingly can't find what it is looking for).  Doesn't seem to matter from what directory I issue the commands.
This happened after updating from v3.1.0 to v3.4.0, which went through without any complaints.
When I issued "cordova platform update ios" or "cordova platform update android", I got a complaint that a "platforms" directory was missing from the directory 2 levels up from where my project directory is.
Here's the error trace (from an OSX-Mavericks machine):
$ cordova platform update android
Error: ENOENT, no such file or directory '/Users/scott/Dropbox/platforms'
    at Object.fs.readdirSync (fs.js:654:18)
    at Object.module.exports.listPlatforms (/usr/local/lib/node_modules/cordova/src/util.js:106:19)
    at update (/usr/local/lib/node_modules/cordova/src/platform.js:104:48)
    at CLI.platform (/usr/local/lib/node_modules/cordova/src/platform.js:281:20)
    at new CLI (/usr/local/lib/node_modules/cordova/src/cli.js:158:26)
    at Object.<anonymous> (/usr/local/lib/node_modules/cordova/bin/cordova:41:16)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)

A: In-place upgrades of multiple cordova versions at once is not really supported.  You may have luck downgrading to cordova 3.2, updating your project, then cordova 3.3, etc.
However, the easiest and safest way to upgrade with such big moves is by re-creating your project using cordova create with the --copy-from argument to create a clone of your previous app assets.
If you really want to try one more shot of an in-place upgrade, I suggest you delete your .cordova directories in your workspace and home dir.  Won't necessarily fix your issues, but thats a change we've made in recent releases to not use those configs as much.


text:
Q: PayPal SOAP API Error 13606 When trying to call Refund API method with Payer ID and amount When I try to call RefundTransaction API method usiong PayerID i get Error "13606 Feature Not Enabled. You are not enabled for this feature.".
What it does mean? Is there a way to enable it?
To reproduce you can go to https://devtools-paypal.com/apiexplorer/PayPalAPIs and try to execute RefundTransaction method with PayerID and Amount filled in.

A: Direct from PayPal Support:

TransactionID and PayerID are marked "conditional", but you couldn't set blank.
For example, A buyer purchased several items in different period , but if you call RefundTransaciton API only set PayerID,
  PayPal couldn't judge in which transaction to refund, and also could not refund the amount about all of these items.
PayPal is not allowed this case happen.
So at least you have to set the transaction ID while calling the refund API.

So the solution is to always specify TransactionID.
Yes, their own API Documentation says:
"Either the transaction ID or the payer ID must be specified."
But apparently this is not the case.
If you don't log subscr_payment IPN calls, you can look up TransactionID from a PayerID by using the TransactionSearch API request. Put your PayerID in the ProfileID search field.


text:
Q: How to install Google Test on Ubuntu without root access? I am trying to install Google Test according to this answer on Ubuntu without root access, as I need learn and use it at work.
Managed to get these done in my own user folder:
$ mkdir ~/temp
$ cd ~/temp
$ unzip gtest-1.7.0.zip
$ cd gtest-1.7.0
$ mkdir mybuild
$ cd mybuild
$ cmake -DBUILD_SHARED_LIBS=ON -Dgtest_build_samples=ON -G"Unix Makefiles" ..
$ make

It seems I already have gtest in /usr/src/gtest altough I don't want to use this, because it was not me who installed it and I'm not sure about its version, nor in its availability. Can't even delete it without permission.
Still the instruction ends as:
$ cp -r ../include/gtest ~/usr/gtest/include/
$ cp lib*.so ~/usr/gtest/lib

What am I missing here?

A: Let's say you want to install googletest in /home/me/googletest.
Browse to the googletest GitHub repo https://github.com/google/googletest. (Do not use a possibly -out-of-date version you may have got elsewhere.)
Using the Clone or Download link, either clone or download-and-extract
the source as (let's say) ./googletest under your current directory CWD (where CWD is not /home/me/).
Then in CWD:-
$ mkdir googletest_build
$ cd googletest_build
$ cmake -DCMAKE_INSTALL_PREFIX:PATH=/home/me/googletest ../googletest
$ make
$ make install

After this, you will find:-
/home/me/googletest/
                lib/
                    libgmock.a
                    libgmock_main.a
                    libgtest.a
                    libgtest_main.a
                include/
                        gmock/
                            # gmock header files
                        gtest/
                            # gtest header files

You can then use gtest/gmock headers in your source code like:
#include <gtest/gtest.h>
#include <gmock/gmock.h>

and compile and link a gtest/gmock program like:
g++ -pthread -I/home/me/googletest/include -c -o my-unit-tester.o my-unit-tester.cpp
g++ -o my-unit-tester my-unit-tester.o -L/home/me/googletest/lib -lgtest -lgmock -pthread

using the -I... option to tell the compiler where gtest/gmock headers reside and
using the -L... option to tell the linker where gtest/gmock libraries reside.
Pass -pthread to both compiler and linker because the gtest/gmock libraries are
built multi-threading by default.
After installing you no longer need either CWD/googletest or CWD/googletest_build.
You may wish to pass additional options to cmake, in which case the build products will differ as per the meaning of those additional options.


text:
Q: Default lock settings SQL Server 2008 R2 I was looking for an answer to this, but I wasn't able to find the exact answer to my question.
The problem is that I'm actually having some SQL issues due to transactions lock at my database. I want to know, by default, does a SELECT statement lock a table? I found that if I use table hints such as HOLDLOCK or TABLOCK the select would lock the table untill it's completion, but when no table hint is specified what is the behavior of SQL? Joins would affect it's behavior?
And another question, picture the following scenario:
I start a connection and transaction at my .NET application and bind them to a command, which runs a stored procedure containing only a SELECT statement. Will the select lock the table due to the transaction or not?
Thanks for the attention.
Best regards.

A:
I want to know, by default, does a SELECT statement lock a table?

Yes.  All transactions create locks.  Not all locks are blocking (shared locks usually are not for example) but all transactions [that interact with the database] create locks.  Locks are how the query engine keeps track of what it's writing or reading.
Even if you specify NOLOCK or READUNCOMMITTED (which you generally don't want to do) you'll still get locks because the data needs to be consistent even if it's dirty, and the locks ensure that it is.  That is to say, even if it returns uncommitted records (dirty), there are no records that are incomplete or partially changed (inconsistent).

I found that if I use table hints such as HOLDLOCK or TABLOCK the select would lock the table [until] it's completion, but when no table hint is specified what is the behavior of SQL?

There are no default lock hints.  The query engine determines what it needs dynamically.  SELECT will tend towards Shared or RangeS key-range depending on the query.  INSERT/UPDATE/DELETE will tend towards exclusive locks.  The system will generally favor the lowest granularity, row locks, but will escalate them to page locks or table locks if it thinks it should.  Note: they're called "lock hints" and not "lock commands" because the query engine will ignore them if it has to.
The closest thing you'll find to default lock hints is the transaction isolation level, which generally controls how queries in a transaction function and defaults to READ COMMITTED.
Dynamic locking, lock granularity, lock escalation, and the lock hierarchy are all explained in the MS doc I already linked in the comment.
There's a huge amount of nuance and complexity to the locking system.  The same query on a different system might get different locks because the table sizes were different or memory pressures were different.
You can also modify the locking system significantly with ALLOW_SNAPSHOT_ISOLATION and READ_COMMITTED_SNAPSHOT database options, but I would not make those changes lightly.  It does make the database perform somewhat more like Oracle, however.

Joins would affect it's behavior?

Very much so.  To do a join, the query engine typically has to either scan indexes or the actual tables.  Indexes are subject to locks just like tables are, so I'd expect Shared or RangeS-S locks to appear on objects in the database.

And another question, picture the following scenario: I start a connection and transaction at my .NET application and bind them to a command, which runs a stored procedure containing only a SELECT statement. Will the select lock the table due to the transaction or not?

Yes.
If you're using System.Data.SqlClient.SqlTransaction, the default isolation level is ReadCommitted, which (unsurspisingly) maps to the READ COMMITTED isolation level.  If you're using System.Transactions, however, then you will default to Serializable, which maps to SERIALIZEABLE (the strictest isolation level).


text:
Q: Transpose values in excel using C# I saw this link - C# Transpose() method to transpose rows and columns in excel sheet in stackoverflow and this is what I am trying to do. But the guy is pretty unhelpful in the answers as he does not provide the full information needed. I am simply wanting to transpose cells A9:B15 in my excel sheet and then copy them either into a new xls file, a new worksheet, or better yet delete the current worksheet contents and replace it with the newly transposed paste contents. Clearly it can be done through the WorksheetFunction.Transpose method but I can't seem to get it to work as I don't know what rng or value2 are? I could create a datatable but surly using this method seems a more appropriate way of doing it. Here is the code from the stackoverflow question. .
Object[,] transposedRange = (Object[,])xlApp.WorksheetFunction.Transpose(rng.Value2);

xlApp.ActiveSheet.Range("A1").Resize(transposedRange.GetUpperBound(0), transposedRange.GetUpperBound(1)) = transposedRange;

Here is my code so far:
        Application excel = new Application();
        Workbook wb = excel.Workbooks.Open(@"P:\Visual Studio 2013\Projects\Debugging\Debugging\test.htm");
        Microsoft.Office.Interop.Excel.Range rng = excel.get_Range("A9:B15");
        Object[,] transposeRange = (Object[,])excel.WorksheetFunction.Transpose(rng);
        transposeRange = excel.ActiveSheet.Range("A1").Resize(transposeRange.GetUpperBound(0), transposeRange.GetUpperBound(1));
        wb.SaveAs(@"P:\Visual Studio 2013\Projects\Debugging\Debugging\testing.xls");

Not sure if I have done the rng right. I am so confused by this.

A: Is there some reason you need to do this in C#?
If what you want is just what you state, VBA code can accomplish this also.  Just

*

*read the transposed range into a variant array

*clear the worksheet

*write the variant array back to the worksheet at the cell of your choice.

*Note that when you write the variant array back to the worksheet, the destination range must be the same size as the array.

Option Explicit
Sub TransposeRange()
    Dim RGtoTranspose As Range
    Dim V As Variant
Set RGtoTranspose = Range("A9:B15")
V = WorksheetFunction.Transpose(RGtoTranspose)

Cells.Clear
Range("a1").Resize(UBound(V, 1), UBound(V, 2)).Value = V

End Sub

A: Seems like nobody actually bothered to answer this and its still the top search engine hit for this issue (@ July 2019, go figure...!), so here's my 2 cents...
I did not understand the hype about the WorksheetFunction.Transpose method. "Objectifying" things around isn't perhaps the cleanest way to go about this, particularly when using the Excel Interop anyway. At the end of the day, Transpose has been a dynamic parameter of the PasteSpecial() method since time immemorial. So why not use it as such? I think this was what prompted some people to suggest using VBA instead of C#... Anyway, this code works and does what the question requires methinks:
First get the references right...
using System;
using Microsoft.Office.Interop.Excel;
using Excel = Microsoft.Office.Interop.Excel;

Then try this...
    string filePath = @"P:\Visual Studio 2013\Projects\Debugging\Debugging\test.htm";
    string savePath = @"P:\Visual Studio 2013\Projects\Debugging\Debugging\testing.xls";

    var excelApp = new Excel.Application()
    {
        Visible = true      //This is optional
    };
    Workbooks workbook = excelApp.Workbooks;
    workbook.Open(filePath);

    Range range = excelApp.get_Range("A9:B15");
    range.Copy();

    excelApp.ActiveSheet.Range("A1").PasteSpecial(Transpose: true);     //voila... :)
    range.Delete(XlDeleteShiftDirection.xlShiftToLeft);     //delete original range

    if (!System.IO.File.Exists(savePath))           //is the workbook already saved?
    {
        excelApp.ActiveWorkbook.SaveAs(savePath);   //save
    }
    else
    {
        Console.WriteLine("File \"{0}\" already exists.", savePath);    //or do whatever...
        Console.ReadLine();
        return;
    }

It could be simplified further... but it is more readable like this.

A: This was asked a long time ago but I will let my sollution anyway.
Refs:
using Microsoft.Office.Interop.Excel;
using Excel = Microsoft.Office.Interop.Excel;

The trick here is to get the _Application Variable
in case you are using VSTO ADDIN with Workbook you can do like this:
var app = Globals.ThisWorkbook.Parent as _Application;

For other kind of project do like this:
_Application app2 = new Excel.Application();

My sample (sheet1 is my worksheet):
        var sheet1 = Globals.Planilha1;
        var arr = new string[]
        {
            "test1",
            "test2",
            "test3",
            "test4",
            "test5",
            "test6",
        };

        // For VSTO ADDINS with Workbook
        //var app = Globals.ThisWorkbook.Parent as _Application;

        // For any kind of Excel Interop project
        _Application app = new Excel.Application();

        sheet1.Range["A1:A" + arr.Length].Value = app.WorksheetFunction.Transpose(arr);

The Transpose function can only deal with arrays, lists won't work.
Just place the array inside the app.WorksheetFunction.Transpose function and it will work pretty well.
Output:


text:
Q: Get error when user has input a string in a scanf that keep float variable I am practicing c programming now and I made some BMI calculator. It works great but when user input string or character on the first scanf that send data to float variable 'weight' . It passed all scanf after that and showed error to me that Your BMI is 1.#J . How to solve this error? Here is my code.
#include <stdio.h>

int main()
{
  float weight;
  float height;
  float result;
  float c_height;

  printf("Enter your weight as kilogram...\n\n> ");
  scanf("%f",&weight);
  //If user input char or string , it passed all thing and showed error.

  printf("\nEnter your height as centimetres...\n\n> ");
  scanf("%f",&height);

  c_height=(height/100)*(height/100);
  result=weight/c_height;

  if(result<18.50)
  {
    printf("\nYour BMI is %.2f\n\n",result);
    printf("You are underweight! Try to eat more frequently\n\n");
    printf("Thank you for using my program!\n\n");

}else if(result>=18.50 && result<22.90)
{
    printf("\nYour BMI is %.2f\n\n",result);
    printf("You are healthy! Keep eating healthy\n\n");
    printf("Thank you for using my program!\n\n");

}else if(result>=22.90 && result<24.90)
{
    printf("\nYour BMI is %.2f\n\n",result);
    printf("You are a little overweight! Avoid eating some fat and an oil\n\n");
    printf("Thank you for using my program!\n\n");

}else if(result>=24.90 && result<29.90)
{
    printf("\nYour BMI is %.2f\n\n",result);
    printf("You are overweight! Avoid eating fat and do exercise often\n\n");
    printf("Thank you for using my program!\n\n");

}else if(result>=29.90)
{
    printf("\nYour BMI is %.2f\n\n",result);
    printf("You are obese! Do exercise everyday and eat carefully!\n\n");
    printf("Thank you for using my program!\n\n");

}else
{
    printf("Error occured!!");
}
return 0;

}

A: scanf will return the number of values read in, so should be one in your example, as you are reading in a single float value.
You could check that scanf returns that value and if it doesn't do some kind of recovery such as reading until end of line:
while(scanf("%f",&height) != 1)
{
  int c;
  while((c = getchar()) != '\n' && c != EOF)
    ;
  printf("Enter your weight as kilogram...\n\n> ");
}

A: To pass to the next argument  add an fflush(stdin) after the scanf :
scanf("%f",&weight);

  fflush(stdin);

and you need to controle your input like this :
if (scanf("%lf", &weight) == 1)
    printf("It's float: %f\n", weight);
else
    printf("It's NOT float ... \n");


text:
Q: Session variables not 'updating' first time loading page - XMLHttpRequest, PHP I'm trying to have session variables updated with an XMLHttpRequest, and have them output on the page.
When loading the page, they don't show. It just says "today: ", "yesterday: ", without the session variables.
When I reload the page, they show correctly. I don't understand why it's not working the first time -- clearly something to do with the order of the code, but from my understanding, everything here is as it should be?
JavaScript:
    //simple strings to demonstrate problem:
    var date = "04052020";
    var yesterday = "03052020";

    var xmlhttp=new XMLHttpRequest();
    xmlhttp.onreadystatechange=function() {
        if (this.readyState==4 && this.status==200) {

            document.getElementById("streak").innerHTML = "<?php
                echo "
 today: ".$_SESSION['todayDate'];
                echo "
 yesterday: ".$_SESSION['yesterdayDate'];
            ?>";
        }
    }
    xmlhttp.open("GET","../practice/includes/stats.inc.php?date="+date+yesterday+"h",true);
    xmlhttp.send();

PHP file (stats.inc.php):
    $datesIn = $_GET['date'];

    $today = substr($datesIn, 0, 8);
    $_SESSION['todayDate'] = $today;

    $yesterday = substr($datesIn, 8, 8);
    $_SESSION['yesterdayDate'] = $yesterday;


text:
Q: IE mouseleave event not contains right mouse coordinates Can somebody help me?
Im trying to handle mouseleave event in js, and doing some login based from which parts (coordinates) window it leaves, actually e.clientX and e.clientY params.
Its correct work in Chrome/Safari/Firefox, but unfortunately not in IE.
In all version of IE, when mouse leave the window, e.clientX and e.clientY equals -1, and it disappoint me.
Does somebody met with this situation? And which is the best way to avoid it.
Thnks for you attention :)


text:
Q: How do I manually set the active image for jquery-lightbox? I am trying to create a photo viewer in Ruby on Rails using jquery-lightbox. You can see the design of it in the image below.
You click on the smaller images to have the selected image appear in the large space above. If you click the large image, you can view a lightbox slideshow of all the images at their originally uploaded resolution.
I have all of this working so far, but I need the lightbox to start at the currently selected image, rather than always starting at the first image. I've tried calling the changeImage function (returns TypeError) and changing the activeImage property (does nothing).
How can this be done?
Here is the code I'm using, which is currently all in my show.html.erb:
<a href="<%= @actor.avatar.url(:large) %>" onclick="javascript:setActiveImage();" class="lightbox" title="<%= @actor.name %>" rel="actor"><%= image_tag @actor.avatar.url(:slide), :id => "actor_headshot", :alt => @actor.name %>

<% @actor.photos.each do |photo| %>
  <a href="<%= photo.photo.url(:large) %>" class="lightbox" rel="actor">
<% end %>

  <% @photos.each_with_index.map do |photo, index| %>
      <a href="#" onclick="javascript:swapHeadshot('<%= photo.url(:slide) %>', <%= index %>);"><%= image_tag photo.url(:thumb), :class => "actor_photo_list_item" %>
    <% end %>

A: By default jQuery Lightbox comes with prev/next buttons. You might wanna take a look into that code an create a function based on either one of them since they most likely will provide you an answer.
Inside the code it says:
$('#lightboxImage').attr('src', opts.imageArray[opts.activeImage][0])width(newWidth).height(newHeight);
resizeImageContainer(newWidth, newHeight);

I think that's the code you're looking for.
// Edit: made the same mistake as the one above, except he's given an answer already.

A: changeImage sounds like the name of a function, but your code is:
$('.lightbox').lightbox.changeImage =(_am); //tries to change a function variable to a number

Are you sure it shouldn't be:
$('.lightbox').lightbox.changeImage(_am); //calls the function passing a variable


text:
Q: display same table data in multiple times on click of add button using javascript I am having 3 text boxes in a table if i click add button the same text boxes need to append in the same page using javascript.Please help me

A: Ypur question is not clear but i guess you want something like this
function buttonClick(parent){
var test = document.createElement("input");
test.setAttribute("type", "text");
test.setAttribute("name", "someName");

parent.appendChild(test);
}

call this function on button click event with a parent element as arguement


text:
Q: ConfigurationManager ConnectionString Throwing Error and returning null I am totally stunned as why one of my unit tests is failing. It is a simple test to see if the correct connectionstring is returned. My App.config looks like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
   <system.web>
      <compilation defaultLanguage="c#" debug="true" />
   </system.web>
   <connectionStrings>
      <add name="DbConnectionString" connectionString="Test_HighOnCoding_Db" />
   </connectionStrings>
</configuration>

And here is my simple unit test which always throws null exception:
[TestFixture]
public class when_retrieving_database_name_from_config
{
    [Test]
    public void should_get_the_correct_database_name()
    {
       var dbName = ConfigurationManager.ConnectionStrings["DbConnectionString"].ConnectionString;

       // dbName is always null

       Assert.AreEqual("Test_HighOnCoding_Db",dbName);
    }
 }

A: My original answer does not apply per your comment below.
One thing I'll suggest checking, then; Is your app.config file being moved into the directory with your program, and being renamed to the same as the program, with .config added?
So, program.exe has program.exe.config as the config file?`
It looks like you have a Web application here; if so, your configuration file should be web.config rather than app.config. Then, you should be using the WebConfigurationManager from the System.Web.Configuration namespace.

A: It is a simple fix - put the app.config in your test project.
Because you are running from a test, the app.config needs to be in your test project, and NOT with your actual program project.
When executing your test, the context of the running application is from your test assembly, so ConfigurationManager.ConnectionStrings will be looking ONLY in your test project bin folder for YourTestAssembly.dll.config (which is auto generated from your app.config in you test project folder).

A: if your testdll is MyTests.dll your app.config in that sub-projet will become MyTests.dll.config. Unfortunately nunit wants "MyTests.config" (without the ".dll.")
to solve this issue

*

*create a nunit-project for "MyTests"

*

*open nunit-gui

*create a new nunit project "MyTests.nunit" in the bin folder

*add MyTests.dll to MyTests.nunit

*save the nunit project.

*exit nunit

*add "MyTests.nunit" to your solution

*

*copy "MyTests.nunit" to the project source. make shure that settings are

*buildaction = none

*copy to Ouptut Dir = always

*create a configfile "MyTests.config" for "MyTests.nunit"

*

*under project settings/build events/PostBildEventCommandLine add

*copy $(ProjectDir)\app.config $(TargetDir)\$(TargetName).config

now you can run your unittest by opening "MyTests.nunit"


text:
Q: Youtube analytics API - different information in case of owning a channel? I want to retrieve some data from youtube channels, which I am not the owner of. I have the following questions:

*

*List item 1) Are there proposed ways to do this and

*List item 2) is the information I can access different from the one that I can access as a channel owner?
Thanks!


text:
Q: How to display the values of a model that contains a HashMap of objects? I have a hashmap as follows:
HashMap<String, Object> myHashMap = new HashMap<String, Object>();

The data in it looks like this:
{CompanyName=null, CompanyId=null}

I would like to iterate over this and display values from it in my presentation layer.
I add it to my model as follows:public String
showPage(Map model)
{
        HashMap<String, Object> myHashMap =  new HashMap<String, Object>();

        model.put("company", myHashMap);

        return "page";
}

My JSP

${companyName}

<fieldset>

        <form:label path="companyName" cssErrorClass="form-error">Issuer Name</form:label>

</fieldset>
<input type="submit" value="Next" class="round blue ic-right-arrow" />

I get the following error:
Caused by: org.springframework.beans.NotReadablePropertyException: Invalid property 'companyName' of bean class [java.util.HashMap]: Bean property 'companyName' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?

A: try like below it might work
${company["CompanyName"]}


text:
Q: HTML5 & CSS3 fixed navigation bar I'm trying to create my first website manually, and I have a few questions on how to do things. Please note I want to accomplish this in pure HTML5, no JS. All I have right now is a navigation header, which should stay fixed at the top of the page no matter how far one scrolls. However, in order to get an image to respect this header size, I've had to resort to using css in the following manner:
main {
    position: absolute;
    top: 60px;
    z-index: -1;
}

Is there a a more elegant way to accomplish this? Additionally, is there a more relative way to accomplish spacing than using px? I know about rem for font, but is there anything similar for spacing? My reading indicates that retina screens honor a 2px conversion, but what about 4k screens?
Also, how do I center text vertically in the header spacing?
Lastly, how do I reference a locally installed font on a person's desktop, hopefully negating the need to download a font from the server?
css3
* { all: unset }

@font-face {
    font-family: 'biolinum';
    src: url('LinBiolinum_R.woff'),
         local('Linux Biolinum O');
}

.logo {
    float: left;
    height: 50px;
    padding: 5px;
}

.image {
    height: auto;
    width: 100%;
    background: black;
}

header {
    position: fixed;
    height: 60px;
    width: 100%;
    background: white;
}

main {
    position: absolute;
    top: 60px;
    z-index: -1;
}

nav {
    list-style-type: none;
    float: right;
    font-family: 'biolinum';
    font-size: 1.25rem;
    color: #465053;
    text-transform: uppercase;
}

p {
    font-family: 'biolinum';
    font-size: 1rem;
    color: #465053;
    text-align: justify;
}

title {
    display: none;
}

html5

        <title>Title</title>

        <link rel='icon' href='images/logo.svg'>
        <link rel='stylesheet' href='css/style.css'>

                about
                design
                analysis
                contact

A:
I'm trying to create my first website manually, and I have a few questions on how to do things. Please note I want to accomplish this in pure HTML5, no JS. All I have right now is a navigation header, which should stay fixed at the top of the page no matter how far one scrolls. However, in order to get an image to respect this header size, I've had to resort to using css in the following manner:
Is there a a more elegant way to accomplish this?

Another way to do it is like this:
body
{
    overflow: hidden;
}
header {
    height: 20vh;
}
main {
    height: 80vh;
    overflow: scroll;
}

Whether you think that is more or less elegant is up to you.

Additionally, is there a more relative way to accomplish spacing than using px? I know about rem for font, but is there anything similar for spacing? My reading indicates that retina screens honor a 2px conversion, but what about 4k screens?

You can use "vh" as I did above, which is percentage of viewport height.

Also, how do I center text vertically in the header spacing?

nav {
    text-align: center;
}

This will center the text within the nav.

Lastly, how do I reference a locally installed font on a person's desktop, hopefully negating the need to download a font from the server?

p {
    font-family:"Times New Roman";
}

If it is installed on the users desktop you should be able to reference it like this.


text:
Q: Rails: running my seeds file and elasticsearch throws: more than one indices So I'm running a large and fairly complicated seeds file. I batch the creation of all types of associated records before batch saving them. I'm running into an issue where I'm given this error:
Elasticsearch::Transport::Transport::Errors::BadRequest: [400]
{"error":{"root_cause":
[{"type":"illegal_argument_exception","reason":"Alias
[clients_development] has more than one indices associated with it
[[clients_development_20170106095823597,
clients_development_20161123102035835]], can't execute a single index
op"}],"type":"illegal_argument_exception","reason":"Alias
[clients_development] has more than one indices associated with it
[[clients_development_20170106095823597,
clients_development_20161123102035835]], can't execute a single index
op"},"status":400}
/Users/

Looks like I have a db issue? Test/dev db, maybe? I've run through a lot of rake commands, but they amount this this bad boy:
rake db:drop && rake db:create && rake db:migrate && rake db:schema:dump && rake db:test:prepare

I run into the same error along the way of this. Any one have an idea on what's going on?

A: You might try making sure that you don't have Elasticsearch running in more than one place. After that, try reindexing all records:
rake searchkick:reindex:all


text:
Q: GNU GRUB version 2.02~beta2-9ubuntu1 WHAT IS HAPPENING My computer (Acer Aspire One) that has Ubuntu installed started showing this on boot:
GNU GRUB version 2.02~beta2-9ubuntu1

*Ubuntu

Advanced Options for Ubuntu

Memory Test (memtest86+)

Memory Test (memtest86+, serial console 115200)

And I have no idea how to fix it.
Please tell me specifically how to fix it I don't know programming.

A: Nothing wrong has happened, everything is completely fine, that's just the GRUB menu. Either you press enter now or just wait for 10 secs to boot to your OS.
For better understanding from GNU:

GNU GRUB is a Multiboot boot loader. It was derived from GRUB, the
  GRand Unified Bootloader, which was originally designed and
  implemented by Erich Stefan Boleyn.
Briefly, a boot loader is the first software program that runs when a
  computer starts. It is responsible for loading and transferring
  control to the operating system kernel software (such as the Hurd or
  Linux). The kernel, in turn, initializes the rest of the operating
  system (e.g. GNU).


text:
Q: Concatenating synthesized tones in python I'm using the following code which will generate a wav file which contains a tone at 440 Hz lasting for 2 seconds.
from scipy.io.wavfile import write
from numpy import linspace,sin,pi,int16

def note(freq, len, amp=1, rate=44100):
 t = linspace(0,len,len*rate)
 data = sin(2*pi*freq*t)*amp
 return data.astype(int16) # two byte integers

tone = note(440,2,amp=10000)

write('440hzAtone.wav',44100,tone) # writing the sound to a file

I was wondering if I could modify the code, basing it off the note method, in order to actually generate a tune with python.
I tried adding two different tones, and as expected the two tones play simultaneously, creating something which sounds a bit like a dial tone:
tone1 = note(440,2,amp=10000)
tone2 = note(480,2,amp=10000)
tone = tone1+tone2

write('440hzAtone.wav',44100,tone)

I also tried multiplying the two tones, but this just generates static.
I also tried genreating tones of different lengths and adding them, however this causes an exception to be raised, like so:
tone1 = note(440,2,amp=10000)
tone2 = note(480,1,amp=10000)
tone = tone1+tone2

write('440hzAtone.wav',44100,tone)

causes:
ValueError: operands could not be broadcast together with shapes (88200) (44100)

So, I was wondering - how can I concatenate different tones like this to make a tune?

A: You can do this using numpy.concatenate, (as already posted). You need to specify the concatenation axis also. Using very low rate to illustrate:
from scipy.io.wavfile import write
from numpy import linspace,sin,pi,int16,concatenate

def note(freq, len, amp=1, rate=5):
 t = linspace(0,len,len*rate)
 data = sin(2*pi*freq*t)*amp
 return data.astype(int16) # two byte integers

tone1 = note(440,2,amp=10)
tone2 = note(140,2,amp=10)
print tone1
print tone2
print concatenate((tone2,tone1),axis=1)

#output:
[ 0 -9 -3  8  6 -6 -8  3  9  0]
[ 0  6  9  8  3 -3 -8 -9 -6  0]
[ 0  6  9  8  3 -3 -8 -9 -6  0  0 -9 -3  8  6 -6 -8  3  9  0]

A: numpy.linspace creates a numpy array. To concatenate the tones, you'd want to concatenate the corresponding arrays. For this, a bit of Googling indicates that Numpy provides the helpfully named numpy.concatenate function.


text:
Q: Make Button Follow Mouse Cursor I'm trying to make a button follow the cursor, but my code only seems to just go to the mouse cursor right after execution and just stay there. Can anyone give me the correct code and help me?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            button1.Location = Cursor.Position;

        }
    }
}

A: I would suggest overriding the OnMouseMove method of the MainForm and using the Location property of the MouseEventArgs e argument. This will provide the correct Client coordinates of the cursor taking into account where MainForm is located on the screen. Then you can offset that value using the Width and Height properties of buttonMoveMe to center it on the mouse.
public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
    }
    protected override void OnMouseMove(MouseEventArgs e)
    {
        base.OnMouseMove(e);
        var point = new Point(
            e.Location.X - (buttonMoveMe.Width / 2),
            e.Location.Y - (buttonMoveMe.Height / 2));
        buttonMoveMe.Location = point;
    }
}

Be aware that this event _will not be received when the mouse is over the button itself. The button will be getting the MouseMove events (not the MainForm) in this case. In other words, this basic suggestion only moves the button when the mouse leaves the button.

A: I think you need to use the MouseMove event.
So these are things you need to do:

*

*Create a button control which is going to follow the cursor. (I will call it yourButton)

*Open event menu of the control (click on it in the constructor).

*Find event MouseMove inside Mouse category.

*Double click on it. (This will automatically create the method which will be linked to the event)

*In this method write: yourButton.Location = e.Location;
So it should look like that:
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
    yourButton.Location = e.Location;
}

In my example I made button follow my cursor inside the form.
If you need shorter way, you can just copy-paste the method I wrote before and in the form class constructor add:
this.MouseMove += Form1_MouseMove;

In this way your code would look like that:
public Form1()
{
    InitializeComponent();
    this.MouseMove += Form1_MouseMove;
}

private void Form1_MouseMove(object sender, MouseEventArgs e)
{
    yourButton.Location = e.Location;
}

Hope this will help you, have a nice day!
UPD:
In case you want the cursor to be in the center of the button, you should edit our previous Form1_MouseMove and add one more event.

*

*Edit the code of Form1_MouseMove, now it should be:
yourButton.Location = new Point(e.X - yourButton.Width / 2, e.Y - yourButton.Height / 2);

*Now you need to use MouseMove method of the button (Follow the previous steps, but for button (Click on it -> Events -> Mouse category -> double click on MouseMove))

*In newly created method write:
yourButton.Location = new Point(e.X + yourButton.Left - yourButton.Width / 2, e.Y + yourButton.Top - yourButton.Height / 2);
Hope this helped now)

A: Your Form1_Load method is only executed, as its name says, when the form is loaded.
You want to execute your code every time the mouse move, si you can do it like this (not tested):
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        this.MouseMove += Form1_MouseMove;
    }

    private void Form1_MouseMove(object sender, MouseEventArgs e)
    {
        button1.Location = Cursor.Position;
    }
}


text:
Q: Play audio .flac vs .fla in IIS via virtual directory I do have an audio angular app with Microsoft dotnet core 6 backend and many audio files accesses via virtual directory.  I can access any files except files with .flac extension (I have added .flac and audio/flac to mime type file in IIS).  The error code is 404.  However, if I change the file extension from .flac to .fla then it works and I can play it as Flac file.
How can I tell the iis to accept/ access the .flac file?
I am running windows 10 64bit with IIS.
Thanks.


text:
Q: Finding the PDF of $Y = X^2$ given the pdf and cdf of $X$, where $X$ is uniformly distributed Example picture
In the above picture (taken from here), they use an alternative way to find the pdf using a change of variables rather than the fundamental theorem of calculus. Specifically, my question involves this part:
$$y = x ^2 \rightarrow dy = 2xdx \rightarrow dx = \frac{dy}{2 \sqrt{y}}$$
$$f_X(x) dx = \frac{dx}{2} = \frac{dy}{4 \sqrt{y}} = f_Y(y) dy$$
How do they equate $\frac{dy}{4 \sqrt{y}}$ to $f_Y(y) dy$ ? I can't figure out how they got this equality

A: $F_Y(y) = F_X(x)$ so $$\dfrac{\mathrm d F_Y(y)}{\mathrm d y}=\dfrac{\mathrm d F_X(x)}{\mathrm d y}$$
Apply the Chain Rule to obtain:
$$f_Y(y) = f_X(x)\dfrac{\mathrm d x}{\mathrm d y}$$
Now substitute $x:= +\surd y$ and $\mathrm dx := (\mathrm d y)/2\surd y$  (or rather $\tfrac{\mathrm d x}{\mathrm dy}=\tfrac{\mathrm d \surd y}{\mathrm d y}=\tfrac 1{2\surd y}$ )
$$f_Y(y) = f_X(\surd y)\dfrac {1}{2\surd y}$$

The rest is that $f_X(x) = 1/2$ under $x\in(0..2)$  because this example is uniformly distributed over that support.
$$f_Y(y) = \dfrac {1}{4\surd y}\quad\big[ ~y\in(0..4)~\big]$$

A:
I can't figure out how they got this equality

In your example $X\sim U(0;2)$ thus $f_X(x)=\frac{1}{2}$
You arrive at
$$dx=\frac{dy}{2\sqrt{y}}$$
thus this is the same as
$$f_X(x)dx=\frac{1}{2}dx=\frac{1}{2}\cdot\frac{dy}{2\sqrt{y}}=f_Y(y)dy$$

but your main question is how to apply this procedure when $X$ is gaussian. Before doing the calculation, it is important to know if your gaussian is centered (gaussian with mean 0) or it is not...


text:
Q: Finding the right marker size for a scatter plot I want to plot a grid where each node in the grid is drawn by a dot, with a certain color code (taken from a vector stored in the node).

the grid here varies in size depending on the size of the simulations I am running.  I have yet to figure out the relationship between the canvas size and the marker size.  Now I use the following formula:
markersize = (figsize*figsize*dpi*dpi)/(xdim*ydim)
plt.scatter(X, Y, s=markersize/3, marker='s', c=Z, cmap=cm.rainbow)
plt.show()

that is I square the sigsize and the dpi (use 15 and 80 respectively), and divide by the dimensionality of the grid.  Finally I divide this by 3 as I found this to work.
But I haven't been able to work out how to analytically get the right marker size.  What I want is a grid where each square uses as much a space as it can but without "infringinig" on the other nodes' space, so that the markers overlap.
As far as I can read the figsize is given in inches.  dpi is - dots per inch, and the markersize is specified in - points.  If the points is the same as dots, you would then have dpifigsize amount of dots on each axis.  The xdimydim is the amount of nodes in my grid.  Dividing the pow(dpifigsize, 2) / xdimydim should then give the amounts of dots per node, and the right size for each marker I thought. But that made the markers too big.  I diveded by 3 and it sort of worked practically for the sizes I usually run, but not for all.  (I am guessing a point and a dot is not the same, but what is the relation?)
How do I work out the correct answer for this?  Ideally I would like a very granular picture where I could zoom in an certain areas to get a finer look at the color nuances.

A: If you want to control the marker size precisely and have it scale with the figure, you can use a patch instead of a regular marker. Here's an example:
from matplotlib import pyplot as plt
from matplotlib.patches import Circle

x = [1, 2, 3, 4, 5]
y = [1, 3, 1, 2, 4]
colors = [10, 215, 30, 100]

cmap = plt.cm.jet
fig = plt.figure()
ax = fig.add_subplot(111, aspect='equal')

for (x, y, c) in zip(x, y, colors):
    ax.add_artist(Circle(xy=(x, y), radius=0.5, color=cmap(c)))

ax.set_xlim(0, 6)
ax.set_ylim(0, 6)
plt.show()

You could also use a rectangle instead of a circle.


text:
Q: How to use my C# webservice methods and call them to my website I have a c# webservice with some methods that look like this:
[OperationContract]
    public List<CSMaquina> GetMaquinaByLoja(String IDLoja)
    {
        try
        {
            string queryString = "SELECT * FROM Maquina WHERE LJA_ID = @LJA_ID";
            List<CSParameter> Parameters = new List<CSParameter>();
            CSParameter parameter = new CSParameter();
            parameter.FieldName = "LJA_ID";
            parameter.FieldSize = 0;
            parameter.FieldType = (int)enFieldType.Integer;
            parameter.Value = IDLoja;
            Parameters.Add(parameter);

            DataTable dt = ExecuteQuery(queryString, Parameters, CommandType.Text);

            List<CSMaquina> Maquinas = new List<CSMaquina>();
            CSMaquina maquina;

            foreach (DataRow row in dt.Rows)
            {
                maquina = new CSMaquina();
                maquina.LJA_ID = int.Parse(row["LJA_ID"].ToString());
                maquina.MAQ_Numero = int.Parse(row["MAQ_Numero"].ToString());

                Maquinas.Add(maquina);
            }

            return Maquinas;
        }
        catch (Exception ex)
        {
            throw new FaultException(
                 new FaultReason(ex.Message),
                 new FaultCode("General"));
        }
    }

I would like to know if you can help me using that kind of methods to fill a comboBox in my site. I'm new in this webservices stuff so if you can say/teach to me the best way to integer that in my site I'll by very thankful.


text:
Q: Taking the sum of a list without sum() I have a list that gets generated when a user inputs a random number they want. I want to add the sum together with out using sum(). How could I do this?
xAmount = int(input("How man numbers would you like to input: "))

numList = []

for i in range(0, xAmount):
     numList.append(int(input("Enter a number: ")))

print(numList)

From here

A: You don't need a list at all.
xAmount = int(input("How man numbers would you like to input: "))
result = 0

for i in range(0, xAmount):
     result = result + int(input("Enter a number: "))

print(result)

A: Store the sum in a temp variable. Keep adding the input numbers to the temp variable:
xAmount = int(input("How man numbers would you like to input: "))

numList = []
numList_sum = 0

for i in range(0, xAmount):
     inputted_number = int(input("Enter a number: "))
     numList_sum += inputted_number
     numList.append(inputted_number)

print(numList)
print(numList_sum)

A: To sum a list just iterate over the list, adding up the individual values:
num_total = 0
for value in numList:
    num_total += value

You could also use reduce but this might not meet your h/w requirements either:
from functools import reduce
from operator import add
num_total = reduce(add, numList, 0)


text:
Q: Determinism with insert in unordered containers If I insert the same (size and value) elements in two unordered containers, will traversing the containers with two iterators always give the same element in the same position?
If yes, can a (single!) hash function be made to break this determinism ?

A: It depends: if you insert the same elements in the same order into two different unordered containers, then the order should be the same across both containers, even though the order itself is unspecified.
The reasoning is a little convoluted: all operations like hash(k) and the reallocations are deterministic. There is no actual quote in the Standard though,  but the ability to do a find() in O(1) after an insert() seems to rule out any kind of randomized or otherwise non-deterministic insertion.
However, if you change the order of insertion, then all bets are off because internal reallocations will change the order of elements:
23.2.5 Unordered associative containers [unord.req]

9 The elements of an unordered associative container are organized
  into buckets. Keys with the same hash code appear in the same bucket.
  The number of buckets is automatically increased as elements are added
  to an unordered associative container, so that the average number of
  elements per bucket is kept below a bound. Rehashing invalidates
  iterators, changes ordering between elements, and changes which
  buckets elements appear in, but does not invalidate pointers or
  references to elements. For unordered_multiset and unordered_multimap,
  rehashing preserves the relative ordering of equivalent elements.


text:
Q: single signon support for mediawiki I'm attempting to support single signon in a system that includes MediaWiki.  I have a universal cookie that can be used to make a remote call to get logged in user information, but I'm struggling with MediaWiki's documentation/code base to see where I might plug in my 'check'.  Since php doesn't have a 'servlet filter' concept per se, I need to embed something into the mediawiki page that will make the call and set up $wgUser.
Does anyone have any experience of where I might do that? There must be some plug points I can tap into (templates somehow?), but my php is too weak to ferret it out in the mediawiki code.

A: You'll need to create an AuthPlugin.  You'll do this by defining a new class that extends the AuthPlugin class.  In your LocalsSettings.php file, tell MediaWiki to use your AuthPlugin by setting $wgAuth equal to a new instance of that new class.  You'll probably use some hooks such as UserLoadFromSession, too.
You might find it easier to review a preexisting Single Sign-on extension to see how it operates.  One example is the QISSingleSignOn extension.


text:
Q: Algorithm for counting common group memberships with big data I need to write a program that counts the number of times two users are in the same group. The users are given by username and groups by id.
For example, with the input (stored in a text-file):
john 32
john 21
jim 21
jim 32
bob 32

I want the result:
john-jim 2
john-bob 1
jim-bob 1

This sounds trivial. But the problem is: I have 1,8 million groups and 300,000 users. And a lot of memberships (I'm expecting at least an average of 50 per user, possibly much more). This means a HUGE amount of data and processing.
I've written 5 different programs doing this, none of which has been able to cut the amount of data:  It was too slow as an PostgreSQL query. Too memory consuming running in a Map in Java working memory (first heap space, after optimization I got the rare "GC overhead limit exceeded"). Too slow to write continuously to database from Java (even when optimized using batch-queries). Growing increasingly desperate, I've tried some more exotic things, like writing all the pairs to an array, then sorting them (O(n log (n))) and then counting them peu à peu. But it was still way too much data to store in memory.
Any ideas on an algorithm for doing this? Or is it impossible?

A: An RDBMS is specialized in operations like sorting. Doing this outside the DB will hardly ever come even close in performance. Do it with SQL!
This would do the job (simplified in update):
SELECT t1.usr || '-' || t2.usr, count(*) AS ct
FROM   usr_grp t1
JOIN   usr_grp t2 USING (grp_id)
WHERE  t2.usr > t1.usr   -- prevent dupes and get sorted pair
GROUP  BY t1.usr, t2.usr;

Depending on how many overlaps you have, this potentially produces a HUGE amount of rows, as you said. So this is never going to be fast.
Raises the question: What's the purpose of producing millions of rows that nobody can process? Are you sure, the operation makes sense to begin with?
To make it faster, you could ..

*

*Upgrade! PostgreSQL 8.4 is rather outdated by now. In particular, PostgreSQL 9.2 had its focus on big data. You can expect much better performance for a job like this.
And nobody should be running 8.4.0. For security reasons alone, but you are missing out on lot of bug-fixes, too. The current point-release is 8.4.17. I quote the linked web-site:

We always recommend that all users run the latest available minor
  release for whatever major version is in use.

*

*use an integer as surrogate key for users, so you deal with integers only in usr_grp. Makes table and indexes smaller and processing faster. If the n:m table (usr_grp) has a much bigger cardinality than the table usr, this should be faster, even if it means additional joins.

SELECT u1.usr  || '-' || u2.usr, count(*) AS ct
FROM   usr_grp t1
JOIN   usr_grp t2 USING (grp_id)
JOIN   usr u1 ON t1.usr_id = u1.usr_id
JOIN   usr u2 ON t2.usr_id = u2.usr_id
WHERE  t2.usr_id > t1.usr_id
GROUP  BY u1.usr_id, u2.usr_id;

*

*Create a multi-column index (if you don't have it yet).
grp_id must come first. Why does this matter?

    CREATE INDEX usr_grp_gu_idx ON usr_grp(grp_id, usr_id);

*

*Put a lot of RAM into your machine and increase the settings for work_mem and shared_buffers.

Test case
I took the numbers @OldCurmudgeon reported for his test case and created a comparable test case in PostgreSQL.
-> SQLfiddle demo.
~ 250 ms in this public test database.
The result is not ordered (no ORDER BY) since this hasn't been specified.
As compared to 2.5 minutes, reported below. Factor 600.

A: How about letting your file system do it.
For each entry - open a file named for the group ID and append the new user's name. You will end up with one file per group.
You now have - for example:
Group-21.txt
 jim
 john

Group-32.txt
 bob
 jim
 john

Now run through all files, generating every user-name pair in it (I would sort the names and perform a standard combination process on them). For each pair, append a "1" to a file with a specific name.
You now have - for example:
User-jim-john.txt
 11

User-bob-jim.txt
 1

User-bob-john.txt
 1

You now have the pairs in file names and counts (in unary so all you really need is the file size in bytes) in the files.
Almost all of this could be done in parallel although phase 1 must complete before phase 2 begins. To improve speed - add cores - buy a faster disk. There is no memory limit, just disk.
Added: I've just run some simulation tests on this algorithm using just one thread
1800 groups, 300 users and 15000 memberships all randomly generated took about 2.5 minutes.
900 groups, 150 users and 7500 memberships took 54 seconds.

A: Whatever the solution, the complexity depends on the number of pairs generated, not necessarily on the number of groups or persons. For different group sizes:

*

*a group with 10 members produces C(10,2) = 45 pairs

*a group with 100 members produces C(100,2) = 4950 pairs

*a group with 1000 members, 499500 pairs...

*with 10000 members, a single group will produce close to 50 million pairs! A single group can thus out weight the entire cost of the rest of the computation.

So my first suggestion would be to weed out very large groups in the dataset. If you can't omit large groups, and find out that it is not going to fit in memory or it will take ages to plow through it with a single thread, you can use Map-Reduce to automatically parallelize the computation as follows. If you start with group memberships such as:
32 -> john, jim, bob
21 -> john, jim

you can use the map step to produce all pairs:
john-jim -> 32, john-bob -> 32, jim-bob -> 32
john-jim -> 21

These will get aggregated for you by name pair. Then in reduce, just count the occurrences of each key. This assumes that you have plenty of disk to store all pairs.