res.end() not closing the script execution in NodeJS

Question: return res.end() not closing script execution.
Initially it renders the form and when i submit it executes the code block below closing brace of if statement.
I think execution should have ended on the line return res.end().
const http = require("http");

const server = http.createServer((req, res) => {
  const url = req.url;
  if (url === "/") {
    res.write("");
    res.write("<title>FORM</title>");
    res.write(
      "<form action='/message' method='POST'><input type='text' name='message' /><button>Send</button></from>"
    );
    res.write("");
    return res.end();
  }
  res.setHeader("Content-Type", "text/html");
  res.write("");
  res.write("<title>APP</title>");
  res.write("
Demo APP
");
  res.write("");
});

server.listen(4000);

Answer: Please add console.log(req.url) to the start of your request handler.  You will find that:
return res.end();

does indeed stop the execution of that particular request by returning from the request handler callback.
But, you are most likely then getting another incoming http request, probably for favicon.ico.  In general you should never have code in a request handler that pays zero attention to what resource is being requested unless it's sending back an error like a 404 because there are lots of requests that can potentially be made to your http server for somewhat standard resources sucn as robots.txt, favicon.ico, sitemap.xml and so on and you shouldn't be answering for those requests unless you are sending the appropriate data for those requests.
Comment: @faheemkhan - Did this answer your question?  If so, you can indicate that to the community here by clicking the checkmark to the left of the answer.  That will also earn you some reputation points for following the proper procedure here.
Answer: You might want to put the remainder of the code in ELSE block to ensure it is run only when URL!=="/"
Comment: That won't really make a difference here.  The `return` does indeed stop the rest of that particular request from executing.  The likely issue here is that there are other incoming http requests for other resources that are executing the rest of the code.
Comment: My bad, I have missed the RETURN part.


Cows and Ducks Word Problem

Question: Greg wants to know how many cows and ducks are in the meadow. After counting 56 legs and 17 heads, the farmer knows. How many cows and ducks are in the meadow?
Comment: Any thoughts?  Hint:  if there are $C$ cows and $D$ ducks....how many legs are there?  How many heads?
Comment: In Animal Farm by George Orwell, the animals defined bird's wings to count as legs because their main function is locomotion rather than manipulation. This allowed them keep chanting "Four legs good, two legs bad" without excluding the ducks and geese and chickens. I just assume that this is not the case here.
Answer: There are $17$ animals (unless there might be some two-headed cows or something).
If they were all ducks, there would be $34$ legs.  Each cow adds 2 extra legs.  We need $56-34=22$ extra legs, so there are $11$ cows and $6$ ducks.
Or you can set this up as a simple algebra problem:
Comment: I always prefer non-algebra solutions to these problems. Setting up the two equations with two unknowns, while guaranteed to find an answer if there is one, takes time to do, and it takes time to solve, and the method of solution has little to do with cows and ducks.
Comment: Having polled three cows, I find that *they* do not consider two of their legs "extra."
Answer: Let $C$ be the number of cows, and $D$ the number of ducks. Each animal has just one head (I hope), so $C + D = 17$. On the other hand, each cow has four legs, and each duck has two legs, so $4C + 2D = 56$. Now you have two linear equations in two unknowns. Can you solve for $C,D$?

Cows and Ducks Word Problem


Route 53 - cloudfront distribution not showing when creating A record

Question: I'm creating an A record in my Route 53 hosted zone for a subdomain. When I select "Alias to Cloudfront distribution", only US East zone shows in the list, containing an undesired distribution:

However I want to point to another distribution which is not showing in the list. Any idea why it's not showing? The distribution is ready and can be accessed using the cloudfront URL, pointing to a static s3 hosting bucket. I created it using amplify cli hosting, s3+cloudfront option if it matters.
Thanks for any help.
Comment: Have you set correct Alternate Domain Name in your CF distro which matches the R53 domain?
Comment: @Marcin That solved the problem. Many thanks!
Comment: Glad to hear. If you don't mind, I will provide an answer for future reference:-)
Answer: Based on the comments.
The issue was caused because the CloudFront distribution in question did not have Alternate Domain Name set witch matches the record in Route53. From docs:

The distribution must include an alternate domain name that matches the domain name that you want to use for your URLs instead of the domain name that CloudFront assigned to your distribution.
Answer: I encountered this even when the distribution was deployed with the correct alternate domain name added. It seems like a bug in the Console as copy-pasting the cloudfront domain (id.cloudfront.net) worked fine.


How to improve Pull-offs

Question: I can get a nice sound with hammer-ons, but when I do pull-offs, seems like the second note loses a lot of its.. power.
I did some research over the web and seems like you have to do some kind of little bending when pulling of your fingers, but that didn't worked too well for me.
Any advice?
Answer: It is obviously much easier to hammer your finger quickly onto the fretboard to hit the string, than it is to let your finger come off the string. The idea is to pull-off to the side, i.e. across the fretboard, not lift-off, hence the name.
This doesn't need to be much, and in fact if you do it too far you will bend the note.
I find callouses help a little, as my fingertip is more rigid, but that is not necessary.
Additionally, you can make the guitar string more "live" by increasing the gain. With high enough gain, you can touch a string with a feather and it will ring out.
Comment: _Obviously much easier_? – Actually, convincing-sounding hammer-ons are quite a bit more difficult on many instruments than pull-offs, especially on bass instruments (wide string spacing gives plenty of room to literally pluck the string with the pull-off finger).
Comment: I think you misread my post. That's exactly what i said:-) The pull off rather than the lift off
Answer: JustinGuitar touches on this in his excellent Finger Gym video. As Dr Mayhem has said, it's critical to not merely "lift off" your finger, but rather add a nuanced perpendicular-to-the-strings motion, or as Justin calls it, a "flick off".
Answer: A pull-off is pretty well using a fretting hand finger to pluck the string. Whatever you may do to make a string sound, using a r.h. finger, the same will apply to produce a pull-off. You must pluck the string in an upwards or downwards stroke, at rightangles to the string, with your r.h. finger. So, the same applies for a pull-off. If you're pulling off to another fretted note on the same string, press a little harder with the second note finger, in order to stop the string being pulled sideways and out of tune.
A good practice regime is to play, say, top string fret5, hammer on to fret 6, pull-off to 5 again. Keep this going until each note is the same tone and volume, then change fingers - for both notes when it's good- and all without stopping a regular rhythm. Slowly at first, of course, and don't rush either the hammer on or the pull-off.
Answer: I saw a video a while ago (cant find it anymore) in which the teacher said that the pull-off should be quick in order to produce the correct sound. Quick doesnt mean fast (that's probably why you lose power). Think about snapping finger, if you do it slow you dont produce any sound. So when you litterally "pull-off" (dont put too much strenght in this) the string with one finger , the other finger below should be there in that exact same time of the movement. Remember also not to move the hand but just the fingers. Then practice it with the metronome and you'll get it! Hope that helps
EDIT: that's the video

How to improve Pull-offs


http post com BodyRequest Sqlserver

Question: Olá,
como faço para conseguir um requisição post passando um xml como data?
tentei assim em uma outra requição GET e funcionou:
<code>        DECLARE @Tabela TABLE ( CampoXML XML);

        DECLARE @URL VARCHAR(8000)
        SELECT @URL = 'url?parametros='
        DECLARE @Response varchar(8000)
        DECLARE @XML xml
        DECLARE @Obj int
        DECLARE @Result int
        DECLARE @HTTPStatus int
        DECLARE @ErrorMsg varchar(MAX)
        EXEC @Result = sp_OACreate 'MSXML2.XMLHttp', @Obj OUT
        EXEC @Result = sp_OAMethod @Obj, 'open', NULL, 'GET', @URL, false
        EXEC @Result = sp_OAMethod @Obj, 'setRequestHeader', NULL, 'Content-Type', 'application/x-www-form-urlencoded'
        EXEC @Result = sp_OAMethod @Obj, send, NULL, ''
        EXEC @Result = sp_OAGetProperty @Obj, 'status', @HTTPStatus OUT

        INSERT @Tabela ( CampoXML )
        EXEC @Result = sp_OAGetProperty @Obj, 'responseXML.xml'--, @Response OUT

        SELECT * FROM @Tabela
</code>
porém preciso fazer uma requição post, e passar por body o xml abaixo:
<code> <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
 <acertaContratoEntrada xmlns="http://...">
   <usuario>usuario</usuario>
   <senha>senha</senha>
 </acertaContratoEntrada>
</code>
agradeço as repostas
Answer: Vou deixar aqui a solução,
Consegui fazer a requisição POST passando dados pelo body pelo sqlserver com o código abaixo:
<code>-- Informação a enviar pelo body
DECLARE @BODY_XML VARCHAR(8000) =
' <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <acertaContratoEntrada xmlns="http://...">
    <usuario>usuario</usuario>
    <senha>senha</senha>
    </acertaContratoEntrada>'

DECLARE @Tabela TABLE ( CampoXML XML);

DECLARE @URL VARCHAR(8000)
SELECT @URL = 'http://minha-url'
DECLARE @Response varchar(8000)
DECLARE @XML xml
DECLARE @Obj int
DECLARE @Result int
DECLARE @HTTPStatus int
DECLARE @ErrorMsg varchar(MAX)
EXEC @Result = sp_OACreate 'MSXML2.XMLHttp', @Obj OUT
EXEC @Result = sp_OAMethod @Obj, 'open', NULL, 'POST', @URL, false
EXEC @Result = sp_OAMethod @Obj, 'setRequestHeader', NULL, 'Content-Type', 'application/xml' -- ALTERAÇÃO NECESSARIA PARA FUNCIONAR
EXEC @Result = sp_OAMethod @Obj, send, NULL, @BODY_XML
EXEC @Result = sp_OAGetProperty @Obj, 'status', @HTTPStatus OUT

-- ================ INSERE NA TABELA TEMPORARIA
INSERT @Tabela ( CampoXML )
EXEC @Result = sp_OAGetProperty @Obj, 'responseXML.xml'--, @Response OUT

select * from @Tabela
</code>

http post com BodyRequest Sqlserver


Let $F(x,y)=\int_{a}^{x} f(t,y)dt$. Find $F_x$ and $F_y$. If $G(x)=\int_{a}^{g(x)} f(t,x)dt$, find $G'(x)$

Question: If $$f:[a,b]\times [c,d] \to \mathbb{R}$$ is continuous and $f_{y}$ is continuous, let $$F(x,y)=\int_{a}^{x} f(t,y)dt.$$

Find $F_x$ and $F_y$.
If $G(x)=\int_{a}^{g(x)}f(t,x)dt$, find $G'(x)$

My try:
For (1) $$F(x+h,y)-F(x,y)=\int_{a}^{x+h} f(t,y)dt-\int_{a}^{x}f(t,y)dt=\int_{x}^{x+h}f(t,y)dt$$
Let $\int f(t,y)dt= H(t,y)$. Then $\int_{x}^{x+h}f(t,y)dt=H(x+h,y)-H(x,y)$. Hence $$F_x= \frac {\partial H(x,y)}{\partial x} $$. I am kind of stuck here.
$F_{y}$ is easy. $$F(x,y+h)-F(x,y)=\int_{a}^{x}\left(f(t,y+h)-f(t,y)\right) dt$$
Hence $$F_{y}=\int_{a}^{x}\frac{\partial f}{\partial y} dt $$
For (2) we have $$G(x+h)-G(x)=\int_{a}^{g(x+h)}f(t,x+h)dt-\int_{a}^{g(x)} f(t,x)dt$$
$$=\int_{a}^{g(x+h)}f(t,x+h)dt-\int_{a}^{g(x)} f(t,x+h) dt+ \int_{a}^{g(x)} f(t,x+h) dt-\int_{a}^{g(x)} f(t,x)dt$$
$$=\int_{g(x)}^{g(x+h)} f(t,x+h) dt+\int_{a}^{g(x)} \left(f(t,x+h)-f(t,x)\right)dt$$
If I let $\int f(t,x+h) dt= H(t,x+h)$. Then we have
$$ \frac{G(x+h)-G(x)}{h}=\frac{H(g(x+h),x+h)-H(g(x),x+h)}{g(x+h)-g(x)}. \frac{g(x+h)-g(x)}{h}+\int_{a}^{g(x)}\frac{ \left(f(t,x+h)-f(t,x)\right)}{h}dt$$
Taking limit on both sides we have $$G'(x)=H'(g(x),x+h).g'(x)+\int_{a}^{g(x)}\frac{ \partial f}{\partial x}dt$$
From here How do I get thr result??
Thanks for the help!!
Comment: What is your question? It seems you are perfectly able to compute all the derivatives!
Comment: @Siminore I need to write $H$ in terms of $f$
Answer: Although you need to justify some passage to the limit,
$$
\partial_1 F(x,y) = \int_a^x f(t,y)\, dt,
$$
$$
\partial_2 F(x,y) = \int_a^x \partial_2 f(t,y)\, dt.
$$
Since $G(x)=F(g(x),x)$, by the chain rule
$$
G'(x)=\partial_1 F(g(x),x)g'(x) + \partial_2 F(g(x),x).
$$
Comment: How do i get them in my process?
Comment: Your $H$ is not a function of $t$...
Answer: Just trust the force of calculus! For $F_{.1}:=F_x$ you can disregard the $y$ and differentiate the integral with respect to the upper limit:
$$F_{.1}(x,y)=f(x,y)\ .\tag{1}$$
For $F_{.2}$ you can disregard that the upper limit could be variable under other circumstances. Just differentiate under the integral sign:
$$F_{.2}(x,y)=\int_a^x f_{.2}(t,y)\>dt\ .\tag{2}$$
The function $G$ can be written in terms of $F$ as
$$G(x)=F\bigl(u(x),v(x)\bigr)$$
with $u(x):=g(x)$, $\>v(x):=x$. The chain rule gives
$$G'(x)=F_{.1}\bigl(u(x),v(x)\bigr)u'(x)+F_{.2}\bigl(u(x),v(x)\bigr)v'(x)\ .$$
Plugging in $(1)$ and $(2)$ now produces
$$G'(x)=f\bigl(g(x),x\bigr)\cdot g'(x)+\int_a^{g(x)} f_{.2}(t,x)\>dt\cdot 1\ .$$


How to know which line of code in Try block generates error

Question: Currently I have a block of code with try and catch. In try block i have used some logic based on IO and Database, Now how to know that which line of code generates / getting an exception in try block for io or db related code.
Comment: Look at the exception stack trace?
Comment: You could debug and step?
Comment: I have used Multiple catch block related to IO and DB exceptions. Is there any another way to detect excetions...
Comment: You could check what type of Exception is thrown?
Comment: http://msdn.microsoft.com/en-us/library/vstudio/sc65sadd.aspx
Comment: use two try catches perhaps? divide your logic between them. Otherwise, *why* do you need to know which line throws the error?
Comment: Go to *Debug* - *Exceptions* and enable everything. Than the debuggers breaks before you step into the catch block at the correct line.
Comment: +1 for what @Jon said....Use Stack Trace.
Comment: Maybe you should think about using smaller and more *try* - *catch* blocks and/or explicitly declare the kind of exception each catch block can handle.
Answer: Its Pretty Simple in .Net. In Your .Net Window Press Ctrl + Alt + E. The Exceptions window will be opened. There you can see Common Language Runtime Exceptions Enable those two check boxes. You can get the Error line when ever the Exception is occurred. After pressing F5 it will goes to catch block.


Is there a difference between 'decrescendo' and 'diminuendo'?

Question: I'm a lifelong musician, and this is something I've always wondered about. I know that decrescendo translates to "decreasing" and diminuendo to "diminishing", but does this have any practical difference when it comes to playing or writing music? In my experience I've noticed decrescendo markings used over shorter bars and phrases, and diminuendo used more often to mark longer passages and pages where the <code>></code> would be clumsy. Should I be interpreting these two marking differently when I am reading music?
Comment: Yes, of course: dim. or decresc. I was wrong, sorry!
Comment: the abbreviation  for both is dim. They mean the same. You can choose, it's up to you.
Comment: Not sure about this but it seems to me that decrescendo always (or mostly) follows a passage of increased loudness. I can't imagine a piece beginning with *mf* being marked *decrescendo* a few bars later. But I can imagine a piece starting the same way, but then marked *f*, and then a few bars later, *decrescendo*. In other words, I don't *think* you can decresc unless you've recently got louder. Perhaps it suggests a return to the level of the previous dynamic marking, but I've certainly never heard anything about them being interpreted differently from each other.
Comment: @Albrecht Hügli 1  I'm sure I've seen *decresc.* Or was it just the start of a *decresc  -  en  -  do*?
Comment: Dolmetsch defines them identically.
Comment: I see a lot of agreement here - if one of you puts it in an answer I would be happy to accept!
Comment: @OldBrixtonian You can certainly decrease the volume from a mf whether you call it decrescendo or diminuendo. Anyway, personally I always use either the term diminuendo or a hair pin symbol when writing music. And when talking the term "decrescendo" sounds too similar to the term "crescendo" while the term "diminuendo" is clearly different. It makes it easy to hear what you mean.
Comment: @Lars Peter Schultz I don't think you quite understood what I was trying to say. Can you think of an example of its use where there has so far only been a single dynamic marking in the piece?
Answer: There is some discussion about whether Franz Schubert used the two terms to mean slightly different things, 'diminuendo' being a 'decrescendo' combined with a slight slowing down. Otherwise the two terms are used completely interchangeably.


Do an action when woocomerce saves a product

Question: I need to save some options when a woocommerce product gets saved.
Is there any way to do it?
Answer: You could use save_post action hook!

save_postDocs

You could use this boilerplate to do your custom work when a product gets saved!
add_action('save_post', 'do_some_custom_work');

function do_some_custom_work( $post_id )
{

    if ('product' == get_post_type($post_id)) {

        // Do what is necessary here!

        die('You hit the right hook!!!');
    }
}

Note:

In addition to $post_ID, you could pass $post and $update to your callback function as well. Please read the documentation for more details!

add_action('save_post', 'do_some_custom_work', 10, 3);

function do_some_custom_work( $post_id, $post,  $update )
{

    if ('product' == get_post_type($post_id)) {

        // Do what is necessary here!

        die('You hit the right hook!!! This is the product id: ' . $post->ID);
    }
}


indefinido não é uma função-undefined is not a function/React Native

Question: Eu estou com um problema, estou fazendo um curso e está dando esse erro no react native, vou mostrar todo o código abaixo, alguem pode ajudar?procurei sobre mas não achei resposta
Esse é o erro:
[Unhandled promise rejection: TypeError: undefined is not a function (near '...setCurrentRegion...')]
* src\pages\Main.js:11:8 in loadInitialPosition
- node_modules\regenerator-runtime\runtime.js:45:44 in tryCatch
- node_modules\regenerator-runtime\runtime.js:271:30 in invoke
- node_modules\regenerator-runtime\runtime.js:45:44 in tryCatch
- node_modules\regenerator-runtime\runtime.js:135:28 in invoke
- node_modules\regenerator-runtime\runtime.js:145:19 in Promise.resolve.then$argument_0
- node_modules\promise\setimmediate\core.js:37:14 in tryCallOne
- node_modules\promise\setimmediate\core.js:123:25 in setImmediate$argument_0
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:146:14 in _callTimer
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:194:17 in _callImmediatesPass
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:458:30 in callImmediates
* [native code]:null in callImmediates
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:407:6 in __callImmediates
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:143:6 in __guard$argument_0
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:384:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:142:17 in __guard$argument_0
* [native code]:null in flushedQueue
* [native code]:null in invokeCallbackAndReturnFlushedQueue

Main.js
import React,{useState,useEffect} from 'react';
import { StyleSheet } from 'react-native';
import MapView from 'react-native-maps';
import { requestPermissionsAsync, getCurrentPositionAsync} from 'expo-location'

function Main() {
    const { currentRegion, setCurrentRegion } = useState(null);

    useEffect(() => {
        async function loadInitialPosition() {
            const {granted} = await requestPermissionsAsync();

            if(granted) {
                const {coords} = await getCurrentPositionAsync({
                    enableHighAccuracy: true,
                });
                const { latitude, longitude } = coords

                setCurrentRegion({
                    latitude,
                    longitude,
                    latitudeDelta: 0.04,
                    longitudeDelta: 0.04,
                })
            }
        }

    loadInitialPosition();
    }, [])

    if(!currentRegion){
        return null;
    }
    return <MapView initialRegion={currentRegion} style={{ flex: 1 }}/>
}

const style = StyleSheet.create({
    map: {
        flex: 1,
    },
})

export default Main;

App.js
import React from 'react';
import { StatusBar } from 'react-native';
import Routes from './src/pages/routes';

export default function App() {
  return (
    <>
    <StatusBar barStyle="light-content" backgroundColor='#7D47E0'/>
    <Routes/>
    </>
  );

package
{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject"
  },
  "dependencies": {
    "@react-native-community/masked-view": "^0.1.6",
    "expo": "~36.0.0",
    "expo-location": "~8.0.0",
    "react": "~16.9.0",
    "react-dom": "~16.9.0",
    "react-native": "https://github.com/expo/react-native/archive/sdk-36.0.0.tar.gz",
    "react-native-gesture-handler": "~1.5.0",
    "react-native-maps": "0.26.1",
    "react-native-reanimated": "~1.4.0",
    "react-native-safe-area-context": "0.6.0",
    "react-native-screens": "2.0.0-alpha.12",
    "react-native-web": "~0.11.7",
    "react-navigation": "^4.0.10",
    "react-navigation-stack": "^2.0.15"
  },
  "devDependencies": {
    "@babel/core": "^7.0.0",
    "babel-preset-expo": "~8.0.0"
  },
  "private": true
}

Profile
import React from 'react';
import { View } from 'react-native'

function Profile() {
    return <View/>
}

export default Profile;

Routes.js
import { createAppContainer } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack'

import Main from './Main';

import Profile from './profile';

const Routes = createAppContainer(
    createStackNavigator({
        Main: {
            screen: Main,
            navigationOptions: {
                title: 'DevRadar',
            }
        },
        Profile: {
            screen: Profile,
            navigationOptions: {
                title: 'Perfil no github',
            }
        },
    }, {
        defaultNavigationOptions : {
            headerTintColor: '#FFF',
            headerStyle: {
                backgroundColor: '#7D40E7'
            }
        },
    })
);

export default Routes;

Comment: Seu useState não deveria desestruturar um array? Tu tá tentando como se fosse um objeto no retorno dele
Comment: manda o erro ai cara
Comment: Vou editar e colocar no inicio
Comment: vc não ta esquecendo de importar nada no Main.js?
Comment: mano, ta igual do curso,e no dele dá tudo certo
Comment: Não tá igual, tenta `const [currentRegion, setCurrentRegion] = useState(null);`, lembro que o Diego fala que o retorno é um array
Comment: puts, verdaade uma "{ }", valeu ai não tava vendo de jeito nenhum
Answer: Substitua
const { currentRegion, setCurrentRegion } = useState(null)

por:
const [ currentRegion, setCurrentRegion ] = useState(null)


Refresh after adding DIV dynamically using jQuery Mobile

Question: I'm trying to add a div dynamically using jQuery mobile, but after adding it, the CSS is not applied even with the refresh.
The is the example.
Code :
$(function() {
     $("#data").append('

Div2

Content Div2...

');
     $("#data").listview("refresh");
});

Answer: Use collapsibleset() instead of listview("refresh"):
$("#data").collapsibleset();

See DEMO.
Comment: Ah, I see. Try just `collapsibleset()`. I've updated my answer.
Answer: I"m use such method
try{
    $("#data").listview("refresh");
}catch{
    $("#data").listview();
}finally{
    $('[data-role=collapsible]').collapsible();
}

This problem occurs when an item is added to the dynamic


Excel trying to two compare columns in two different worksheets and return data from third column

Question: I  have one worksheet with company name in column c and company town in column d and company id in column e.
I have a second worksheet with the same company names in column c and the company towns in column d. I am missing company ids. I need to pull in the company id number  to this second worksheet.
How can I compare the two columns in the first worksheet in order to match the company name and town to bring in the company id to the second worksheet? What is the easiest way to do this in excel?
Comment: Sorry I'm not sure how best to implement vlookup here in my case
Comment: What are the names of your two sheets?
Answer: I'll nominate your worksheets. The first you named i'll call it "Sheet1", and the second one, "Sheet2". You replace these names with your actual names of the worksheets
On "Sheet2",
Select E2 and put this: =vlookup(c2,Sheet1!C:E,3,FALSE)
Then you copy the formula down to your last company name (or drop it down)
"C2" is the value that you look for; Sheets1!C:E is the range where it looks up for your value ("!" this sign indicates another sheet) ; "3" is the number of column from the previous range (being "1" the company name, "2" the company town and "3" the company ID);
"FALSE" indicates exact coincidence ("true" is aproximated  coincidence)
The companies are always in the same town or same companies are in different towns and with different IDs? because that changes it all
Comment: Thanks so much - yes so the problem is that there are same companies in different towns. So the way I dealt  with this is I used CONCAT, MATCH, INDEX which seemed to work


Setting a background in flutter from a list

Question: I would like to have a page called Theme with grid images, and when I click on an image, to select that image as my background to home page.
This is a list I have:
List<Theme2> themeitems = [
  Theme2(
    background: 'assets/images/theme/deskWhite.png',
    selected: false,
  ),
  Theme2(
    background: 'assets/images/theme/greenDrop.png',
    selected: false,
  ),
  Theme2(
    background: 'assets/images/theme/leaf.png',
    selected: false,
  ),
],

This is a home page where I would like to set a background image:
child: Scaffold(
          body: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/theme/sand.png'),
         ////// image: AssetImage(themeitems[idx].background.selected), // I know this is not correct
                fit: BoxFit.cover,
              ),
            ),
            child: Column(.........

So, how could I set background image from one of these list items?
I tried using themeitems[index].selected = !themeitems[index].selected; but I am not sure how to use it correctly. If there is a problem like this on the net, please send me a link.
Thank you for your time.
Answer: Based on your code, I think it's easier to rename your images into something more sequentially, for example: image1.png, image2.png, image3.png,...
You can store it in a list, but I think you don't need to do that, as long as you've added your images in your assets folder.
And then, to select the image, inside your code:
int index = 0; //this variable is to store your selected index

child: Scaffold(
          body: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/theme/image$index.png'), //So if the index = 0, so image).png will appear. And, so on.
                fit: BoxFit.cover,
              ),
            ),
            child: Column( //YOUR CODE


How much storage would be required to store a human genome?

Question: I'm looking for the amount of storage in bytes (MB, GB, TB, etc.) required to store a single human genome. I read a few articles on Wikipedia about DNA, chromosomes, base pairs, genes, and have some rough guess, but before disclosing anything I'd like to see how others would approach this issue.
An alternative question would be how many atoms are there in human DNA, but that would be off topic for this site.
I understand that this will be an approximation, so I'm looking for the minimal value that would be able to store DNA of any human.
Comment: Vote to reopen because this is definitely not opinion based
Comment: As for the number of atoms, this depends on the composition. A and T are smaller molecules than G and C. The structure of the molecule is the beef, though, not its atomic composition, so this isn't really a very useful calculation. (For what it's worth, e.g. the A molecule aka [deoxyadenosine](https://en.wikipedia.org/wiki/Deoxyadenosine) is C10H13N5O3 so 31 atoms.)
Comment: See also https://www.biostars.org/p/5514/
Comment: Except for users slayton, Paul Amstrong and rauchen all other answers given are dead wrong in its essence or far from complete. In the answers user (fail to) mentioned compression methods or is poorly explained. See my answer to clarify the 4 times downsizing of the genome as seen in many answers.
Comment: I'm voting to close this question as off-topic because it is off-topic here, should be on https://bioinformatics.stackexchange.com/
Comment: 938 Megabytes compressed. Here is a [link to a repository](http://hgdownload.cse.ucsc.edu/goldenPath/hg38/bigZips/) containing it in a file called: hg38.chromFa.tar.gz
Comment: "I am having trouble wrapping my head around the fact that it only takes a cd's worth of software to make a human." Nobody claimed that. You need both that CD amd a living female to make a human. Merely having the genome is not enough I think!
Answer: If you trust such things, here is what Wikipedia claims (from  http://en.wikipedia.org/wiki/Human_genome#Information_content):

The 2.9 billion base pairs of the haploid human genome correspond to a
  maximum of about 725 megabytes of data, since every base pair can be
  coded by 2 bits. Since individual genomes vary by less than 1% from
  each other, they can be losslessly compressed to roughly 4 megabytes.
Comment: Thought about it for a day, and realized this: If you stored some base case human DNA, any subsequent human's DNA would only need to be stored as the diff between it and the base case. For same sex examples DNA is 99.9% the same. And across sexes it's like 98.5%.
Comment: Just to add some biological commentary, "haploid" here means only one copy of each chromosome. The human reference assembly is haploid (and a mosaic of multiple people). An actual individual genome will be diploid (2 copies of each chromosome, except X and Y) but again only variant between the two copies at a small subset of sites.
Comment: Also worth to remember that not all information encoded within DNA base pairs there is also [epigenetic](https://en.wikipedia.org/wiki/Epigenetics) information.
Comment: @cowlinator These definitions are … bad. "Heritable" in this case means "heritable" *between dividing mother and daughter cells*, not heritable between multi-cellular organisms and their offspring (that would be *transgenerational* epigenetic inheritance, which exists but is incredibly rare, and most claimed cases of it are based on bad science and are generally not accepted by experts). But the person who wrote that sentence is probably not entirely clear on what they mean, because there's no excuse for the sentence's bad phrasing. Check out the the "talk" page of the Wikipedia article.
Comment: this makes sense. base pairs are basically 4-nary. a 4-nary number is 2 bits, so double the size. so that's 5.8 gigabits or 5.8/8 gigabytes which is 0.725 GB or 725 MB. the 'compression' is only possible because you can store a diff against the mapped genome instead of storing your entire genome.
Comment: @Annarfych This is extremely misleading since epigenetic information is, by definition, not inheritable (despite misguided claims to the contrary in the popular press). *Heritable* information is stored in the DNA only.
Comment: @cowlinator Categorically no. And just to cut this short, I did research in epigenetics for my PhD and postdoc. For once I actually know what I'm talking about.
Comment: @KonradRudolph, That is incorrect.  Epigenetic information is, by definition, inheritable.
Comment: @KonradRudolph, so, epigenetics is not "the study of heritable phenotype changes that do not involve alterations in the DNA sequence"?  What is epigenetics?  (I ask because this is the definition used by wikipedia and merriam-webster)
Comment: Does this also include non-coding dna?
Answer: You do not store all the DNA in one stream, rather most the time it is store by chromosomes.
A large chromosome take about 300 MB and a small one about 50 MB.

I think the first reason why it is not saved in 2 bits per base pair is that it would cause a hurdle to work with the data. Most of the people would not know how to convert it. And even when a program for conversion would be given, a lot of people in large companies or research institutes are not allowed to/need to ask or do not know how to install programs...
1GB storage costs nothing, even the download of 3 GB takes only 4 minutes with 100 Mbitsps and most companies have faster speeds.
Another point is that the data isn't as simple as you get told.
e.g. The method for sequencing invented by Craig_Venter was a great breakthrough but has its down sides. It could not separate long chains of the same base pair, so it is not always 100% clear if there are 8 A's or 9 A's. Things you have to take care of later on...
Another example is the DNA methylation because you can't store this Information in a 2-bit representation.
Comment: +1 from me. However, I have no clue what does "large" or "small" chromosome mean?
Comment: These numbers don't tally with what Wikipedia says (see the table at http://en.wikipedia.org/wiki/Human_genome#Information_content); I'm not saying you're wrong, but can you explain the discrepancy?
Comment: Some of a genome's DNA methylation changes over the lifetime of the organism.  Including DNA methylation data for a human genome would be more like a detailed snapshot of a person at a particular moment, rather than a generic description of the individual.  Although, the OP didn't specify which they wanted.
Comment: Why would you store the whole thing for every individual? 99% of DNA is the same between humans so you would only have to store each person's deviations from the average.
Comment: It looks like he is quoting Mbp (million of base-pairs, each base-pair being a single position in the genome) rather than MB which can assume a 2-bit encoding of each position
Answer: Basically, each base pair takes 2 bits (you can use 00, 01, 10, 11 for T, G, C, and A). Since there are about 2.9 billion base pairs in the human genome, (2 * 2.9 billion) bits ~= 691 megabytes.
I'm no expert, however, the Human Genome page on Wikipedia states the following:
Raw MB:

Male (XY): 770MB
Female (XX): 756MB

I'm not sure where their variance comes from, but I'm sure you can figure it out.
Comment: Realistically, more than 2 bits are required, as there are other bases stored in sequence information (`N`, for example, where data is not mappable and therefore unknown). The IUPAC nucleotide codes include more than the standard four, and this can increase storage overhead.  http://www.ebi.ac.uk/2can/tutorials/aa.html
Comment: @AlexReynolds @o0' http://www.bioinformatics.org/sms2/iupac.html is a better link for those IUPAC codes. AIUI, a particular genome "scan" needs more than 2 bits due to imprecision, thus `R` for either A or G, `N` for any base, `.` for a gap, etc. If we could read a genome perfectly, it would be just 2 bits per base.
Comment: The X chromosome is single for females. Males have as extra the Y chrom. to be coded, which as we all know distinct from X crhom.
Comment: @AlexReynolds broken link :/
Comment: It also depends on how you define [Megabyte](https://en.wikipedia.org/wiki/Megabyte): binary 2^20 or metric 10^6 bytes. You use binary, so your number is lower.
Comment: @ZF007 human females have TWO X chromosomes. Males have one X and one Y.
Comment: @xbello .. do you assume more than 100.000 bp difference between both X's to be relevant to include twice the information or can we assume its <1.000 bp? And thus neglect-able in the discussion?!
Comment: X chromosome carries about 5-6 million variants, so it's safe to say that a difference of 100K between them is probable. If you only want to store a haploid human genome, then yes, you can discard a whole X chromosome along with half the autosomes. But in the real world we have to store each variant AND its zygosity, to have a truly "lossless" storage.
Comment: ... in such a case we have to compensate for ... 44 more chromosomes. I reckon that it would become a different question because then you need to know if you need to keep in mind real substitutions (only protein level) or/and also RNA-fold level, etc.? So ... if you want to dig into that post a new question and toss a "@".
Comment: Since male DNA is shorter than female's due to the fact that Y chromosome contains less genes than X (female: XX; male: XY), your calculation of Mb for male and female DNA seems to be swapped.
Answer: Yes, the minimum storage space needed for whole human DNA is about 770 MB.
However, the 2-bit representation is impractical. It is hard to search through or do some computations on it. Therefore, some mathematicians designed more effective way to store those sequencies of bases and use them in searching and comparation algorithms. One such example is GARLI.
This application runs on my PC right now, and I have the human genome stored in 1563 MB.
Answer: The human genome contains over 3 billion base pairs. So if you represented each base pair as two bits then it would take over 6.15 × 10⁹ bits or approximately 770 MB.
Comment: @SDGuero, base-pairs are base 4 not base 2, so you need at least 2 bits to represent a base pair.
Comment: @zf007 Base pairs are represented by the TOKENS of a, c, g and t.  A token is not the same as a character. There is no reason a can't be encoded as 00, c as 01, g as 10 and t as 11
Comment: There's the discrepancy ; you're asserting the need for a human readable file, which is not in the original post.
Comment: bits ~= bytes. 2.9 billion bits is around 350 MB
Comment: BS on the bit lingo... each nucleotide base is 1 character and thus 1 byte, regardless of character conversion table (AscII, UTF-8, etc) used; not including 2byte Asian coding.
Comment: @MatBailie..  Please elaborate and include the point you want to make in your comment because for now it missing. Have you read my answer that addresses the coding style ('A' as 1 byte or 'ATCG' or any other quadruplet represented in 1 byte) and the requirement of having DNA string humanly readable in fasta files?
Answer: just did it too. the raw sequence is ~700 MB. if one uses a fixed storage sequence or a fixed sequence storage algoritm - and the fact that the changes are 1% i calcuated ~120 MB with a perchromosome-sequenceoffset-statedelta storage. that's it for the storage.
Answer: There are 4 nucleotide bases that make up our DNA these are A,C,G,T therefore for each base in the DNA takes up 2bits. There are around 2.9billion bases so thats around 700 megabytes. The weird thing is that would fill a normal data cd! coincidence?!?
Answer: Most answers except users slayton, rauchen, Paul Amstrong are dead wrong if its about pure storage one-on-one without compression techniques.
The human genome with 3Gb of nucleotides correspond with 3Gb of bytes and not ~750MB. The constructed "haploid" genome according to NCBI is currently 3436687kb or 3.436687 Gb in size. Check here for yourself.
Haploid = single copy of a chromosome.
Diploid = two versions of haploid.
Humans have 22 unique chromosomes x 2 = 44.
Male 23rd chromosome is X, Y and makes 46 in total.
Females 23rd chrom. is X, X and thus makes 46 in total.
For males it would be 23 + 1 chromosome in data storage on a HDD and for females 23 chromosomes, explaining the little differences mentioned now and then in answers. The X chrom. from males is equal to X chrom. from the females.
Thus loading the genome (23 + 1) into memory is done in parts via BLAST using constructed databases from fasta-files. Regardless of zipped versions or not nucleotides are hardly to be compressed. Back in the early days one of the tricks used was to replace tandem repeats (GACGACGAC with shorter coding e.g. "3GAC"; 9byte to 4byte). The reason was to save harddrive space (area of the 500bm-2GB HDDD platters with 7.200 rpm and SCSI connectors). For sequence searching this was also done with the query.
If "coded nucleotide" storage would be 2-bit per letter then you get for a byte:
A = 00
C = 01
G = 10
T = 11
Only this way you fully profit from positions 1,2,3,4,5,6,7 and 8 for 1 byte of coding. For example the combination 00.01.10.11 (as byte 00011011) would then correspond for "ACTG" (and show in a textfile as an unrecognizable character). This alone is responsible for a four times reduction in file-size as we see in other answers. Thus 3.4Gb will be downsized to 0.85917175 Gb... ~860MB including a then required conversion program (23kb-4mb).
But... in biology you want to be able to read something thus compression gzipped is more than enough. Unzipped you can still read it. If this byte filling was used it becomes harder to read the data. That's why fasta-files are plain-text files in reality.
Comment: ZF007, you missed my point about minimality. The question was: "How much memory would be *required* to store human DNA?" with further detail "...I'm looking for *minimal* value that would be able to store DNA of any human."
You are [trying to answer a different question](https://en.wikipedia.org/wiki/Attribute_substitution), namely "How much memory would it take to store human DNA *in a readable form used by biologists to communicate genome data*?"
if you compress the readable text data with good compression algorithm, that will bring its size well below 2 bits per basepair.
Comment: The point is, that 1 out of 4 base pairs are coded with 2 bits of information. This is how much data is *required* to code it - you cannot code with less. But you may choose to code it in a different way: you may use a whole byte, or draw a picture which takes few kB, or make an audio recording. All this would still allow to store required information, but that would not be *required* or *minimal* coding. You  arbitrarily imposed readability criteria (using standard text editor), which is not what was asked in original question.
Comment: You can as well store it as a pictire or audio recording, or even video - and it will take terabates to store. But this is not *required* and *minimal*, as it was asked.
Comment: @il--ya... I'm missing the point you try to make... (I guess you like moving around 250km of TDK tape.. weighing 600kg and takes three hours to rewind)?
Comment: That is unfortunately not how it works in biology. The method of communication between scientists is either verbally, paper or textfile-formats that can easily be read from a screen. In the case you have one base-pairs, filling a byte with zeros or ones will suffice. However, there are 4 bases (2 pairs). In a byte you have 4 positions for a basepair and 4 positions that indicate the type of basepair. Data-compression works but humans need readability. A single pixel in RGB code (3 values and an intensity value) uses 32byte. Mere 8 bits for a letter. Thus no point to make it a Mona Lisa, right?
Comment: as stated by OP ***I'd like to see how others would approach this issue***. Addressing this issue means to keep information humanly readable without required fancy tools to install which is a general NO-GO Life Sciences. **Minimalism** as you state it il--ya is basically an encode/encrypt/compression operation on the binary code string and thus becomes unsearchable. Also, from a long term perspective continues compression/decompression actions on a more or less unaccessible dataset slows down a genome/chromosome search tremendously which costs more money than an extra SDD/HDD or 2gig of RAM.
Comment: Good answer.  That link isn't working at the moment however by the way.
Comment: @sdanse ... seems an expired link indeed. It can be found here with some effort if you download the fasta yourselves: https://www.ncbi.nlm.nih.gov/grc/human/data
Comment: @sdanse ... here it is: https://ftp.ncbi.nih.gov/genomes/Homo_sapiens/ARCHIVE/BUILD.37.3/
Answer: All answers are leaving off the fact that nuDNA is not the only DNA that defines a human genome. mtDNA is also inherited and it contributes an additional 16,500 base pairs to a human genome, bringing it more in line with the Wikipedia guess of 770MB for males, and 756MB for females.
This does not mean that a human genome can easily be stored on an 4GB USB stick. Bits do not represent information by themselves, it is the combination of bits that represent information. So in the case of nuDNA and mtDNA, the bits are encoded (not to be confused with compressed) to represent proteins and enzymes that in themselves would requires many MBs of raw data to represent, especially in terms of functionality.
Food for thought: 80% of the human genome is called "non-coding" DNA, so did you actually really believe that the entire human body and brain can be represented in a mere 151 to 154MBs of raw data?
Answer: One base -- T, C, A, G (in the base-4 number system: 0, 1, 2, 3) -- is encoded as two bits (not one), so one base pair is encoded by four bits.
Comment: Except that bases in a pair compplement each other, so don't add any information. So both base and base pair can be encoded with two bits.
Comment: @RogerJohansson No, only the "AT" base pair is valid in DNA. Likewise for "TA", "CG" and "GC". No other base pair combination exists.
Comment: @ZF007 They exist but they do not occur stably in human genomes and are therefore not relevant for genome storage. Their biological relevance is important only in the context of mutations (and there only transiently) and RNA modifications. In particular (in the context of this answer), genomic data isn't stored as "base pairs", it's stored as a sequence of single bases, and each position can be encoded in two bits. This isn't theoretical, this is how it's *actually* done (except that, for most applications, genetic data is stored in (gzipped) ASCII, not bit-compressed).
Comment: If you have an "A" what do you complement it with?
"AC" "AG" "AT" are all valid.

Likewise, if you have "T" the "TG" "TC" "TA" are valid

, So what do you do?
Comment: @KonradRudolph there are at least nine purines (https://en.wikipedia.org/wiki/Purine). All of them can be used to substitute A or G. This would make the solution to OP's question more complex. I agree to keep it simple and stick to A, G, T and C.
Answer: There is only 2 types of base pairs, Cytosine can only bind to Guanine, and Adenine can only bind to thymine,
So each base pair can be considered a single bit.
This means that an entire strand of Human DNA ~3 billion "Bits" would be right around ~350 megabytes.
Comment: You have 2 types of pairs, and they can be in two directions - so you need two bits for each pair. This is why most posts above write ~700MB, and not 350MB.


User accounts authentication from Active Directory

Question: I'm looking into Active Directory user account authentications.The situation is like this.I have a Forest DC at data centre 1, and infrastructure child DC at some site.
I want the infrastructure servers administrative user accounts authenticated from the Forest DC, and the other user accounts at the site to be authenticated from the infrastructure child DC at the site.
My question is, is this a good approach, or it is better to have all accounts authenticated at the Forest DC.
The advantage I see with my approach is that in case WAN is down, the infrastructure child DC will be able to authenticate the local user accounts. In case all accounts are authenticated at Forest DC and WAN is down the accounts cannot be authenticated at all, unless I have AD replication of Forest DC at the site ?
Or is it that once the infrastructure child DC join the Forest they will have AD replication automatically ?
Could someone elaborate on this approach.
Thank You
Comment: If you want to make it such that the forest users can be authenticated at any site when the WAN link is down you either need to 1) allow for cached logons (which I am against - especially for administrative accounts), and/or 2) provide a DC for each domain in each site.
Answer: Users authenticate to Domain Controllers in the domain to which they belong.
The Domain partition does not replicate to other domains in the Forest. Attributes marked for Global Catalog replication will replicate to all Global Catalog servers in the Forest, but user and computer accounts in the Domain partition do not replicate to other domains in the Forest.
Comment: I believe I might not be clear enough.

I have a forest DC a.local, 3 child dcs (b.a.local, c.a.local, d.a.local) in the same forest and same site.

I want to have the child DCs authenticate from the Forest DC (main DC), and the clients to authenticate from the child DC because as I see if all authentication is done at forest DC and WAN is down then the clients AND child DCs wont be able to authenticate.

My question is is this a good approach, unlike where all end clients, and child DCs authenticate from the Forest DC due to the reason given above.


Polynomial with Certain Conditions

Question: Is it possible to create a polynomial $p(x)$, in terms of $a,b,c \geq0, \in\mathbb{R}$ and $\epsilon >0, \in \mathbb{R}$, has a fixed degree (aka, a degree $n$ that does not depend on $a,b,c, \epsilon$), $p(0)=a$, and on $[b,c]$, $|p(x)| \leq \epsilon$?
EDIT: I will also accept the specific case of $\epsilon=1$ and $b \in [0.1,0.9]$
Comment: "can be anything" must be precised: to you mean that you want to know whether for any set of positive numbers $a,b,c,\epsilon$ there exists a degree $n$ such that ... ?
Comment: Do you mean that $a,b,c,\epsilon, n$ (where $n$ is the degree) are defined beforehand? In this case, the answer is no in general.
Comment: @JeanMarie Yes, $a,b,c, \epsilon$ are all defined beforehand, but degree $n$ can be anything, as long as it doesn't change depending on $a,b,c, \epsilon$.
Comment: @JeanMarie Yes.
Answer: Let $n$ denote the degree of the polynomial.
First case) If the question is with quantifiers in this order $\forall a,b,c,\epsilon,  \ \exists n$ etc. (therefore $n$ is function of $a,b,c,\epsilon$) the answer is "yes". Here is why.
For didactic reasons, I will consider first the particular case $a=1,b=1,c=3$.
Consider Chebyshev polynomials $T_k$ (https://en.wikipedia.org/wiki/Chebyshev_polynomials),
known to be such that:
$$|T_k(x)| \le 1 \ \ \ \text{for} \ \ -1 \le x \le 1$$
Then define:
$$t_k(x):=\dfrac{1}{T_k(-2)}(x+1)T_k(x-2)$$
Therefore we have $t_k(0)=1$ and
$$\max_{1 \le x \le 3} t_k = \dfrac{3}{T_k(-2)}$$
The result follows because we can take $k$ such that $|T_k(-2)|$ is
as large as we want.
In the general case, consider the inverse of transformation $X=\dfrac{c-b}{2}x+\dfrac{b+c}{2}$ that maps line segment $x \in [-1,1]$ onto $X \in [b,c]$.
$ t_k(x):=\underbrace{\dfrac{a (c+1)}{T_k(\tfrac{b+c}{b-c})}}_{A} * \dfrac{(x+1)}{(c+1)} *
T_k\left(\dfrac{2x-(b+c)}{c-b}\right)\tag{1}$
(please note that the $(c+1)$ expressions can be cancelled. Now let us examine (1):

The two conditions are fulfilled.

As the middle expression is bounded by $1$, we just have to make sure that expression (A) can be made arbitrarily small. This will be done by playing on degree $k$: indeed Chebyshev polynomial $T_k(x)$ for $x$ outside $[-1,1]$ can be written:

$$T_k(x)=\cosh(k \ \text{arccosh}(x))\tag{2}$$
therefore can be made arbitrarily large for any $x$ outside $[-1,1]$ (which is the case here for $x=-\tfrac{b+c}{c-b}<-1$).
Second case) If, on the contrary (it was not the way I had understood the question) the question is with quantifiers in this order:
$"\exists n$ (such that) $\forall a,b,c,\epsilon$, one can find a polynomial verifying the two conditions", the answer is "no".
Edit: Here is why. Let us fix for example the degree $n$ to $4$. Do we agree that your issue is equivalent to disprove the fact that if a polynomial $p(x)$ is such that :
$$\max_{x \in [-1,1]} p(x) \in [-1,1] \ \text{and prove that} \ p(-2) \ \text{can't be arbitrarily large} ?\tag{3}$$
(it will be easier to make a reasoning on interval $[-1,1]$ and arbitrary value $x_0=-2$ instead of $[0.1,0.9]$ and $x_0=0$ in order to avoid transformations of polynomials $T_n$).
Let us expand $p(x)$ on the basis of polynomials $T_n(x)$ (for $n\leq 4$):
$$p(x)=\sum_{k=0}^4 a_kT_k(x)\tag{4}$$
Due to condition (3), and the fact that $\max_{x \in [-1,1]}|T_k(x)|=1$:
$$\sum |a_k| \leq 5 \tag{5}$$
Using now relationship (2):
$$p(-2)=\sum_{k=0}^4 a_k \cosh(k \ \text{arccosh}(-2))$$
which is a bounded quantity due to (5).
Therefore $p(-2)$ cannot achieve arbitrary large values.
Comment: Also, after testing it, I do say it works, so even though it's not *exactly* what I wanted, it's good enough, so I'll wait a bit before accepting. +1 from me!
Comment: If we can achieve $|f(x)| \le \epsilon$ for any positive $\epsilon$, $\epsilon = 1$ is just a particular case. But maybe you mean something else ?
Comment: Yes, I'm referring to a specific case, please see the **EDIT** to the question.
Comment: Good enough for me. Accepted!
Comment: @DUO Thanks. Besides, I propose you to erase the different comments/exchanges we have had that have no interest for future readers.

Polynomial with Certain Conditions


Theme specific Drupal modules? Possible?

Question: Anyone know if it is possible to have Drupal modules enabled/active only when a current theme is present?
Working on a feature where I only need one module to be enabled when the site is accessed via a specific theme controlled by the ThemeKey module in Drupal 7.
Comment: Maybe you can disable not the module, but the effects of that module (the basic example is disabling a block in a specific theme). What are the effects that you want to disable?
Comment: In short I just need to make sure that for a specific theme of mine not to execute the actions of the Front Page Module which redirects a user to a different URL. The idea is for my mobile theme where it is a shell site with links to an iframe. Example is [here via iOS](http://www.openreporter.org/m/) where the content is actually just a bare-bone theme fed through and iFrame. Viewable only on iOS.
Comment: (Context mobile detect)[http://drupal.org/project/context_mobile_detect] is a lightweight module that detect if user is using a mobile browser. Could be useful?
Comment: It works for blocks and such but nothing in regards to disabling modules. But we may be going in the right direction. Perhaps there is some PHP code we can add on to showcase modules as a selectable option.
Answer: Themes are enabled/disabled in Drupal by altering the flag in the database table system. And these settings are common for all the users irrespective of which device/ how they are accessing your page.
So in your case it is about making sure that only the files from necessary modules are loaded based on the current theme.
You can use $theme global variable to find out the current theme, and then based on that you can fetch the files from the necessary modules only. You can check the code from js module how the second part can be implemented. You need to have patience though ;)
Comment: Ok. Just so I understand in my templates file add a function that will do this? http://api.drupal.org/api/drupal/includes%21database%21database.inc/function/db_query/7
Answer: It might be possible, with some hacks, but definitely is not built in and nothing I would encourage. Modules configuration is global. Enabling and disabling them is often slow, as no one bothers to optimize something that is meant to occur once in the lifetime anyway. So allowing this would kill your performance.
Second problem is cache. Proxies can, and often will serve responses from cache, even redirections. So your site might not be able to even know what type of browser accessed it. It might be unable to even notice it is accessed.
Last but not least, if search engine robot detects you serve it different content than you serve to it's clients, your position in result will go down the drain. They are pretty good at detecting changes in theming, but different module sets are only needed if you want to generate actual content differently, or to decide if to perform redirection. Both actions are no-go for SEO purposes.
TL;DR : Probably possible. Don't do it.


XAMPP MySQL batch file

Question: I am using XAMPP to run Apache, PHP and MySQL on a bunch of remote laptops for our clients.  It is just the XAMPP directory with all the files (thumbdrive version, no registry values are added or modified).  I have an install file that puts an icon on the user's desktop that runs start.bat from the XAMPP directory.  Start.bat basically starts Apache, then MySQL, and then opens a browser to localhost.  Everything works great, except that when the icon is clicked the second time, a second mysqld.exe service starts.  Apache does not start twice if the icon is clicked twice, but MySQL does.  I've tried several Google and Stack Overflow suggestions to check if a service is running and, if so, stop the service from starting again; however, none of those worked.
The batch file that starts MySQL basically has this one command:
<code>mysql\bin\mysqld --defaults-file=mysql\bin\my.ini --standalone --console
</code>
How can I keep mysqld.exe from starting twice?  Also, is it a big deal if it is running twice?  Will that cause any problems when running a query from PHP?
Answer: I also posted this on StackOverflow (one of our other devs asked the same question).  Here is the answer I found through trial and error (and prayer!):
Modify mysql_start.bat to have this content:
<code>@echo off
apache\bin\pv mysqld.exe %1 >nul
if ERRORLEVEL 1 goto Process_NotFound
echo MySQL is running
goto END
:Process_NotFound
echo Process %1 is not running
mysql\bin\mysqld.exe --defaults-file=mysql\bin\my.ini --standalone --console
goto finish
:finish
</code>
This checks if the service is running and starts it if not.

XAMPP MySQL batch file


Java Placing Tetris Like Blocks Algorithm

Question: So I've been working on this game, in java, I've gotten it working using python and pygame, but when I tried to port it to java using libgdx, I cannot figure out what I am doing wrong, it will compile, however when it runs pieces will overlap, and I'm not completely sure the reasoning  for that. I have if (!ICERECTANGLES.contains(CURRENTRECT)) Which should prevent this from happening, however it does not appear to be stopping this incident.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Rectangle;`

Map<Integer, int[][]> ICEBLOCKS = new HashMap<Integer, int[][]>();
Map<Integer, int[][]> PIECES = new HashMap<Integer, int[][]>();

private void iceBegin(){
    int PIECESADDED = 0;
    Random RANDOM = new Random();
    for (int x = 0; x < BOARDWIDTH; x++){
        for (int y = 0; y < BOARDHEIGHT; y++){
            System.out.println( x + ", " + y);
            int LOOPNUM = 0;
            boolean FIT = false;
            while (!FIT){
                LOOPNUM += 1;
                if (LOOPNUM == 5) break;
                //Arrange the dictionary/array containing all of the pieces
                Map<Integer, int[][]> PIECESDICT = new HashMap<Integer, int[][]>();
                int[][] first = new int[][]{ {0,0}, {0,1}, {0,2}, {1,1} };
                PIECESDICT.put(1, first);
                int[][] second = new int[][]{ {0,0}, {0,1}, {1, 1} };
                PIECESDICT.put(2, second);
                int[][] third = new int[][]{ {0,0}, {0,1}, {1,0} };
                PIECESDICT.put(3, third);
                int[][] fourth = new int[][]{ {0,0}, {0,1}, {1,0}, {1,1} };
                PIECESDICT.put(4, fourth);
                int[][] fifth = new int[][]{ {0,0}, {1,0}, {2,0} };
                PIECESDICT.put(5, fifth);
                int[][] piece = new int[1][4];
                piece = PIECESDICT.get(RANDOM.nextInt(PIECESDICT.size()) + 1);
                int[][] PIECE = new int[piece.length][2];
                // fails in this for loop!!!!
                for (int i = 0; i < piece.length; i++){
                    PIECE[i][0] = piece[i][0];
                    PIECE[i][1] = piece[i][1];
                }
                //forward_backward determines whether the piece will be facing forward or backwards
                //also known as left or right
                boolean for_back = RANDOM.nextBoolean();
                if (for_back){
                    for (int[] P: PIECE){
                        if (P[0] > 0) P[0] = P[0] * -1;
                    }
                }
                boolean PIECETRUE = true;
                // Makes sure that the block will fit without overlapping any other pieces
                for (int[] item: PIECE){
                    item[0] = item[0] + x;
                    item[1] = item[1] + y;
                    if (item[0] <= BOARDWIDTH && item[0] >=0){
                        if (item[1] <= BOARDHEIGHT && item[1] >= 0){
                            Rectangle CURRENTRECT = new Rectangle();
                            CURRENTRECT.x = item[0] * 50;
                            CURRENTRECT.y = item[1] * 50;
                            CURRENTRECT.width = 50;
                            CURRENTRECT.height = 50;
                            if (!ICERECTANGLES.contains(CURRENTRECT)){
                                PIECETRUE = PIECETRUE;
                            }
                            else PIECETRUE = false;
                        }
                        else PIECETRUE = false;
                    }
                    else PIECETRUE = false;
                }
                //then if piece fits add the rectangles to the rectangle array, and also add the PIECE to the PIECES array
                if (PIECETRUE == true){
                    PIECES.put(PIECES.size(), PIECE);
                    for (int[] item: PIECE){
                        Rectangle CURRENTRECT = new Rectangle();
                        CURRENTRECT.x = item[0] * 50;
                        CURRENTRECT.y = item[1] * 50;
                        CURRENTRECT.width = 50;
                        CURRENTRECT.height = 50;
                        ICERECTANGLES.add(CURRENTRECT);
                        ICEBLOCKS.put(ICEBLOCKS.size(), item);
                        PIECESADDED += 1;
                        System.out.println("New Piece Added: " + CURRENTRECT);
                    }
                    PIECES.put(PIECES.size(), PIECE);
                    break;
                }
            }
        }
    }

In case you are wondering exactly what I want it to do here is the Python code that it is supposed to duplicate.
def randomPieces():
global PIECESPOS
POINTSTAKEN = []
PIECESPOS = {}
MovesAv = True
for x in range(BOARDWIDTH):
    for y in range(BOARDHEIGHT):
        PIECESDICT = {1: [[0,0], [0,1], [0,2], [1,1]], 2: [[0,0], [1,0], [0,1]], 3: [[0,0], [0,1], [1,1]], 4: [[0,0], [0,1], [1,0], [1,1]], 5: [[0,0], [1,0], [2,0]]}
        NUMTIMES = 0
        FIT = False
        while FIT != True:
            NUMTIMES += 1
            if NUMTIMES == 50:
                FIT = True
            piece = PIECESDICT[random.randint(1, len(PIECESDICT))]
            PIECE = []
            for item in piece: PIECE.append(item);
            for_back = bool(random.randint(0,1))
            if for_back:
                for item in PIECE:
                    if item[0] > 0: item[0] = item[0]*(-1);
            PIECETRUE = True
            for item in PIECE:
                item[0], item[1] = (item[0] + x), (item[1] + y)
                if item[0] <= BOARDWIDTH and item[0] >= 0:
                    if item[1] <= BOARDHEIGHT and item[1] >= 0:
                        if item not in POINTSTAKEN:
                            if PIECETRUE:
                                PIECETRUE = PIECETRUE
                        else:
                            PIECETRUE = False
                    else:
                        PIECETRUE = False
                else:
                    PIECETRUE = False
            if PIECETRUE:
                PIECESPOS[len(PIECESPOS)] = PIECE
                for item in PIECE: POINTSTAKEN.append(item)
                FIT = True

I would appreciate any guidance and advice on how to manipulate the algorithm to allow for no overlapping and not every single coordinate taken.
Answer: int[][] PIECE = {};

creates an array of size 0.
Hence these statements
PIECE[i][0] = piece[i][0];
PIECE[i][1] = piece[i][1];

will not work.
You might want to change
int[][] PIECE = {};

to
int[][] PIECE = new int[x][y];//eg. int[][] PIECE = new int[2][4];


How to get rid of a duplicate title on the front page?

Question: When I first made the front page, I created a Basic Page and selected "Promoted to Front Page" and thought I was done.  Drupal insisted on showing this page as an article summary, and no manner of tweaking settings on my part prevented this behavior.  I decided instead to put the main front page content in a block because it will seldom ever change.
I created my block, and yay!  No more summarized front page content.  However, the title of the page shows twice.  The first is the title of the original basic page I created, the second is the title of the block I created.  I've already cleared the cache and there was no change.
How do I get rid of the duplicate?
Comment: What does your page.tpl.php file look like?
Answer: It sounds like you have node as your front page which lists summaries of content that is promoted to the front page by default. That's the way Drupal comes configured out of the box. If I understand correctly, what you're looking for though is a single node to be displayed in full on the front page.
You can change it from node (which shows a list) to your specific Node at admin/config/system/site-information or Configuration -> Site Information under the "Front Page" section. Simply change "node" to "node/[node-id]" where [node-id] = the nid of the node you want to appear on the front page:
Comment: This the solution I was looking for in the first place before setting up a block.  It's been ages since I've had to set up a Drupal website and I missed this.  Thank you! :)
Answer: I will address your situation by telling you both the solution to your previous problem, followed by your current conundrum.
The "promoted to front page" option is intended to be a list of several things (think of the front page of a blog).  If you want a single front page, then change the settings for the front page (under admin/config/system/site-information).  It is currently set to "node", which is a list of everything that is "promoted to the front page".  Instead, change it to "node/#" (where "#" is the number of the node itself).
The other option is the way that you did it.  It works, but as you see, it's a bit of a kludge.  You can hide the title of the block by editing the block contents.  There are 2 titles, so to speak.  One is used for identification on the block administration page (the description), and one is for display (the title).  Just leave the title blank.
Answer: Assuming you want to keep the block as your page content rather than setting a node to be displayed as the front page, there are a few ways to get rid of the title on the front page.  Preferably using CSS since you don't have a H1 anywhere else on the page.
.front .page__title {
  display: none;
}

Or you could remove it completely by duplicating your themes page.tpl.php > removing the line that prints the page title > saving it to your templates folder as page--front.tpl.php
Comment: I didn't wish to keep the block, but did it because I didn't initially see the option to set a single node as the front page.  Thanks anyway. :)


What is the mistake I made that cannot read the length of the array object?

Question: public int addFighter()
{
    if(team==null)
    {
        Team[] team=new Team[1];//increase the size by 1 from null to 1
        team[0]=new Team(); //calling default constructor
        return team.length;//the array length here is printable
    }

}

I have a setter to save added information:
public void setData(String type, int healthUnits)
{
    int length=this.team.length;//NullPointerException
    this.team[length-1].setType(type);
    this.team[length-1].setHealth(healthUnits);
}

What is my problem here?
In addFighter(), when I check the array object is null, then I declare the array size is 1, and initialize team[0] by calling default constructor. It can read the length of array object is 1 in addFighter(), but why the length cannot be read in setData(), since I already initizlized the array object from null to 1?
From my understing, NPE happens when uninitizlized variable or object being called, but why in my case, NPE happends when my object is initizlized?
I don't know what mistake I made, need some inspirations. Thanks :)
Comment: When you have `Team[] team=new Team[1];` in that `if` block, you are NOT setting the value of `this.team` to the array you're instantiating. You're creating anew array variable in the scope of that if block. You should have `this.team = new Team[1]`
Comment: Did you meant to write `Team[] team=new Team[1];` as `this.team=new Team[1];`?
Answer: Team[] team=new Team[1];

The way you have written this line creates a new variable, also named team, with no relationship whatsoever to this.team.
The correct way to do what you want is to replace this line with
team=new Team[1];

Comment: Thank you so much for helping me find my problem out! Thanks!
Answer: Use this instead,
public int addFighter()
{
    if(team==null)
    {
        team=new Team[1];//increase the size by 1 from null to 1
        team[0]=new Team(); //calling default constructor
        return team.length;//the array length here is printable
    }

}


CollectionView: Changing scroll direction of each section individually

Question: I have a collectionView with 3 sections. I want to change the scroll direction of section 1 without adding an extra collectionViewController inside the section cell. Is it possible to achive this with using only 1 collectionView?
Answer: You can do this by dropping UiCollectionView into Uitableview cells.
enter link description here
Answer: you can put multiple UICollectionView in UITableViewCell set the UICollectionViewFlow and then set the scrollDirection example shown below for rough idea.
enter image description here
Answer: Set the scrollDirection of the collection view's collectionViewLayout.
Docs are
https://developer.apple.com/reference/uikit/uicollectionviewflowlayout#//apple_ref/doc/uid/TP40012182-CH1-SW6


Drupal Module for arranging Nodes of special type into a table||chart

Question: I'm trying to map Nodes of special Types on the basis of their field datas in a table or a chart.
The table should look like this:Table Example
Explanation: Table Header and first row are the datas of two specified fields. The node titles (rest of table) are mapped on the free table rows/columns according to their field values. Since i got no solution for this i tried to look for an approach with graphs. But it doesn't turn out as an easier way.
Maybe i've overlooked something. I would be really glad if anybody have a solution for this problem.
Answer: I'm really glad that I found a good and comfortable solution for my problem.
There are two modules available: Views Table Group, Views Merge Rows
At the beginning, I had some problems with the settings. After a few tryings I got along with these:  check "Use values of this field as a filter" instead of "Use the first value of this field"
Note: I've just seen the merged rows logged out! So you had to change the visibility/accessibility settings or just log out to check the table.
My result:


A composition of projections with three fixed points -- is it necessarily the identity?

Question: We are given a line $l$. The line is mapped onto itself through a series of projections that involve other lines and -- importantly! -- conics. In the end, points $A$, $B$, and $C$ on $l$ appear to be mapped to itself. Is the composition of projections the identity?
I prove that it is, but I'm not sure about the proof. Could someone verify, please?
Proof. I prove by choosing an arbitrary point $O$ on line $l$. The cross-ratio of $O,A,B,C$ is then given by $\frac{OB}{AB}\cdot\frac{AC}{OC}$. Now assume the transformation sends $O$ to some point $O'$. Since we work only with lines and conics, the cross-ratio is preserved, so we have:
$$
\frac{O'B}{AB}\cdot\frac{AC}{O'C}=\frac{OB}{AB}\cdot\frac{AC}{OC},
$$
or
$$
\frac{O'B}{O'C}=\frac{OB}{OC}.
$$
Now one needs to examine several cases of relative positions of points $O,O',B,C$, also keeping in mind that the distances are signed. This is straightforward and in all of them either $O'O=0$ or it doesn't have a solution, which proves the claim. End of proof.
Would that be good enough?
Answer: Yes, you proof seems to be correct, provided you mean what I think you mean with "projections involving lines and conics". I assume you mean projections onto another line w.r.t. a point (not lying on any of those two lines) and stereographic projections onto conics. Also note that the first kind of projection can be seen as a special case of the second kind (using a degenerate conic consisting of two lines).
You could also argue this differently: A bijection $f$ on a line which preserves cross-ratios (in the real case it even is sufficient for $f$ to map harmonic quadruplets to harmonic quadruplets) must be a projective transformation. And a projective transformation on a line is uniquely determined by the image of three points, so if $f$ has three fixed points it must be the identity.


Proving $\left(a+\frac{2}{a}\right)^2+\left(b+\frac{2}{b}\right)^2\ge \frac{81}{2}$ for all positive real $a,b$ such that $a+b=1$

Question: I approached this problem in two different ways, but only one was successful. I'll post the latter as an answer, while here follows the first approach:
I expanded the squares:
$$a^2+\frac{4}{a^2}+4+b^2+\frac{4}{b^2}+4\ge\frac{81}{2} \\ a^2+b^2+\frac{4}{a^2}+\frac{4}{b^2}\ge \frac{65}{2}$$ and then multiplied both sides by $a^2b^2$ to get $$a^2b^2(a^2+b^2)+4(a^2+b^2)\ge\frac{65}{2}a^2b^2 \\ (a^2+b^2)(a^2b^2+4)\ge\frac{65}{2}a^2b^2, $$ which, combining $a+b=1$ and $(a+b)^2=a^2+b^2+2ab$, can be rewritten as $$(1-2ab)(a^2b^2+4)\ge\frac{65}{2}a^2b^2.\tag{$\star$}$$ Setting $c=ab$ makes $(\star)$ an inequality in one variable, but it didn't help me. Is this totally the wrong track? And, I was wondering if there are other approaches besides what I came up with.
Answer: The function $f: x \mapsto (x+\frac2x)^2$ is convex on $(0,\infty)$, so by Jensen's inequality we have
$$
\frac{\left(a+\frac2a\right)^2+\left(b+\frac2b\right)^2}{2} = \frac{f(a)+f(b)}{2} \geq f\left( \frac{a+b}{2} \right) = f\left(\frac12\right) = \left( \frac92 \right)^2 = \frac{81}{4}.
$$
Comment: Nice! Thank you, I didn't know Jensen's inequality.
Answer: To begin with, we note that equality occurs when $a=b=1/2$. Thus, assuming WLOG $a>b$ and using $b=1-a$, let us  differentiate the LHS to show it is increasing: $$2\left(a+\frac{2}{a}\right)\left(1-\frac{2}{a^2}\right)+2\left(1-a+\frac{2}{1-a}\right)\left(-1+\frac{2}{(1-a)^2}\right)>0 $$ $$ \left(a+\frac{2}{a}\right)\left(1-\frac{2}{a^2}\right)>\left(1-a+\frac{2}{(1-a)}\right)\left(1-\frac{2}{(1-a)^2}\right).\tag{1}$$ Again, we differentiate to show the LHS of $(1)$ is increasing: $$\left(1-\frac{2}{a^2}\right)^2+\frac{4}{a^3}\left(a+\frac{2}{a}\right)>0$$ whereas its RHS is decreasing: $$-\left(1-\frac{2}{(1-a)^2}\right)^2-\frac{4}{(1-a)^3}\left(1-a+\frac{2}{1-a}\right)<0,$$ and we are done.
Answer: your calculations are ok, we are looking at the inequality $$(1-2c)(c^2+4)\geq \frac{65}{2}c^2$$ with $c=ab$ for $c$ we get $$a^2+b^2=1-2ab\geq 2ab$$ from here we get $$\frac{1}{4}\geq ab=c$$ and our inequality is equivalent to $$\frac{-1}{2}(4c-1)(c^2+16c+8)\geq 0$$
ready.
Comment: A friendly advice: It looks like you're translating the German word *fertig* as "ready". This however is not idiomatically correct. Use "done" instead.


How to locally extend Base operator in Julia (in module)

Question:
I don't know how to locally extend a Base operator and I couldn't find anything about that.
I can obviously redefine it in the global scope (REPL or module) doing :
import Base.-

-(x, y::Nothing) = nothing
-(x::Nothing, y) = nothing

But I would like to have this to stay private in my module and not exported automatically to the global scope, in order not to pollute it, and still be able to use extensions in some functions in the module.
I tried let ... end blocks or even to redefine it inside my module's functions but it seems to prevent from importing Base properly.
I would like something like :
module MyModule
export my_visible_function

function -(x, y::SomeType)
# Base.- extension with x and ::SomeType
end

function my_visible_function()
# code using Base.- extension
end

end

Is there anyway to do that?
Thanks for help.
Answer: You can create your own - function that shadows Base.:- within your module. This will work as long as Base.:- is not explicitly called before you define your - function in your module. (More on that below.)
Then you can define your - function in such a way that it falls back to Base.:- for most calls.
Here's an example:
module A
export foo

-(::Any, ::Nothing) = nothing
-(x, y) = Base.:-(x, y)
foo(x, y) = x - y

end

julia> using .A

julia> foo(1, 3)
-2

julia> foo(1, nothing)

julia> 1 - 3
-2

julia> 1 - nothing
ERROR: MethodError: no method matching -(::Int64, ::Nothing)

Here's an example that shows that it's ok to use Base.:- in a function definition before you define your own - function:
# This works.

module B
export foo, bar

bar(x, y) = Base.:-(x, y)

-(::Any, ::Nothing) = nothing
-(x, y) = Base.:-(x, y)

foo(x, y) = x - y

end

The only time this won't work is if you explicitly call - (from Base) before you define your own -. Here's an example of that:
julia> module C
       export foo

       1 - 3
       -(::Any, ::Nothing) = nothing
       -(x, y) = Base.:-(x, y)
       foo(x, y) = x - y

       end
ERROR: error in method definition: function Base.- must be explicitly imported to be extended


Are transgender people allowed to play tennis on the WTA/ATP tour?

Question: Are transgender people allowed to play tennis on the WTA & ATP tours as their non-original gender? I know that Renee Richards was the first one to play at a Grand Slam, about 20 years ago.
Does the rulebook accept deny entry currently for people who have changed sex? Are the rules different on ITF & ATP/WTA circuit?
I know this question can be asked of any sport, but I am restricting it to tennis only.
Answer: WTA
In short, male to female transitions can participate under a set of conditions with respect to gender identity, hormonal treatment, and testosterone levels. Female to male transitions cannot participate if they are going through hormonal treatment.
WTA defines this in their Gender Participation Policy, most recently updated in December 2016:

The following guidelines set forth the eligibility of entry into and
  participation of transgender players in WTA Tournaments:
A) A player
  who transitions from male to female (also known as a trans female
  (MTF)) is eligible to enter into and participate in WTA Tournaments
  under the following conditions:

i. The player has declared that her
    gender identity is female. The declaration cannot be changed, for
    purposes of entry into any WTA Tournament, for a minimum of four (4)
    years. 2
ii. The player undergoes hormonal treatment for gender
    transition and demonstrates that her total testosterone level in serum
    has been below 10 nmol/L for at least twelve (12) months prior to her
    first WTA Tournament (with the requirement for any longer period to be
    based on a confidential, case-by-case evaluation, considering whether
    or not twelve (12) months is a sufficient length of time to minimize
    any advantage during competition).
iii. The player's total
    testosterone level in serum must remain below 10 nmol/L throughout the
    period of desired eligibility to enter into and participate in any WTA
    Tournament. iv. Compliance with these conditions may be monitored by
    testing, which testing shall be administered in WTA's sole discretion
    based on standards of reasonableness and fairness and in consultation
    with physicians and medical experts. In the event of non-compliance,
    the player's eligibility for competition in WTA Tournaments will be
    suspended for twelve (12) months.

B)  A player who transitions from female to male (also known as a trans male (FTM)) is not eligible
  to enter into or participate in any WTA Tournaments if he is undergoing hormonal treatment
  for gender transition.

ATP
The policy in the ATP is less clear as it's not specifically addressed in the way the WTA addresses the matter (that I could find). This is addressed in "Entries" in rule 7.02 of the 2017 ATP Official Rulebook:

Gender / Age Limitation
ATP will use the age of a player on the first (1st) day of the qualifying competition.
  Male players age sixteen (16) or older are not limited in the number of tournaments
  they may enter.

However, in the Foreword under the "Exhibits" section, it states:

Note: Except where otherwise stated, every reference in these Rules of Tennis to the
  masculine includes the feminine gender.

I'm not sure if this means females are included as males, or because since mixed doubles rules are covered in the document, females and males are both referred to in the same manner (ie, s/he).

ITF
Transitions before puberty are recognized as the latter gender (ie, if an individual transitions from female to male before puberty, said individual will be recognized as male).
Transitions after puberty are eligible to participate in male or female competitions respectively with respect to surgery, legal gender identity, verifiable hormonal therapy, and two years after a gonadectomy.
The ITF goes into this in Appendix A of the 2017 ITF Pro Circuit Regulations:

Any individuals undergoing sex reassignment from male to female before
  puberty are regarded as girls and women (female), while those
  undergoing reassignment from female to male are regarded as boys and
  men (male).
Individuals undergoing sex reassignment from male to
  female after puberty (and the converse) are eligible for participation
  in female or male competitions, respectively, under the following
  conditions:

a. Surgical anatomical changes have been completed,
    including external genitalia changes and gonadectomy.
b. Legal
    recognition of their assigned sex has been conferred by the
    appropriate official authorities.
c. Hormonal therapy appropriate for
    the assigned sex has been administered in a verifiable manner and for
    a sufficient length of time to minimise genderrelated advantages in
    sport competitions.
d. Eligibility should begin no sooner than two
    years after gonadectomy.
Comment: I think "every reference in these Rules of Tennis to the masculine includes the feminine gender" means that if it says "if a player does X he will be penalized in Y manner" or "a player shall not make contact with ABC with his hand" applies to all players, not just male ones, and is irrelevant for this question.
Comment: FTM should be listed on ATP rulebook right?
Comment: @KharoBangdo I didn't find anything specific for the ATP. Doesn't mean it's not out there.


Flask button not getting detected

Question: What's wrong with my button click detector?
$('.start2').on('click', function() {

and here is the button
<button class="start2">START</button>

Comment: Could you explain more you problem ?
Answer: Nothing wrong you should just pass a callback function doing what you want,
Example:

$('.start2').on('click', function() {

  console.log("hello")
});

<button class="start2">START</button>
Answer: From What I can see you are missing }
$('.start2').on('click', function() {
  console.log('clicked!!!');
});

Answer: socket.on('connect', function() {
    socket.send('Admin connected');
});

$('.start2').on('click', function() {
    socket.send('dxdd');
});

The first function works, the second one doesn't.
Answer: You need to make it do something when it's clicked.
<button class="start2" onclick="return funcName(input_you_can_choose_to_not_have_it);">START</button>

Then you just need to add the code when the function (funcName) is called.
Like (In Javascript):

Did it help?

Flask button not getting detected


Expo FileSystem.uploadAsync with multiple files

Question: I got new requirements to support the upload of multiple files in a single request, in my Expo React Native app. The use case is submitting a case with data fields and attached files (so a multipart form request). I used to support a single file using Expo's: FileSystem.uploadAsync, and the code looks like this:
   const options = {
       mimeType: claimData.fileAttachment.mimeType,
       uploadType: FileSystemUploadType.MULTIPART,
       fieldName: "file",
       headers: {
          // Auth token and other headers
       },
       parameters: {
         // The data fields I mentioned
       },
     };

    return await uploadAsync(apiUrl, singleFileUrl, options);

After carefully reading the Expo docs of the FileSystem API
I haven't found any suggestion on how to handle multiple files, has anyone faced this before? How could I support it without doing a radical change in backend code.
Answer: Build a list of files to be uploaded then upload them as batch.
async function uplaodFile({ fileName, fileUrl }) {
  const options = {
    mimeType: claimData.fileAttachment.mimeType,
    uploadType: FileSystemUploadType.MULTIPART,
    fieldName: fileNmae,
    headers: {
      // Auth token and other headers
    },
    parameters: {
      // Extra fields
    },
  };

  return await uploadAsync(apiUrl, fileUrl, options);
}

async function uploadFiles() {
  const files = [
    {
      fileName: "File-01",
      fileUrl: "file://path/to/file1",
    },
    {
      fileName: "File-02",
      fileUrl: "file://path/to/file2",
    },
    {
      fileName: "File-03",
      fileUrl: "file://path/to/file3",
    },
  ];

  try {
    const uploadPromises = files.map(
      async (file) => await uploadFile({ ...file }),
    );

    const uploadResponses = await Promise.all(uploadPromises);
    //uploadResponses will contains list of file upload response (resolves & rejects)
  } catch (error) {
    console.error(error);
  }
}

Comment: I updated my question with more details. It needs to be a single request, isn't this multiple requests?
Comment: Promise.all will execute multiple file upload requests in parallel.
Comment: Alternative not work with standard Expo Go - https://www.npmjs.com/package/react-native-fs#file-upload-android-and-ios-only


orientation from acceleration?

Question: I have an object that has a sensor attached on it. This sensor calculates the acceleration in all axis and angular acceleration in all axis(Keep the gravity force in mind). How can I get the Pitch, Yaw and Roll(Orientation) from the known acceleration and angular acceleration values?
Answer: There is a body of literature on producing the navigation solution from these kind of inertial measurement sensors. Pitch, yaw and roll are interdependent outcomes of a double integration process that takes into account the interplay between the different components and the object they are attached to.
Gravity is a useful indicator in some situations and a distraction in others. Similarly the Earth's rotation can be important. One interesting effect of such a system is that measuring while stationary can be used to estimate the latitude, from the angle between the gravity vector and the Earth rotation vector.

orientation from acceleration?


Emulate http_file but for a file from another repository

Question: I'm including a repository that has an extra_deps rule of the form:
maybe(
    http_file,
    name = "external_dependency",
    downloaded_file_path = "foo.h",
    sha256 = "<some_sha>",
    urls = ["https://example.com/foo.h"],
)

If I have an existing repository, foo_repo, that provides foo.h, how can I substitute the target for it in place of external_dependency? http_file apparently provides @external_dependency//file, so I can't simply define an alias.
Answer: Using https://github.com/bazelbuild/bazel/blob/master/tools/build_defs/repo/http.bzl as a reference, you can define a custom repository rule that provides @external_dependency//file. For example:
def _repository_file(ctx):
    ctx.file("WORKSPACE", "workspace(name = \"{name}\")".format(name = ctx.name))
    ctx.file("file/BUILD.bazel", """
filegroup(
    name = "file",
    srcs = ["{}"],
    visibility = ["//visibility:public"],
)
""".format(ctx.attr.source))

repository_file = repository_rule(
    attrs = {"source": attr.label(mandatory = True, allow_single_file = True)},
    implementation = _repository_file,
    doc = """Analogue of http_file, but for a file in another repository.

Usage:
repository_file(
    name = "special_file"
    source = "@other_repo//path/to:special_file.txt",
)
    """,
)

Now use:
repository_file(
    name = "external_dependency",
    source = "@foo_repo//path/to:foo.h",
)


XML parser configured does not prevent nor limit external entities resolution. This can expose the parser to an XML External Entities attack

Question: We had a security audit on our code, and they mentioned that our code is vulnerable to EXternal Entity (XXE) attack.
Explanation- XML External Entities attacks benefit from an XML feature to build documents dynamically at the time of processing. An XML entity allows inclusion of data dynamically from a given resource. External entities allow an XML document to include data from an external URI. Unless configured to do otherwise, external entities force the XML parser to access the resource specified by the URI, e.g., a file on the local machine or on a remote system. This behavior exposes the application to XML External Entity (XXE) attacks, which can be used to perform denial of service of the local system, gain unauthorized access to files on the local machine, scan remote machines, and perform denial of service of remote systems. The following XML document shows an example of an XXE attack.
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE foo [
<!ELEMENT foo ANY >
<!ENTITY xxe SYSTEM "file:///dev/random" >]><foo>&xxe;</foo>

This example could crash the server (on a UNIX system), if the XML parser attempts to substitute the entity with the contents of the /dev/random file.
Recommendation- The XML unmarshaller should be configured securely so that it does not allow external entities as part of an incoming XML document. To avoid XXE injection do not use unmarshal methods that process an XML source directly as java.io.File, java.io.Reader or java.io.InputStream. Parse the document with a securely configured parser and use an unmarshal method that takes the secure
parser as the XML source as shown in the following example:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setExpandEntityReferences(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document document = db.parse(<XML Source>);
Model model = (Model) u.unmarshal(document);

And written code is below where found the XXE attack-
1- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
2- DocumentBuilder db = dbf.newDocumentBuilder();
3- InputSource is = new InputSource();
4- is.setCharacterStream(new StringReader(xml));
5-
6- Document doc = db.parse(is);
7- NodeList nodes = doc.getElementsByTagName(elementsByTagName);
8-
9- return nodes;

I am getting XXE attack on the line no 6.
Please help how can I resolve the above issue. Anyone help is appreciated !
Answer: For a detailed explanation and options for remediation I suggest you look at OWASP XEE Cheat Sheet
We had a similar issue raised and resolved it by disabling DOCTYPES (the first suggestion on the link above) as we didn't need them:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);

Answer: For javax.xml.parsers.DocumentBuilderFactory,the following setting would be enough to prevent XXE attack
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

// Disallow the DTDs (doctypes) entirely.
dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);

// Or do the following:
dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
dbf.setXIncludeAware(false);
dbf.setExpandEntityReferences(false);