text:
Q: How to deduce open mapping theorem from closed graph theorem? These two theorems are equivalent but I can not figure out how to deduce the open mapping from the closed graph. Can anyone give a hint or some reference?

A: The proof linked to by David is the standard one, but the write-up strikes me as  somewhat clumsy.
Here's my take on this argument:
Suppose $T: X \to Y$ is continuous and onto.

*

*The map $\pi: X \to \bar{X} = X/ \operatorname{Ker}{T}$ is open, onto and continuous. The map $T$ factors over $\pi$ via a continuous linear bijection $\bar{T}: \bar{X} \to Y$ by definition of the quotient topology.

*By continuity of $\bar{T}$ the graph of $\bar{T}$ is closed. Switching coordinates $(\bar{x},y) \mapsto (y,\bar{x})$ is a homeomorphism $\bar{X} \times Y \to Y \times \bar{X}$ and it maps the graph of $\bar{T}$ to the graph of $\bar{T}^{-1}$, so the graph of the linear map $\bar{T}^{-1}$ is closed, too. By the closed graph theorem $\bar{T}^{-1}$ is continuous.

*For all open $U \subset X$ the set $T(U) \subset Y$ is open because it is the pre-image of the open set $\pi(U)$ under the continuous map $\bar{T}^{-1}$, hence $T$ is open.
Note: Step 2. is a proof of the inverse mapping theorem from the closed graph theorem.


