text:
Q: Unable to open the HTML file on the remote machine on my local machine I have a virtual machine (ubuntu 16.04) which I use via putty.
I have server folder with my server script learning_server.js which looks like(the node-nodule is the folder)
`
var version = '2019 March';
console.log('NodeJS Server - '+version);
/* ************************************** */

// ================== load nodejs packages =================
var http = require('http');
var https = require('https')
var async = require('async');
var ip = require("ip");
var url = require('url');
var fs = require('fs');
var request = require('request');
var moment = require('moment');
let fastcsv = require('fast-csv');

// ================== server port =================
var port = 5000;

// ================== load raw data =================
var inputDataFile = "data/AoT_Chicago.complete.2019-03-17/nodes.csv";

let readableStreamInput = fs.createReadStream('./'+inputDataFile);
let csvData = [];
var updatedData = [];
let minVal=1, maxVal=25;

// As the input file is CSV, using fast-csv node module to read the contents and save it to an a array.
fastcsv
    .fromStream(readableStreamInput, {headers: true})
    .on('data', (data) => {
      let rowData = {};

      Object.keys(data).forEach(current_key => {
         rowData[current_key] = data[current_key];
      });
      csvData.push(rowData);
    })
    .on('end', () => {
        console.log('No of rows read: ', csvData.length);

        // ================== server setup ==================
        var server = http.createServer();
        server.on('request', request);
        server.listen(port, '0.0.0.0');
        console.log('Server IP is '+ip.address() + ' port '+port)
        console.log('Server is Ready...')
        function request(request, response) {
            var store = '';

            // Start processing the contents of the http request
            request.on('data', function(data) { store += data; });

            // Once we reach the end of the http request, start creating the response to send to the client.
            request.on('end', function() {
                try {
                    response.setHeader('Content-Type', 'application/json');
                    response.setHeader("Transfer-Encoding", "chunked");
                    response.setHeader("Access-Control-Allow-Origin", "*");
                    response.setHeader("Access-Control-Allow-Methods", "POST");
                    response.setHeader("Access-Control-Allow-Headers", "Content-Type");

                    // As long as the client sends a valid request with key "data_request" in it, server returns the whole data as JSON string in the response.
                    var jsonData = JSON.parse(store);

                    if(jsonData.hasOwnProperty('data_request')){
                        let retn = JSON.stringify(csvData);
                        response.end(retn);
                        console.log('data sent')
                        updatedData=csvData;
                    } else if(jsonData.hasOwnProperty('updated_data_request')){
                        // To simulate the condition where the data sent by the server changes based on key words in the client request,
                        // data is randomly generated if the request has "updated_data_request" as key.
                        updatedData=[];
                        for (i = 0; i < csvData.length; i++) {
                            var rowData = {};
                            var val=Math.floor(Math.random() * (maxVal - minVal + 1)) + minVal;
                            rowData["number"]=val;
                            updatedData.push(rowData);
                        }

                        let retn = JSON.stringify(updatedData);
                        response.end(retn);
                        console.log('updated data sent')
                    } else if(jsonData.hasOwnProperty('deleted_data_request')){
                        // To simulate the condition where the data sent by the server is same as previous request but some points are removed now.

                        var index=Math.floor(Math.random() * (updatedData.length));
                        updatedData.splice(index,1);
                        let retn = JSON.stringify(updatedData);
                        response.end(retn);
                        console.log('deleted data sent')
                    }

                } catch(error) {
                    // server error, need be re-run
                    console.log('*** ERROR: Server error ***');
                    console.log(error);
                }
            });
        }
    })
`

I also have a client folder with my client script learning_client.js which looks like(the node-nodule is the folder)
`var version = '2019 March';
/* ************************************** */

// server's ip address (same machine in this case)
var serverIP = 'localhost';
// Port number on which server is listening
var serverPort = '5000';

// Function to create a request for the server
function reqJSON(jsonData) {
    return $.ajax({
                type: "POST",
                url: "http://"+serverIP+":"+serverPort,
                cache: false,
                crossDomain: true,
                data: jsonData,
                processData: false,
                dataType: 'json',
                headers: {
                    "Content-Type":"text/plain;charset=UTF-8",
                },
                timeout: 15000, // 15s
            })
};

var colorCounter=0;
colors=['green','blue','red']
updateData("data_request");

function updateData(request_key) {
    console.log(request_key);
    // Use given key to request the data from server
    var request_obj = {};
    request_obj[request_key]={}
    req = JSON.stringify(request_obj)
    console.log(req);
    // Create the request
    reqJSON(req).then(function(data, error){

        // Got the response from the server. "data" contains the data returned by the server
        console.log(data);

        // Start creating visualization using "data"

        var scale = d3.scaleLinear()
                        .range([5,15])
                        .domain(d3.extent(data, function(d){return d.number;}))

        var svg=d3.select("svg");
        svg.style("background-color", "white");

        var svg_rect=svg.node().getBoundingClientRect();

        // Create circles for each data point
        var datapoints=svg.selectAll("circle")
            .data(data)

        //Enter section: Invoked only for creating the new data points
        datapoints.enter().append("circle")
            .attr("cx", function(d,i) {return 50*(i+1) + 5;})
            .attr("cy", svg_rect.y+svg_rect.height/2)
            .attr("r", function(d) {return scale(d.number);})
            .style("fill", colors[colorCounter%colors.length]);

        //Update section: Invoked only for upating the existing data points
        datapoints.transition()
            .duration(500)
            .attr("cx", function(d,i) {return 50*(i+1) + 5;})
            .attr("cy", svg_rect.y+svg_rect.height/2)
            .attr("r", function(d) {return scale(d.number);})
            .style("fill", colors[colorCounter%colors.length]);

        //Exit section: Invoked only for deleting the removed data points.
        datapoints.exit().remove();

        //Create text showing the number that represents the corresponding circle.
        var datapointsText = svg.selectAll("text")
            .data(data)

        //Enter section
        datapointsText.enter().append("text")
            .attr("x", function(d,i) {return 50*(i+1) + 5;})
            .attr("y", svg_rect.y+svg_rect.height/2+50)
            .style("text-anchor", "middle")
            .style("font-size", "1em")
            .text(function(d) {return d.number;});

        //Update section
        datapointsText
            .attr("x", function(d,i) {return 50*(i+1) + 5;})
            .attr("y", svg_rect.y+svg_rect.height/2+50)
            .style("text-anchor", "middle")
            .style("font-size", "1em")
            .text(function(d) {return d.number;});

        //Exit section
        datapointsText.exit().remove();

        colorCounter++;
    })

}
`

and I have an html folder with the html (learning_index.html) file
`<!doctype html>

    <title>Simple Client Demo (NodeJS)</title>
    <meta charset="utf-8">
    <link href="/home/ricky/D3js/css/style.css" rel="stylesheet" media="screen" type="text/css">

        <svg width="1080" height="200"></svg>

        <input name="updateButton"
           type="button"
           value="UPDATE"
           onclick="updateData('updated_data_request')" />
        <input name="deleteButton"
           type="button"
           value="DELETE"
           onclick="updateData('deleted_data_request')" />

`

via putty I am able to start the server using node server/js/learning_server.js
the output shows as
`NodeJS Server - 2019 March
No of rows read:  91
Server IP is 10.158.56.133 port 5000
Server is Ready...
`

now I am trying to open the learning_index.html file using my local windows machine
`http://10.158.56.133:5000/D3js/client/html/learning_index.html`
but it shows
`This site can't be reached 10.158.56.133 took too long to respond.
Search Google for 158 133 5000 D3js client html learning index
ERR_CONNECTION_TIMED_OUT`

Can you please tell what am I doing wrong?

A: my first guess would be that the firewall on your Ubuntu VM is blocking port 5000.
You should have a tool called "Uncomplicated Firewal (UFW)" installed on your ubuntu machine by default.
Running the following command should allow remote machines to connect to that port:
sudo ufw allow 5000

Once that command has been run, you can try again from your browser to see if you can access the page.


text:
Q: Does Keras add any delay/overhead compared to pure TensorFlow? I'm working on a project that requires object detection and recognition on images fed by a live camera.
For it to work well it should perform the evaluation for a single frame as quick as possible.
Going straight for TensorFlow instead of using Keras with TF backend will improve the performance of the whole model during the evaluation?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to sort by month, year in MySQL? I have column of month and year that data type is varbinary.
I tried:
SELECT * FROM traffic
WHERE '2015'<= year AND year <='2015'
    AND NOT (
       ( 2015= year AND month <05) OR
        ( 2015= year AND month >11)
    ) ORDER BY Year, month;

The output is:
month
10
11
5
6
7
8
9

but I want
month
5
6
7
8
9
10
11

What can I do to get the expected output?

A: You need to cast the month string into int
order by cast(month as unsigned)

A: Try this,
select * from traffic
WHERE '2015'<= year AND year <='2015'
    AND NOT (
       ( 2015= year AND month <05) OR
        ( 2015= year AND month >11)
    ) ORDER BY Year * 1,month * 1;

*1 will convert string data type into month integer.

A: My suggestion is to change the datatype of year and month to INT in table itself because it doesn't have any benefit when it's stored in VARCHAR, then run your own code and it will return expected result without making change
ALTER TABLE <tablename> MODIFY <columnname> INT UNSIGNED;


text:
Q: Trouble evaluating this integral $$\int_{-\infty}^\infty a{|x|}^ke^{-{|x|}^b}dx$$
where $a\in \mathbb{R}$  and $0<b<1$ and $k\in \mathbb{R}$
I am trying to work it towards a gamma function, but the absolute values are putting me off - any help?

A: Hint. One may write, by parity of the integrand,
$$
\int_{-\infty}^\infty a{|x|}^ke^{-{|x|}^b}dx=2a\int_{0}^\infty {x}^ke^{-{x}^b}dx=\frac{1}{b}\cdot \Gamma \left(\frac{k+1}{b}\right), \quad \tfrac{k+1}{b}>-1,
$$ where we have performed the change of variable $u=x^b$ to get an expression in terms of the Gamma function.


text:
Q: How can I count the number of 1's and 0's in the second dimension of a PyTorch Tensor? I have a tensor with size: torch.Size([64, 2941]), which is 64 batches of 2941 elements.
Across all 64 batches, I want to count the total number of 1s and 0s in the second dimension of the tensor, all the way to the 2941th so that I will have those counts as a tensor of size torch.Size([2941])
How do I do that?

A: You can sum them:
import torch
torch.manual_seed(2020)

# x is a fake data, it should be your tensor with 64x2941
x = (torch.rand((3,4)) > 0.5).to(torch.int32)
print(x)
# tensor([[0, 0, 1, 0],
#         [0, 0, 1, 1],
#         [0, 1, 1, 1]], dtype=torch.int32)

ones = (x == 1.).sum(dim=0)
print(ones)
# tensor([0, 1, 3, 2])

And if x is binary, you can have the number of zeros by a simple subtraction:
zeros = x.shape[1] - ones


text:
Q: SQLite Complex Query Help I have a very complex query going on in SQLite, and I need a bit of help understanding how to do it.
The following example is of my Database:
Category:

CatID | CatTitle
----------------
  1   | XYZ
  2   | Sample

Content:

ItemID | ItemCatID | ItemText | ItemText2 | ItemText3 | ItemText4
-----------------------------------------------------------------
  1    |     1     |   Test   |    Bla    |  Sample   |  MoreContent
  2    |     1     |   Test2  |  BlaBla   |  Sample2  |  Other Content
  3    |     2     |   Test3  |  BlaBla2  |  Sample3  |  Other Content2

Now, I basically want to do a query, on a search string.. (i.e. "%XYZ%" with the wildcards) and I want to search not only the CatTitle, but also ItemText, ItemText2 and ItemText3
The parameters I want to return though are: CatID, CatTitle, ItemID, and if possible, "ItemFilteredText" (which can be anything from ItemText to ItemText4, depending on which is the match)
Heres the thing, If the Query Matches CatTitle, then if it returns ItemID, it should be the FIRST ItemID and NOT the LAST ItemID
I have the following SQL somewhat working...
select DISTINCT Category.CatID,
       Category.CatTitle,
       Content.ItemID,
       Content.ItemText,
       Content.ItemText2,
       Content.ItemText3
from   Content,Category
where  Category.CatID =  Content.ItemCatID
       AND ( Category.CatTitle like'%XYZ%'
             OR Content.ItemText like '%XYZ%'
             OR Content.ItemText2 like '%XYZ%'
             OR Content.ItemText3 like '%XYZ%')
GROUP BY Category.CatTitle ORDER BY Category.CatID ASC

It returns the data... but Grouping By Category.CatTitle means that Content.ItemID would return 2, instead of 1
Any Ideas?

A: Assuming that you are using integers for content.ItemID and the first result is characterized by a lower ItemID modify the query to include min(Content.ItemID)
select DISTINCT Category.CatID, Category.CatTitle, min(Content.ItemID), Content.ItemText, Content.ItemText2, Content.ItemText3 from Content,Category where Category.CatID = Content.ItemCatID AND (Category.CatTitle like'%XYZ%' OR Content.ItemText like '%XYZ%' OR Content.ItemText2 like '%XYZ%' OR Content.ItemText3 like '%XYZ%') GROUP BY Category.CatTitle ORDER BY Category.CatID ASC

should do the work.


text:
Q: Saving dates in a matrix ("origin must be supplied") with r I am writing my bachelor thesis and I have not much experience with r so far.
My problem is that my dates which I made with this commands :
t<-strptime(x, "%d.%m.%Y %H.%M")

don't work anymore when I save them in a matrix with the other information on those specific dates.
I am a bit confused because it works just fine when I don't put them in a matrix like this    t[1:10]
But that happens as soon as I try to save them in a matrix
matrix1<-matrix(c(t,v2,v3,v4),nrow=length(v2))

Fehler in as.POSIXct.numeric(X[[i]], ...) : 'origin' muss angegeben werden

It's German but it means origin must be supplied.
Any ideas what I have to do to fix it? I am a bit frustrated :)

A: t (terrible name by the way, easily confused with the t function) is a POSIXlt object, which internally is a list. First you should check, what c(t,v2,v3,v4) returns (I don't know how v2 etc are defined).
Then we can look into the documentation in help("matrix"):

data
  an optional data vector (including a list or expression vector). Non-atomic classed R objects are coerced by as.vector and all attributes discarded.

The important bit is "all attributes discarded". This is what you get if you discard the attributes (which include the class attribute) of a POSIXlt object:
x <- strptime(c("2016-05-09 12:00:00", "2016-05-09 13:00:00"), format = "%Y-%m-%d %H:%M:%S")
attributes(x) <- NULL
print(x)
# [[1]]
# [1] 0 0
#
# [[2]]
# [1] 0 0
#
# [[3]]
# [1] 12 13
#
# [[4]]
# [1] 9 9
#
# [[5]]
# [1] 4 4
#
# [[6]]
# [1] 116 116
#
# [[7]]
# [1] 1 1
#
# [[8]]
# [1] 129 129
#
# [[9]]
# [1] 1 1
#
# [[10]]
# [1] "CEST" "CEST"
#
# [[11]]
# [1] NA NA

A matrix can't contain POSIXlt objects (or any objects, i.e., anything with an explicit class).

A: Roland is right. You can't have Posixlt objects in a matrix. What you can do is save those dates as numeric timestamps in the matrix and convert them back to dates while accessing
Converting to numeric timestamp:
>date<- as.numeric(as.POSIXct("2014-02-16 2:13:46 UTC",origin="01-01-1970"))
>date
[1] 1392545626

Then save those timestamps in a matrix as you do and to convert it back to date, use the above command again without converting it into a numeric.


text:
Q: Ruby Looping for a Dynamic System I am new here but my problem is hard to explain so I will make it as simple as possible. I have to make a program that searches PubMed. The query gets a bunch of ID numbers that link to articles and these articles have info attached to them like when they were created, who create them, keywords, etc. I have to sort them by year, that I can do. Then I have to sort the mesh_headings (keywords associated with the article) by year as well. These have to be counted though. So it will output something like :
Number of Results: 15
2015: 11
--->MH1: 13
--->MH2: 5
--->MH3: 12
2014: 3
--->MH1: 12
--->MH2: 3
ETC ETC ETC

I have no idea how to sort the mesh_headings by year. If there are any ideas I would love to hear them. When I try and do a loop like in the code below where it asks if the year created has an array it can be put into and if not it will make one and push it in. It gives me a tIDENTIFER error. Thanks in advance
for i in 0..date_array2.size
date_hash.each {|key, value| puts "#{key} = #{value}"}
if "#{created_year}_array" == true
    puts "#{created_year}_array".class
    "#{created_year}_array".push(mesh_headings)
else
    "#{created_year}_array" = Array.new(Array.new)
    "#{created_year}_array".push(mesh_headings)

end

end


text:
Q: Modal React-bootstrap now show from other component O have a compnent that is a modal.
import { Modal } from "react-bootstrap";

function ModalDelete(show) {

  return (

      <Modal show={show}>
        <Modal.Header>Hi</Modal.Header>
        <Modal.Body>asdfasdf</Modal.Body>
        <Modal.Footer>This is the footer</Modal.Footer>
        <Modal.Footer>
          <button >Delete</button>
          <button>Save</button>
        </Modal.Footer>
      </Modal>

  );

}

export default ModalDelete;

If i try to use inside other component, not works fine.
The screen goes to dark like the modal wants to show, but not appears.
If i copy the modal code inside the component where i want to show, the modal works.
I don't know what is happen.
The parent component:
function UploadImage({ input }) {
    const onDrop = useCallback((file) => {
      input.onChange(file);
      getImages()
        .then(imagesFolder => {
          console.log(imagesFolder);
          if(imagesFolder.includes(file[0].name)){
            console.log('tengo tu imagen');
          }else{
            console.log('NO TENGO LA IMAGEN,,,,');
            setImage(file);
          }
        })
        .catch (error => console.log(error));
    },[setImage]);

    const { getRootProps, getInputProps} = useDropzone({
      accept: "image/jpeg",
      noKeyboard: true,
      onDrop,
    });

    const [show, setShow] = useState(false);
    const handleRemoveClick = () => {
      setShow(true);
      console.log(show);

    };

    return (

        {image.length === 0 ? (

            <input {...getInputProps()} />

Click or Drag to Upload

        ) :(

            <Modal show={show} />
            {image[0].name}

        handleRemoveClick()}>

        )}

    );
  }

maybe i need to do more things, but i don't know it.
Thanks

A: A react function component receives its props in the first argument sent to the function as an object, so when you write:
<Modal show={show} />

The modal component should look like:
function ModalDelete(props) {

  return (

      <Modal show={props.show}>
        <Modal.Header>Hi</Modal.Header>
        <Modal.Body>asdfasdf</Modal.Body>
        <Modal.Footer>This is the footer</Modal.Footer>
        <Modal.Footer>
          <button >Delete</button>
          <button>Save</button>
        </Modal.Footer>
      </Modal>

  );
}

A: Update with response:
I have an error on my code, in my parent component i don't put the correct component.
Where is
return (

        {image.length === 0 ? (

            <input {...getInputProps()} />

Click or Drag to Upload

        ) :(

            <Modal show={show} />
            {image[0].name}

        handleRemoveClick()}>

        )}

    );

i have to put
<ModalDelete show={show} />

That is the component where inside is the modal react-bootstrap.
Now works


text:
Q: Evaluate an integral of a region
Let $R$ be the finite region in the positive quadrant bounded by the
hyperbolas $xy = 1$, $xy = 4$, $xy^2 = 1$ and $xy^2 = 5$.
Evaluate
$$\int_Rx^4y^7\, dx\,dy.$$

Would this become a standard double integral question, once the limits have been determined? How would I determine the limits?

A: Actually, a change of variables will be more convenient here.
Let $u=xy$, $v=xy^2$, then $1\leq u\leq 4$, $1\leq v\leq5$ and $x^4y^7=uv^3$. Since
$$\frac{\partial u}{\partial x}\frac{\partial v}{\partial y}-\frac{\partial u}{\partial y}\frac{\partial v}{\partial x}=2xy^2-xy^2=xy^2=v,$$
we can convert this integral into
$$\int_1^4\int_1^5uv^3\cdot\frac1v\,dv\,du.$$


text:
Q: mobile navigation bar using jquery i'm trying to design my first website, I've built my menu bar which has a couple of levels. everything works fine. now i want to make it mobile-friendly.
so i want to make the levels open up on click using jquery. i've managed to open to the first level but when i click on the second level i can't seem to open the third level...
here's the code:

jQuery(document).ready(function() {

      jQuery("#menu-trigger").click(function() {
        jQuery("ul#nav").slideToggle();
      });
      $(window).resize(function() {
        if ($(window).width() > 500) {
          $('ul#nav').removeAttr('style');
        }
      });
      $('ul#nav li').click(function() {
          if ($(window).width() <= 500) {
            $(this).find('ul').not('ul .submenu2').slideToggle();

          });

        $('ul#nav li ul .submenu').click(function() {
          $(this).find('ul .submenu2').slideToggle();
        });
      });
#menu-trigger {
  display: inline-block;
}
ul#nav li {
  float: none;
  border-bottom: solid 2px #d5dce4;
  position: relative;
}
ul#nav li:last-child {
  border-bottom: none;
}
ul#nav {
  display: none;
  position: absolute;
  top: 140px;
}
ul#nav a {
  width: 100%;
}
ul#nav ul.submenu {
  display: none;
  position: static;
}
ul#nav ul.submenu2 {
  display: none;
  position: static;
}
ul#nav li:hover .submenu {
  display: none;
}
ul#nav .submenu li:hover .submenu2 {
  display: none;
}
  menu

home

what is it?▼

about

objectives

implementation

5th grade▼

geography◂

work page

explenation

exemples

reflections

it's my first attempt at web design so i'm sorry for the bad code...
thanks in advance!

A: See your code for third level submenu2 is the class of ul element so remove the space between
Try :
$('ul#nav li ul .submenu').click(function(){
    $(this).find('ul.submenu2').slideToggle();
    });
});

See fiddle here: http://jsfiddle.net/sachinkk/nsujjoje/

jQuery(document).ready(function() {

jQuery("#menu-trigger").click(function(){
    jQuery("ul#nav").slideToggle();
});
$(window).resize(function(){
    if ($(window).width() > 500){
        $('ul#nav').removeAttr('style');
    }
});
$('ul#nav li').click(function(){
    if ($(window).width() <= 500){
    $(this).find('ul').not('ul .submenu2').slideToggle();
    }
});

$('ul#nav li ul .submenu').click(function(){
    $(this).find('ul.submenu2').slideToggle();
    });
});
#menu-trigger{
    display:inline-block;
}
ul#nav li {

    float:none;
    border-bottom: solid 2px #d5dce4;
    position:relative;
}
ul#nav li :last-child{
    border-bottom:none;
}
ul#nav {
    display:none;
    position:absolute;
    top:140px;
}
ul#nav a {
width: 100%;
}
ul#nav ul.submenu {
    display:none;
    position: static;
}
ul#nav ul.submenu2 {
display: none;
position: static;
}
ul#nav li:hover .submenu {
display: none;
}