text:
Q: php json decode bool(true) I have Json array returned from API
$json_array = curl_exec($curl);
var_dump($json_array);
echo '<br>'.mb_detect_encoding($json_array);`

{"code":"TEXT","name":"/generic/PRODUCT","desc":"/generic/PRODUCT_DESC","productCategory":"/market/prodcats/"}bool(true)

ASCII
echo '<pre>'; print_r(json_decode($json_array));

Returns same array not decoded. Any suggestions what could be?

json_last_error();
Call to undefined function json_last_error() in /var/www/index.php on line 59

A: By default json_decode function returns stdClass, if you want an array you should send the second parameter equals to True.
$json_array = curl_exec($curl);
var_dump($json_array);
echo '<pre>'; print_r(json_decode($json_array,TRUE));

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mikrotik NAT halves WAN speed I have a 951G-2HnD as a router. All connections are via ethernet cables. I observe the following:

*

*When I connect to the ISP via router, speed is about 270 Mbit/s, while ISP claims my plan has 500 Mbit/s speed limit.

*When I connect cable from ISP directly to ethernet port on my PC, I indeed get about 500 Mbit/s download speed.

*When I download files from another PC connected to the same router, the speed is about 900 Mbit/s which is correct for gigabit LAN.

Now because of 3, I think that the problem is not in router processing power. I suppose something is wrong with NAT processing. How do I improve speed so NAT connection is as fast as direct one? Or at least how do I debug the problem?
Just in case, I disabled all NAT rules except the main one:
/ip firewall nat chain=srcnat action=masquerade out-interface=ether1-gateway

This did not improve the speed.

A: David's answer is correct. To summarize, the hardware is capable of switching at the speed you got, but only routing at a fraction of that. Therefore, the problem is the routing, not just the NAT, although that probably doesn't help.
Take a look at these results for routers that should be capable of routing that much traffic:
https://mikrotik.com/product/RB750Gr3#fndtn-testresults
https://mikrotik.com/product/RB3011UiAS-RM#fndtn-testresults
Any of these three should be enough unless you're doing a large amount of very small packet routing.
Another possibility is the CHR product - you can run your router in a VM and give it as much CPU and RAM as you need. $30 covers the cost for a 1Gbps cap.
EDIT: Somehow https://mikrotik.com/product/hap_ac2#fndtn-testresults has better results than the 3011 for non-full-size packets despite having significantly less CPU and RAM, and being on the same architecture.

A: The 951G-2HnD has a rated peak routing speed of 250-300Mbps. It does its switching in hardware and should be able to switch at wire speed. So it sounds like you're getting roughly the performance the hardware is capable of.


text:
Q: Stepformwizard is not getting hidden. Overflowing on right of the screen Am not very expert in jquery and stepformwizard. Am working on code written by someone else. The issue is the multistepformwizard fieldset is used and the next step should be loaded only when Next button is clicked. But  currently both of the steps are visible on the screen with extra horizontal scrollbar. I dont want the step 2 form to be visible. Here is the html and jquery code.

                <form  action="<?php echo base_url()?>service/service_request" method="POST" id="wizard_example_6" autocomplete="off">
                    <input type="hidden" value="<?php echo $ownerArr[0]['email_id']; ?>" name="email_id">
                <input type="hidden" value="<?php echo $ownerArr[0]['phone']; ?>" name="mobile">
                    <fieldset>
                            <legend>Basic information about your car</legend>

                                        Vehicle Brand
                                        <select id="u_car_id" class="form-control" name="car_id" required>
                                            <option selected disabled value="">Select a Car</option>
                                            <?php foreach ($cars as $car_details) : ?>
                                            <option value="<?php echo $car_details['user_car_id']; ?>"><?php echo $car_details['makesTitle']; ?>   (<?php echo $car_details['modelsTitle']; ?>) <?php echo $car_details['car_reg_no']; ?></option>
                                            <?php endforeach; ?>
                                        </select>

                                        Variants
                                        <input type="text" class="form-control"  name="variant" placeholder="Variants" required data-parsley-group="block0"  id="variant" readonly pattern="^[a-zA-Z\s]*$">

                                        Transmission
                                        <input type="text" class="form-control" placeholder="Transmission" name="transmission" readonly required data-parsley-group="block0" id="transmission" pattern="^[a-zA-Z\s]*$">

                            <legend class="clearfix">Select service for your car?  Add New Car</legend>

                                        <input id="option-one" name="service_type" value="1" class="styled-radio " type="radio" data-parsley-group="block0" required data-required-message="Please check one service">
                                        Basic Service:
                                            3 months or 5000 kms (whichever is earlier)

</fieldset>
<fieldset>
                            <legend>Vehicle picked up address  </legend>

                                        Select Address
                                        <select class="form-control" id="user_add_id" name="pick_id">
                                            <option selected disabled>Select Address</option>
                                            <?php $i=1; foreach ($address as $user_details) : ?>
                                            <option value="<?php echo $user_details['add_id'] ?>"> Address <?php echo $i; ?></option>
                                            <?php $i++; endforeach; ?>
                                            <option id="neww" class="neww" value="neww">Select new Address</option>
                                        </select>

                                        Address Type
                                        <select class="form-control" id="add_type" name="add_type" disabled>
                                            <option value="" selected disabled>Select Address Type</option>
                                            <option value="Home">Home Address</option>
                                            <option value="Office">Office Address</option>
                                            <option value="Other">Other Address</option>
                                        </select>

                                    <input class="nocsript-finish-btn sf-right nocsript-sf-btn" type="submit" value="submit"/>

</fieldset>
        </form>

I have skipped some part as its a long form. I want the second fieldset should only be visible when user clicks on next button
here is the jquery
 w6 = $("#wizard_example_6").stepFormWizard({
        onNext: function(b, a) {
            return $("#wizard_example_6").parsley().validate("block" + b)
        },
        onFinish: function(b) {
            return $("#wizard_example_6").parsley().validate()
        }
    });
    var d = window.location.hash.match(/^#step-(\d+)/),
        c = 0;
    null !== d && (c = d[1] - 1);
    w7 = $("#wizard_example_7").stepFormWizard({
        startStep: c,
        onNext: function(b, a) {
            window.location.hash = "#step-" + (b + 2)
        },
        onPrev: function(b, a) {
            window.location.hash = "#step-" + b
        },
        onFinish: function(b) {
            window.location.hash = "#form-sended"
        }
    })
};
$(document).ready(function() {
    prepare_example();
    $("pre code").each(function(c, b) {
        hljs.highlightBlock(b)
    });
    var d = $(location).attr("search").match(/t=([a-z]+)/);
    "undefined" != typeof d && null != d ? ($(".sf-wizard").parent().removeClass("sf-sea").addClass("sf-" + d[1]), $(".bt-" + d[1]).removeClass("btn-default").addClass("btn-info")) : $(".bt-sea").removeClass("btn-default").addClass("btn-info")
});

Please help me with this. I have tried using  but no luck also changed css display:none inplace of block but couldnt resolve the issue.


text:
Q: Mongoose update results with exactly which fields got modified
*

*I have multiple update REST APIs written in node.js which use mongodb
as the backend DB.

*These update APIs are atomic in nature and at a
time update individual sections of the mongodb document for a user profile
example: location API, personal Info API etc.

I am looking for a capability to know which individual fields are modified within the document. for instance, If the location API contains country, state, city and if the update was really made to country. I want to track country as the only field change.
Mongoose does not report the fields which are really for modified in the document.
Below is the sample:
Model.users.update({_id: "12345"}, {$set: update}, {upsert:true}, function (err, resp) {
        if (err) { return console.log(err);
 ----
});

Response:
{ ok: 1,
  nModified: 1,
  n: 1,
  lastOp: Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1469188533 },
  electionId: 5765d40f7dd9376cd6345122

}

A: use mongoose Middleware for this purpose
http://mongoosejs.com/docs/middleware.html
schema.post('update', function(doc, next) {

        // this._update.$set  contains all the fields which are updated
        if (this._update.$set.country) {
          concole.log('country is modified');
        }

    });


text:
Q: Writing and Reading from CSV - Python I am working on an IoT project, where a sensor sends data and is stored in a CSV file. A python program then reads this file every 30 seconds and reads 300 rows and do some processing. So, at 30 second, rows 1-300 will be read and at 60 second, rows 300-600 will be read.
At the same time data is getting stored into this as well.
So is it possible in some way to implement this in python where one program is writing data into a file while another is reading from the file.


text:
Q: Mostrar alert de bootstrap despues de un elemento Tengo el siguiente divque contiene un input con su respectivo id:

        <input type="text" class="form-control input-lg" id="caja1" name="caja1"
        value="">

Quiero mostrar una alerta de bootstrap despues del inputcuando ocurre determinada acción, lo tengo de la siguiente manera:
$(".input-group #" + idCajaIden).after('
strong>ADVERTENCIA! Filtro/Bolsa ya existe!.
');

Pero cuando la muestro queda de la siguiente manera:

Como puedo mostrar la alerta de la caja correctamente sin que me quede asi feo e incrustado?
Muchas gracias por la ayuda.

A: el código es correcto pero se lo debes asignar al padre (.input-group) y no al propio input
$(".input-group #" + idCajaIden).parent().after('
strong>ADVERTENCIA! Filtro/Bolsa ya existe!.
');

agrega el parent()
saludos


text:
Q: aspectj-maven-compiler plugin : how to weave JRE System.*? I'm trying to detect where a mysterious System.gc() comes from,
so I'm hoping to create a pointcut on all calls to System.gc()
the doc describes how to weave existing jars and existing dirs, but
how do I weave the JDK itself ?
Thanks a lot

A: You can weave rt.jar beforehand and replace it in your JDK/JRE. Note that load time weaving will not work as the Javaagent does not have access to bootstrap classloader.
However, quick search reveals that there is only one place in the whole JDK (Sun 1.6.0_26) that calls System.gc() explicitly:
java.nio.Bits#reserveMemory

Maybe you can simply attach a debugger and put a breakpoint on gc() method?
That being said you can use call() advice as opposed to execution() which will weave calling client code rather than target method. So you only have to weave your code and all libraries rather than the JDK.


text:
Q: finding substring Thanks in advance.
    I have a string:
A = 'asdfghjklmn'

How can I get a substring having a maximum length which is a multiple of three?

A: You can use slice notation and integer arithmetic.
>>> a = 'asdfghjklmn'
>>> a[:len(a)//3*3]
'asdfghjkl'
>>> len(a)
11
>>> len(a[:len(a)//3*3])
9

In general, n//k*k will yield the largest multiple of k less than or equal to n.

A: It seems like you're looking for something like this:
>>> A = 'asdfghjklmn'
>>> mult, _ = divmod(len(A), 3)
>>> A[:mult*3]
'asdfghjkl'

here resulting string will have length which is multiple of three and it will be the longest possible substring of A with such length.

A: Yet another example:
>>> A = '12345678'
>>> A[:len(A) - len(A)%3]
'123456'
>>>

A: Is this what you want?
A = 'asdfghjklmn'
A[0:(len(A)/3)*3]
'asdfghjkl'

A: With the foreword that it will never be as efficient as the ones that actually use math to find the longest multiple-of-3-substring, here's a way to do it using regular expressions:
>>> re.findall("^(?:.{3})*", "asdfghjklmn")[0]
'asdfghjkl'

Changing the 3 quantifier will allow you to get different multiples.


text:
Q: How to read special character? I have a record like below
A^]B^]C^]^]^]

record fields are separated by ^] and its a special character. I cant see this value while doing cat in linux but if -A operator.
Want to know how can I read such record with special character (^]) as field separator in Java?
What should I mention for field separator to detect it?

A: ^] is known as caret notation, and means byte value 29, which is a non-displayable ASCII/Unicode control character. That's why you normally can't see it.
In Java, you can use octal escape or Unicode escape to represent such a character:

*

*Octal escape: \35

*Unicode escape: \u001D
If you read in a line of text, ending up with s = "A^]B^]C^]^]^]", where ^] represents the special byte 29 character, then you can get the field values by splitting the string using s.split("\35", -1).
Here is code showing it:
String line = "A\u001DB\u001DC\u001D\u001D\u001D";
System.out.println("line = \"" + line + '"');
System.out.println("line.length() = " + line.length());
String[] fields = line.split("\35", -1);
for (String s : fields)
    System.out.println('"' + s + '"');

Output
line = "ABC"
line.length() = 8
"A"
"B"
"C"
""
""
""

The code used Unicode escape to build the string, but octal escape in the split(), just to show that they are the same character.
As you can see, the string is 8 characters long, but only the 3 displayable characters can be seen when printing it.
Splitting does however show that there are 6 fields (separated by 5 separators).


text:
Q: multiple cascade paths sql server 2017 create self referencial foreign key I have this create table script
CREATE TABLE Categories (
  Id int IDENTITY(1,1) not null,
  ParentId int null,
  [Order] int default 0,
  Published bit not null default 0,
  Deleted bit not null default 0,
  CONSTRAINT PK_Categories_Id PRIMARY KEY CLUSTERED (Id),
  CONSTRAINT FK_Categories_ParentId FOREIGN KEY (ParentId) REFERENCES  Categories(Id) on delete     cascade,
  Title nvarchar(255) NOT NULL,
  CreatedAt DateTime not null default GETDATE(),
  UpdatedAt DateTime not null default GETDATE()
 );

and i get an error
Msg 1785, Level 16, State 0, Line 1
Introducing FOREIGN KEY constraint 'FK_Categories_ParentId' on table 'Categories' may cause   cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify    other FOREIGN KEY constraints.
Msg 1750, Level 16, State 1, Line 1
Could not create constraint or index. See previous errors.

how to add on delete cascade to the foreign key constraint ?

A: Unfortunately, SQL Server just does not allow referential actions on self-referencing foreign keys - as opposed to some other databases.
One possible workaround would be to use an instead of delete trigger, that follows the relationships and delete all children rows:
create trigger trg_categories
on categories
instead of delete
as
    with cte as (
        select id from deleted
        union all
        select cte.id
        from cte
        inner join categories cat on cat.parentid = cte.id
    )
    delete cat
    from categories cat
    where exists (select 1 from cte where cte.id = cat.id)
;


text:
Q: imagebutton image url not changed dynamic on repeater I am using repeater to bind data & on header template i am using imagebutton for sorting column.
My Client Side Code:
 <asp:Repeater runat="server" ID="RptClientDetails" OnItemDataBound="RptClientDetails_ItemDataBound">
                            <HeaderTemplate>

                                                Client Name
                                                <asp:ImageButton runat="server" ID="ImgbtnNameUp" ImageUrl="~/Images/BlackUp.png"
                                                    OnCommand="lbtnSortingAccending_Click" CommandArgument="Name" Height="15px" Width="20px" />
                                                <asp:ImageButton runat="server" ID="ImgbtnNameUpDown" ImageUrl="~/Images/BlackDown.png"
                                                    OnCommand="lbtnSorting_Click" CommandArgument="Name" Height="15px" Width="20px" />

                                                Total Balance Due
                                                <asp:ImageButton runat="server" ID="ImgbtnTotalBalanceDueUp" ImageUrl="~/Images/BlackUp.png"
                                                    OnCommand="lbtnSortingAccending_Click" CommandArgument="TotalBalanceDue" Height="15px"
                                                    Width="20px" />
                                                <asp:ImageButton runat="server" ID="ImgbtnTotalBalanceDueDown" ImageUrl="~/Images/BlackDown.png"
                                                    OnCommand="lbtnSorting_Click" CommandArgument="TotalBalanceDue" Height="15px"
                                                    Width="20px" />

                            </HeaderTemplate>
                            <ItemTemplate>

On C# Code:
protected void lbtnSorting_Click(object sender, CommandEventArgs e)
{
    string sortExpression = e.CommandArgument.ToString();
    List<ARDTO> SirtlingListOBj = (List<ARDTO>)Session["GetClientList"];
    int Showall = (int)Session["ShowAll"];

    ImageButton imgBtnobj = new ImageButton();
    imgBtnobj = (ImageButton)sender;
    imgBtnobj.ImageUrl = "";
    imgBtnobj.ImageUrl = "/Images/greenDown.png";
}

Here i want to change ImageURl... But it's not working...
So, any body can help me here...
What's wrong here ?
or can i change it via css ?

A: This should do the trick without having to worry about the rendered names.
The Datalist is handled on the serverside so that the ImageUrl path is completely rendered. this should leave a nice simple OnClientClick call to the jquery at the bottom which sets the Image1 src.
Also, I didn't see the actual call to the SimpleModal plugin, so I added it to the JS as I couldn't see how you were getting any sort of popup at all based on the code snippets

    <asp:Image ID="Image1" ImageUrl="" runat="server" />

    <asp:DataList ID="DataList1" runat="server" RepeatDirection="Horizontal" RepeatColumns="5" >
        <ItemTemplate>
            <asp:ImageButton ID="ThumbnailImg" ImageUrl='<%# Eval("n1") %>' Height="100" Width="150" BorderStyle="Ridge" runat="server" OnClientClick="ShowFullImg(this);" />
        </ItemTemplate>
    </asp:DataList>


text:
Q: C++11 multiple read and one write thread mutex I have an application, where some STL containers are read in 3 threads, and written in 2. I know there is TBB for multi-threaded containers, but it is not an option in my application.
So I want to make the program thread-safe using std::mutex and my bare hands. This is a simple version of what I did:
int readers = 0;
std::mutex write;

// One write, no reads.
void write_fun()
{
    write.lock();// We lock the resource
    while(readers > 0){}// We wait till everyone finishes read.
    // DO WRITE
    write.unlock();// Release
}

// Multiple reads, no write
void read_fun()
{
    // We wait if it is being written.
    while(!write.try_lock()){}
    write.unlock();

    readers++;
    // do read
    readers--;
}

Is this the correct way to do this in C++11?

A: This is safe, but still likely not fair or performant:
std::atomic<int> readers;
std::mutex write;

// One write, no reads.
void write_fun()
{
    write.lock();// We lock the resource
    while(readers > 0){}// We wait till everyone finishes read.
    // DO WRITE
    write.unlock();// Release
}

// Multiple reads, no write
void read_fun()
{
    // We wait if it is being written.
    write.lock();
    readers++;
    write.unlock();

    // do read
    readers--;
}

A solution with condition variables could avoid busy waiting for readers to fall to 0, left as an exercise for the reader.

A: Pretty close, couple things to note, in c++ for exception safety and readability, IMO, it is good to use RAII locks. What you really need is a shared_mutex like in boost or coming in c++14.
std::shared_mutex write; //use boost's or c++14

// One write, no reads.
void write_fun()
{
    std::lock_guard<std::shared_mutex> lock(write);
    // DO WRITE
}

// Multiple reads, no write
void read_fun()
{
    std::shared_lock<std::shared_mutex> lock(write);
    // do read
}

If you don't want to use boost @howardhinmant was do kind as to give a link to a reference implementation


text:
Q: How to call multiple elements by class and .innerHTML? I am having problems calling multiple elements with the same class name when  using .innerhtml. For instance the url I am working with is:
https://www.amazon.com/s/ref=nb_sb_noss_2?url=search-alias%3Daps&field-keywords=hen
and when I enter the following code in chrome console I get:
document.getElementsByClassName('a-size-small a-color-secondary')

by
Adore Plush Company
Get it by Tuesday, Jun 21
...
...

But when I enter: document.getElementsByClassName('a-size-small a-color-secondary').innerHTML
I get "undefined". The goal is to get just the text between the span tags.
Can someone give me some guidance? I have tried with different variations including var and even Selection method. It worked with Selection for the first class element but didn't work at all with SelectionAll. Thanks for any help.

A: document.getElementsByClassName('a') will give the Object with class name .
for example class name is a and there are many spans with a , then you need get the span value by using index of that object
 var x =document.getElementsByClassName('a');

 console.log("value of spans"+x[0].innerHTML);

COdepen-http://codepen.io/pen/


text:
Q: VBA Copy data list with variable length So what i am trying to do is copy a data list to another location (eventually to another tab but i can figure that out myself). The data list is variable in length but it is filled into another cell manually.

*

*List that needs to be copied is 2 rows wide (H & I) and x columns long (from row 2 to "end")

*The value in cell N6 is the amount of rows

*So the range that needs to be copied is H2 to I(amount of rows +1)

Here is my code
Sub Copycells()
Dim wb As Workbook
Dim wb1 As Worksheet
Dim LastRow As Long

Set wb = ThisWorkbook
Set wb1 = wb.Sheets("Sheet1")

'check data for list length

LastRow = Worksheets("Sheet1").Cells(6, "N").Value + 1

'copy data
Range("V2:W?").Copy Range("H2:I?")

End Sub

So where i'm struggling is how to fill in the range for the copy, in a sense combining the row letter with the variable number.

A: I think you might have mistaken columns for rows and rows for columns in the explanation, that you give in your question.
However, I'm fairly sure i understand what you want the code to do.
Try this:
Sub Copycells()
Dim wb As Workbook
Dim wb1 As Worksheet
Dim LastRow As Long

Set wb = ThisWorkbook
Set wb1 = wb.Sheets("Sheet1")

'check data for list length

LastRow = Range("N6").Value + 1

'copy data
Range("H2:I" & LastRow).Copy
End Sub

You need to specify where the copied list needs to be pasted, but I'll let you have a try on that on your own.


text:
Q: Can't bind path to image to the template - Angular My code is

I'm trying to set the path to an image to the src of an img tag but I'm getting
ERROR Error: Uncaught (in promise): Error: Template parse errors:
Parser Error: Unexpected token . at column 1 in [../../../../../../public/assets/images/2019-02-16T14:43:00.869Zpp1.jpg] in ng:///ComponentsModule/SidebarComponent.html@5:8 ("
      ][src]="../../../../../../public/assets/images/2019-02-16T14:43:00.869Zpp1.jpg"
        alt=""
     "): ng:///ComponentsModule/SidebarComponent.html@5:8

The complete idea is to make a GET requests to a user document that has a userImgPath property to the location where the image is. Then bind it to the src="" from an img tag. But i can't event do this first. I don't know whats wrong, thats the path to the image. The directory and the image already exist.
UPDATE:
After pzaenger answer I get this.

A: Escape the path using '':

A: Adding to what @pzaenger mentioned, you need to have the image served from the correct place. If you have generated the app using angular-cli, you can have the image in src/assets folder and use in template like [src]="'assets/photo.jpg'"
Edit: You can modify the angular.json or angular-cli.json (if generated using angular-cli) to change the folders that are added to assets in the build.

A: use src insted [src] the second one is for string interpolation
examples:

Edit:
If thats inside the application the path should be assets/images/imagename.jpg or ./assets/images/imagename.jpg


text:
Q: JavaScript: Change image based on value typed in a textbox I'm wondering if there is a way to use a JavaScript onChange event to change the SRC for an image based on a number typed in a textbox on a form.  For example, if the user types a number beginning with the number 3, I'd like to SRC to point to one image, but if the user types a number beginning with the number 4, I'd like the SRC to point to a different image, and I'd like other SRC changes when the user types a number beginning with 5, or a number beginning with 6.
Thanks in advance!

A: Below I have provided a fully commented example of how this can be done.
html
<input id="myid" type="text">

javascript
window.onload = function() { // because we are grabbing DOM elements we need to ensure the elements are first loaded.
    var elm = document.getElementById("myid"),
        img = document.getElementById("myimg"); // here we grab the input box and the image
    elm.onkeyup = function(event) { // capture the input keyup
        if (this.value.length === 1) { // make sure we are only checking the first value
            switch (event.keyCode) { // here we are running the switch statement against the keyup event keycode value
            case (48):
                img.src = "http://dummyimage.com/100x100/000/fff&text=0";
                break;
            case (49):
                 img.src = "http://dummyimage.com/100x100/000/fff&text=1";
                break;
            case (50):
                 img.src = "http://dummyimage.com/100x100/000/fff&text=2";
                break;
            case (51):
                 img.src = "http://dummyimage.com/100x100/000/fff&text=3";
                break;
            case (52):
                 img.src = "http://dummyimage.com/100x100/000/fff&text=4";
                break;
            case (53):
                 img.src = "http://dummyimage.com/100x100/000/fff&text=5";
                break;
            case (54):
                 img.src = "http://dummyimage.com/100x100/000/fff&text=6";
                break;
            case (55):
                 img.src = "http://dummyimage.com/100x100/000/fff&text=7";
                break;
            case (56):
                 img.src = "http://dummyimage.com/100x100/000/fff&text=8";
                break;
            case (57):
                 img.src = "http://dummyimage.com/100x100/000/fff&text=9";
                break;
            }
        }
    }

}

A: Thanks, all for your help.
:)
Here is the final solution I developed.  I used an onkeyup event, as it was better suited to my needs.  The HTML I used:
    <form name="AddCardToAccount" id="AddCardToAccount" action="" method="post">

    <input type="text" name="cardNumber" id="cardNumber" size="31" onkeyup="handleKeypress(this,event);">

I added some case numbers to cover the numbers of the key pad, in addition to the numbers of the keyboard. Here is the JavaScript I used:
        function handleKeypress(inCardNumber,e) {
            var inCardNumber = document.AddCardToAccount.cardNumber;
            var imgToSwap = document.AddCardToAccount.imgCC;
            var charCode;
            if(e && e.which){
                charCode = e.which; // For Firefox
                }
                else if(window.event){

                    e = window.event;
                    charCode = e.keyCode; // For IE

            }
            if (inCardNumber.value.length === 1) {
                switch (charCode) {
                    case (48):
                        imgToSwap.src = "includes/sci/images/imgNoCC_.gif";
                    break;
                    case (49):
                    imgToSwap.src = "includes/sci/images/imgNoCC_.gif";
                        break;
                    case (50):
                    imgToSwap.src = "includes/sci/images/imgNoCC_.gif";
                    break;
                case (51):
                    imgToSwap.src = "includes/sci/images/imgAmexCC_.gif";
                    break;
                case (52):
                    imgToSwap.src = "includes/sci/images/imgVisaCC_.gif";
                    break;
                case (53):
                    imgToSwap.src = "includes/sci/images/imgMcCC_.gif";
                    break;
                case (54):
                    imgToSwap.src = "includes/sci/images/imgDiscCC_.gif";
                    break;
                case (55):
                    imgToSwap.src = "includes/sci/images/imgNoCC_.gif";
                    break;
                case (56):
                    imgToSwap.src = "includes/sci/images/imgNoCC_.gif";
                    break;
                case (57):
                    imgToSwap.src = "includes/sci/images/imgNoCC_.gif";
                    break;
                case (96):
                    imgToSwap.src = "includes/sci/images/imgNoCC_.gif";
                    break;
                case (97):
                    imgToSwap.src = "includes/sci/images/imgNoCC_.gif";
                    break;
                case (98):
                    imgToSwap.src = "includes/sci/images/imgNoCC_.gif";
                    break;
                case (99):
                    imgToSwap.src = "includes/sci/images/imgAmexCC_.gif";
                    break;
                case (100):
                    imgToSwap.src = "includes/sci/images/imgVisaCC_.gif";
                    break;
                case (101):
                    imgToSwap.src = "includes/sci/images/imgMcCC_.gif";
                    break;
                case (102):
                    imgToSwap.src = "includes/sci/images/imgDiscCC_.gif";
                    break;
                case (103):
                    imgToSwap.src = "includes/sci/images/imgNoCC_.gif";
                    break;
                case (104):
                    imgToSwap.src = "includes/sci/images/imgNoCC_.gif";
                    break;
                case (105):
                    imgToSwap.src = "includes/sci/images/imgNoCC_.gif";
                    break;
            }
        }
    }


text:
Q: Why nm report wrong too bigger offset value for the symbol of variable on the library written by C and embedded on golang object? I have a library which has a following variables:
const static volatile int64_t  head1   = 0xffffffffffffffff;
const static volatile int64_t  head2   = 0xffffffffffffffff;
const static volatile int64_t  seed = 1;
const static volatile int64_t  tail1   = 0xffffffffffffffff;
const static volatile int64_t  tail2   = 0xffffffffffffffff;

I've compiled it to the library file as libnantoka.a. Then linked into the go module by the cgo as follows:
/*
#cgo LDFLAGS: -L. -lssl -lcrypto -lpthread -ldl -lm -lnantoka
#include <nantoka.h>
#include <stdbool.h>
*/
import "C"

Then, created executable file main by go build -o main main.go
I've found the offset address of seed by pattern matching by binary as follows:
od -A x -x main | grep "0001 0000 0000 0000"
0d61f0 ffff ffff ffff ffff 0001 0000 0000 0000

It's seems that the offset address of symbol seed might be 0xd61f8. Also, I've made sure as follows:
od -A x -x -j 0xd61e0 main | head -n4
0d61e0 7472 000a 0000 0000 ffff ffff ffff ffff
0d61f0 ffff ffff ffff ffff 0001 0000 0000 0000
0d6200 ffff ffff ffff ffff ffff ffff ffff ffff
0d6210 3130 3332 3534 3736 3938 3130 3332 3534

It indicates that 0xd61f8 must be the 64bit int with value 1, between 128bit all "f". I've be sure of that the offset address of the symbol seed must be 0xd61f8.
But, the result of nm is surprisingly that:
nm main | grep seed
000e61f8 r seed

The result e61f8 must be the offset address from the start of .rodata segment, but bigger than the real offset address from the file top!
I'm confusing why nm reports so big wrong offset? I really appreciate any suggestions from you! Thank you.
By the way, the environment is Raspberry Pi model B, go version is 1.13.5 as follows:
uname -a
Linux raspberrypi 4.19.50+ #896 Thu Jun 20 16:09:52 BST 2019 armv6l GNU/Linux

go version
go version go1.13.5 linux/arm

Also section infos of the main is as follows:
Sections:
Idx Name          Size      VMA       LMA       File off  Algn
  0 .interp       00000019  00010174  00010174  00000174  2**0
                  CONTENTS, ALLOC, LOAD, READONLY, DATA
  1 .note.ABI-tag 00000020  00010190  00010190  00000190  2**2
                  CONTENTS, ALLOC, LOAD, READONLY, DATA
  2 .note.go.buildid 00000064  000101b0  000101b0  000001b0  2**2
                  CONTENTS, ALLOC, LOAD, READONLY, DATA
  3 .note.gnu.build-id 00000024  00010214  00010214  00000214  2**2
                  CONTENTS, ALLOC, LOAD, READONLY, DATA
  4 .gnu.hash     00000568  00010238  00010238  00000238  2**2
                  CONTENTS, ALLOC, LOAD, READONLY, DATA
  5 .dynsym       00000b70  000107a0  000107a0  000007a0  2**2
                  CONTENTS, ALLOC, LOAD, READONLY, DATA
  6 .dynstr       00000974  00011310  00011310  00001310  2**0
                  CONTENTS, ALLOC, LOAD, READONLY, DATA
  7 .gnu.version  0000016e  00011c84  00011c84  00001c84  2**1
                  CONTENTS, ALLOC, LOAD, READONLY, DATA
  8 .gnu.version_r 000000a0  00011df4  00011df4  00001df4  2**2
                  CONTENTS, ALLOC, LOAD, READONLY, DATA
  9 .rel.dyn      00000020  00011e94  00011e94  00001e94  2**2
                  CONTENTS, ALLOC, LOAD, READONLY, DATA
 10 .rel.plt      00000368  00011eb4  00011eb4  00001eb4  2**2
                  CONTENTS, ALLOC, LOAD, READONLY, DATA
 11 .init         0000000c  0001221c  0001221c  0000221c  2**2
                  CONTENTS, ALLOC, LOAD, READONLY, CODE
 12 .plt          00000530  00012228  00012228  00002228  2**2
                  CONTENTS, ALLOC, LOAD, READONLY, CODE
 13 .text         00094338  00012758  00012758  00002758  2**3
                  CONTENTS, ALLOC, LOAD, READONLY, CODE
 14 .fini         00000008  000a6a90  000a6a90  00096a90  2**2
                  CONTENTS, ALLOC, LOAD, READONLY, CODE
 15 .rodata       0004001c  000a6a98  000a6a98  00096a98  2**3
                  CONTENTS, ALLOC, LOAD, READONLY, DATA
 16 .typelink     00000cfc  000e6ab8  000e6ab8  000d6ab8  2**3
                  CONTENTS, ALLOC, LOAD, READONLY, DATA
 17 .itablink     0000002c  000e77b4  000e77b4  000d77b4  2**2
                  CONTENTS, ALLOC, LOAD, READONLY, DATA
 18 .gopclntab    0005fd79  000e77e0  000e77e0  000d77e0  2**3
                  CONTENTS, ALLOC, LOAD, READONLY, DATA
 19 .ARM.exidx    00000008  0014755c  0014755c  0013755c  2**2
                  CONTENTS, ALLOC, LOAD, READONLY, DATA
 20 .eh_frame     00000004  00147564  00147564  00137564  2**2
                  CONTENTS, ALLOC, LOAD, READONLY, DATA
 21 .tbss         00000008  00157ee8  00157ee8  00137ee8  2**2
                  ALLOC, THREAD_LOCAL


text:
Q: lazy load with large number of images I have this code for lazy load images:
$.fn.isInViewport = function() {
    var elementTop = $(this).offset().top;
    var elementBottom = elementTop + $(this).outerHeight();

    var viewportTop = $(window).scrollTop();
    var viewportBottom = viewportTop + $(window).height();

    return elementBottom > viewportTop && elementTop < viewportBottom;
};

$(window).on('scroll', function() {
    $('.imgli').each(function(){
        if ($(this).isInViewport()) {
            $(this).attr("src", $(this).attr("data-src")).removeAttr('data-src');
        }
    });
});

It works with about 700 images, but I'm interesting - what about 20.000 images (max)?
Is there any way to check this, without really loading 20.000 images, because I don't have so much of them, for now.
Each image is about 100kb max.

A: First of all you can always copy your existing images to make it 20.000 though it is a little bit pointless.
Secondly you can force reload the picture every time it appears in a viewport.
$(window).on('scroll', function() {
    $('.imgli').each(function(){
        if ($(this).isInViewport()) {
            $(this).attr("src", $(this).attr("data-src") + "?" + $.now());
        }
    });
});

So you can just scroll the page and see how the pictures are getting loaded every time they appear in a viewport.
Additionally eavoid using $(this) more than it's necessary.
A better way is to save it to a variable. That way you save memory.
$(window).on('scroll', function() {
    $('.imgli').each(function() {
        var image = $(this);
        if (image.isInViewport()) {
            image.attr("src", image.attr("data-src") + "?" + $.now());
        }
    });
});


text:
Q: Is It Possible to Update a WCF Service Reference in a Web Deployment Project I think the question title neatly sums up what I am after. I have a web app and a service and I would like the build script to check if the service has been updated since the last build and if so, run the "update service reference" script that is available when you right-click on a service.
Any ideas?

A: I'm not sure, but I think there's a way to do this through the Visual Studio SDK. I recall that, for instance, there's an object model that you can reference to display the "Add Web Reference" dialog. No doubt you can also do an "Update Web Reference". It should then be possible to create an MSBUILD task that will do this for you.
You should also consider that there may already be such tasks out there. Check on Codeplex and other such places for public collections of MSBUILD tasks, some of which may help.

A: We use a PowerShell script to run the wsdl.exe tool for us(or in your case svcutil.exe).  The script runs out to the service and pulls a fresh wsdl and re-gens the proxy.  You can use  to get to PS.  The only trickery is to get the namespacing correctly, but there is an option on wsdl.exe for that.
<Target Name="UpdateWebReferences">

<Exec WorkingDirectory="$(SolutionRoot)"
      Command="$(PS) -Noninteractive -Command $(SolutionRoot)\tools\PowerShell\Compile-Wsdl.ps1 -ukf $(ConfigFilePath)"
      Condition=" Exists('$(ConfigFilePath)') And Exists('$(SolutionRoot)\tools\PowerShell\Compile-Wsdl.ps1') " />

The above goes in your team build.  The meat of the powershell function is as follows:
$projectFile = [xml]( Get-Content $projectFilePath )

if ( $projectFile -and $WSDL_LANGUAGE -ne "VB")
{
    $ns = $projectFile.Project.PropertyGroup[ 0 ].RootNamespace
}
else
{
    $ns = $NAMESPACE_PREFIX
}

foreach( $webRefDir in Get-ChildItem $dir.FullName )
{
    $webRefName = $webRefDir.Name

    if ( [System.String]::IsNullOrEmpty( $ns ) )
    {
        $namespace = $webRefName
    }
    else
    {
        $namespace = $( "{0}.{1}" -f $ns, $webRefName )
    }

    Write-Host $( "Compiling Web Reference: {0} using Namespace: {1}..." -f $webRefName, $namespace )

    $outputPath = $( "{0}\{1}" -f $webRefDir.FullName,$REFERENCE_FILE )

    $xpath = "/configuration/appSettings/add[@key='{0}']" -f $webRefName

    if ( $URL_KEY_FILE )
    {
        $xml = [xml](Get-Content $URL_KEY_FILE)
        $url = $xml.SelectSingleNode( $xpath )

        if ( $url )
        {
            $urlOrPath = $url.Value
        }
        else
        {
            Write-Warning $( "Could not find key {0} in {1}..." -f $webRefName, $URL_KEY_FILE )
        }
    }
    else
    {
        $urlOrPath = $( Get-ChildItem $webRefDir.FullName -r -filter "*.wsdl" ).FullName
    }

    if ( $urlOrPath )
    {
        wsdl /nologo /language:$WSDL_LANGUAGE /n:$namespace /o:$outputPath /urlkey:$webRefName $urlOrPath
    }

    Write-Host "....................................................."
}

All that is required for this is you must have the "Web References" folder checked in.  It loops over each directory and creates the correct namespace.  The script is long, but I'd be willing to email it.


text:
Q: D3 not displayed within jupyter notebook I am writing this html/javascript/d3 code within jupyter notebook, which runs without any error but it doesn't display anything. Ideally it should display two circles, one with color blue and other with color green. What could be an issue?
HTML('')

HTML('''

Sample


text:
Q: WPF - Bind image property to Image control Suppose I have string Name and Image Photo as properties of a class in my DataContext. I need to bind them to controls is a DataTemplate.
I thought this would work but it doesn't:
<Image Source="{Binding Photo}"/>

Why not? Should I my Photo have another type? (BitmapImage perhaps?)
How can I bind an Image control to an Image property?
Thanks!
Edit: As usual, after clicking submit I saw that the error is very clear: there's no converter from Image to ImageSource. How would my converter be to convert Image to ImageSource?

A: Yes, if I make my property BitmapImage it all works just fine.
Sorry for the stupid question.

A: It doesn't really makes sense to have a data property of type Image, since Image is a control (if you really want to do that you could bind to Photo.Source). You should use an ImageSource instead (or a BitmapImage, like you did, since BitmapImage inherits from ImageSource).


text:
Q: Running and installing missing modules for script through SSH I want to run a python script on a Linux Box(I'm connecting to it through SSH on OSX terminal). In order for this script to run, the computer must have the SUDS module installed. I was wondering what would be the best way to install SUDS on computers that run my script and do not have SUDS installed in them. My script is in a folder the has a virtual env. The structure of my folder is:
MainFolder
-------script.py, env folder
                  |----------binFolder, includeFolder, libFolder

Should I code my script to install SUDS from the script itself?Or is there a better method to achieve this?
Also, I would like to know if there's a way to run my virtualenv through the SSH and use pip to install in the Linux Box?

A: Well it depends if you are deploying it only on this server and do not want to distribute the code than you would have to run the following command (assuming you have pip and python-tools)
sudo pip install SUDS

but if you get an error back saying that the command pip is not installed you will need to run the following command
sudo apt-get install python-pip python-dev build-essential

If you want to distribute it than I would do open source on github
with the instructions of how to use the program and run it I would add a dependencies list of all the external modules you used for your script.
Hope this helped.


text:
Q: Sandwich property of the line integral by arclength Let $L\subset\mathbb R^2$ be a continuous smooth simple line given by $L = \{(\phi_1(t), \phi_2(t)): t\in [\alpha,\beta]\subset\mathbb R\}$.
Let $T\in\mathfrak T$ be a partition of $[\alpha,\beta]$, so the line $L$ gets 'chopped' into arcs $$L = X_0X_1\cup X_1X_2\cup\ldots\cup X_{n-1}X_n $$
Let $f,g,h:L\to\mathbb R$ be some functions. Denote
$$\sigma (T) = \sum_{j=1}^n f(Q_j)s_j$$
where $Q_j\in X_{j-1}X_j$ is an arbitrary point on the sub-arc and $s_j$ denotes the length of $X_{j-1}X_j$.
Denote by $\lambda (T)$ the maximal length of a subinterval in $T$. Define
$$\exists \lim_{\lambda (T)\to 0}\sigma (T)\Longrightarrow \lim_{\lambda (T)\to 0}\sigma (T) = \int _Lf\mbox{d} s $$

Let $f\leq h\leq g$ and $\int_Lf = \int_Lg =: A$. Show that $\exists \int_Lh=A$.

Attempt
The integrability def. is equivalent to $$\forall\varepsilon >0,\exists\delta >0; \forall T\in\mathfrak T\left (\lambda (T)<\delta\Longrightarrow \left\lvert \sigma (T)-A \right\rvert <\varepsilon \right ) $$
The thing I don't understand is this; are the points $Q_j$ in the subarcs picked the same when we compute $\sigma (T)$ for $f,g,h$? If so then it would be trivial that $$\sigma _f(T)\leq \sigma _h (T)\leq \sigma _g(T) $$
Would then have
$$-\varepsilon < \sigma _f(T)-A\leq \sigma _h(T)-A\leq \sigma _g(T)-A <\varepsilon $$
If not, though, then we can't guarantee $\sigma _f (T)\leq \sigma _h(T)$, can we? Or am I going about this in a wrong way?

A: You find $\delta_1$ for $f$ and $\delta_2$ for $g$ and take $\delta=\min\{\delta_1,\delta_2\}$. Then you consider a partition $T_0$ for $h$ with $\lambda(T_0)<\delta$ and consider arbitrary points $P_j\in X_{j-1}X_j$. In the definition of limit for $f$ and $g$,  you can take any partition $T$ as long as $\lambda_i(T)\le \delta_i$ and any choice of points $Q_j$ in the subintervals of $T$, so the partition $T_0$ and this particular choice of points $P_j$ is admissible. And then you can continue as in your proof.
So yes you can take the same points for all three functions, but only because you know that for two of them the limit exists. Hope this make sense.
Think about the proof of the squeeze theorem. Same principle.


text:
Q: Go api working on colleague's computer, endpoints returning 404 on mine? I'm building a basic API in Go, and after my code working perfectly earlier today, my endpoints are all returning 404s. I have a basic handler function below to illustrate.
Someone else on my team was able to run this code successfully, so I don't think it's the actual code. I'm concerned there is something about my computer or browser environment that are causing the 404s (or I made a stupid mistake). All of the imports are for the rest of the api functionality.
The two print lines telling me the database connection & server is running, so the program itself is running, but the endpoints are all returning 404s after working correctly this morning.
What can I look into or try here?
I've restarted my computer, cleared my browser cache, restarted the server a bunch, etc. Any version of turn it off and on again that I could think of has been tried.
package main

import (
    "database/sql"
    "fmt"
    "log"
    "net/http"
    "os"

    _ "github.com/go-sql-driver/mysql"
    "github.com/gorilla/mux"
    "github.com/joho/godotenv"
)

var port = "8080"
var db *sql.DB
var host string

func main() {
    // Getting environment variables that are secret
    host = "localhost:8080"

    err := godotenv.Load("week2.env")
    if err != nil {
        log.Fatal("Error loading .env file")
    }
    // Connecting to the MySQL database
    pw, _ := os.LookupEnv("MYSQL_ROOT_PASSWORD")
    user, _ := os.LookupEnv("MYSQL_USER")
    ds := fmt.Sprintf("%s:%s@tcp(db:3306)/google_books", user, pw)
    database, err := sql.Open("mysql", ds)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("successfully connected to db")
    db = database
    defer db.Close()
    // Setting up a mux router
    router := mux.NewRouter()

    // Telling the server what to listen for and what to do
    router.HandleFunc("/", hello)

    // Creating the server
    fmt.Printf("listening on port %s\n", port)
    err = http.ListenAndServe(":"+port, router)
    if err != nil {
        fmt.Println(err)
    }
}
func hello(w http.ResponseWriter, r *http.Request) {
    setHeaders(w, r)
    fmt.Println("hello world this is the homepage")
}

// setHeaders sets the headers for the response
func setHeaders(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Access-Control-Allow-Origin", "*")
}

A: With the information you provided, I will have to guess a little.
Your 404 error could be related to a database error.
When you run database, err := sql.Open("mysql", ds), you are opening a connection, but not necessarily authenticating yet.
Add a ping below the sql.Open line to test it, like this:
err = db.Ping()
if err != nil{
    log.Fatalf("%s", err)
}

Also, in you request, make sure you add more information to the response body so you know exactly where the 404 was generated.


text:
Q: Flot canvas is not rendering in UI when using with knockoutjs I have problem going on with flot grap and knockout js
Flot Graph working when out side the knockout binding div
In the fiddle the (div placeholder) for graph is nicely drawing if it is outside the knockout binding divs.
Here is the jsfiddle - http://jsfiddle.net/keyur12/g9aLe/
Flot Graph not working when inside the knocout binding div
As soon as if we add the div placeholder inside the knockout binding div then the canvas for the flot grap is not working.
Here is the jsfiddle - http://jsfiddle.net/keyur12/fGBBR/

    Test 1

People

 hi1

Any help is appreciated.

A: All markup within the foreach block is duplicated for each element within the array. So, in your markup above, you will have one

for each person in the people array. So that will result in duplicate "placeholder" elements.
Also, you are trying to draw the graph in the document ready function with
 $.plot($("#placeholder"), data, options);

Which won't work because the element won't even exist yet. Can you explain what you are trying to do? Are you trying to draw a graph for each person? If so, you should create a custom binding (see: custom binding doc

A: Finally found my own solution after some hard work and re-thinking.
Basically to make the flot graph work inside the knockout binding one has to identify how observables are assigned the values.

*

*if using getJSON call
if observables are assgined values inside the getJSON call then the $.plot($("#placeholder0"), data, options); should go inside getJSON call as well with unique index to placeholders. Not in $(document).ready(function(){});
example:
$.getJSON("someURL",function(data){
    self.someObservableArray(data.someArrayObjects);
    $.plot($("#placeholder0"), data, options);
  });

*if not using the getJSON call then call to $.plot($("#placeholder0"), data1, options); should be in
$(document).ready(function(){}); after ko.applybindings();
example:
 $(document).ready(function(){
    ko.applybindings(new appModel());
    $.plot($("#placeholder0"), data, options);
    });

Here is the updated fiddle with working example - http://jsfiddle.net/keyur12/fGBBR/3/


text:
Q: wixproj/msbuild program creating automatically unwanted folder in the solution tree I want to remove folder from my deployment folder.
I'm using removedir task.
<ItemGroup>
  <FolderToExcludefromDeploymentFolder Include="$(SourceDir)\Support" />
</ItemGroup>
<Target Name="BeforeBuild" BeforeTargets="Build">
  <RemoveDir Condition="Exists('$(sourceDir)\Support')" Directories="@(FolderToExcludefromDeploymentFolder)" />
</Target>

In that case i get a folder in the solution tree.

In case of trying to delete the folder i get this error and the itemgroup element will automatically will be removed.

How can i fix this?

A: The only way I could fix this issue is to move all problematic properties to BeforeBuild target and set them as DefineConstants.
<Target Name="BeforeBuild">
<PropertyGroup>
  <SourceDir>$(MSBuildProjectDirectory)..\..\..\Example</SourceDi>
  <FolderToExclude>$(MSBuildProjectDirectory)..\..\..\Example\Support</FolderToExclude>
  <DefineConstants>$(DefineConstants);SourceDir=$(SourceDir);FolderToExclude=$(FolderToExclude)</DefineConstants>
</PropertyGroup>
<RemoveDir Condition="Exists('$(sourceDir)\Support')" Directories="@(FolderToExclude)" />
</Target>

This solution worked for me but didn't find the reason behind this.


text:
Q: Buffer to uint32 NODEJS I'm trying to read the first 4 bytes of a buffer and convert that into an uint32, but I can't do it, the code is as follows
        socket.on('data', (buffer) => // New data from client
        {
            // Some sh*t like that -> let size = buffer[0...4];
        });

Thanks <3


text:
Q: How to migrate a db2 database I have a db2 database on a device which does not have internect connectivity and would like to move this database to another place. I have taken a backup from my database, can I use the 'restore' command to create a clone of this database?

A: To move a Db2 database from on-premise to Db2 Warehouse on Cloud, one option is to use IBM Lift CLI.  https://www.lift-cli.cloud.ibm.com/
You will need to have internet connectivity from the place your data resides on-premise - either a Db2 database, or failing that CSV files.
If all you have is a Db2 backup image, you would need to restore that into a local database, or use the (chargeable) utility High Performance Unload to extract table data as CSV files from the backup image.  IBM Lift CLI does not support Db2 backup images as a source for migration to the cloud.
Note that if you use CSV files, you will need to extract the DDL from the source database and create the empty tables on the target.


text:
Q: Threejs merge with multiple materials applies only one material I have searched on this and found several examples on stackoverflow, but the answers have not solved my problem.
What I have tried:
First I create the geometry bucket to be used for the group and an array to store my materials.
var totalGeom = new THREE.Geometry();
var materials = [];

I then run through my data (strData) with a for loop and call addMapMarker3d.
  for(var i=0; i<strData.length;i++){
     addMapMarker3d([strData[i].lat,strData[i].lon], strData[i].time, measureColors[i]);
  }

The addMapMarker3d function is as follows:
addMapMarker3d = function(latLng, height, color){
  var max = 600;
  var dist = 25;
  var opacity = (height/max);

  var geometry = new THREE.BoxGeometry( Math.floor(dist), height, Math.floor(dist));

  //create the material and add it to the materials array
  var material = new THREE.MeshBasicMaterial({ transparent:true, color: Number(color), opacity:opacity});
  this.materials.push(material);

  //create a mesh from the geometry and material.
  var cube = new THREE.Mesh( geometry, material);

  //leaf is a simple lat/lng to pixel position converter
  var actualMarkerPos = leaf.getPoint(latLng);
  //apply the position on a 5000x5000 cartesian plane
  var extent = 5000;
  cube.position.setZ((actualMarkerPos[1] * extent) - extent/2);
  cube.position.setX(-((actualMarkerPos[0] * extent) - extent/2));
  cube.position.setY(height/2);

  //update the matrix and add the cube to the totalGeom bucket
  cube.updateMatrix();
  totalGeom.merge( cube.geometry, cube.matrix);
}

After the for loop runs and all the cubes are created:
  var mats = new THREE.MeshFaceMaterial(materials)
  var total = new THREE.Mesh(totalGeom, mats);

  world.scene.add(total);

The question
While the geometry merge functions, and my view port is running at a much improved FPS, all the cubes have exactly the same color and opacity. It appears the merge is using a single material of the 10k I supplied. Is there some way to ensure that the geometry uses the material supplied in the array? Am I doing something incorrect?
If I try this in addMapMarker3d:
totalGeom.merge( cube.geometry, cube.matrix, materials.length-1);

I get "Uncaught TypeError: Cannot read property 'transparent' of undefined" and nothing renders, which I don't understand, because by the examples, each geometry should index to a material in the materials array.
three.js r.70

A: The following technique uses just one material, but allows you to retain the individual color of each merged object.  I don't know if it's possible to retain the individual alpha of each merged object.
http://jsfiddle.net/looshi/nsknn53p/61/
For each mesh, set each of its geometry.faces color :
function makeCube(size, color) {
    var geom = new THREE.BoxGeometry(size, size, size);

    for (var i = 0; i < geom.faces.length; i++) {
        face = geom.faces[i];
        face.color.setHex(color);
    }
    var cube = new THREE.Mesh(geom);
    return cube;
}

Then, in the parent geometry you are going to mesh into, set its material vertexColors property.
var parentGeometry = new THREE.Geometry();
var parentMatrial = new THREE.MeshLambertMaterial({
    color: 0xffffff,
    shading: THREE.SmoothShading,
    vertexColors: THREE.VertexColors
});

   // in a loop you could create many objects and merge them
for (var i = 0; i < 1000; i++) {
      cube = makeCube(size, color);
      cube.position.set(x, y, z);
      cube.rotation.set(rotation,rotation,rotation);
      cube.updateMatrix()
      parentGeometry.merge(cube.geometry, cube.matrix);
}
// after you're done creating objects and merging them, add the parent to the scene
parentMesh = new THREE.Mesh(parentGeometry, parentMatrial);
scene.add(parentMesh);

A: My original question was not answered: Is there some way to ensure that the geometry uses the material supplied in the array?
The answer is yes. Multiple materials can be applied to a single mesh during merge. After pushing the material to the materials array, the merge will utilize the geometry face material index. The merge will apply multiple materials when an array is supplied to new THREE.MeshFaceMaterial([materialsArray]) as the total mesh is created. This solves the mystery of the syntax. Just because you supply an array of materials does not mean that the merge will use each material in an iterative fashion as the objects are merged as of r71. The faces must inform the merge which material in the material array to use.
I am using this for a non rendered scene, and the final obj is exported. If you need render performance, see one of the other answers for some options.
A simple for loop on the face array on the geometry informs the merge which material to apply:
  addMapMarker3d = function(latLng, height, color){
  var max = 600;
  var dist = 25;
  var opacity = (height/max);

  var geometry = new THREE.BoxGeometry( Math.floor(dist), height, Math.floor(dist));

  //create the material and add it to the materials array
  var material = new THREE.MeshBasicMaterial({ transparent:true, color: Number(color), opacity:opacity});
  this.materials.push(material);

  //set the material index of each face so a merge knows which material to apply
  for ( var i = 0; i < geometry.faces.length; i ++ ) {
    geometry.faces[i].materialIndex = this.materials.length-1;
  }

  //create a mesh from the geometry and material.
  var cube = new THREE.Mesh( geometry, material);

  //leaf is a simple lat/lng to pixel position converter
  var actualMarkerPos = leaf.getPoint(latLng);
  //apply the position on a 5000x5000 cartesian plane
  var extent = 5000;
  cube.position.setZ((actualMarkerPos[1] * extent) - extent/2);
  cube.position.setX(-((actualMarkerPos[0] * extent) - extent/2));
  cube.position.setY(height/2);

  //update the matrix and add the cube to the totalGeom bucket
  cube.updateMatrix();
  totalGeom.merge( cube.geometry, cube.matrix);
}

A: The only reason you are seeing improved performance is because, after the merge, there is only one material. If you want your scene to have multiple materials you should not merge.
Adding to the same group:
var group = new THREE.Object3D();
group.add (object1);
group.add (object2);
group.add (object3);


text:
Q: Responding with a basic fact to imply a point of view is clearly flawed or wrong What is a word or concept that describes a situation where one person puts forth a point of view, and another person does not directly address the position, but instead responds with an obvious, basic fact whose implications cast doubt on the correctness or strength of the point of view? This is intended to belittle the point of view.

A: Counterexample: "used to argue that a certain [...] position is wrong by showing that it does not apply in certain cases".

A: There are some slang terms I can think of: zinger, for instance. "She hit him with a zinger."
Not for very formal writing, of course. Another would be "put down," again, not formal at all. But both imply that the other speaker is right and the original speaker is wrong. "Comeback" is a third, but doesn't imply the correctness of the second speaker necessarily.


text:
Q: Convert Pandas dataframe to csv string Here is an example of what I am trying to get:
I have:
import pandas as pd
df = pd.DataFrame({'A' : [0, 1], 'B' : [1, 6]})

My goal is:
',A,B\n0,0,1\n1,1,6\n'

I can achieve this with lazy and horrible:
df.to_csv('temp.csv') # create unnecessary file
body = open('temp.csv').read()

Also to_string() methods looks very promising; however, the best I can come up with is this:
body = df.to_string()[1:].replace('  ', ',') + '\n'

This does not create an unnecessary file, but seems sloppy and perhaps not very reliable.
Am I missing a simpler solution?

A: In [10]: df = pd.DataFrame({'A' : [0, 1], 'B' : [1, 6]})

In [11]: import io

In [12]: s = io.StringIO()

In [13]: df.to_csv(s)

In [14]: s.getvalue()
Out[14]: ',A,B\n0,0,1\n1,1,6\n'

A: The simplest way is just to not input any filename, in this case a string is returned:
>>> df = pd.DataFrame({'A' : [0, 1], 'B' : [1, 6]})
>>> df.to_csv()
',A,B\n0,0,1\n1,1,6\n'


text:
Q: Find out which frame in DOM initiated a postMessage (in IE11) In JavaScript, once I've received a 'message' event, is there a way to find out which frame in the DOM model has initiated it? This would be helpful when debugging a large web application where a particular message could have come anyone of 15-20 frames. The message event has a source property, but if the frame is cross-domain, it's not accessible:

Since I know these things vary from browser to browser, I'm asking specifically about IE11.

A: I found a way that actually works even when cross-domain - I add a DOM element by evaluating it in the Add Watch window. Then I search the DOM tree for that element, and figure out the frame in this way.
For example, this code works:
var foo_btn = document.createElement("BUTTON"); var foo_t = document.createTextNode("FOOBAR FOOBAR"); foo_btn.appendChild(foo_t); document.body.appendChild(foo_btn);

You just click Add Watch and paste it, and then after it executes, you can search for FOOBAR FOOBAR in the DOM tree.


text:
Q: C++ Tic tac toe program I am writing a tic-tac-toe program for a pretty basic C++ course and have a problem that's stumped me for a bit.
Below is the code for the userMove() function that takes input from the user and writes an 'X' to the char array board[2][2].  It works most of the time, but the problem is if the user inputs row = 1 column = 0, both board[1][0] and board[0][2] are changed to 'X'.
Does anyone see why this is happening?
//! The function userMove().
/*!
 The function userMove() takes two integer inputs from the terminal user,
 checks to see if the move is a valid one, and updates the char array board.
 */
void userMove() //take player's move
{
   //! The int row stores the user's first integer input.
   int row;
   //! The int column stores the user's second integer input.
   int column;

   cout << "Enter the row where you'd like your X:";
   cin >> row;
   cout << "Enter the column where you'd like your X:";
   cin >> column;

    //! This if statement checks that the user has selected a blank space for
    //! their next move.  If the space is already taken, the user is informed
    //! with an error message and the userMove() function is called
    //! recursively.
   if(board[row][column] == ' ')
   {
      board[row][column] = 'X';
   }
   else
   {
      cout << "Invalid move\n";
      this->userMove();
   }
}

A: Your dimensions are wrong. Array dimensions count elements, instead of denoting the highest index:
char board[3][3];

/**
 * Now you may access the following:
 *
 *   board[0][0]
 *   board[0][1]
 *   board[0][2]
 *   board[1][0]
 *   board[1][1]
 *   board[1][2]
 *   board[2][0]
 *   board[2][1]
 *   board[2][2]
 */

With a board[2][2], you have fewer elements than you think, and when you try to do things like getting the value of the non-existent element board[0][2], you may just so happen to get the value of board[1][0] instead (due to how memory accesses work, and how arrays are laid out in memory) — that's why you think the write is occurring on both of these elements.

A: You need to define your board as
char board[3][3];

for it to be 3x3. This allows indices from 0 to 2.
Also, you shouldn't really be calling the function recursively when a simple loop would do.


text:
Q: AJAX with .change() not working? I have 2 drop down menus. One of them shows the provinces in the country, and when one of the provinces selected, the second one should show the districts of the selected province.
The code below works properly and the drop down shows the provinces:
$(document).ready(function () {
        $.ajax({
            url: "http://blabla.com/dev/provinces"
        }).then(function (data) {
            var data = JSON.parse(data)["response"];
            var dropdown = $("#province");

            data.forEach(function (province) {
                dropdown.append("<option value=" + province["p_name"] + ">" + province["p_name"] + "</option>")
            });
        })
    });

However other drop down does not show the districts of the selected province by using the code below:
$("#province").change(function () {
        $.ajax({
            url: "http://blabla.com/districts?province=["+ $(this).val()+"]"
        }).then(function (data) {
            var data = JSON.parse(data)["response"];
            var dropdown = $("#district");

            data.forEach(function (district) {
                dropdown.append("<option value=" + district["d_name"] + ">" + district["d_name"] + "</option>")
            });
        })
    });

Second code give the following error on console:

"Uncaught SyntaxError: Unexpected token A"

What is the problem with the second one?
Thanks.
EDIT: HTML of the drop down menus' are like these:
Province
<select id="province"></select>

District
<select id="district"></select>

A: The problem seems to be the response coming from the RESTful API call, which was not JSON by accident. When I fixed it, the code I posted worked fine. Thanks anyways.


text:
Q: How to capture windows 10/windows 11 advanced display settings for multiple monitors I am trying to capture the following displays information connected to my laptop programatically using powershell but I am unable to find a way. This information can be found via the windows GUI at Settings > Display > Advanced Display Information (2 screenshots attached below).
Here's the information I am trying to capture
Display Name: (In this case, display name for internal would be but the external one would be "ASUS VP 228)

Display Resolution: 1680x1050 and 1920x1080 for the 2 displays

Whether it's an internal/external display: True and False

Refresh rate: 60Hz and 60Hz

Here's what I've tried
Get-WmiObject win32_videocontroller

Returns the resolution under parameter VideoModeDescription but even then, it seems to return the value of "Active Signal Resolution" (from the screenshot) below).
Get-WmiObject Win32_Desktopmonitor

DeviceID            : DesktopMonitor1
DisplayType         :
MonitorManufacturer : (Standard monitor types)
Name                : Generic PnP Monitor
ScreenHeight        :
ScreenWidth         :

Only get output information for 1 out of the 2 monitors and don't get ScreenHeight or ScreenWidth` values.
get-ciminstance -namespace root\wmi -classname wmimonitorbasicdisplayparams

Active                        : True
DisplayTransferCharacteristic : 120
InstanceName                  : DISPLAY\IVO8C66\5&462698&0&UID256_0
MaxHorizontalImageSize        : 31
MaxVerticalImageSize          : 17
SupportedDisplayFeatures      : WmiMonitorSupportedDisplayFeatures
VideoInputType                : 1
PSComputerName                :

Active                        : True
DisplayTransferCharacteristic : 120
InstanceName                  : DISPLAY\ACI22C3\5&462698&0&UID265_0
MaxHorizontalImageSize        : 48
MaxVerticalImageSize          : 27
SupportedDisplayFeatures      : WmiMonitorSupportedDisplayFeatures
VideoInputType                : 1
PSComputerName

Gives me the correct monitor count but doesn't give me any other information.
I then tried using the DumpEDID tool and it gave me more information but didn't give me current monitor resolution or whether it's an internal display or not.
DumpEDID v1.07
Copyright (c) 2006 - 2018 Nir Sofer
Web site: http://www.nirsoft.net

*****************************************************************
Active                   : Yes
Registry Key             : DISPLAY\ACI22C3\5&462698&0&UID265
Monitor Name             : ASUS VP228
Serial Number            : G6LMTF155938
Manufacture Week         : 26 / 2016
ManufacturerID           : 26884 (0x6904)
ProductID                : 8899 (0x22C3)
Serial Number (Numeric)  : 155938 (0x00026122)
EDID Version             : 1.3
Display Gamma            : 2.20
Vertical Frequency       : 50 - 75 Hz
Horizontal Frequency     : 24 - 83 KHz
Maximum Image Size       : 48 X 27 cm (21.7 Inch)
Maximum Resolution       : 1920 X 1080
Support Standby Mode     : No
Support Suspend Mode     : No
Support Low-Power Mode   : Yes
Support Default GTF      : No
Digital                  : Yes