ul#nav .submenu li:hover .submenu2 {
display: none;
}
 menu

home

what is it?▼

about

objectives

implementation

5th grade▼

geography◂

work page

explenation

exemples

reflections

JS executing only when your browser width less than 500px as per your login :)

A: You can use:
 $(this).children('.submenu').slideToggle();

In this way you don't have limit of level. Every sub-level have the same class .submenu
.children([selector ]) method allows us to search through the children of these elements in the DOM tree


text:
Q: Why do people ask IOI tech support for general Oasis questions in Ready Player One? In Ready Player One Wade manipulates his assumed identity in order to be arrested and placed in indentured servitude in IOI's tech support department. During his shift people ask him questions about Oasis items like swords. IOI is an ISP (Internet Service Provider) while the Oasis is a console. Nobody would call up Verizon or AT&T and ask them why their Xbox in-game-purchase wasn't working.
We also see earlier on in the book that Wade worked 40 hours a week for a GSS subcontracted tech support firm. What service was IOI therefore providing?

A: In this instance, a customer bought an item at auction and then wasn't able to use it. So there are two possibilities.

*

*IOI was the seller (they probably get a lot of surplus items with their army of sixers) so this customer was calling them direct because he couldn't use the item he bought from them.

*IOI is the auction house ( like eBay ). So the customer was calling IOI to try and get a refund or log a complaint. Just like you might do if you had a bad deal on eBay. And the customer doesn't have to be logical, "Jo schmo sold me an item I cant use, but I'll call IOI to complain because they allowed the deal to happen" kind of thing.
Jontia notes there is also the chance that as part of the ISP service, IOI may provide general technical support for the Oasis (since it seems to the only service anyone uses).

A:
"A large portion of IOI's business centered around providing access
  to the OASIS and on selling goods and services inside it."

*

*pg 33 - Kindle Edition

Yes they are an ISP but they are also selling in-game items- so it makes total sense that somebody may have a question about such items


text:
Q: Deriving an alternate form of the Cauchy Integral Formula There is a well known formula in complex analysis called the Cauchy Integral Formula:
$$f(z) = \frac{1}{2\pi i} \int_{C} \frac{f(p)}{p-z} \, dp$$
which holds for the circle of integration $C$ when $f$ is holomorphic in an open region containing the disk defined by $C$ and any $z$ strictly inside the disk outlined by $C$.
There is an alternate formula which I am trying to derive for the special case when $C$ is a circle of radius $R$ around the origin:
$$ f(z) = \frac{1}{2 \pi} \int_{0}^{2\pi} f(Re^{i \theta}) \mathbb{R}\left(\frac{Re^{i\theta} + z}{Re^{i\theta} - z}\right) \, d\theta$$ where the symbol $\mathbb{R}(\cdot)$ is meant to mean the real part of some complex number.
Additional Information:
Here is a hint from the text: note that if $w = \frac{R^{2}}{\overline{z}}$, then the integral of $\frac{f(p)}{p -w} $ around $C$ is $0$, which I'm pretty sure follows from holomorphicity of said integrand. However, this has not been much help to me.
What I've tried:
It is necessary and sufficient to show:
$$ f(z) + \frac{1}{2 \pi} \int_0^{2\pi} f(Re^{i \theta}) \mathbb{I}\left(\frac{Re^{i\theta} + z}{Re^{i\theta} - z}\right)i \, d\theta$$
$$ = \frac{1}{2 \pi} \int_{0}^{2\pi} f(Re^{i \theta}) \mathbb{R}\left(\frac{Re^{i\theta} + z}{Re^{i\theta} - z}\right) \, d\theta + \frac{1}{2 \pi} \int_0^{2\pi} f(Re^{i \theta}) \mathbb{I}\left(\frac{Re^{i\theta} + z}{Re^{i\theta} - z}\right)i \, d\theta$$
*Here I've only added the "imaginary" version of the formula to both sides. Now working with the right hand side:
$$
\begin{align}
& = \frac{1}{2 \pi} \int_0^{2\pi} f(Re^{i \theta})\frac{Re^{i\theta} + z}{Re^{i\theta} - z}d\theta \\[8pt]
& = \frac{1}{2 \pi} \int_0^{2\pi} f(Re^{i \theta})\frac{Re^{i\theta} + z}{Re^{i\theta} - z}d\theta \\[8pt]
& = \frac{1}{2 \pi} \int_0^{2\pi}\frac{f(Re^{i \theta})}{Re^{i\theta} - z}(Re^{i\theta} + z) \, d\theta \\[8pt]
& = \frac{1}{2 \pi} \int_0^{2\pi}\frac{f(Re^{i \theta})}{Re^{i\theta} - z}Re^{i\theta}d\theta + \frac{1}{2 \pi} \int_{0}^{2\pi}\frac{f(Re^{i \theta})}{Re^{i\theta} - z}z \, d\theta \\[8pt]
& = \frac{1}{2 \pi i} \int_0^{2\pi}\frac{f(Re^{i \theta})}{Re^{i\theta} - z}Rie^{i\theta}d\theta + \frac{1}{2 \pi} \int_{0}^{2\pi}\frac{f(Re^{i \theta})}{Re^{i\theta} - z}z \, d\theta \\[8pt]
& = \frac{1}{2\pi i} \int_C \frac{f(p)}{p-z}dp + \frac{1}{2 \pi} \int_0^{2\pi}\frac{f(Re^{i \theta})}{Re^{i\theta} - z}z \, d\theta \\[8pt]
& = f(z) + \frac{1}{2 \pi} \int_0^{2\pi}\frac{f(Re^{i \theta})}{Re^{i\theta} - z}z \, d\theta
\end{align}
$$
And canceling $f(z)$ from both sides yields:
$$ \int_0^{2\pi} f(Re^{i \theta}) \mathbb{I}\left(\frac{Re^{i\theta} + z}{Re^{i\theta} - z}\right) \, d\theta =\int_0^{2\pi}\frac{f(Re^{i \theta})}{Re^{i\theta} - z}z \, d\theta$$
But I don't know where to take it from here.

A: This is called the Poisson integral formula, by the way.
$$\dfrac{1}{2\pi}\int_0^{2 \pi} f(Re^{i\theta})\ \text{Re}\left(\frac{Re^{i\theta}+z}{Re^{i\theta}-z}\right)\ d\theta = \frac{1}{4\pi} \int_0^{2\pi} f(Re^{i\theta}) \left( \frac{Re^{i\theta}+z}{Re^{i\theta}-z} + \frac{Re^{-i\theta} + \overline{z}}{Re^{-i\theta}-\overline{z}}\right)\ d\theta $$
Break this up into four terms. Taking $\zeta = R e^{i\theta}$ on the circle,
$$\frac{1}{4\pi}\int_0^{2\pi} f(Re^{i\theta}) \frac{Re^{i\theta}}{Re^{i\theta} - z}\ d\theta = \frac{1}{4\pi i} \oint_C f(\zeta) \dfrac{d\zeta}{\zeta - z}  = \frac{f(z)}{2}$$
$$ \eqalign{\frac{1}{4\pi}\int_0^{2\pi} f(Re^{i\theta}) \frac{z}{Re^{i\theta} - z}\ d\theta &=
\frac{1}{4\pi i} \oint_C f(\zeta) \frac{z}{\zeta-z} \frac{d\zeta}{\zeta}\cr
&= \frac{1}{4\pi i} \oint_C \left( \frac{f(\zeta)}{\zeta - z} - \frac{f(\zeta)}{\zeta} \right) \ d\zeta = \frac{f(z)}{2} - \frac{f(0)}{2}\cr}$$
$$\eqalign{\frac{1}{4\pi}\int_0^{2\pi} f(Re^{i\theta}) \frac{Re^{-i\theta}}{Re^{-i\theta} - \overline{z}}\ d\theta &= \frac{1}{4 \pi i} \oint_C f(\zeta) \frac{R^2 \zeta^{-1}}{R^2 \zeta^{-1} - \overline{z}} \frac{d\zeta}{\zeta}\cr
&= \frac{1}{4\pi i} \oint_C \left( \frac{f(\zeta)}{\zeta} + \frac{\overline{z} f(\zeta)}{R^2 - \overline{z} \zeta}\right) d\zeta = \frac{f(0)}{2}
}$$
(note that if $\overline{z} \ne 0$, $|R^2/\overline{z}| > R$).  I'll let you do the last term.


text:
Q: Eclipse Web Indent to new line Trying to get indentation correct in html files.
Following this SO answer but hasn't resolved https://stackoverflow.com/a/18365664/461887
What I am getting

when I press enter

what I want is

    |


text:
Q: Speed performance for recursion and iteration – Why do they both run at the same speed for different "small" numbers? I'm trying to optimize code that I have. In order to do that, I wrote this code to see the effect of recursion vs. iteration. The code "counts" to 10-to-the-n'th power.
public Form1()
{
    InitializeComponent();
    Stopwatch sw = new Stopwatch();
    sw.Start();
    recurse(4);
    //iterate(4);
    sw.Stop();
    Text = sw.Elapsed.TotalMilliseconds.ToString();
}

void recurse(int i)
{
    if (i < 1) return;
    for (int x = 0; x < 10; x++) recurse(i - 1);
}

void iterate(int i)
{
    i = (int)System.Math.Pow(10, i);
    for (int x = 0; x < i; x++) ;
}

I'm getting this unexpected result: when n is 1 through 4 the speed is around 0.5 ms for both recursion and iteration. -Instead of 4 being 1000 times slower than 1 which is what I expected. Only for greater numbers does it start to have a more intuitive speed, the iteration also being faster than the recursion.
Why the same speed for 10 times as for 10,000 times?

A: Even if you do correct the code to calculate the same thing in both cases, do not test things like that in one run. You're not going to get a proper result unless the test itself takes at least a second. Run it one million times and then divide the total time. When you're testing something that's going to take only a millisecond or two, you should make sure the test takes long enough to ignore the differences of cold cache, times of .Start() and .Stop() calls, small GC delay in the meantime, etc. Also make sure the actual work takes more time than empty counting loop (that is for(many times) recurse(x) has high enough x that the for itself is not relevant)
Your result of 0.5ms in a single run is more or less meaningless here. Also if it's a jitted language, I'd recommend calling the same function before testing, to ensure it's already compiled - otherwise it's going to add overhead.
TL;DR - overhead of other things happening around your function is higher than the time your function takes to execute.

A: I think the problem is in your implementation of recurse.  Unless I am reading it incorrectly, recurse only runs 4 times and iterates 1 to 10 in each.  While iterate calculates 10^4 - 10,000 and then counts from 0 to 10,000.
So, you are not doing a fair comparison.
Revision:  If you are truly getting responses in the 0.5ms range, then you may have exceeded the accuracy of the functions involved.  This MS article http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx has an example with nanosecond timing that you might find helpful.  It is a bit more work, but might provide insight.


text:
Q: Backward compatibility when using iOS 4.0 libraries I'm looking to use UISwipeGestureRecognizer for implementing a tweetie like interface for my application. (Replacing the view of a tableview cell with a custom view on detecting a swipe) However, this API was added only in version 3.2+ of iOS. I need to support all the devices running OS versions 3.0+, so I'm not sure what to do in this scenario. It seems to be a terrible waste of effort to implement the swipe detection myself when Apple has already done it (not to mention the possibility of ending up with a lower quality output), but it looks like it's a fairly common scenario. How should I handle this?
Thanks in advance,
Teja.