Supported Display Modes  :
     720 X  400  70 Hz
     640 X  480  60 Hz
     640 X  480  67 Hz
     640 X  480  72 Hz
     640 X  480  75 Hz
     800 X  600  56 Hz
     800 X  600  60 Hz
     800 X  600  72 Hz
     800 X  600  75 Hz
     832 X  624  75 Hz
    1024 X  768  60 Hz
    1024 X  768  70 Hz
    1024 X  768  75 Hz
    1280 X  720  60 Hz
    1152 X  864  75 Hz
    1280 X  960  60 Hz
    1440 X  900  60 Hz
    1280 X 1024  60 Hz
    1280 X 1024  75 Hz
    1680 X 1050  60 Hz
    1920 X 1080  60 Hz

*****************************************************************

*****************************************************************
Active                   : Yes
Registry Key             : DISPLAY\IVO8C66\5&462698&0&UID256
Manufacture Week         : 0 / 2019
ManufacturerID           : 53030 (0xCF26)
ProductID                : 35942 (0x8C66)
Serial Number (Numeric)  : 0 (0x00000000)
EDID Version             : 1.4
Display Gamma            : 2.20
Maximum Image Size       : 31 X 17 cm (13.9 Inch)
Maximum Resolution       : 1920 X 1080
Support Standby Mode     : No
Support Suspend Mode     : No
Support Low-Power Mode   : No
Support Default GTF      : No
Digital                  : Yes