A: You have quantified the problem quite accurately.
In short, you can't use it <3.2. Even if it existed as an undocumented API, Apple would reject the app for doing so.
I think you're "okay" with supporting >=3.2 as I believe the lion's share of people use that now - but I'm just speaking off the cuff.
We have these same issues when releasing apps under 4.0 - wanting to add stuff like Multitasking support - and cutting off 3.x users.
Apple should allow multiple app versions to support multiple OS versions - but - they don't!
Sorry for the bad news - but I'm in the middle of sorting out a similar issue right now, making a universal application for iPad (3.2) and iPhone (4.0) - and having to basically choose between multitasking or iPad support!


text:
Q: jQuery UI: Acceder a elementos de una lista sortable() Estoy empezando a trastear con jQuery UI para ordenar los elementos de una lista de canciones; veo que .sortable() actúa sobre la lista en sí, no sobre sus elementos, pero si quiero acceder exactamente al elemento que estoy clicando, ¿cómo lo puedo hacer?
La lista es la siguiente:

    <form class="cancion-lista row d-flex" method="post" action="<?=url_base?>recopilatorios/indice" data-id-cancion="<?=$id_cancion?>">

        <?=$orden?>

            <?=$titulo_cancion?>
             de
            <?=$nombre_autor?>
            (<button class="boton-enlace" role="link" name="recopilatorio" value="<?=$recopilatorio?>"><?=$ano?></button>)

            <span class="enlace-youtube" data-video="<?=$id_youtube?>">

        x

    </form>

    ...

El form se puede repetir entre 1 y 15 veces dentro de un bucle PHP.
Su aspecto, para, por ejemplo, seis elementos form es el siguiente (el título y subtítulo de la lista y los botones quedan fuera del div para evitar que se puedan ordenar):

Y, por ejemplo, este script:
$(function()
{
    $('.ordenar').sortable(
    {
        update: function()
        {
            var hijos = $(this).children();
            console.log(hijos);
        }
    });

    $('.ordenar').disableSelection();
});

Cuando terminas de arrastrar un elemento de la lista, un form, te imprime por pantalla un array con todos los form, porque this, claro, hace referencia al div con class="ordenar", pero ¿si quisiera que imprimiese el <?=$orden?> del form en concreto que acabo de manipular?

A: El segundo parámetro del evento contiene el elemento arrastrado, la nueva posición la obtienes con index().
    $('.ordenar').sortable(
    {
        update: function(event, ui)
        {
            console.log(ui.item.attr('data-id-cancion')+" en "+ui.item.index());
        }
    });


text:
Q: Special case: wrong order of updates for fly-away How can I track down the location of the "Special case: wrong order of updates for fly-away!" error?
This error message is defined in Datasnap.DSIntf as
const
  ...
  ERRCODE_FLYAWAY_WRONGORDER = 13;  { Special case: wrong order of updates for fly-away }
  ...
  DBERR_FLYAWAY_WRONGORDER  = ERRBASE_ALC + ERRCODE_FLYAWAY_WRONGORDER;

but nowhere else in the Delphi sources can I find references to substring FLYAWAY_WRONGORDER.*
My intention was to compile with debug dcu's, then put a breakpoint on the line where the exception is raised and check the call stack UP to find the cause.
I'm currently stepping DOWN into the code until the error occurs, but that is less efficient (complex app).
Placing a TApplicationEvents with a breakpoint in its OnException handler does not give me usable call stack information:

So, how can I (efficiently) track down the place where this error is generated?
Background on what is going on:

*

*Form uses DevExpress TcxScheduler connected to TcxSchedulerStorage component in datamodule, connected to nested TClientDataSets

*Code saves all changes to these datasets (ApplyUpdates)

*In BeginUpdate/EndUpdate for these DevExpress components, I then insert, delete and update records in these datasets, move around while doing so, even change parent IDs in detail datasets so that they drop from the current detail dataset 'in view'.The error occurs when I Edit, then Post a record doing exactly that.

*Delphi Tokyo 10.2.3, Win32 app

*Any other info on that error message is welcome, I was not able to find anything.

I actually 'fixed' the error by calling ApplyUpdates for the master dataset in a few places, but since I'm not really sure about the cause I want to investigate this further. So my question is not How do I fix the error in my code, it is How do I find the error in my code?
* There is a CheckForFlyAway routine in TCustomADODataSet.InternalPost in Data.Win.ADODB but we don't use ADO, I cannot set breakpoints in those routines.


text:
Q: Changing column label Python plotly? How to change column titles? First column title should say "4-Year" and 2nd column title "2-Year". I tried using label={} but kept getting an error.
df = pd.read_csv('college_data.csv')
    df1 = df[df.years > 2]
    df2 = df[df.years < 3]

    #CUNY College Table
    fig = go.Figure(data=[go.Table(
        header=dict(values=list(df1[['college_name', 'college_name']]),
                    fill_color='paleturquoise',
                    font_color='gray',
                    align='left',
                    height = 50,
                    font=dict(size=26),
                    ),
        cells=dict(values=[df1.college_name, df2.college_name],
                height = 50,
                fill_color='lavender',
                align='left',
                font=dict(size=20),
                ))
    ])
    fig.update_layout(title = "CUNY Colleges",
                        width = 900,
                        height = 1320,
                        font_family='Palanquin',
                        font=dict(size=30),
                        showlegend = False)

    st.plotly_chart(fig)

A: Change
values=list(df1[['college_name', 'college_name']]),

to
values=["4-year", "2-year"],

e.g.
fig = go.Figure(data=[go.Table(
        header=dict(values=["4-year", "2-year"],
        ...

Calling list on a pandas DataFrame returns a list of the column names of that dataframe, so list(df1[['college_name', 'college_name']]) is essentially identical to ['college_name', 'college_name'].


text:
Q: Update table using join - The multi-part identifier "Fileld" could not be bound I'm updating the fields using update query, which i gave the below code, when I'm update my query it shows the below error, & need the clear solution.

Error : The multi-part identifier "a.NOTYETTAKEN" could not be bound.

--DROP TABLE #Temp

CREATE TABLE #Temp
(NOTYETTAKEN Int,
WORKINPROGRESS Int,
COMPLETED Int,
UNDERTESTING Int,
NOTPOSSIBLE Int,
STATUSNAME Nvarchar(50),
DEPARTMENTNAME Nvarchar(50),
COUNTS Int)

INSERT INTO #Temp
SELECT 0,0,0,0,0,StatusName,DepartmentName,COUNT(*) AS 'COUNTS'
FROM Test..Task
GROUP BY  StatusName,DepartmentName

--DROP TABLE #Temps

CREATE TABLE #Temps
(NOTYETTAKEN Int,
WORKINPROGRESS Int,
COMPLETED Int,
UNDERTESTING Int,
NOTPOSSIBLE Int,
DEPARTMENTNAME Nvarchar(50),
COUNTS Int)

INSERT INTO #Temps(DEPARTMENTNAME)
SELECT DISTINCT DEPARTMENTNAME FROM Test..Task

SELECT * FROM #Temp
SELECT * FROM #Temps

UPDATE #Temps SET
a.NOTYETTAKEN=b.NOTYETTAKEN,
a.WORKINPROGRESS=b.WORKINPROGRESS,
a.COMPLETED=b.COMPLETED,
a.UNDERTESTING=b.UNDERTESTING,
a.NOTPOSSIBLE=b.NOTPOSSIBLE
FROM #Temps a
INNER JOIN #Temp b
ON a.DEPARTMENTNAME=b.DEPARTMENTNAME

A: A table alias specified in a FROM clause cannot be used as a qualifier in SET column_name so your update query is not valid one.
You should write like below by creating an alias in an update statement on SQL Query.
UPDATE a
SET    a.NOTYETTAKEN = b.NOTYETTAKEN
      ,a.WORKINPROGRESS = b.WORKINPROGRESS
      ,a.COMPLETED = b.COMPLETED
      ,a.UNDERTESTING = b.UNDERTESTING
      ,a.NOTPOSSIBLE = b.NOTPOSSIBLE
FROM   #Temps a
       INNER JOIN #Temp b
            ON  a.DEPARTMENTNAME = b.DEPARTMENTNAME

A: Try this.
  UPDATE a SET
        a.NOTYETTAKEN=b.NOTYETTAKEN,
        a.WORKINPROGRESS=b.WORKINPROGRESS,
        a.COMPLETED=b.COMPLETED,
        a.UNDERTESTING=b.UNDERTESTING,
        a.NOTPOSSIBLE=b.NOTPOSSIBLE
        FROM #Temps a
        INNER JOIN #Temp b

ON a.DEPARTMENTNAME=b.DEPARTMENTNAME


text:
Q: 'Invalid or incomplete multbyte or wide character' with 'column' I'm on a Linux system and I'm trying to use 'column' on a file that I've spiked with an extended character to use as the separator.  Reason being that any normal printing character is liable to show up where I don't want separation to occur, so by using 'sed' to find only those places where I do what the columns to separate, and adding an extended character at those places, then using that same extended character as the 'column' separator I should be OK.
Alas, trying to use hex character AE:
$ column -ts\xAE junk1
column: Invalid or incomplete multibyte or wide character

... or any other extended character doesn't work and I've tried every combination of quotes and other tricks I can think of.  But ts sounds like 'column' is open to using extended characters, so I just have to enter the thing properly.

A: If you want to print Unicode lower case æ, which is u00E6, you can use this:
$ printf '\u00E6\n'
æ

So, if your file looks like this:
$ printf 'foobarbaz\u00E6bar\u00E6baz bar something else whohooo!\n'
foobarbazæbaræbaz bar something else whohooo!

You could use column like so:
$ printf 'foobarbaz\u00E6bar\u00E6baz bar something else whohooo!\n' |
    column -ts$'\u00E6' -o "::::::::"
foobarbaz::::::::bar::::::::baz bar something else whohooo!

Note the ANSI escape format ($'characterCode'); see What does it mean to have a $"dollarsign-prefixed string" in a script? I used -o "::::::::" so you can easily see the columns.


text:
Q: How to apply custom zoom to UIImagePicker camera? I have an custom camera control having slider to apply zoom. I am able to zoom image with following code:
self.pickerReference.cameraViewTransform = CGAffineTransformScale(CGAffineTransformIdentity, zoom, zoom);

But when i get image in didFinishPickingMediaWithInfo I get original image for UIImagePickerControllerOriginalImage, not the zoomed one. And for UIImagePickerControllerEditedImage there is no image.
I have also tried:
currentImage = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
UIImageView *v = [[UIImageView alloc]initWithImage:currentImage];
UIGraphicsBeginImageContext(v.bounds.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextScaleCTM(context, zoom, zoom);
[v drawRect:pickerReference.view.bounds];
CGContextRestoreGState(context);
zoomedCurImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// Write image to PNG file
[UIImageJPEGRepresentation(zoomedCurImg, 0.4) writeToFile:imgPath atomically:YES];

This does apply zoom to original image but zoom is applied always at top left corner & not to where it is to be applied.
Please suggest solution. Thanks in advance.

A: I had a similar issue with a different piece of code and turning off auto layout fixed it for me.  Not sure if that applies here but it's worth a shot.


text:
Q: Display from Dropdown selection with post I found this solotion everywhere on the web but i cant figure it out why it won't work.
So i have this drop-down
<select name="gender">
  <option value="">Choose Gender</option>
  <option value="1" name="male">Male</option>
  <option value="2" name="female">Female</option>
</select>

Then i have the following php code
if (isset($_POST['gender']) === 1){
   echo 'Gender: Male
 ';
}else if (isset($_POST['gender']) === 2){
   echo 'Gender: Female
 ';
}else{
   echo 'Gender: Not Set
 ';
}

And all i get from the output is

Gender: Not Set

Sooo what am i missing here?
p.s im a newbie. Be gentle.

A: For starters, isset() returns a bool, not the value being tested.  (Note the semantics of "is set", which is a yes/no concept.)  Additionally, === also compares types and I suspect all posted values are strings by default.  Remove the isset() calls and use a less-strict comparison:
if ($_POST['gender'] == 1){
    echo 'Gender: Male
 ';
}else if ($_POST['gender'] == 2){
   echo 'Gender: Female
 ';
}else{
   echo 'Gender: Not Set
 ';
}

If you do want to use isset() to check the existence of the value at all before examining the value, you can wrap the whole thing in that condition:
if (isset($_POST['gender'])){
    if ($_POST['gender'] == 1){
        echo 'Gender: Male
 ';
    }else if ($_POST['gender'] == 2){
       echo 'Gender: Female
 ';
    }else{
       echo 'Gender: Not Set
 ';
    }
}


text:
Q: Переименование нового файла на имя старого и удаление старого файла У меня есть 2 файла. Нужно переименовать новый файл на имя старого и удалить старый файл.
Пробовал делать так:
boolean successful = tempFile.renameTo(inputFile);

Не получилось.

A: Естественно не получится! И Java тут не причем. Вы пытаетесь задать 2 файла с одинаковым именем в одной папке, операционная система вам этого не позволит.
Нужно скопировать имя старого файла, удалить его и уже тогда переименовывать новый.

A: Получилось таким образом (нужно еще добавить проверку на ошибки):
inputFile.delete();
boolean successful = tempFile.renameTo(inputFile);


text:
Q: For a newly created file, is there any difference between write() and append() methods? For a newly created file, is there any difference between write() and append() methods, in Python?

A: The write method overwrites the content in a text file while the append method appends text to the file.
If there is nothing in the file however, then write is the same as append (they both write new text into the file).

A: When you open a file in append mode, the seek pointer points to the end of the file (the pointer position will be non-zero if the file is not empty).
On new (empty) files, the end is equal to the beginning. So appending is the same as overwriting.


text:
Q: Magnetic field lines of a toroid magnet I am not sure what are the magnetic field lines of a torroid magnet like this one:

In particular, at the center of the magnet, is the field null or is it maximal?


text:
Q: Создать один экземпляр и экспортировать его много раз Занимаюсь сейчас разработкой бекенд-приложения, api. У меня есть ORM Sequelize и, соответственно, модели для представления разных таблиц. Создание модели выглядит примерно так:
const { Sequelize, DataTypes, Model } = require('sequelize');

class User extends Model {}

User.init({
  // Model attributes are defined here
  firstName: {
    type: DataTypes.STRING,
    allowNull: false
  },
  lastName: {
    type: DataTypes.STRING
    // allowNull defaults to true
  }
}, {
  // Other model options go here
  sequelize, // We need to pass the connection instance
  modelName: 'User' // We need to choose the model name
});

Ситуация в том, что эту модель мне надо экспортировать в разных сервисах. И при том я явно не могу написать module.exports = User, потому что в таком случае я буду много раз создавать одну и ту же модель. А это, вроде как, не есть желательное поведение.
Как я могу создать объект единожды, а потом экспортировать его экземпляр много раз?

A: Инициализация происходит один раз, потом уже всё кэшируется NodeJs и отдается просто ссылка. Можете проверить добавив вывод console.log('User model created') после вызова User.init


text:
Q: MySQL - Which way is better to check if a column is null or empty Well, when we are going to select records which include nothing in a column, we can use this:
SELECT * FROM my_table WHERE NULLIF(my_column, '') IS NULL;

But, in most cases, I see developers use this:
SELECT * FROM my_table WHERE my_column IS NULL OR my_column = ''

Is there any preference between these two? (e.g. performance, default support, version support, etc.)
If yes, please explain.

A: Evaluating the two expressions on a single row should not take such a big difference. The reason people use the second version is the use of indexes. Mysql has a special optimization for this and can use it even with the or.
See IS NULL Optimization

IS NULL Optimization
MySQL can perform the same optimization on col_name IS NULL that it can use for col_name = constant_value. For example, MySQL can use indexes and ranges to search for NULL with IS NULL.
If a WHERE clause includes a col_name IS NULL condition for a column that is declared as NOT NULL, that expression is optimized away. This optimization does not occur in cases when the column might produce NULL anyway; for example, if it comes from a table on the right side of a LEFT JOIN.
MySQL can also optimize the combination col_name = expr OR col_name IS NULL, a form that is common in resolved subqueries. EXPLAIN shows ref_or_null when this optimization is used.

A: As per my knowledge best way with respect to execution time or performance is :
SELECT * FROM my_table WHERE my_column = ''

Reference : How do I check if a column is empty or null in mysql

A: Calling a function on a field (in a condition) automatically discards any potential indexes on that field that could be used to speed up the query. Using OR in a list of conditions generally does the same (but for all indexes).
However, with the former, you end up making a function call for every row; with the latter there is the possibility to take advantage of short circuit evaluation.
Of course, there is a third option which can make use of indexes...
SELECT * FROM my_table WHERE my_column IS NULL
UNION
SELECT * FROM my_table WHERE my_column = ''

but then the cost of the UNION/two queries may outweigh the benefit of index use; depending on actual data.

A: The two constructs are not the same.  From the MySQL documentation page:
NULLIF(expr1,expr2)

Returns NULL if expr1 = expr2 is true, otherwise returns expr1.
This is the same as:
  CASE WHEN expr1 = expr2
  THEN NULL
  ELSE expr1
  END.

Therefore, this logic is testing a column for "NULL or an empty string."

*

*If my_column is presently NULL, the function will return its value (NULL ...) because it is not equal to an empty-string.

*If my_column is an empty string, the function will return NULL.

*If any other value, that value will be returned.

I heartily agree with Naveed's answer in saying, "this is 'cute' ... don't be 'cute'." His answer ("use OR ...") results in very simple SQL that is instantly obvious at first glance.  This "clever" solution is not. (And it is probably slightly-less efficient, to boot.)
And, of course, you'd really like to avoid the necessity for this sort of thing when designing your database. You never want to store "empty strings" in a VARCHAR-type field unless it truly is the case that "we have a non-NULL value, and that value really is 'an empty string.'"

A: Generally, the reason why people will include the ='' portion is because SQL Server stores that as an empty string, which is not the same as NULL.
Link to reference:
openshac's answer


text:
Q: Why is RNG different for TensorFlow 2 and 1? import numpy as np
np.random.seed(1)
import random
random.seed(2)
import tensorflow as tf
tf.compat.v1.set_random_seed(3)  # graph-level seed
if tf.__version__[0] == '2':
    tf.random.set_seed(4)  # global seed
else:
    tf.set_random_seed(4)  # global seed

from tensorflow.keras.initializers import glorot_uniform as GlorotUniform
from tensorflow.keras import backend as K

init = GlorotUniform(seed=5)(shape=(4, 4))
print(K.eval(init))

[[-0.75889236  0.5744677   0.82025963 -0.26889956]
 [ 0.0180248  -0.24747121 -0.0666492   0.23440498]
 [ 0.61886185  0.05548459  0.39713246  0.126324  ]
 [ 0.6639387  -0.58397514  0.39671892  0.67872125]]  # TF 2

[[ 0.2515846  -0.41902617 -0.7859829   0.41573995]
 [ 0.8099498  -0.6861247  -0.46198446 -0.7579694 ]
 [ 0.29976922  0.0310365   0.5031274   0.314076  ]
 [-0.62062943 -0.01889879  0.7725797  -0.65635633]]  # TF 1

Why the difference? This is creating severe reproducibility problems between the two versions - and this or something else, within the same version's (TF2) Graph vs. Eager. More importantly, can TF1's RNG sequence be used in TF2?

A: With enough digging - yes. TL;DR:

*

*TF2 behavior in TF1: from tensorflow.python.keras.initializers import GlorotUniformV2 as GlorotUniform

*TF1 behavior in TF2: from tensorflow.python.keras.initializers import GlorotUniform
TF2 essentially executes the first bullet under the hood; GlorotUniform is actually GlorotUniformV2.

Some details:
Found docs - but code itself terminates at some pywrapped compiled code (TF1 -- TF2 -- for some reason Github refuses to show gen_stateless_random_ops for TF2 and gen_random_ops for TF1, but you can find both in the local install):

tensorflow.python.ops.gen_random_ops.truncated_normal Outputs random values from a truncated normal distribution.
The generated values follow a normal distribution with mean 0 and
  standard   deviation 1, except that values whose magnitude is more
  than 2 standard   deviations from the mean are dropped and re-picked.

tensorflow.python.ops.gen_stateless_random_ops.truncated_normal Outputs deterministic pseudorandom values from a truncated normal distribution.
The generated values follow a normal distribution with mean 0 and
  standard   deviation 1, except that values whose magnitude is more
  than 2 standard   deviations from the mean are dropped and re-picked.
The outputs are a deterministic function of shape and seed.

The first and second are ultimately where GlorotUniform and GlorotUniformV2 route to, respectively. TF2's from tensorflow.keras.initializers imports from init_ops_v2 (i.e. V2), whereas TF1's from init_ops.


text:
Q: Prove that, if a sequence is nested from above and has empty intersection, the probability of its terms tends to zero
Let $(A_n)_{n\geq 1}$ be a sequence in a probability space. Show that $P(A_n)\to 0$ as $n\to \infty$ if $A_{n+1}\subset A_{n}$ for all $n>1$ and $\bigcap_{n=1}^{\infty} A_n = \emptyset.$

Here's my attempt. I'm having difficulty formalising the last step.
First of all:
\begin{align*} 0 &= P(\emptyset)\\
&= P(\bigcap_{i=1}^{\infty}A_i)\\
&= 1-P(\bigcup_{i=1}^{\infty}A_i^{\complement}).
\end{align*}
Then, define
$B_1:= A_1^{\complement}$
$B_2:= A_1\backslash A_2$
...
$B_n:= A_{n}\backslash A_{n+1}$
The $B_n$'s are all disjoint, and so, from $\sigma$-additivity,
\begin{align*} P(\bigcup_{i=1}^{\infty}A_i^{\complement}) &= P(\bigcup_{i=1}^{\infty}B_i) = \sum_{i=1}^{\infty}P(B_i).
\end{align*}
From above, this sum converges to $1$. Hence, its terms converge to $0$, that is to say, $P(B_n)\to 0$ as $n\to\infty$. Intuitively, this should show that $P(A_n)\to 0$ as well. But why should it?

A: $B_i:=X\setminus A_i$ where $X$ is the whole space. Then
$$\bigcup_iB_i=\bigcup_i(X\setminus A_i)=X\setminus\Big(\bigcap_i A_i\Big)$$
by de Morgan's laws. If $\bigcap_i A_i=\emptyset$ then $\bigcup_iB_i=X$. Therefore
$$\Pr\Big(\bigcap_i A_i\Big)=1-\Pr\Big(X\setminus\bigcap_i A_i\Big)=1-\Pr(\bigcup_iB_i\Big)=1-\Pr(X)=1-1=0$$
Since $(A_n)\subset X$ are nested in a decreasing order then for every $n$ we have $$A_n=\bigcap_{1\leqslant i\leqslant n}A_i\Rightarrow A:=\lim_nA_n=\bigcap_{i\in\mathbb{N}}A_i$$
On the other hand $A_{n+1}\subset A_n$ for every $n$ implies $\Pr(A_{n+1})\leqslant\Pr(A_n)$. Also for all $n$ we have $0\leqslant\Pr(A_n)\leqslant \Pr(X)=1$ hence we have a sequence $(\Pr(A_n))$ of real numbers which is bounded and monotonic decreasing. By Bolzano-Weierstrass this sequence converges. Therefore
$$\lim_n\Pr(A_n)=\Pr(\lim_nA_n)=\Pr(A)=\Pr\Big(\bigcap_i A_i\Big)=0$$
where we have used the right continuity of $\Pr(\cdot)$.

A: A measure $\mu:\Omega\rightarrow\mathbb{R}$ has the decreasing continuity property:
If $A_{n+1}\subset A_n$ and  $\mu(\Omega)<\infty \implies \lim_{n\rightarrow \infty}\mu(A_n)=\mu(\cap_{n\in\mathbb{N}}A_n)$.
In particular, a probability measure is finite, so in your case, as  $A_{n+1}\subset A_n$ and $\cap_{n\in\mathbb{N}}A_n=\emptyset$,  by decreasing continuity, we have
$$\lim_{n\rightarrow \infty}\mathbb{P}(A_n)=\mathbb{P}(\cap_{n\in\mathbb{N}A_n})=\mathbb{P}(\emptyset)=0$$


text:
Q: variable in source code - python programming Currently I am having a problem to avoid "don't repeat yourself".
This is my code - I want to rephase to be exact my situation now:
if foo == 1:
   for node in content.findAll('a'):
       link = node.get('href')
elif foo == 2:
   for node in content.findAll('li'):
       link = node.li.get('title')

is there any way I can do it like this: (I know in PHP I can do similar)
if foo == 1:
   char = 'a'
   bar = "node.get('href')"
elif foo == 2:
   char = 'li'
   bar = "node.li.get('title')"

for node in content.findAll(char):
   link = bar

A: Just create a function:
def findAll(content, char, get_code):
    for node in content.findAll(char):
        link = node.li.get(get_code)
    return link

Then,
if foo == 1:
    link = findAll(content, 'a', 'href')
elif foo == 2:
    link = findAll(content, 'a', 'title')

A: This might work for you:
def find_link(content, entity, attribute, path=()):
    for node in content.findAll(entity):
        for part in path:
            node = getattr(node, part)
    return node.get(attribute)

This works for a flat:
# get attribute 'href' from 'a'
find_link(content, 'a', 'href')

and a nested search:
# get attribute 'attr' from div.ul.li
find_link(content, 'div', 'attr', path=['ul', 'li'])

The above tries to mimic your logic. As this finds only the last link,
this version might be better:
def find_link(content, entity, attribute, path=()):
    links = []
    for node in content.findAll(entity):
        for part in path:
            node = getattr(node, part)
        links.append(node.get(attribute))
    return links

It gives you all links.
Finding only th first link could look like this:
def find_link(content, entity, attribute, path=()):
    for node in content.findAll(entity):
        for part in path:
            node = getattr(node, part)
        return node.get(attribute)
enter code here


text:
Q: Wordpress plugin Data, Pull Last Element global $wpdp;
            $dp = $wpdp->prefix."test-enes";
            $result = $wpdb->get_results("SELECT `ingredients` FROM $dp WHERE id = (select max(id) from $dp)");
            print_r ($result);

Output is: Array ( )

And I used this code:
            global $wpdp;
            $dp = $wpdp->prefix."test-enes";
            $result = $wpdb->get_results("SELECT * FROM `test-enes`");
            print_r ($result);
Output is:Array ( [0] => stdClass Object ( [key] => 1 [ingredients] => ) [1] => stdClass Object ( [key] => 2 [ingredients] => ) [2] => stdClass Object ( [key] => 3 [ingredients] => enes ) [3] => stdClass Object ( [key] => 4 [ingredients] => enes ) [4] => stdClass Object ( [key] => 5 [ingredients] => reer ) )

How can I pull the last element of the ingredients row.([ingredients] => reer) Thanks

A: $sql = "SELECT * FROM ".$wpdp->prefix."test-enes ORDER BY id DESC";

Note: the id could be primary key of the table, you can put relevant primary key name


text:
Q: about 'zsh react-native command not found' AFTER SETTING PATH Some time ago, I had the command not found error when running expo, so I set path at ~/.bash_profile and so, after running source ~/.bash_profile, now I can call expo without problems.
Today, I tried running react-native link and the following error appeared:
zsh: react-native command not found
What else could I be doing wrong?

A: Maybe you don't have react native cli installed globally, which is good as it's not needed.
Check in the project directory if react-native is installed
so ./node_modules/react-native/ should exist and has something inside.
If so, you don't need to run react-native directly; try running through npx react-native or npm script.
If not, make sure you have react-native in package.json dependencies section, and run npm install to pull the react-native library folder.


text:
Q: How to redirect website users to a new IP? I found this answer to my question but if the DNS cache for existing.mydomain.com is the problem, wouldn't that solution just result in a infinite circular loop? Or does a DNS lookup for newsub.mydomain.com force a DNS refresh for all subdomains of mydomain.com?

A: newsub.mydomain.com points to the new server.
existing.mydomain.com points to the new server for users who have checked recently, and the old server for those who have not.
The old server redirects to newsub.mydomain.com with a 301 "permanently moved".
There is no loop.
However, you still have to keep the old server running until the DNS TTL for existing.mydomain.com expires.  If you don't, some users might hit the old IP and think your site is down.


text:
Q: When the user opens the app, is it possible to tell what their language is? I have a part of the app which is interactive and can only be used by English speakers. Is there a way to detect the user's language setting as they land on a page, so that I can dynamically hide some features which I only want to show to English speakers?

A: You can check a device language using following code:
java.util.Locale.getDefault().getDisplayLanguage();

A: You can use Locale.getDefault()to get their current preferred locale.  From there, you can use getLanguage to look for the en language code, and getVariant if you are interesting in only US or other variants.

A: You could also consider localising your resources, instead of doing everything programmatically.


text:
Q: activeadmin with Ruby 1.8.7 Working on a legacy server with Ruby 1.8.7 installed, I'd like to use Activeadmin in my Rails 3.0.20 app.
Can anyone tell me what is the last version of Activeadmin that is compatible with Ruby 1.8.7 ?

A: ActiveAdmin was actively tested against REE (which is a variant of Ruby 1.8.7) until v0.5.1. There seems to be a consent of the authors to keep supporting 1.8.7 until explicit notice though (as documented in #1967).


text:
Q: cURL сессия, и передача токена в заголовках собственно что именно делаю, есть страница, с которой нужно получить некоторую информацию, все бы было хорошо, но часть контента подгружается отдельно, и насколько понял с использованием токенна безопасности и сохранением сессии куков.
Бьюсь уже второй день никак не могу получить нужную информацию. Сначала получаю основную страницу, получаю из нее нужный мне ИД и токкен, сохраняю куки, формирую заголовки, и пробую делать запрос к второй странице, которая должна отдать массив в формате джосон, но в итоге получаю ответ 404....
уже наверное все перепробовал, может делаю что-то не так? может кто-то сталкивался с подобной проблемой?
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://marathons.ahotu.com/event/casa-grande-half-marathon-5k');
//первая страница
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/32.0.1700.107 Chrome/32.0.1700.107 Safari/537.36');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt ($ch, CURLOPT_COOKIEJAR, 'COOKI.txt');
curl_setopt ($ch, CURLOPT_COOKIEFILE, 'COOKI.txt');
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch);
}

preg_match('/<meta name="csrf-token" content="(.*?)" \/>/is', $answer, $token); //получаю токен
preg_match('/<add-event-info id="(.*?)" locale="en"/is', $answer, $id); //получаю id

curl_setopt($ch, CURLOPT_URL, 'https://marathons.ahotu.com/media?a_event_id='.$id['1']);
curl_setopt($ch, CURLOPT_POST, false);

//Формирую заголовки

$headers[] = 'X-CSRF-Token:'.$token['1'];
$headers[] = 'Accept: application/json, text/plain, */*';
$headers[] = 'X-Requested-With: XMLHttpRequest';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

curl_setopt($ch, CURLOPT_REFERER,'https://marathons.ahotu.com/event/casa-grande-half-marathon-5k');
curl_setopt($ch, CURLOPT_POSTFIELDS, "");
$answer = curl_exec($ch);
if (curl_error($ch)) {
    echo curl_error($ch);
}
echo $answer;

A: Разве эта страница существует? Её же в принципе нету, попробуйте зайти на неё через браузер.
Хотя, возможно, сервер говорит, что якобы этой страницы нет из-за неверного токена и/или куки.
И ещё: пробовали делать отдельный объект curl для каждого запроса?


text:
Q: React component disappears after one use My UpdateCard component disappears after one use.
The component allows users to edit  a card.
The UpdateCard component shows when the current user is the same as the user that created the card.
I'm propping over the id for the card from another component for the current user and the card id.
After a user successfully edits the card with new information, they press submit, and the card is updated.
After the update occurs, if a user wants to make an edit again, they can't, because the Update CardComponent has disappeared.
I think this is something specific with react that I'm missing.
import React from "react"
import PropTypes from "prop-types"
import { Accordion, Icon, Input, Form, Button, Modal, Dropdown } from 'semantic-ui-react'

//components
import UpdateCard from "./UpdateCard"
import LikeUnlike from "./LikeUnlike"

class Card extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      activeIndex: null,
      search: '',
      currentUser: this.props.currentUser.id
    }
  }
    updateSearch = (event) => {
      this.setState({search: event.target.value.substr(0, 20)})
    }

    //Opens and closes the accordion
    handleClick = (e, titleProps) => {
      const { index } = titleProps
      const { activeIndex } = this.state
      const newIndex = activeIndex === index ? -1 : index
      this.setState({ activeIndex: newIndex })
    }

    render () {

    const { activeIndex } = this.state
    const { showEditMenu } = this

    let filteredCards = this.props.librarys.filter(
        (library) => {
          return library.title.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1 || library.desc.toLowerCase().indexOf(this.state.search.toLowerCase()) !== -1
        }
      )

    return (
      <React.Fragment>

          <Input fluid icon={<Icon name='search' inverted circular link />} value={this.state.search} onChange={this.updateSearch} placeholder="Search Syntaxes" />

            {filteredCards.map((librarys, index)=>{
              return(

                  <Accordion>
                    <Accordion.Title >
                      <Icon
                        name='dropdown'
                        active={activeIndex === index}
                        index={index}
                        onClick={this.handleClick}
                      />

                        <Icon name='trash alternate'
                            onClick={() => {
                                this.props.handleDelete(librarys.id)}}
                        />

                      {
                      //Update Icon
                        librarys.user && librarys.user.id === this.props.currentUser.id ?
                          <UpdateCard
                            handleUpdate={this.props.handleUpdate}
                            libraryId={librarys.id}
                            likes={librarys.likes}
                            librarys={librarys}
                          />
                        : ''
                      }

                        Title: {librarys.title} Likes: {librarys.likes}
                      <LikeUnlike
                        handleUpdate={this.props.handleUpdate}
                        libraryId={librarys.id}
                        librarys={librarys}
                      />
                    </Accordion.Title>
                    <Accordion.Content active={activeIndex === index}>
                        Description:

                        {librarys.desc}

                        Markdown:

                        {librarys.markdown}
                    </Accordion.Content>
                  </Accordion>

              )
            })}

      </React.Fragment>
    );
  }
}

export default Card

A: Happens to me as well, when I use setstate from click function, components tab blanks out and all tree of react components is gone.
onShowClick = e => {
  this.setState({
      showInfo: false
  });
 }


text:
Q: React native doesn't start metro bundler on chrome after i try to run npm start on terminal metro bundler
I'm trying to run an app published by other programmer but it doesn't run metro bundler on google chrome when I type npm start on terminal.
On the other hand, I created a project and run it and it works
my project

A: You need to install the dependencies of the other developer's project by running 'npm install' before starting metro bundler.

A: Open new terminal and run below command, It will bring up expo dev client.
expo start --dev-client

Sometimes it might throw an error as below.

Missing package "metro/src/lib/attachWebsocketServer" in the project. This usually means react-native is not installed. Please verify that dependencies in package.json include "react-native" and run yarn or npm install.

To fixing this issue, run the command
npm install -g expo-cli
npm install expo-dev-client
expo start --dev-client


text:
Q: How to create a flag with getopts to run a command I need help with my getopts, i want to be able to run this command ( mount command) only if i pass a flag ( -d  in this case).
below output is what i have on my script but it doesn't seem to work.

CHECKMOUNT=" "

while getopts ":d" opt
do
  case "$opt" in

  d) CHECKMOUNT="true" ;;

      usage >&2
      exit 1;;
    esac
   done
  shift `expr $OPTIND-1`