Supported Display Modes  :
    1920 X 1080  60 Hz

The script here gives me almost what I want except it doesn't give me the monitor name nor does it give me information whether it's internal or not.
I have attached 2 screenshots from the Settings > Display > Advanced Display page which is the information I am looking to capture.


text:
Q: Spark __getnewargs__ error I am trying to clean a Spark DataFrame by mapping it to RDD then back to DataFrame. Here's a toy example:
def replace_values(row,sub_rules):
    d = row.asDict()
    for col,old_val,new_val in sub_rules:
        if d[col] == old_val:
            d[col] = new_val
    return Row(**d)
ex = sc.parallelize([{'name': 'Alice', 'age': 1},{'name': 'Bob', 'age': 2}])
ex = sqlContext.createDataFrame(ex)
(ex.map(lambda row: replace_values(row,[(col,1,3) for col in ex.columns]))
    .toDF(schema=ex.schema))

Running the code above results in a Py4JError with a very long stack trace ending in the following:
Py4JError: An error occurred while calling o801.__getnewargs__. Trace:
py4j.Py4JException: Method __getnewargs__([]) does not exist
    at py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:333)
    at py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:342)
    at py4j.Gateway.invoke(Gateway.java:252)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:133)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:207)
    at java.lang.Thread.run(Thread.java:745)