FS_TO_CHECK="/dev"

if [ "$CHECKMOUNT" = "true" ]
then
  if cat /proc/mounts | grep $FS_TO_CHECK > /dev/null; then
   # Filesystem is mounted
else
   # Filesystem is not mounted
  fi
fi

A: Your script has a number of problems.
Here is the minimal list of fixes to get it working:

*

*While is not a bash control statement, it's while. Case is important.

*Whitespace is important: if ["$CHECKMOUNT"= "true"] doesn't work and should cause error messages. You need spaces around the brackets and around the =, like so: if [ "$CHECKMOUNT" = "true" ].

*Your usage of getopts is incorrect, I'm guessing that you mistyped this copying an example: While getopts :d: opt should be: while getopts ":d" opt.

*Your usage of shift is incorrect. This should cause error messages. Change this to: shift $((OPTIND-1)) if you need to shift OPTIND.

*The bare text unknocn flag seems like a comment, precede it with #, otherwise you'll get an error when using an unknown option.

*There is no usage function. Define one, or change usage in your \?) case to an echo with usage instructions.

Finally, if your script only requires a single optional argument, you might also simply process it yourself instead of using getopt - the first argument to your script is stored in the special variable $1:
if [ "$1" = "-d" ]; then
    CHECKMOUNT="true"