What is going on here? How do I fix it? I am using PySpark 1.5.2.

A: The error is caused by the reference to ex.columns in the .map(lambda...) statement. You can't have references to an RDD inside the function being used in an RDD transformation. Spark is supposed to issue more helpful errors in this case, but apparently that didn't make it into this version.
Solution is to replace references with copies of the referenced variables:
def replace_values(row,sub_rules):
    d = row.asDict()
    for col,old_val,new_val in sub_rules:
        if d[col] == old_val:
            d[col] = new_val
    return Row(**d)
ex = sc.parallelize([{'name': 'Alice', 'age': 1},{'name': 'Bob', 'age': 2}])
ex = sqlContext.createDataFrame(ex)
cols = copy.deepcopy(ex.columns)
(ex.map(lambda row: replace_values(row,[(col,1,3) for col in cols]))
    .toDF(schema=ex.schema))


text:
Q: UIScrollView paging with animation I have achieved the following using UIScrollView and enabled paging.

I want the centre element of the scrollview to show little bigger than other elements. Need to increase/decrease the font of the text label as the scroll view is scrolling depending on its location.
I tried using transform but hard luck.
Code for adding the label's:
array = [[NSMutableArray alloc] init];

for(int i=0;i<10;i++){
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(x, 0, 150, 50)];
    label.text = [NSString stringWithFormat:@"ID - %d",i];
    label.textAlignment = UITextAlignmentCenter;
    x +=150;
    [self.scrollView addSubview:label];
    [array addObject:label];
}

[self.scrollView setContentSize:CGSizeMake(x, 50)];

Animation which I performed in ScollViewDidScroll
float position = label.center.x - scrollView.contentOffset.x;
float offset = 2.0 - (fabs(scrollView.center.x - position) * 1.0) / scrollView.center.x;
label.transform = CGAffineTransformIdentity;
label.transform = CGAffineTransformScale(label.transform,offset, offset);

CODE: What I have achieved till now:
https://www.dropbox.com/s/h2q4qvg3n4fi34f/ScrollViewPagingPeeking.zip?dl=0

A: Don't use scrollview, used UICollectionView and Make collectionView cell bigger as screen size.
And Enable it's paging property than used it's delegate methods.
It's more preferable and efficient way of paging.

A: It will work using a collection view. Return layout attributes where the transform scale is calculated according to the position. Subclass the UICollectionViewLayout you are using (probably UICollectionViewFlowLayout). To get the resizing based on position to work you should override a few of its methods thusly:
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
{
    return YES;
}

- (NSArray*)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSArray *array = [super layoutAttributesForElementsInRect:rect];

    for (UICollectionViewLayoutAttributes *attributes in array)
    {
        [self updateLayoutAttributesForItemAtIndexPath:layoutAttributes];
    }

    return array;
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewLayoutAttributes *layoutAttributes = [super layoutAttributesForItemAtIndexPath:indexPath];
    [self updateLayoutAttributesForItemAtIndexPath:layoutAttributes];
}

- (UICollectionViewLayoutAttributes *)updateLayoutAttributesScaleForPosition:(UICollectionViewLayoutAttributes *)layoutAttributes
{
    // NOTE: Your code assigning an updated transform scale based on the cell position here

    return layoutAttributes;
}

Probably the main thing you were missing was the override to the shouldInvalidateLayoutForBoundsChange: method


text:
Q: what is mysql binlog dump in show processlist When I did show processlist in mysql I got list of process. One of the process with binlog dump running from quit long time.
What is binlog dump? do I need to kill this. what happen if i kill this process?

A: Generally we are doing show process when we are getting error too many connections, but in my case Mysql is not responding intermittently. So i thought of looking into the processes if there is any long running query, so that I can kill it.
I got binlog dump under Command column in process list.
Command shows the type of command the thread is currently executing.
binlog dump is a thread on a master server for sending binary log contents to a slave server.
If need more information on different values of Command you can refer to:

*

*http://dev.mysql.com/doc/refman/5.1/en/thread-commands.html
For show process

*

*http://dev.mysql.com/doc/refman/5.1/en/show-processlist.html

A: Its a process that constantly runs on the master server needed for replication. You should generally ignore this process, it should be harmless.


text:
Q: How to convert downloaded document object into usable JSON I'm working on a function where will able to download Firestore with a caching system using webrequest and E-tag comparison.
I've successfully complete the local caching system and will record every download data, so that next time you want to download the same data, it will check past downloaded record and compare whether firestore data is modified.
The problem is by using firestore's REST API and webrequest, I ended up retrieve a data that looks like this:

As you can see, the result is troublesome. I could not transfer it by using json format because it's a Firestore Document object. All I know that I can transfer it into a Dictionary<string,object>, but my Class object has more than two levels, the structure of this example is like Class > John > John's personal data, yet each level all contains the key 'field'. Is there any way that I can convert these line into the object I used in C# project?

A: You can do the following steps:

*

*paste the JSON document from your screenshot to https://json2csharp.com/ to generate DTO classes. (replace all the sensitive data inside the document first - only the structure is required!)

*refine the generated DTO classes to your needs

*use Newtonsoft.JSON to deserialize the JSON document into objects of the generated classes
Alternatively you can deserialize the JSON document into a "dynamic" using Newtonsoft.JSON and access all the internals of the document from your code.
This might be a good way if the structure of the original document must be very flexible.


text:
Q: How to pause SpVoice immediately in WPF? I want to do Text-to-speech with many voices in many languages.
I tried SpeechSynthesizer (Ref: System.Speech) but it only allows 2 English voices. After installing 6 English voices from Microsoft site, I still cannot get any other voices.
I changed to SpVoice (Ref: Microsoft Speech Object Library). SpVoice can recognize 6 voices I just installed. The problem is when I call spVoice.Pause(), it always delay 0.5 second before it stops speaking completely. I also tried to set AlertBoundary for SpVoice but it didn't help.
SpeechSynthesizer can pause right away with SpeakAsyncCancelAll but only works with default voices.

A: Basically,the Pause method pauses the voice at the nearest alert boundary and closes the output device, allowing it to be used by other voices.
spVoice.Speak() method can be called synchronously or asynchronously. When called synchronously, the method does not return until the text has been spoken; when called asynchronously, it returns immediately, and the voice speaks as a background process.
I hope you are calling spVoice.Speak() synchronously. Thats why you are getting this issue. So use asynchronous method instead of synchronous,your problem should be solved. Then spVoice.Pause() will pause immediately.
SpVoice spVoice = new SpVoice ();
spVoice.Speak ("Testing spVoice",SpeechVoiceSpeakFlags.SVSFlagsAsync);
//......
spVoice.Pause();


text:
Q: Relay-style pagination with Django REST Framework I'm working on a Django 3.x app (with Django REST Framework) and I need to expose a REST API that will then be consumed by a GraphQL server in order to provide a GraphQL endpoint to a client.
The cursor based pagination provided by Django REST Framework out of the box only provides a next and previous cursors for each request, but Relay requires one opaque cursor for each returned edge/item.
How can I ask Django REST Framework to generate a cursor for each item?


text:
Q: Morphism of varieties defined by the greatest common divisor I'm reading the paper On the Chow Bunches for Different Projective Embeddings of a Complete Variety, Hoyt (1966). In this paper the author wants prove that the Chow monoind $\mathcal{C}_p(X)=\bigsqcup_{d\geq 0}\mathcal{C}_{p,d}(X)$ given by the disjoint union of Chow varieties $\mathcal{C}_{p,d}(X)$ does not depend from the choice of the embedding of the projective variety $X\subseteq\mathbb{P}^n_\mathbb{C}$. In order to do this he needs to prove the following lemma.

I don't understand how the condition (ii) defines a closed set and, similarly, the condition (i) defines an open set. Moreover  the author says that $h$ is a morphism, but it's unclear to me its "proof" of this fact.
Any help to understand these arguments is very well appreciated.

A: First, note that the text and the question at the time of writing disagree. I'll be explaining the text and ignoring the perceived error in the question.
We make one obvious reduction: we may ignore all indices $i$ such that $A_i$ are zero, and assume that $A_i\neq 0$ for all $i$.
Define $Y_{d}$ to be the projectivization of the space of polynomials in indeterminants $\mathfrak{X}$ of degree less than $d$, and define $Z_{d}$ to be the projectivization of the space of homogeneous polynomials in indeterminants $\mathfrak{X}$ of degree exactly $d$.
Consider the two maps from $L\times \prod_{i\in I} Y_{\deg A_i - d}\to \prod_{i,j\in I, i<j} Y_{\deg A_i+\deg A_j}$ given by $((A_1,\cdots,A_t),C_1,\cdots,C_t)\mapsto A_iC_j$ in the $(i,j)$ factor and $((A_1,\cdots,A_t),C_1,\cdots,C_t)\mapsto A_jC_i$ in the $(i,j)$ factor. The locus of agreement of the two morphisms is closed, as the target is separated. Thus the preimage of the complement of this locus of agreement under either morphism is open in the LHS. The image of this set in $L$ under the projection is again open. Thus "GCD of degree less than $d$" defines an open condition on $L$, and "GCD of degree exactly $d$" defines a locally closed condition on $L$, as it's the intersection of "GCD degree $<d+1$" and the complement of "GCD degree $<d$".
Now, we consider iii). $A_i=aB_iG$ is equivalent to $(A_1,\cdots,A_t)$ being in the image of $\Phi:Z_d \times \prod_{i\in I} Z_{\deg B_i} \to L$ defined by $(G,z_1,\cdots,z_t)\mapsto (Gz_1,\cdots,Gz_t)$, and since the source is irreducible, its image must be as well. Anything in the image of this map must have GCD of degree at least $d$.
Since $U$ is the intersection of $\operatorname{im} \Phi$, which is irreducible, and "GCD less than $d+1$", which is open, it is again irreducible. By the previous discussion, it is also locally closed. We've shown what we needed to show about $U$.
The construction that gives $h$ is morally the same as how one constructs a blowup, up to perhaps some cosmetic changes. The point is that once you have something satisfying an equation like $A_iB_j=A_jB_i$, there should be good tools to recover what $B_i,B_j$ should look like if you know $A_i,A_j$. Another proof that $g$ is a morphism may be given by looking at the projection to $Z_d$ of the preimage of $(A_1,\cdots,A_t)$ under $\Phi$ and verifying it consists of one point.


text:
Q: Serial Port Reading into TextBox my eventual aim is to receive data and display it as both a graph and in individual text boxes (or something better!) the data is 2 x temperature readings and a humidity reading, for example the data sent would be "222160" etc.
However before I even tackle that I am having issues simply showing any data in a textbox. This is the code I am using; (Consists of a textbox for the UI)
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;
using System.IO.Ports;
using System.Threading;