elif [ "$1" != "" ]; then
    usage >&2
    exit 1
fi


text:
Q: accordion toggle is not working with api response in angular 7 I'm using angular 7 and accordion is working fine with static data (means create an object in ngOnInit())
After load getting, a response from API accordion is not working
Note: Both static and response data are identical (same object)
//this is code to toggle manually
 const accordions = document.querySelectorAll('[data-toggle="dds__collapse"]');
    accordions.forEach( accordion => {
      new Collapse(accordion, {});
    });

In this first time, it takes a double click on accordion then it works normally.


text:
Q: how many empty sets are there? Would I be correct in saying that in the category of sets, the "class of sets that are isomorphic to the empty set is a proper class"?
In other words, there are LOTS of initial objects in the category of sets, but they're all related to each other via unique isomorphisms?
Similarly, for any category $C$, if $X$ is an object of $C$, then the full subcategory of objects isomorphic to $X$ is a proper class (ie, there are LOTS of them)?
EDIT: Let me elaborate a bit. I'm not entirely sure if I should be considering ZFC or ETCS, etc. I'm asking this question from the point of view of algebraic geometry and its use of category theory. I mean, I know people say that the class of say, all elliptic curves over $\mathbb{C}$ is a proper class, but the class of $\mathbb{C}$-isomorphism classes of elliptic curves is a set. That would seem to imply that every isomorphism class is a proper class, and hence this would seem to say that the isomorphism class (ie, bijection class) of the empty set in the category of sets should also be a proper class, right?
Lana's answer with the extensionality axiom seems to make sense, in that there is only ONE empty set, so that the isomorphism class of the empty set is a singleton set. On the other hand, the isomorphism class of a set with 1 element should be a proper class right?
Generalizing a bit, would it be true that the isomorphism class of any initial (or terminal) object of a category be a singleton set? It seems to me that the isomorphism class of, say $\text{Spec }\mathbb{Z}$ in the category of schemes is a proper class, simply because there are many different presentations of rings isomorphic to $\mathbb{Z}$?

*

*will

A: By extensionality axiom you get that there exists exactly one empty set, and that's all folks!

A: Your conclusion is not entirely correct. While it's perfectly fine to have a context where a category has many initial objects which are isomorphic (but not equal), there is a delicate point to the inaccurate statement:

the class of say, all elliptic curves over $\mathbb{C}$ is a proper class, but the class of $\mathbb{C}$-isomorphism classes of elliptic curves is a set. That would seem to imply that every isomorphism class is a proper class

The fact that there is a proper class of different structure is quite trivial to show, because we can always change one element with another and get a proper class of different, but isomorphic, structures that way.
To say that there is only set-many isomorphism classes is also inaccurate, because the isomorphism classes are proper classes, there is no collection of the form $\{A\mid A\text{ is an isomorphism class of ...}\}$. Only sets can be members of other sets. But it does mean something else, it means that there is a set of pairwise non-isomorphic structures that any other structure is isomorphic to one of them. That is, there is a class of representatives which is a set.
Lastly, it does not mean that every equivalence class is a proper class, just that at least one of the equivalence classes are.
The simplest example of this is equinumerousity (in $\sf ZFC$). There is a proper class of sets of every cardinality, except for the class of sets of cardinality zero. There is only one of those.
If your foundational theory is $\sf ZFC$ or some related theory then there exists only one empty set. If your foundational theory is some category based theory which allows many empty sets, but requires them to be isomorphic, then this is a different case altogether.

A: Let $A$ and $B$ be empty sets, then by logic (namely when if-statements are true) $A \subset B$ and $B\subset A$, so $A = B$ (since $A\subset B$ iff $x\in A\implies x\in B$, but x is not in A, so it is vacuously true, same for $B\subset A$). So there is only one initial object in $\textbf{Set}$ up to equality, not just isomorphism.
Edit: "On the other hand, the isomorphism class of a set with 1 element should be a proper class right?" Yes because the class of sets is a proper class and you can take all of the sets of the form $\{A\}$ where A is a set.
"Generalizing a bit, would it be true that the isomorphism class of any initial (or terminal) object of a category be a singleton set?" No because the objects in a general category need not be just sets.


text:
Q: Disable spacebar in iOS keyboard In my app, I have a text field that accepts a limited number of characters and so don't want the user to be able to add a space between characters if/when they press the spacebar. Instead I would like the spacebar to be unresponsive or do another function like capitalise instead of adding a space.
Is there a way to do this?

A: In Swift
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if string == " " {
        return false
    } else {
        return true
    }
}

A: Use below delegate method of UITextField and disallow the space key. This is in Objective-C.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ( [string isEqualToString:@" "] ){
        return NO;
    }
    else {
        return YES;
    }
}

A: Please go with below Code to identify spacebar.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ( [string isEqualToString:@" "] && range.length==0)
    {
        return NO;
    }
    else
    {
        return YES;
    }
}


text:
Q: Ответ на пост-запрос Есть сервер, который должен отвечать на Post-запрос от API. Сервер устанавливается через ngrok.
IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);

Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
    listenSocket.Bind(ipPoint);
    listenSocket.Listen(10);
    Console.WriteLine("Server is starting...");

    while (true)
    {
        Socket handler = listenSocket.Accept();
        StringBuilder builder = new StringBuilder();
        int bytes = 0;
        byte[] data = new byte[256];

        do
        {
            bytes = handler.Receive(data);
            builder.Append(Encoding.UTF8.GetString(data, 0, bytes));
        }
        while (handler.Available > 0);

        Console.WriteLine(DateTime.Now.ToShortTimeString() + ": " + builder.ToString());

        string message = "HTTP/1.0 200 OK";
        data = Encoding.UTF8.GetBytes(message);
        handler.Send(data);
        handler.Shutdown(SocketShutdown.Both);
        handler.Close();
    }
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
    Console.ReadKey();
}

API - telegram-bot. В моём случае, я просто пишу сообщение боту и он отсылает мне json'овский файл в виде строки со всей необходимой инфой. Но, проблема в том, что Телеграм на мой сервер отсылает бесконечное количество Post-запросов, на которые я не знаю как ответить. Как мне реализовать эту возможность - ответа на post-запрос?


text:
Q: Why I can't use watch by tsc? This is my current typescript and tsc versions:
> npm list typescript -g
└── typescript@1.7.5

> tsc -v
Version 1.0.3.0

The doc says tsc can use -w arg. I tried to uninstall and install the module, it never has the arg. What happened?
Please tell me what the latest tsc version is. Thanks.

A: I know what happened. upgrading-on-windows
My latest global modules locate on C:\Users\<username>\AppData\Roaming\npm. Because I set incomplete path in windows environment variables, It causes I can't call the newest modules.


text:
Q: Error while mounting samba share: CIFS VFS: No username specified I'm trying to mount a samba share on CentOS, Ubuntu and Debian and I'm getting the error "CIFS VFS: No username specified" although everything seems fine.
Here's my /etc/fstab :
//1.2.3.4/share  /mnt/share  cifs rw,iocharset=utf8,uid=root,gid=root,credentials=/root/smbcredentials   0   0

my /root/smbcredentials
username=...
password=...

and my output:
# mount  /mnt/backups
mount: wrong fs type, bad option, bad superblock on //10.13.37.5/backups,
   missing codepage or helper program, or other error
   (for several filesystems (e.g. nfs, cifs) you might
   need a /sbin/mount.<type> helper program)

   In some cases useful info is found in syslog - try
   dmesg | tail or so.
# dmesg | tail
[ 1308.670814] CIFS VFS: No username specified

A: You need to install cifs-utils:
 yum install cifs-utils # centos/redhat/older fedora
 dnf install cifs-utils # newer fedora
 apt install cifs-utils # debian/ubuntu