namespace WFARxSimple
{
    public partial class Form1 : Form
    {
        string rxString;
        public Form1()
        {
            InitializeComponent();
            myport = new SerialPort();
            myport.PortName = "COM5";
            myport.BaudRate = 9600;
            myport.Parity = Parity.None;
            myport.DataBits = 8;
            myport.StopBits = StopBits.One;
            myport.Open();
        }

        private SerialPort myport;
        private void DisplayText(object sender, EventArgs e)
        {
            showRx.AppendText(rxString);
        }

        private void myPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            rxString = myport.ReadExisting();
            this.Invoke(new EventHandler(DisplayText));
        }
    }
}

However I cannot get any data to show in my textbox.

A: You need, at the very least: myPort.DataReceived += myPort_DataReceived;. Do this in Form1().


text:
Q: advantages to put code in app.xaml.cs in wp7 I am wondering if there are any advantages to putting the code into app.xaml.cs (Application_Launching) compared to the code I've put into the mainpage.xaml.cs (MainPage()) section.

A: The key thing to bear in mind is that the Application object in App.xaml.cs is where you get notification of the application lifecycle events.
See Execution Model for Windows Phone on MSDN for more information about this.
By using the Launching/Activated methods on your Application object, you can make sure you are initialising your whole app correctly when it starts or is resumed after tombstoning (or returns from the dormant state in WP7 Mango).
Code in your startup page (MainPage.xaml.cs) is used to initialize that one application page when it is navigated to. This is typically done in the OnNavigatedTo method as you can't rely on pages being freshly constructed every time you navigate to them.
Of course you will also need to handle the other events for application exit and deactivation, and navigation away from each of your pages.
Also bear in mind that if you are targeting WP7 Mango, you can start the app from a deep link in an alarm, reminder or toast to a page other than your normal startup page. If the application starts like this, code in your startup page MainPage.xaml.cs may not run, but code in your Application object always would.


text:
Q: Understanding one usage of "in" keyword in Kotlin I'm trying to understand Kotlin take of generics especially with the in and out keywords. I've written this simple piece to hopefully illustrate my point of confusion.
This is the method that looks and works OK;

Here, IDE gives a hint saying that the type of the item the for loop is iterating over is a Shape. This is good.
Another version of the method above that doesn't seem quite right at first glance (since it's a "consumer"). But all I want to do is to read a list of shapes and that's all what's in this from.

That doesn't work which is maybe right according to the rules but I am not able to connect the dots here. It seems like a safe operation. I can also see Kotlin downs the type to "Any?" which explains why this gives a compiler error already. Can someone explain the potential type unsafety here please?

A: Variance is always a tough concept to work through…
If you're using the terms 'producer' and 'consumer', note that they refer to your interaction with the item in question ' in this case, the MutableList parameter.
Your first function, with a MutableList<out Shape> parameter, can accept a list of Shapes, or a list of any subclass of Shape.  (out means roughly 'or any subclass'.)
In each case, if you're consuming the list, whatever you pull out of the list will always be a Shape (as the IDE confirms).
But if you want to put something into the list (as a producer), you can't tell what would be safe to add, as that would depend on whether it's a subclass, and which one.
Your second function, with a MutableList<in Shape> parameter, is the opposite: it can accept a list of Shapes, or a list of any superclass of Shape.  (in means roughly 'or any superclass'.)
In each case, it's always safe to put a Shape into the list (as a producer).  But you can't tell anything about the type of what you pull out of it (as a consumer): it could be called with a MutableList<Any?>, which could contain Strings or Files or whatever.  So the compiler will give it the universal type, Any? (as the IDE confirms).


text:
Q: cordova - Failed: q is not supported When I build cordova this message view:

Using "requireCordovaModule" to load non-cordova module "q" is not supported. Instead, add this module to your dependencies and use regular "require" to load it.

How fix this problem?
PS. I updated npm before this build problem. So it was not problem buildings before update. Sorry my English))

A: **In my case the following sequence fixed that issue:

Remove ios platform ionic cordova platform rm ios
Remove android platform ionic cordova platform rm android
Remove sqlite storage plugin ionic cordova plugin rm
  cordova-sqlite-storage
Install latest sqlite storage npm package npm i
  cordova-sqlite-storage@latest
Install sqlite storage plugin ionic cordova plugin add
  cordova-sqlite-storage
Add ios platform ionic cordova platform add ios
Add android platform ionic cordova platform add android

A: The following fixed the issue for me
ionic cordova platform rm ios
ionic cordova plugin remove de.appplant.cordova.plugin.local-notification
ionic cordova plugin rm cordova-sqlite-storage
npm i cordova-sqlite-storage@latest
ionic cordova plugin add cordova-sqlite-storage
ionic cordova platform add ios@5.0.1
ionic build
cordova build ios

A: Solved this problem by installing a lower version of cordova. Seems like every version of cordova that is > 8.1.1 breaks a number of plugins.
For instance, the plugin cordova-sqlite-storage failed to install with the following error message:

Failed to install 'cordova-sqlite-storage': CordovaError: Using
  "requireCordovaModule" to load non-cordova module "q" is not
  supported. Instead, add this module to your dependencies and use
  regular "require" to load it.

To solve that issue, I simply removed cordova by calling npm uninstall cordova -g and then installed it globally again with npm install -g cordova@8.1.1
After that fix, no more errors are getting displayed and cordova-sqlite-storage gets installed smoothly!!

Installing "cordova-sqlite-storage" for android

A: Just run npm i cordova-sqlite-storage
This would upgrade the plugin to the latest version in which this issue is already solved.


text:
Q: How to find an inflection point (maximum slope) of a log-log plot? I have a function $f(x)$ and I have plotted it on a log-log plot. I would like to find the location of the inflection point of the function. (note: that means the inflection point in "log-log space" which is not the same as the inflection point of $f(x)$ itself.) I know the following is true: $\frac {d \log y}{d \log x} = \frac{x}{y} \frac{dy}{dx}$. What is the correct formula to find the local maximum of $\frac {d \log y}{d \log x}$?

A: Suppose $y=f(x)$ for some function $f$.  When you make a log-log plot you are essentially introducing two new variables
$$u = \log x,  v = \log y$$
and plotting the function
$$v=g(u)$$
You can express $g$ in terms of $f$ as follows:
$$v = \log y = \log f(x) = \log f(e^u) $$
and therefore the function you are interested in is $g(u) = \log f(e^u)$.
Now, you are looking for the inflection point(s) of $g$.  That means you need to study the second derivative of $g$, i.e. $g''(u) = \frac{d^2v}{du^2}$.  By the chain rule
$$g'(u) = \frac{f'(e^u)e^u}{f(e^u)}$$
and then using the quotient rule and chain rule
$$g''(u) =\frac{f(e^u)\left(f''(e^u)e^{2u}+f'(e^u)e^u\right)-\left(f'(e^u)\right)^2e^{2u}}{(f(e^u)^2}$$
In terms of the original variables $x$ and $y$, this is
$$\frac{y\left(f''(x)x^{2}+f'(x)x\right)-\left(f'(x)\right)^2x^{2}}{y^2}$$
At an inflection point, the second derivative changes sign, which means that either the quantity above is zero (i.e. its numerator is zero), or the quantity is undefined (i.e. its denominator is zero).
The denominator will be zero if $y=0$, but since you are doing a log-log plot presumably you know that $y>0$ so we can discard this case.  The numerator will be zero if
$$ y\left(f''(x)x^{2}+f'(x)x\right)=\left(f'(x)\right)^2x^{2}$$
Once again since we are doing a log-log plot I assume you already know that $x>0$, so we can divide through by $x^2$ to get
$$ y\left(f''(x)+\frac{f'(x)}{x}\right)=\left(f'(x)\right)^2$$
The criterion $g''(u)=0$ is equivalent to this equation relating $f(x)$ and its derivatives $f'(x)$ and $f(x)$.  I don't see any simpler way to write this but perhaps if you know something about $f(x)$ you might be able to simplify it still further.


text:
Q: How to test a skinny controller without retesting the fat model? Before I start, I'm using rails with rspec, shoulda-matchers, and factorygirl to ease testing, so if those libraries contain something helpful to solve the problem below, please let me know.
I was designing my controller and model, and wasn't sure how to go about testing this situation.
I have a game model, which can contain a bunch of players. Players can only be removed if the game hasn't started yet, so I added a remove_player method to my game model and tested it thoroughly.
In my player controller, I have the delete action calling the remove_player method to actually do the work, and then the action causes a redirect.
How can I make a test that the controller is actually doing what it's supposed to (calling remove_player) without retesting the method? I can test to do a redirect, but that won't fail if in the future, the call to remove_player gets deleted.
I know shoulda-matchers has "should_validate_presence_of" and stuff like that, which is the same idea behind this test, but doesn't work with my own methods.

A: I tried out mocks and stubs last night, and they did exactly what I wanted. RSpec's mocks were pretty easy to pick up and are included with the rspec gem.
The basic idea of a stub is a replacement for a real object that you're using to test another object. In the example in my question, I could make a stub of the game model when testing my player controller, and say gamestub.remove_player returns true always. In RSpec you could do that like
@game = double("game") #a double is rspec's mock/stub object
@game.stub(:remove_player?).and_return(true)

A mock is like a little different in that it is not just a replacement for the object you're mocking, but also a part of your test conditions. You can say not only what your fake object would return if it were called, but that it should be called n times (or the test will fail), and what parameters you expect it to be called with. In the example above, i could mock a game and say gamemock.remove_player should be called once and be passed in the current player and return true (or false if i wanted to test what happened if the test failed). Here's an example kind of like what I did for the players controller.
@game = double("game")
Game.should_receive(:find_by_id).with("123").and_return { @game }
@game.should_receive(:remove_player?).with(current_user).and_return(true)
delete :destroy, {:id => 123}
response.should do_whatever

Mocks and stubs are pretty similar. This article tries to highlight differences. To me it seems it's basically how you use them, since mocks have all of the capability of stubs and can be used as one. That's probably why RSpec treats them as one type (double)


text:
Q: What is the value of a CMAttitude quaternion for absolutely no rotation I have a saved rotation quaternion which depicts a specific rotation. I want all the other quaternion which I will get from my iPhone sensor to be transformed to the saved quaternion.
For that formula is sensorQuaternion * Inverse of savedQuaternion.
I want to save a quaternion with absolutely no rotation. What will be the x y z and w values of such quaternion?


text:
Q: sscanf to read custom simple log format? I wrote a simple log file for my website that is in the following format:
TIME: "..." IP: "..." HOST: "..." UA: "..."

And wanted to parse through it with sscanf as part of an exercise. My code was roughly like this, which was run on each line of the log:
list($time, $ip, $host, $ua) = sscanf("TIME: %s IP: %s HOST: %s UA: %s", $line);

Of course this is PHP, but it's irrelevant, now I thought this would work but it just doesn't parse anything. I know now that it's messing up becuase the user agent or time contains spaces, so it doesn't work.
I know not much about sscanf format, but wish to use it for simplicity, is there a way to read the quotes as a single entity (instead of using just plain %s) , so it can work correctly?
I got many logs in similar format, so this would be of great use if I can just get this example to work. Thank you!

A: I guess I'll just use a regular expression, such as "(?:[^\\"]+|\\.)*" to get it done.