text:
Q: Haskell type inference results in error message pointing at the wrong variable loading the following code in ghci
{-# OPTIONS_GHC -Wall   #-}

--following gives a type error about the arg int not str
bug ::  String -> Int -> Int
bug str int =  num
  where num =  str * 10  +  int

-- the following gives a type error about the arg str as expected
works ::  String -> Int -> Int
works str int = str * 10  +  int

that gives the following errors:
:reload
[1 of 1] Compiling Main             ( bugTI.hs, interpreted )

bugTI.hs:6:16: error:
    • Couldn't match type '[Char]' with 'Int'
      Expected: Int
        Actual: String
    • In the expression: num
      In an equation for 'bug':
          bug str int
            = num
            where
                num = str * 10 + int
  |
6 | bug str int =  num
  |                ^^^

bugTI.hs:7:29: error:
    • Couldn't match type 'Int' with '[Char]'
      Expected: String
        Actual: Int
    • In the second argument of '(+)', namely 'int'
      In the expression: str * 10 + int
      In an equation for 'num': num = str * 10 + int
  |
7 |   where num =  str * 10  +  int
  |                             ^^^

bugTI.hs:10:17: error:
    • Couldn't match type '[Char]' with 'Int'
      Expected: Int
        Actual: String
    • In the first argument of '(*)', namely 'str'
      In the first argument of '(+)', namely 'str * 10'
      In the expression: str * 10 + int
   |
10 | works str int = str * 10  +  int
   |                 ^^^
Failed, no modules loaded.

The error for line 7 in the function bug says that it expects int to be a String which makes no sense as it is in an arithmetic expression.
The corresponding err for line 10 in the function works correctly says that it expects str to be an Int which makes sense.
It seems to me that the error for line 7 is at best misleading, at worst (and unlikely) a bug. Can somebody explain why the error points to the wrong variable? I assume there is something I don't understand.

A:
It seems to me that the error for line 7 is at best misleading, at worst (and unlikely) a bug. Can somebody explain why the error points to the wrong variable? I assume there is something I don't understand.

There is nothing "special" about the (*) :: Num a => a -> a -> a, (+) :: Num a => a -> a -> a, etc. functions. These are just functions defined in the Num typeclass.
You can make other types a member of the Num typeclass as well, this often happens if people define their own numerical-like types.
So you could, if you wanted to, define an instance for Num for a String type, or for a list in general. You could for example encode a number by the length of the list, and thus derive arithmetic on it. Then that would look like:
import Data.List(genericReplicate)

instance Num [a] where
    (+) = (++)

    (*) = (<*)

    abs = id

    signum = take 1

    fromInteger = (`genericReplicate` undefined)

    xs - ys = drop (length ys) xs

I agree that this does not make much sense as an instance for Num, but it is is one of the possible ways to implement this.
What Haskell is complaining about is that the two operands and the return type all need to have the same type. Indeed, in the signature Num a => a -> a -> a, the a is used for the two operands and the return type.
Since int has as type Int by the type signature, it means that the two operands of the addition needs to be Ints, and hence the result of str * 10 should be an Int, that is not a problem for 10, but a problem for str. Even if Num [a] would hold, it still means that this would error, since you can not multiply an Int with a Double for example, or add an Integer and Int together.

A: Haskell does type inference in two "directions" at once.

*

*Bottom-up: by looking at all the parts of an expression, what should be the type of the whole expression

*Top-down: by looking at where this expression is used, what type should it have in order to fit into that context

If there is any place where the two do not agree, there will be a type error reported.
GHC's error messages call type it's worked out by "bottom-up" analysis the "actual type", and the type it's worked out by "top-down" analysis the "expected type". But don't be confused by this terminology; it's not that the "expected type" any more correct than the actual type. It is not telling you that the type should be the expected type but actually is the actual type. It's just telling you that two different lines of analysis lead to a contradiction about what the type of the expression is.
As such, it's kind of absurd to say that one of these error messages is "right" and the other is "wrong". They are both just telling you "these 2 things don't match, and they should". The compiler has no way of knowing which of the two types the expression "should" have if it was really correct; frequently neither of the two will work, no matter what else you change.
In particular, let's look at the type inference going on in the message you don't like:
bugTI.hs:7:29: error:
    • Couldn't match type 'Int' with '[Char]'
      Expected: String
        Actual: Int
    • In the second argument of '(+)', namely 'int'
      In the expression: str * 10 + int
      In an equation for 'num': num = str * 10 + int
  |
7 |   where num =  str * 10  +  int
  |                             ^^^

And for reference the code is:
bug ::  String -> Int -> Int
bug str int =  num
  where num =  str * 10  +  int

So to report a type error at the position indicated, we need to have both an "actual" (bottom-up) and "expected" (top-down) type for this occurence of int. The bottom-up type is easy; we know it's Int because the expression int only consists of a single variable reference, and that variable was declared to have type Int.
The expected type for int here depends on the context. int is occurring as the right operand to +, with the left operand being str * 10. + has type Num a => a -> a -> a. So to know what type we "expect" for int we need to know what type str * 10 is inferred as.
* has type Num a => a -> a -> a, so str and 10 must have the same type, and the overall expression str * 10 also has that type. 10 can be any type with a Num instance, but str already has a fixed type from the type signature; it is String (AKA [Char]).
Putting that all together, we now know that

*

*the expressions str, 10, int, str * 10, and str * 10 + int  all must have the same type

*str has type String

*int has type Int
These 3 facts cannot all be true. So we need to emit an error message.
This is the point where you go wrong. You have knowledge of your conceptual ideas about Num - that we do arithmetic on numbers and String isn't a number - so you say clearly we should "expect" Int for all of those, and the error that should be reported is that str has actual type String and expected type Int. But the compiler cannot possible know about your conceptual ideas about what Num is "for". Without that, your interpretation of the code is not any more valid than doing the opposite: saying that all of those expressions are expected to have type str and it's int that doesn't match! Exactly because there is no consistent typing here, there are multiple ways to get "as close as possible" and then report an error. It is essentially arbitrary which form the error takes in the error message1; neither is better than the other. So neither one can be the "wrong" error message.2
Without knowing the really fine details of the type checker implementation, I would hazard a guess based on this that it simply encountered the str * 10 first and "committed" to String at that point; it knows enough even without looking ahead to know that choosing String as the type of both 10 and also of str * 10 is the only possible chance it has of accepting this code, so there is "nothing to lose" by doing that. And then when it later also finds a requirement forcing that same type to also be Int, it reports an error.3
Now you noted in comments that there is also another error under this interpretation that str, 10, and int are all expected to be String. That is the error that this choice will require an instance Num String, and there is no such instance visible to the compiler. It doesn't report that error because it is "behind" this one; the compiler needs to go looking for an Num instance that matches whatever type is chosen for str, 10, and int, but it doesn't make sense to go looking for that instance until after we've figured out what instance we need! That requires pinning down the type involved, and having realised that there is no consistent type it's pointless even trying to resolve the Num constraint. This is an error whether or not Num Int or Num String or Num <anything-else> hold true.

1 As evidence for my claim that which way around the error is reported is arbitrary, I don't even get the same error messages as you when I tried this. I don't know whether it's just a different version of GHC, or whether it would change sometimes even for the same version. But I get an error about int not being String for both bug and works:
foo.hs:6:16: error:
    • Couldn't match type '[Char]' with 'Int'
      Expected: Int
        Actual: String
    • In the expression: num
      In an equation for 'bug':
          bug str int
            = num
            where
                num = str * 10 + int
  |
6 | bug str int =  num
  |                ^^^

foo.hs:7:29: error:
    • Couldn't match type 'Int' with '[Char]'
      Expected: String
        Actual: Int
    • In the second argument of '(+)', namely 'int'
      In the expression: str * 10 + int
      In an equation for 'num': num = str * 10 + int
  |
7 |   where num =  str * 10  +  int
  |                             ^^^

foo.hs:11:17: error:
    • Couldn't match type '[Char]' with 'Int'
      Expected: Int
        Actual: String
    • In the expression: str * 10 + int
      In an equation for 'works': works str int = str * 10 + int
   |
11 | works str int = str * 10  +  int
   |                 ^^^^^^^^^^^^^^^^

foo.hs:11:30: error:
    • Couldn't match type 'Int' with '[Char]'
      Expected: String
        Actual: Int
    • In the second argument of '(+)', namely 'int'
      In the expression: str * 10 + int
      In an equation for 'works': works str int = str * 10 + int
   |
11 | works str int = str * 10  +  int
   |

2 In fact these aren't even the only two possibilities. Absent wider context, it's just as likely that int and str are both "correct", and the bug is that the wrong functions were used on them (i.e. it's + and * that are wrong). GHC could quite reasonably report that this occurrence of + has expected type String -> Int -> Int and actual type Int -> Int -> Int, or something similar; that is also another equivalent way of reporting the same fundamental inconsistency that is present in your code.
I don't believe it will (often? ever?) actually report errors in that form. As far as I can recall it reports errors about arguments not fitting the function, rather than the function not fitting the arguments. I don't actually know why, whether it's a deliberate decision (for simpler error messages?) or just an accident of the type checker code works. But it's always a possibility for the real mistake that the programmer made, so you need to read errors with this sort of possible translation in mind.

3 And I suppose that this doesn't happen in the works case because you don't have the intermediate num definition that can be inferred its own type; instead the str * 10 + int expression occurrs in a context where it is known that it should result in Int, because it is directly the return value of the works function that is declared to return Int. Although as I noted in my previous footnote, this doesn't happen when I run it. But that's fine. There is no one correct order in which GHC is required to consider the pieces of information available to it before it notices the inconsistency.


text:
Q: How to use Model in specific file in lib directory on rails 5
I want to use model in specific file in lib directory in rails 5
for example:

lib/app.rb

i want to use all models in this file
How can i do?

I used require 'models/post'
but i received Post::User not defined, because i used belongs_to :user in Post model

when i added require 'models/user' then i received devise not defined
so i need require all models.

A: The convention in Rails is to have one file per class. So, if you have models Foo and Bar, Rails would try to load foo.rb and bar.rb for you automatically.
You can have multiple models defined in the same file but such a setup won't get autoloaded for you transparently. You have to require the file manually:
require 'app'

You can do this in your controller, for example.


text:
Q: Edit html table row and update It into mysql table using php I have created update button on my every row in table dynamically using JQuery that    successfully editing the table but i don't know how to call php function for updating the database,
i have used juery as
$(document).ready(function () {
      $('.editbtn').click(function() {
    var $this = $(this);
    var tds = $this.closest('tr').find('td').filter(function() {
        return $(this).find('.editbtn').length === 0;
    });
    if ($this.html() === 'Edit') {
        $this.html('Save');
        tds.prop('contenteditable', true);

    } else {
        $this.html('Edit');
        tds.prop('contenteditable', false);
    }
});

questions:
how to pass row id to jquery and then update.php page,
i am waighting for your help, i hav google it many times but not able to solve my problem

A: I will prefer to set id of row on edit button as an attribute, and when you click on edit, you can pick id by this element. Check below code for example:
//Here 1 is id of row which you want to edit
<button class="editbtn" data-id="1">Edit Row</button>

and you can get id on editbtn class click as below:
$('.editbtn').click(function() {
    let rowId = $(this).data("id");
});

And to save updated values, you need to call ajax or need to submit form. You need to pass all data including row id, other fields value in ajax request. I will prefer to use Ajax as it will not load your page and it will look much better for UI.
Hope it will help you.


text:
Q: Result about matrix exponentials and projections that seems like I should be able to cite someone as discovering it If $P$ is a projection, $A$ is a matrix, and $AP=PA$, then $Pe^{tA} = e^{tPA}-I+P$.  Proof:
\begin{align}
Pe^{tA} & = P\sum_{i=0}^\infty \frac{A^it^i}{i!} \\
& = \sum_{i=0}^\infty \frac{PA^it^i}{i!} \\
& = P+\sum_{i=1}^\infty \frac{P^iA^it^i}{i!} \\
& = P+\sum_{i=1}^\infty \frac{(PA)^it^i}{i!} \\
& = e^{tPA}-I+P
\end{align}
This seems like a simple enough result that someone has discovered it before, and (I think) interesting enough that someone might know who.  So I'm interested if anybody has encountered it before, and if so, if they know a reference for it.
EDIT: Corrected something basic in response to a comment.