问:
python logging module is not writing anything to file
I'm trying to write a server that logs exceptions both to the console and to a file. I pulled some code off the cookbook. Here it is:

```<code>logger = logging.getLogger('server_logger')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('server.log')
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
ch.setFormatter(formatter)
fh.setFormatter(formatter)
# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(fh)
</code>```

This code logs perfectly fine to the console, but nothing is logged to the file. The file is created, but nothing is ever written to it. I've tried closing the handler, but that doesn't do anything. Neither does flushing it. I searched the Internet, but apparently I'm the only one with this problem. Does anybody have any idea what the problem is? Thanks for your answers.

答:
Put this

```<code>for handler in logging.root.handlers[:]:
    logging.root.removeHandler(handler)
</code>```

in front of the

```<code>logging.basicConfig(...)
</code>```

see also
Logging module not writing to file

Body:
I'm trying to write a server that logs exceptions both to the console and to a file. I pulled some code off the cookbook. Here it is:

logger = logging.getLogger('server_logger')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('server.log')
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
ch.setFormatter(formatter)
fh.setFormatter(formatter)
# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(fh)

This code logs perfectly fine to the console, but nothing is logged to the file. The file is created, but nothing is ever written to it. I've tried closing the handler, but that doesn't do anything. Neither does flushing it. I searched the Internet, but apparently I'm the only one with this problem. Does anybody have any idea what the problem is? Thanks for your answers.

Body:
Put this

for handler in logging.root.handlers[:]:
    logging.root.removeHandler(handler)

in front of the

logging.basicConfig(...)

see also
Logging module not writing to file


来源: stackexchange

问:
Problem getting real IP in php
I am using this to get real IP but I take empty from $_SERVER['HTTP_CLIENT_IP'], I take not empty only from $_SERVER['REMOTE_ADDR'] .But I dont need the IP of proxy, I need the real ip of computers using some intranet. Can I get it? When $_SERVER['HTTP_CLIENT_IP'] does not return empty?

```<code>function getRealIpAddr()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}
</code>```

答:
The functions on this page are not reliable.

The only reliable IP from $ip = $_SERVER["REMOTE_ADDR"];
Otherwise anyone could fake his IP address by sending the CLIENT_IP header for example.

This Firefox Addon can help you send custom headers. Sending the CLIENT_IP=x.x.x.x header to a server running any of the functions on this page, would mean that clients can choose any IP they want...

ContentLicense: CC BY-SA 2.5

Title: Problem getting real IP in php

Body:
I am using this to get real IP but I take empty from $_SERVER['HTTP_CLIENT_IP'], I take not empty only from $_SERVER['REMOTE_ADDR'] .But I dont need the IP of proxy, I need the real ip of computers using some intranet. Can I get it? When $_SERVER['HTTP_CLIENT_IP'] does not return empty?

function getRealIpAddr()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}

ContentLicense: CC BY-SA 3.0


问:
Cloud Endpoints - Is implementing JWT Possible?
I'm working on a website and there is existing auth using Google cloud Datastore. I can't seem to find any documentation showing how I can generate a JSON web token compatible with cloud Endpoints for the end users. </p>

<p>Any links you can scavenge are greatly appreciated. </p>

答: You can check out this. You still need a Google service account, but only uses its private key to generate JWT.  ESP will validate it.</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm working on a website and there is existing auth using Google cloud Datastore. I can't seem to find any documentation showing how I can generate a JSON web token compatible with cloud Endpoints for the end users.

Any links you can scavenge are greatly appreciated.


问:
Update the ForceSimulation with new bubble radius
I have initialised a bubble chart with force simulation. How do I update the data, ie. change the bubble radius.

I tried restarting the forceSimulation with a new set of nodes, but all the other nodes move as if the charge was increased.

```<code>var nodes=[{'radius':3},{'radius':4},{'radius':5},{'radius':6}];

var sim = d3.forceSimulation(nodes)
    .force('charge', d3.forceManyBody().strength(-1))
    .force('center', d3.forceCenter(width / 2, height / 2))
    .force('collision', d3.forceCollide().radius(function(d) {
      return d.radius
    }))
    .on('tick',ticked)

 function ticked() {
  var u = svgContainer
     .selectAll('circle')
     .data(nodes)
   u.enter()
    .append('circle')
    .attr('fill','orange')
    .merge(u)
    .attr('r', function(d) {
    return d.radius
    })
   .attr('cx', function(d) {
      return d.x
    })
   .attr('cy', function(d) {
      return d.y
    })
  u.exit().remove()
}

function updateBubbles(){
    node[0]['radius]=10;
     sim.nodes(nodes).alpha(1).restart();
}
</code>```

答:
You can change updateBubbles to the following:

```<code>function updateBubbles() {
    svgContainer.selectAll('circle')
        .attr('r', 10);
}
</code>```

The nodes currently move as if charge was increased, because you're setting alpha to 1 and restarting the simulation. This is behavior we expect to see when we instantly reheat the graph.

Body:
I have initialised a bubble chart with force simulation. How do I update the data, ie. change the bubble radius.

I tried restarting the forceSimulation with a new set of nodes, but all the other nodes move as if the charge was increased.

var nodes=[{'radius':3},{'radius':4},{'radius':5},{'radius':6}];

var sim = d3.forceSimulation(nodes)
    .force('charge', d3.forceManyBody().strength(-1))
    .force('center', d3.forceCenter(width / 2, height / 2))
    .force('collision', d3.forceCollide().radius(function(d) {
      return d.radius
    }))
    .on('tick',ticked)

 function ticked() {
  var u = svgContainer
     .selectAll('circle')
     .data(nodes)
   u.enter()
    .append('circle')
    .attr('fill','orange')
    .merge(u)
    .attr('r', function(d) {
    return d.radius
    })
   .attr('cx', function(d) {
      return d.x
    })
   .attr('cy', function(d) {
      return d.y
    })
  u.exit().remove()
}

function updateBubbles(){
    node[0]['radius]=10;
     sim.nodes(nodes).alpha(1).restart();
}

Body:
You can change updateBubbles to the following:

function updateBubbles() {
    svgContainer.selectAll('circle')
        .attr('r', 10);
}

The nodes currently move as if charge was increased, because you're setting alpha to 1 and restarting the simulation. This is behavior we expect to see when we instantly reheat the graph.


问:
How to set dropdown box on website so that select option and scrape data
A website has changed so I can't scrape data from it anymore. Just need to change the set line below I believe but have tried a number of things and none have worked. I'm not very knowledgeable about this area I'm afraid but rest of code is working. Eg url is https://www.gurufocus.com/stock/CFWFF/insider and it is the table of insider transactions I am trying to press the dropdown for and change it to 100 instead of 10:

```<code>t = Timer
noTable = 0
Do
    Set DropDown = doc.querySelectorAll(".el-dropdown-menu__item")
    lastDropDrownItemIndex = DropDown.Length - 1
    If Timer - t > MAX_WAIT_SEC Then
        noTable = 1
        Exit Do
    End If
Loop While lastDropDrownItemIndex < 1
If noTable = 1 Then GoTo noTableEscape
DropDown.Item(lastDropDrownItemIndex).Click
</code>```

Thanks

答:
Ok so, not sure what you are after exactly, but the website you're scraping offers an API which in my opinion could probably make your life a lot easier. To put it simply, this means that it provides an easy way to request for data with the use of some parameters embedded in a URL. It returns the requested data in JSON format.

In the following code I will be using the XMLHTTP request method and a JSON Parser. For this you will need the following:

JSON parser , it helps you parse the downloaded data. Follow the installation instructions to import it in your project

A reference to the Microsoft Scripting Runtime library. The JSON parser needs it.

A reference to the Microsoft WinHTTP Services, Version 5.1 library. It lets you use an HTTP request object.

For demonstration purposes, the following code will only print in the immediate window the first entry's name and position. You can modify the code to fit your needs.

```<code>Sub test()
Dim req As New WinHttpRequest
Dim jsonResponse As String
Dim jsonParsed As Object
Dim url As String
Dim pageNum As Integer
Dim numPerPage As Integer
pageNum = 1 'You can change this parameter to navigate in different pages
numPerPage = 100 'You can change this parameter to control the number of entries
url = "https://www.gurufocus.com/reader/_api/stocks/OTCPK:CFWFF/insider?page=" & pageNum & "&per_page=" & numPerPage & "&sort=date%7Cdesc"

With req
    .Open "GET", url, False
    .setRequestHeader "Accept", "application/json, text/plain, */*"
    .setRequestHeader "Authorization", ThisWorkbook.Worksheets("The name of your Worksheet").Range("A1").Value 'I have stored a string that is essential to the request in cell A1
    .send
    jsonResponse = .responseText
End With
Set jsonParsed = JsonConverter.ParseJson(jsonResponse)
Debug.Print jsonParsed("data")(1)("name") 'get the name parameter of the first entry
Debug.Print jsonParsed("data")(1)("position") 'get the position parameter of the first entry

End Sub
</code>```

Please note that there's a very long string which is essential to the request, which I have stored in cell A1. This string looks like so:

Bearer
  eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImUxYjAwMmYxMjczMGRiMTBmMmZkYjJkNDk0YTU4NjRmZDZjOWY3ZGI4ZmI1NDY1NTQ2MzZlMGJhNzkxODUxNmY4NTM2ZWIzZDNhODhmN2VmIn0.eyJhdWQiOiIyIiwianRpIjoiZTFiMDAyZjEyNzMwZGIxMGYyZmRiMmQ0OTRhNTg2NGZkNmM5ZjdkYjhmYjU0NjU1NDYzNmUwYmE3OTE4NTE2Zjg1MzZlYjNkM2E4OGY3ZWYiLCJpYXQiOjE1NTkwNzA3OTcsIm5iZiI6MTU1OTA3MDc5NywiZXhwIjoxNTY5NDM4NzkzLCJzdWIiOiIiLCJzY29wZXMiOltdfQ.mZ4DqhUk9YAU6JYDBScF8MJ_zHPyL94bAec7LxZTaWipcWf9uesdGDMDC9v_7W-6zrtXAUWhk4YAL70E5rpPjM7gusYH0RfO48O2PnaV8gsqXoNCFwFBOHuxh109q7X0YsNkfX2wX8m3XigtK9A_YAGID7wxgX96lwzBevsDJ3borHMcJlQtxidF_Bq2D5WPASsuy3jdY80HkOCR1y4eaSIswBEtK5rPj_xy7VXRbYGhLklqw4wgHgq4blfaHnVVmPXf6k8mx45ye8vPecS-w9kjuDOHVn2mvU6mpBzqEpbH4lqpiqmYG7M-CvB1joEAcMQtcilCvsdfKOusoC2MU4_vPtF3Q4ZFVaEcXIQgomdKtFa_XGpCudit45b2rEFacKMUENqLj_sPwYkgM1IPl1lQfR-VpigqnCHPAxVQAPzqwJvS6CxuYOPmvnrx23fBAillP7LtDHwHtlMpgZUjdB5y6IWsia76crM4kbkrKn3zc8xoAGb1fIrgJlY-9hOzrwsmrchantEdYOFZjcMJvhCnlfvnEm6kT2Sdcu4o6TndTZJjrVmD4mb-jNGy4kw_mAx1DfyqR7GLtCVSzcSLKgrrwCJEL22K2bfXH2HExXvgLFbPXivVZJc70TnF9lJmx_dx79cxAm7szFGIdrs56bAC4mdKpvKL3BNmVY-J-G0

The same string should work for you as well.

The result looks like so:

```<code>Brown, James Michael
Senior Officer
</code>```

Each one of the 100 data entries has the following structure:

It's fairly easy to loop through all the entries as well. For example, to print the name of all the entries you would have to do this:

```<code>Dim item As Object
For Each item In jsonParsed("data")
    Debug.Print item("name")
Next item
</code>```

Finally, you can also loop through all the parameters of each entry. For example, the following code prints all the parameters and their corresponding values for the first entry:

```<code>Dim key As Variant
For Each key In jsonParsed("data")(1).Keys
    Debug.Print key & ": " & jsonParsed("data")(1)(key)
Next key
</code>```

So this way you can basically  access any parameter you want for each entry.

Body:
A website has changed so I can't scrape data from it anymore. Just need to change the set line below I believe but have tried a number of things and none have worked. I'm not very knowledgeable about this area I'm afraid but rest of code is working. Eg url is https://www.gurufocus.com/stock/CFWFF/insider and it is the table of insider transactions I am trying to press the dropdown for and change it to 100 instead of 10:

t = Timer
noTable = 0
Do
    Set DropDown = doc.querySelectorAll(".el-dropdown-menu__item")
    lastDropDrownItemIndex = DropDown.Length - 1
    If Timer - t > MAX_WAIT_SEC Then
        noTable = 1
        Exit Do
    End If
Loop While lastDropDrownItemIndex < 1
If noTable = 1 Then GoTo noTableEscape
DropDown.Item(lastDropDrownItemIndex).Click

Thanks

Body:
Ok so, not sure what you are after exactly, but the website you're scraping offers an API which in my opinion could probably make your life a lot easier. To put it simply, this means that it provides an easy way to request for data with the use of some parameters embedded in a URL. It returns the requested data in JSON format.

In the following code I will be using the XMLHTTP request method and a JSON Parser. For this you will need the following:

JSON parser , it helps you parse the downloaded data. Follow the installation instructions to import it in your project

A reference to the Microsoft Scripting Runtime library. The JSON parser needs it.

A reference to the Microsoft WinHTTP Services, Version 5.1 library. It lets you use an HTTP request object.

For demonstration purposes, the following code will only print in the immediate window the first entry's name and position. You can modify the code to fit your needs.

Sub test()
Dim req As New WinHttpRequest
Dim jsonResponse As String
Dim jsonParsed As Object
Dim url As String
Dim pageNum As Integer
Dim numPerPage As Integer
pageNum = 1 'You can change this parameter to navigate in different pages
numPerPage = 100 'You can change this parameter to control the number of entries
url = "https://www.gurufocus.com/reader/_api/stocks/OTCPK:CFWFF/insider?page=" & pageNum & "&per_page=" & numPerPage & "&sort=date%7Cdesc"

With req
    .Open "GET", url, False
    .setRequestHeader "Accept", "application/json, text/plain, */*"
    .setRequestHeader "Authorization", ThisWorkbook.Worksheets("The name of your Worksheet").Range("A1").Value 'I have stored a string that is essential to the request in cell A1
    .send
    jsonResponse = .responseText
End With
Set jsonParsed = JsonConverter.ParseJson(jsonResponse)
Debug.Print jsonParsed("data")(1)("name") 'get the name parameter of the first entry
Debug.Print jsonParsed("data")(1)("position") 'get the position parameter of the first entry

End Sub

Please note that there's a very long string which is essential to the request, which I have stored in cell A1. This string looks like so:

Bearer
  eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImUxYjAwMmYxMjczMGRiMTBmMmZkYjJkNDk0YTU4NjRmZDZjOWY3ZGI4ZmI1NDY1NTQ2MzZlMGJhNzkxODUxNmY4NTM2ZWIzZDNhODhmN2VmIn0.eyJhdWQiOiIyIiwianRpIjoiZTFiMDAyZjEyNzMwZGIxMGYyZmRiMmQ0OTRhNTg2NGZkNmM5ZjdkYjhmYjU0NjU1NDYzNmUwYmE3OTE4NTE2Zjg1MzZlYjNkM2E4OGY3ZWYiLCJpYXQiOjE1NTkwNzA3OTcsIm5iZiI6MTU1OTA3MDc5NywiZXhwIjoxNTY5NDM4NzkzLCJzdWIiOiIiLCJzY29wZXMiOltdfQ.mZ4DqhUk9YAU6JYDBScF8MJ_zHPyL94bAec7LxZTaWipcWf9uesdGDMDC9v_7W-6zrtXAUWhk4YAL70E5rpPjM7gusYH0RfO48O2PnaV8gsqXoNCFwFBOHuxh109q7X0YsNkfX2wX8m3XigtK9A_YAGID7wxgX96lwzBevsDJ3borHMcJlQtxidF_Bq2D5WPASsuy3jdY80HkOCR1y4eaSIswBEtK5rPj_xy7VXRbYGhLklqw4wgHgq4blfaHnVVmPXf6k8mx45ye8vPecS-w9kjuDOHVn2mvU6mpBzqEpbH4lqpiqmYG7M-CvB1joEAcMQtcilCvsdfKOusoC2MU4_vPtF3Q4ZFVaEcXIQgomdKtFa_XGpCudit45b2rEFacKMUENqLj_sPwYkgM1IPl1lQfR-VpigqnCHPAxVQAPzqwJvS6CxuYOPmvnrx23fBAillP7LtDHwHtlMpgZUjdB5y6IWsia76crM4kbkrKn3zc8xoAGb1fIrgJlY-9hOzrwsmrchantEdYOFZjcMJvhCnlfvnEm6kT2Sdcu4o6TndTZJjrVmD4mb-jNGy4kw_mAx1DfyqR7GLtCVSzcSLKgrrwCJEL22K2bfXH2HExXvgLFbPXivVZJc70TnF9lJmx_dx79cxAm7szFGIdrs56bAC4mdKpvKL3BNmVY-J-G0

The same string should work for you as well.

The result looks like so:

Brown, James Michael
Senior Officer

Each one of the 100 data entries has the following structure:

It's fairly easy to loop through all the entries as well. For example, to print the name of all the entries you would have to do this:

Dim item As Object
For Each item In jsonParsed("data")
    Debug.Print item("name")
Next item

Finally, you can also loop through all the parameters of each entry. For example, the following code prints all the parameters and their corresponding values for the first entry:

Dim key As Variant
For Each key In jsonParsed("data")(1).Keys
    Debug.Print key & ": " & jsonParsed("data")(1)(key)
Next key

So this way you can basically  access any parameter you want for each entry.


问:
Can't update php database with a flash application
I am having some problem here. I am trying to develop a flash database manager for my company, and I already have the insert and "search" functions working okay. The problem comes up when trying to get the UPDATE working. Ill post both codes here:

PHP (UPDATED)

```<code><?php
//connect to the local MySQL
$connect=mysql_connect("localhost", "****", "****");

//select your database
mysql_select_db("****");

//Variables
$ID=$_POST[IDPost];

$Nome=$_POST[Nome];
$Tipo=$_POST[Tipo];
$Empresa=$_POST[Empresa];
$Morada=$_POST[Morada];
$CodPostal=$_POST[CodPostal];
$Email=$_POST[Email];
$Contacto1=$_POST[Contacto1];
$Contacto2=$_POST[Contacto2];
$DataNascimento=$_POST[DataNascimento];
$Profissao=$_POST[Profissao];
$Notas1=$_POST[Notas1];
$Notas2=$_POST[Notas2];

//query the database
$query="

UPDATE
    GestaoClientes
SET
    Nome = '$Nome',
    Tipo = '$Tipo',
    Empresa = '$Empresa',
    Morada = '$Morada',
    CodPostal = '$CodPostal',
    Email = '$Email',
    Contacto1 = '$Contacto1',
    Contacto2 = '$Contacto2',
    DataNascimento = '$DataNascimento',
    Profissao = '$Profissao',
    Notas1 = '$Notas1',
    Notas2 = '$Notas2'
WHERE
    ID = '$ID'";

$result=mysql_query($query);

if (!mysql_query($query,$connect))
{
    die('Error: ' . mysql_error());
    echo "Result=NotOk";
}else{
    echo "Result=Ok";
}

mysql_close($connect);
?>
</code>```

Flash

```<code>public function editInfo(MouseEvent):void
        {
            var request:URLRequest = new URLRequest ("link.php");
                request.method = URLRequestMethod.POST;
                trace("called");

                var variables:URLVariables = new URLVariables();

                variables.IDPost = NField.text;

                variables.Nome = NomeField.text;
                variables.Email = NomeField.text;
                variables.Morada = MoradaField.text;
                variables.CodPostal = CodPostalField.text;
                variables.Tipo = TipoField.text;
                variables.Empresa = EmpresaField.text;
                variables.Profissao = ProfissaoField.text
                variables.DataNascimento = DataNascimentoField.text;
                variables.Notas1 = Notas1Field.text;
                variables.Notas2 = Notas2Field.text;

                request.data = variables;

                var loader:URLLoader = new URLLoader (request);
                loader.addEventListener(Event.COMPLETE, onComplete);
                loader.dataFormat = URLLoaderDataFormat.VARIABLES;
                loader.load(request);

            function onComplete(e:Event):void
            {
                trace("ok");
            }
</code>```

}

When I try going to the php in the browser if just gives me the error:

```<code>Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Nome' = '', 'Tipo' = '', 'Empresa' = '', 'Morada' = '', 'CodPostal' = '', 'Emai' at line 4
</code>```

This although is probably normal, since Im not passing any "POST" variables through the browser.

The flash doesent return any errors when trying this code, so I assume the connection itself is okay, but it doesent do the update either. Is there something wrong with this code? Thanks.

UPDATE: I now changed my code, and it does not show the syntax error, but still doesent update within the flash. Any ideias why? :/ thanks

答:
Remove the single quotes around the column names. Backticks (`) are allowed, single quotes (') are not.

I hope you realize that if your code really looks like above you have a massive security hole in your application, as anyone can execute arbitrary sql code.

Body:
I am having some problem here. I am trying to develop a flash database manager for my company, and I already have the insert and "search" functions working okay. The problem comes up when trying to get the UPDATE working. Ill post both codes here:

PHP (UPDATED)

<?php
//connect to the local MySQL
$connect=mysql_connect("localhost", "****", "****");

//select your database
mysql_select_db("****");

//Variables
$ID=$_POST[IDPost];

$Nome=$_POST[Nome];
$Tipo=$_POST[Tipo];
$Empresa=$_POST[Empresa];
$Morada=$_POST[Morada];
$CodPostal=$_POST[CodPostal];
$Email=$_POST[Email];
$Contacto1=$_POST[Contacto1];
$Contacto2=$_POST[Contacto2];
$DataNascimento=$_POST[DataNascimento];
$Profissao=$_POST[Profissao];
$Notas1=$_POST[Notas1];
$Notas2=$_POST[Notas2];

//query the database
$query="

UPDATE
    GestaoClientes
SET
    Nome = '$Nome',
    Tipo = '$Tipo',
    Empresa = '$Empresa',
    Morada = '$Morada',
    CodPostal = '$CodPostal',
    Email = '$Email',
    Contacto1 = '$Contacto1',
    Contacto2 = '$Contacto2',
    DataNascimento = '$DataNascimento',
    Profissao = '$Profissao',
    Notas1 = '$Notas1',
    Notas2 = '$Notas2'
WHERE
    ID = '$ID'";

$result=mysql_query($query);

if (!mysql_query($query,$connect))
{
    die('Error: ' . mysql_error());
    echo "Result=NotOk";
}else{
    echo "Result=Ok";
}

mysql_close($connect);
?>

Flash

public function editInfo(MouseEvent):void
        {
            var request:URLRequest = new URLRequest ("link.php");
                request.method = URLRequestMethod.POST;
                trace("called");

                var variables:URLVariables = new URLVariables();

                variables.IDPost = NField.text;

                variables.Nome = NomeField.text;
                variables.Email = NomeField.text;
                variables.Morada = MoradaField.text;
                variables.CodPostal = CodPostalField.text;
                variables.Tipo = TipoField.text;
                variables.Empresa = EmpresaField.text;
                variables.Profissao = ProfissaoField.text
                variables.DataNascimento = DataNascimentoField.text;
                variables.Notas1 = Notas1Field.text;
                variables.Notas2 = Notas2Field.text;

                request.data = variables;

                var loader:URLLoader = new URLLoader (request);
                loader.addEventListener(Event.COMPLETE, onComplete);
                loader.dataFormat = URLLoaderDataFormat.VARIABLES;
                loader.load(request);

            function onComplete(e:Event):void
            {
                trace("ok");
            }

}

When I try going to the php in the browser if just gives me the error:

Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''Nome' = '', 'Tipo' = '', 'Empresa' = '', 'Morada' = '', 'CodPostal' = '', 'Emai' at line 4

This although is probably normal, since Im not passing any "POST" variables through the browser.

The flash doesent return any errors when trying this code, so I assume the connection itself is okay, but it doesent do the update either. Is there something wrong with this code? Thanks.

UPDATE: I now changed my code, and it does not show the syntax error, but still doesent update within the flash. Any ideias why? :/ thanks


问:
How to Use Intent for Media Player?
I want to use intent for my homework application. When i click button1, my SoundActivity opening, after playing sound1.mp3 file. But i wanna when i clicked button2, sound2.mp3 file playing in SoundActivity..

This is my MainActivity.java codes:

```<code>button1=findViewById(R.id.button1);
button2=findViewById(R.id.button2);

button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            Intent intent = new Intent(this, SoundActivity.class);

            }
        });

button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            Intent intent = new Intent(this, SoundActivity.class);

            }
        });
</code>```

This is my Sound Activity side:

```<code>sound1 = MediaPlayer.create(this, R.raw.bell);
sound2 = MediaPlayer.create(this, R.raw.siren);

sound1.start();
</code>```

答:
```<code>'Another way is that you just pass a key like which song you want to play on button click listener like'

button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            Intent intent = new Intent(this, SoundActivity.class);
            intent.putExtra("SOUND", "sound1");
            startActivity(intent);

            }
        });

button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            Intent intent = new Intent(this, SoundActivity.class);
            intent.putExtra("SOUND", "sound2");
            startActivity(intent);

            }
        });

'get this key in sound activity and pass the sound on the basis of condition like'

Bundle bundle = getIntent().getExtras();
        String sound = bundle.getInt("SOUND");

if(sound.equals(sound1)){
play_sound = MediaPlayer.create(this, R.raw.bell);
}else if(sound.equals(sound2)){
play_sound = MediaPlayer.create(this, R.raw.siren);
}

play_sound.start();

'Hope you get the best'
</code>```

Title: How to Use Intent for Media Player?

Body:
I want to use intent for my homework application. When i click button1, my SoundActivity opening, after playing sound1.mp3 file. But i wanna when i clicked button2, sound2.mp3 file playing in SoundActivity..

This is my MainActivity.java codes:

button1=findViewById(R.id.button1);
button2=findViewById(R.id.button2);

button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            Intent intent = new Intent(this, SoundActivity.class);

            }
        });

button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            Intent intent = new Intent(this, SoundActivity.class);

            }
        });

This is my Sound Activity side:

sound1 = MediaPlayer.create(this, R.raw.bell);
sound2 = MediaPlayer.create(this, R.raw.siren);

sound1.start();


问:
Load data from sqlite file Swift 4.2
I have large database in sqlite file
so I am trying to access it directly from my data.sqlite file
but I am not able to access it . I had achieved that task in past using  objective C

Steps Taken:

1:Drag data.sqlite file into project

2:Trying to access it via fmdb

Output: path=== /var/mobile/Containers/Data/Application/557B2961-52D8-4B14-BABC-BF4829852127/Documents/data.sqlite

```<code>let documentsDirectory = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString) as String
pathToDatabase = documentsDirectory.appending("/(databaseFileName)")

func openDatabase() -> Bool {
 print("path=== \(pathToDatabase ?? "empty")")
      if database == nil {
           if FileManager.default.fileExists(atPath: pathToDatabase) {
                database = FMDatabase(path: pathToDatabase)
//code is not entering in that if , it should be there becasuse I already included my sqlitefile
 }
        if database != nil {
            if database.open() {
                return true
            }
        }
        return false
    }
</code>```

答:
Your file is clearly not in documents directory, you should access it in main bundle

```<code>let dbUrl = Bundle.main.url(forResource: "data", withExtension: "sqlite")
</code>```

If you need to copy the database in documents directory, use following instead

```<code>let fileManager = FileManager.default
let dbUrl = fileManager.urls(for: .documentDirectory, in: .userDomainMask).last!.appendingPathComponent("data.sqlite")
if !fileManager.fileExists(atPath: dbUrl.path) {
    let url = Bundle.main.url(forResource: "data", withExtension: "sqlite")!
    try? fileManager.copyItem(at: url, to: dbUrl)
}
</code>```

Usage

```<code>let database = FMDatabase(url: dbUrl)
</code>```

Title: Load data from sqlite file Swift 4.2

Body:
I have large database in sqlite file
so I am trying to access it directly from my data.sqlite file
but I am not able to access it . I had achieved that task in past using  objective C

Steps Taken:

1:Drag data.sqlite file into project

2:Trying to access it via fmdb

Output: path=== /var/mobile/Containers/Data/Application/557B2961-52D8-4B14-BABC-BF4829852127/Documents/data.sqlite

let documentsDirectory = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString) as String
pathToDatabase = documentsDirectory.appending("/(databaseFileName)")

func openDatabase() -> Bool {
 print("path=== \(pathToDatabase ?? "empty")")
      if database == nil {
           if FileManager.default.fileExists(atPath: pathToDatabase) {
                database = FMDatabase(path: pathToDatabase)
//code is not entering in that if , it should be there becasuse I already included my sqlitefile
 }
        if database != nil {
            if database.open() {
                return true
            }
        }
        return false
    }

Body:
Your file is clearly not in documents directory, you should access it in main bundle

let dbUrl = Bundle.main.url(forResource: "data", withExtension: "sqlite")

If you need to copy the database in documents directory, use following instead

let fileManager = FileManager.default
let dbUrl = fileManager.urls(for: .documentDirectory, in: .userDomainMask).last!.appendingPathComponent("data.sqlite")
if !fileManager.fileExists(atPath: dbUrl.path) {
    let url = Bundle.main.url(forResource: "data", withExtension: "sqlite")!
    try? fileManager.copyItem(at: url, to: dbUrl)
}

Usage

let database = FMDatabase(url: dbUrl)


问:
Which strategy is better to validate a csv line?
For simplicity, given a csv line with two fields: login and score from 0 by 100 for some passed test.

csv line examples

```<code>cool;95
clever;900
loser;10;-1
freak;ten
;50
</code>```

The task is to validate a csv line.

I have two beans for a test result and a csv line.

I see 3 low level strategies for a csv line parsing.

Strategy 1. All checks are inside the csv line bean.

```<code>class CsvLine {
    private String csvLine;

    //constructors
    ...

    public Result getResult() throws LineException {
        String[] fields = csvLine.split(";");
        if(fields.length != 2) {
            throw new LineException();
        }
        //other possible checks with csvLine and its fields
        ...
        //in the case everything is ok
        return new Result(login, score);
    }
}

class Result {
    private String login;
    private int score;

    //trivial constructor
    public Result(String login, int score) {
        this.login = login;
        this.score = score;
    }
    ...
}
</code>```

Strategy 2. All checks are inside the result bean.

```<code>class CsvLine {
    ...
    public Result getResult() throws LineException {
        return new Result(csvLine);
    }
}

class Result {
    ...
    public Result(String csvLine) throws LineException {
        String[] fields = csvLine.split(";");
        if(fields.length != 2) {
            throw new LineException();  //own exception
        }
        this.login = getLogin(fields[0]);   //private method with checks
        this.score = getScore(fields[1]);   //conversion and checks
    }
    ...
}
</code>```

Strategy 3. Checks for the line structure are inside the csv line bean and checks for fields validness are inside the result bean.

```<code>class CsvLine {
    ...
    public Result getResult() throws LineException {
        String[] fields = csvLine.split(";");
        if(fields.length != 2) {
            throw new LineException();
        }
        try {
            return new Result(fields[0], new Integer(fields[1]).intValue());
        } catch(IllegalArgumentException e) {
            throw new LineException();
        }
    }
}

class Result {
    ...
    public Result(String login, int score) {
        if("".equals(login)) {
            throw new IllegalArgumentException();
        }
        if(score < 0 || score > 100) {
            throw new IllegalArgumentException();
        }
        this.login = login;
        this.score = score;
    }
}
</code>```

Complete validation of a csv line is located inside one and the same bean in strategies 1 and 2.

But each bean contains checks for its own fields and for fields of associated bean.

Meanwhile, in strategy 3, validation is located in proper way, but separated.

What to prefer?

Or do both approaches make sense?

答:
I'd propose a different stategy.

Parsing of the File and it content should be in one place. Normally I'd say you do not want to spread this across multiple classes, so that might not be the case if you want to do some fancy parallel processing.

Another question would be how do you need to handle invalid lines? Reject the file alltogether or only take those lines that are valid? When you work with large amount of data you are bound to end up with some kind of inconsistency, yet you do not want to stop processing all of it.

Unless your are getting these CSVLine objects from somewhere, I would probably not bother to create them. But you might want to have some method for handling each line, which only returns the result or an exception in case the line is invalid.

In relation to @Sambit answers:
Be wary of the amount of content you need to process. If you need to handle larger files, then reading them completly into your memory is not advisable.
In that case you want to process the files in smaller parts, for example lines.

What you should end up with, is a class, where you can see that it`s responsible for processing the csv - name something like CSVParser and where you can see what content it's actually expecting and what validation it is doing. So all of that could be handled in a static way.

Something like this:

```<code>class CSVParser {

    private CSVParser() {
    }

    public final static class Result {  // immutable object

        public final String login;
        public final int score;

        Result(String login, int score) {
            this.login = login;
            this.score = score;
        }
    }

   // LineException only if required else you might want to return a
   // different object containing the parsed lines in form of a result
   // and the invalid lines that could not be handled. Or you write them
   // to another file, and only give back the FileHandle ...
   // depends on the usecase (in that case get rid of the LineException alltogether).
    public static List<Result> parseFile(File file) throws IOException, LineException  {
        // file handling, calls line processing
    }

    static Result parseLine(String line) throws LineException {

         String[] columns = line.split(";");

         // validation checks, parsing and exception throwing here

         // result creation afterwards
         return new Result();
    }
}

</code>```

Body:
For simplicity, given a csv line with two fields: login and score from 0 by 100 for some passed test.

csv line examples

cool;95
clever;900
loser;10;-1
freak;ten
;50

The task is to validate a csv line.

I have two beans for a test result and a csv line.

I see 3 low level strategies for a csv line parsing.

Strategy 1. All checks are inside the csv line bean.

class CsvLine {
    private String csvLine;

    //constructors
    ...

    public Result getResult() throws LineException {
        String[] fields = csvLine.split(";");
        if(fields.length != 2) {
            throw new LineException();
        }
        //other possible checks with csvLine and its fields
        ...
        //in the case everything is ok
        return new Result(login, score);
    }
}

class Result {
    private String login;
    private int score;

    //trivial constructor
    public Result(String login, int score) {
        this.login = login;
        this.score = score;
    }
    ...
}

Strategy 2. All checks are inside the result bean.

class CsvLine {
    ...
    public Result getResult() throws LineException {
        return new Result(csvLine);
    }
}

class Result {
    ...
    public Result(String csvLine) throws LineException {
        String[] fields = csvLine.split(";");
        if(fields.length != 2) {
            throw new LineException();  //own exception
        }
        this.login = getLogin(fields[0]);   //private method with checks
        this.score = getScore(fields[1]);   //conversion and checks
    }
    ...
}

Strategy 3. Checks for the line structure are inside the csv line bean and checks for fields validness are inside the result bean.

class CsvLine {
    ...
    public Result getResult() throws LineException {
        String[] fields = csvLine.split(";");
        if(fields.length != 2) {
            throw new LineException();
        }
        try {
            return new Result(fields[0], new Integer(fields[1]).intValue());
        } catch(IllegalArgumentException e) {
            throw new LineException();
        }
    }
}

class Result {
    ...
    public Result(String login, int score) {
        if("".equals(login)) {
            throw new IllegalArgumentException();
        }
        if(score < 0 || score > 100) {
            throw new IllegalArgumentException();
        }
        this.login = login;
        this.score = score;
    }
}

Complete validation of a csv line is located inside one and the same bean in strategies 1 and 2.

But each bean contains checks for its own fields and for fields of associated bean.

Meanwhile, in strategy 3, validation is located in proper way, but separated.

What to prefer?

Or do both approaches make sense?

Body:
I'd propose a different stategy.

Parsing of the File and it content should be in one place. Normally I'd say you do not want to spread this across multiple classes, so that might not be the case if you want to do some fancy parallel processing.

Another question would be how do you need to handle invalid lines? Reject the file alltogether or only take those lines that are valid? When you work with large amount of data you are bound to end up with some kind of inconsistency, yet you do not want to stop processing all of it.

Unless your are getting these CSVLine objects from somewhere, I would probably not bother to create them. But you might want to have some method for handling each line, which only returns the result or an exception in case the line is invalid.

In relation to @Sambit answers:
Be wary of the amount of content you need to process. If you need to handle larger files, then reading them completly into your memory is not advisable.
In that case you want to process the files in smaller parts, for example lines.

What you should end up with, is a class, where you can see that it`s responsible for processing the csv - name something like CSVParser and where you can see what content it's actually expecting and what validation it is doing. So all of that could be handled in a static way.

Something like this:

class CSVParser {

    private CSVParser() {
    }

    public final static class Result {  // immutable object

        public final String login;
        public final int score;

        Result(String login, int score) {
            this.login = login;
            this.score = score;
        }
    }

   // LineException only if required else you might want to return a
   // different object containing the parsed lines in form of a result
   // and the invalid lines that could not be handled. Or you write them
   // to another file, and only give back the FileHandle ...
   // depends on the usecase (in that case get rid of the LineException alltogether).
    public static List<Result> parseFile(File file) throws IOException, LineException  {
        // file handling, calls line processing
    }

    static Result parseLine(String line) throws LineException {

         String[] columns = line.split(";");

         // validation checks, parsing and exception throwing here

         // result creation afterwards
         return new Result();
    }
}


问:
React-select container option width
i' tryin the react-select library, and i like it.

I'm playing with it but i dont' understand how to change the width of the options container.

i tried to saw the documentation at official react select but i didn't find the right section about the width of the options container.

could someone kindly help me :) ?

this is my custom style right now :

```<code>const customStyles = {
      option: (provided, state) => ({
        ...provided,
        borderBottom: '1px solid #979797',
        width: 219,
        borderRadius: 5,
      }),
      control: () => ({
        // none of react-select's styles are passed to <Control />
        width: 219,
        border: '1px solid #979797',
        display: 'flex',
        borderRadius: '5px',
      }),
      valueContainer: (provided) => ({
        ...provided,
        width: 219,
      }),
    }
</code>```

答:
The Menu component is the one you want to modify:

```
menu: (provided, state) => ({
  ...provided,
  width: 50,
}),
```

Title: React-select container option width

Body:
i' tryin the react-select library, and i like it.

I'm playing with it but i dont' understand how to change the width of the options container.

i tried to saw the documentation at official react select but i didn't find the right section about the width of the options container.

could someone kindly help me :) ?

this is my custom style right now :

const customStyles = {
      option: (provided, state) => ({
        ...provided,
        borderBottom: '1px solid #979797',
        width: 219,
        borderRadius: 5,
      }),
      control: () => ({
        // none of react-select's styles are passed to <Control />
        width: 219,
        border: '1px solid #979797',
        display: 'flex',
        borderRadius: '5px',
      }),
      valueContainer: (provided) => ({
        ...provided,
        width: 219,
      }),
    }

Body:
The Menu component is the one you want to modify:

menu: (provided, state) => ({
  ...provided,
  width: 50,
}),


问:
How to hide or cover a MS Access ActiveX Web Browser control?
I have a database in which users enter a value into Textbox1 on a form; the form also has an ActiveX Web Browser control (acxWebBrowser1), plus another blank Textbox2, and finally a command button.  After the user enters text into Textbox1 and clicks the command button, the VBA code will navigate to a specific web page in acxWebBrowser1, enter the Textbox1 value into the web page form, and then obtain a result in the web page in acxWebBrowser1.  The result is then grabbed by the VBA code and entered into Textbox2 on the database form.

What I need to be able to do is hide the ActiveX Web Browser control to (a) prevent the user from messing with the web page, and (b) to prevent the clutter and distraction of the ActiveX Web Browser since the VBA code does all the necessary interactions with the web page behind the scenes.

Problem is, I cannot get the acxWebBrowser1 to stay hidden behind a rectangle box control on the form because the browser automatically moves itself to the top of the stack of controls.  If I reduce the size of the acxWebBrowser1 control to be very tiny, the web page does not function properly.  If I make the web browser control not visible, then the code cannot grab the needed values.  I cannot use a POST approach to avoid using the web browser.  (I might be wrong about not being able to use POST--maybe someone can point me to how to do that if that is the way to go.)

How can I hide or put something on top of the web browser control?

答:
Three hours later, it dawned on me how to accomplish hiding the ActiveX Web Browser but still get it to be accessible to the VBA code.  Simple:  Don't update the screen when running the code to access the ActiveX Web Browser and use the .Visible property to "show" the Browser Control when VBA needs to access it (but it won't be visible to the user if screen updating is off) and then hide the Browser Control when VBA is done accessing it.

Here's the code I used to accomplish that:

```<code>Application.Echo False  'turn off screen updating
Me.acxWebBrowser1.Visible = True  'make web browser control "visible" to VBA code

     {do stuff, like:  process web page}

Me.btnClickMe.SetFocus  'set focus on the button so we can hide the web browser control
Me.acxWebBrowser1.Visible = False  'make web browser invisible so user is not distracted
Application.Echo True  'turn screen updating back on
Me.Refresh  'refresh the screen; this is probably not necessary
</code>```

Just be

absolutely sure to turn screen updating (echo) back on

You should send any error handling to code that sets Application.Echo True otherwise you will not be able to see or do anything if the code crashes after setting echo to False.

Body:
Three hours later, it dawned on me how to accomplish hiding the ActiveX Web Browser but still get it to be accessible to the VBA code.  Simple:  Don't update the screen when running the code to access the ActiveX Web Browser and use the .Visible property to "show" the Browser Control when VBA needs to access it (but it won't be visible to the user if screen updating is off) and then hide the Browser Control when VBA is done accessing it.

Here's the code I used to accomplish that:

Application.Echo False  'turn off screen updating
Me.acxWebBrowser1.Visible = True  'make web browser control "visible" to VBA code

     {do stuff, like:  process web page}

Me.btnClickMe.SetFocus  'set focus on the button so we can hide the web browser control
Me.acxWebBrowser1.Visible = False  'make web browser invisible so user is not distracted
Application.Echo True  'turn screen updating back on
Me.Refresh  'refresh the screen; this is probably not necessary

Just be

absolutely sure to turn screen updating (echo) back on

You should send any error handling to code that sets Application.Echo True otherwise you will not be able to see or do anything if the code crashes after setting echo to False.


问:
What does "The constructor ... is ambiguous" mean?
I would like to know what the error message in Eclipse means:

The constructor Case(Problem, Solution, double, CaseSource) is ambiguous

答:
The problem exists when you try to instantiate a class that could apply to more than one constructor.

For example:

```<code>public Example(String name) {
    this.name = name;
}

public Example(SomeOther other) {
    this.other = other;
}
</code>```

If you call the constructor with a String object, there's one definite constructor. However, if you instantiate new Example(null) then it could apply to either and is therefore ambiguous.

The same can apply to methods with similar signatures.

Body:
The problem exists when you try to instantiate a class that could apply to more than one constructor.

For example:

public Example(String name) {
    this.name = name;
}

public Example(SomeOther other) {
    this.other = other;
}

If you call the constructor with a String object, there's one definite constructor. However, if you instantiate new Example(null) then it could apply to either and is therefore ambiguous.

The same can apply to methods with similar signatures.


问:
How to generate documentation for multiple files with Stardoc?
I'm not able to generate documentation for multiple bazel rules in separate files with Stardoc 0.3.0 and Bazel 0.24.1.

This is my setup. There are three bazel rules in separate files.

BUILD

bzl_library(
    name = "bzl",
    srcs = ["antlr2.bzl", "antlr3.bzl", "antlr4.bzl"],
    deps = [
        "@bazel_skylib//:bzl_library",
    ],
)
stardoc(
    name = "single-docs",
    input = "antlr2.bzl",
    out = "antlr2_single.md",
)
stardoc(
    name = "multi-docs",
    input = "doc.bzl",
    out = "doc.md",
    deps = [":bzl"],
)
```

<p>And one file to load them:</p>

<p><code>doc.bzl</code></p>

```load("//antlr:antlr2.bzl", "antlr2")
load("//antlr:antlr3.bzl", "antlr3")
load("//antlr:antlr4.bzl", "antlr4")
```

<p>It builds, but the generated file is essentially empty:</p>

<p><code>doc.md</code></p>

<pre class="lang-html prettyprint-override"><code><!-- Generated with Stardoc: http://skydoc.bazel.build -->
</code>```

If I do what the documentation suggests:

BUILD

...
stardoc(
    name = "multi-docs",
    input = "doc.bzl",
    out = "doc.md",
)
```

<p>I receive an error:</p>

```Exception in thread "main" java.lang.IllegalStateException: File antlr/doc.bzl imported '//antlr:antlr2.bzl', yet antlr/antlr2.bzl was not found, even at roots [.].
    at com.google.devtools.build.skydoc.SkydocMain.recursiveEval(SkydocMain.java:420)
    at com.google.devtools.build.skydoc.SkydocMain.eval(SkydocMain.java:338)
    at com.google.devtools.build.skydoc.SkydocMain.main(SkydocMain.java:205)
Caused by: java.nio.file.NoSuchFileException: antlr/antlr2.bzl
    at com.google.devtools.build.skydoc.SkydocMain.getInputSource(SkydocMain.java:453)
    at com.google.devtools.build.skydoc.SkydocMain.recursiveEval(SkydocMain.java:404)
    at com.google.devtools.build.skydoc.SkydocMain.recursiveEval(SkydocMain.java:416)
    ... 2 more

```

Am I doing something wrong or is this a bug?

BTW, the single file target single-docs generates correctly.

答:
I finally figured it out. Don't know whether this is something that's gonna be changed/fixed in the future or just not yet properly documented: You have to alias the rules!

doc.bzl

load("//antlr:antlr4.bzl", _antlr4 = "antlr4")
load("//antlr:antlr2.bzl", _antlr2 = "antlr2")
load("//antlr:antlr3.bzl", _antlr3 = "antlr3")

antlr4 = _antlr4
antlr3 = _antlr3
antlr2 = _antlr2
```

Body:
I'm not able to generate documentation for multiple bazel rules in separate files with Stardoc 0.3.0 and Bazel 0.24.1.

This is my setup. There are three bazel rules in separate files.

BUILD

bzl_library(
    name = "bzl",
    srcs = ["antlr2.bzl", "antlr3.bzl", "antlr4.bzl"],
    deps = [
        "@bazel_skylib//:bzl_library",
    ],
)
stardoc(
    name = "single-docs",
    input = "antlr2.bzl",
    out = "antlr2_single.md",
)
stardoc(
    name = "multi-docs",
    input = "doc.bzl",
    out = "doc.md",
    deps = [":bzl"],
)

And one file to load them:

doc.bzl

load("//antlr:antlr2.bzl", "antlr2")
load("//antlr:antlr3.bzl", "antlr3")
load("//antlr:antlr4.bzl", "antlr4")

It builds, but the generated file is essentially empty:

doc.md

If I do what the documentation suggests:

BUILD

...
stardoc(
    name = "multi-docs",
    input = "doc.bzl",
    out = "doc.md",
)

I receive an error:

Exception in thread "main" java.lang.IllegalStateException: File antlr/doc.bzl imported '//antlr:antlr2.bzl', yet antlr/antlr2.bzl was not found, even at roots [.].
    at com.google.devtools.build.skydoc.SkydocMain.recursiveEval(SkydocMain.java:420)
    at com.google.devtools.build.skydoc.SkydocMain.eval(SkydocMain.java:338)
    at com.google.devtools.build.skydoc.SkydocMain.main(SkydocMain.java:205)
Caused by: java.nio.file.NoSuchFileException: antlr/antlr2.bzl
    at com.google.devtools.build.skydoc.SkydocMain.getInputSource(SkydocMain.java:453)
    at com.google.devtools.build.skydoc.SkydocMain.recursiveEval(SkydocMain.java:404)
    at com.google.devtools.build.skydoc.SkydocMain.recursiveEval(SkydocMain.java:416)
    ... 2 more

Am I doing something wrong or is this a bug?

BTW, the single file target single-docs generates correctly.


问:
Why IDBKeyRange.upperBound not working in Firefox?
This part of code works fine in Chrome, but in Firefox it returns an empty array! What's the problem?</p>

```<code>const transaction = DB.transaction(['history_object_store'], 'readonly');
const store = transaction.objectStore('history_object_store');
const index = store.index('id');
const openCursor = index.openCursor(IDBKeyRange.upperBound(50));
new Promise((resolve, reject) => {
  const entries = [];
  openCursor.onsuccess = function(e){
    const cursor = e.target.result;
    if(cursor) {
      entries.push(cursor.value)
    } else {
      resolve(entries);
    }
  }
});
</code>```

答: Probably you have different data loaded in Chrome and Firefox. I don't think there are any bugs in either Chrome's or Firefox's IndexedDB implementations that would lead to such a significant difference for such a simple situation.</p>

Body:
This part of code works fine in Chrome, but in Firefox it returns an empty array! What's the problem?

const transaction = DB.transaction(['history_object_store'], 'readonly');
const store = transaction.objectStore('history_object_store');
const index = store.index('id');
const openCursor = index.openCursor(IDBKeyRange.upperBound(50));
new Promise((resolve, reject) => {
  const entries = [];
  openCursor.onsuccess = function(e){
    const cursor = e.target.result;
    if(cursor) {
      entries.push(cursor.value)
    } else {
      resolve(entries);
    }
  }
});


问:
What is the time complexity of this coin changing combination algorithm?
Hello I have just solved this leetcode question: https://leetcode.com/problems/coin-change-2/

The objective is to find the number of different possible combinations of coins we can use to generate an amount assuming we have an infinite number of coins from each denomination.

I know this problem has a DP solution that runs in O(amount*len(coins)) and I can add memoization to the solution below to achieve that.

However I am struggling to find the time complexity of the naïve approach below:

```<code>def change(amount, coins):
    def helper(amount, coins, id):
        if amount == 0:
            return 1
        res = 0
        for i in range(id, len(coins)):
            if coins[i] <= amount:
                res += helper(amount - coins[i], coins, i)
        return res

    res = helper(amount, coins, 0)
    return res
</code>```

So what I am actually doing is a DFS where I try to use the first coin as much as possible before backtracking and moving to the next coin. So once I start to use the next coin I can't use the first one again --> this allows me to not count permutations in my result.

I know the time complexity of this solution is O(exponential) and I also know it is O(V + E) because it is DFS.

Can someone give the exact form of the time complexity ? What is the exponential term exactly ? Or how can I count the edges and vertices in my graph ?

答: Assume a case where amount, n, is very large and the values of each coin is very small compared to n and let the size of the coin array be c. In fact, in the worst case, we can assume the value of every coin to be about 1. In the tree representing the call stack that your solution builds, each node would branch c times. Each level of the tree subtracts the value of a coin (in the worst case is about 1) from n so the depth (or height) of the tree would be n. So we're looking at a c-branch tree with height n. The number of vertices, V = c^0 + c^1 + c^2 + c^3 + ... + c^(n-1) + c^n. You can see what this series reduces to here. The calculation for number of edges, E, is similar. This algorithm has O(c^n) time complexity.</p>

Body:
Hello I have just solved this leetcode question: https://leetcode.com/problems/coin-change-2/

The objective is to find the number of different possible combinations of coins we can use to generate an amount assuming we have an infinite number of coins from each denomination.

I know this problem has a DP solution that runs in O(amount*len(coins)) and I can add memoization to the solution below to achieve that.

However I am struggling to find the time complexity of the naïve approach below:

def change(amount, coins):
    def helper(amount, coins, id):
        if amount == 0:
            return 1
        res = 0
        for i in range(id, len(coins)):
            if coins[i] <= amount:
                res += helper(amount - coins[i], coins, i)
        return res

    res = helper(amount, coins, 0)
    return res

So what I am actually doing is a DFS where I try to use the first coin as much as possible before backtracking and moving to the next coin. So once I start to use the next coin I can't use the first one again --> this allows me to not count permutations in my result.

I know the time complexity of this solution is O(exponential) and I also know it is O(V + E) because it is DFS.

Can someone give the exact form of the time complexity ? What is the exponential term exactly ? Or how can I count the edges and vertices in my graph ?


问:
Oracle function error: ORA-00932: inconsistent datatypes: expected CHAR got MDSYS.SDO.GEOMETRY
I am attempting to create a function (at the database level) that is to be called from a web map. The function is to enable that when a user clicks on a point the associated region (polygon) is also selected/highlighted. Points and regions are associated at the attribute level via the value in a column called code (eks. not spatially).

I have created the below code but it returns the error:

ORA-00932: inconsistent datatypes: expected CHAR MDSYS.SDO_GEOMETRY (?)

Code:

```<code>create or replace function region_select
  (
      p_geom in sdo_geometry
  )

RETURN SDO_GEOMETRY
DETERMINISTIC

IS
  v_pointId number;
  v_code number;
  geom_out sdo_geometry;

BEGIN

select point_id into v_pointId from points where geom = p_geom;
select code into v_code from points where point_id = v_pointId;

    if (v_pointId is not null)
    then
    select geom into geom_out from regions where code  = v_code;
    RETURN geom_out;
    end if;

-- error handling
exception
when others then
    raise_application_error(-20001,'An error was encountered - '||
sqlcode ||' -error- '|| sqlerrm);
    rollback;
end;
</code>```

答:
First of all, where geom = p_geom shows that a spatial selection is used (not for REGIONS, but for POINTS) - and you cannot check geometry equality using where geom = p_geom. You should use select point_id into v_pointId from points t where SDO_EQUALS(t.geom,p_geom) = 'TRUE' - this presupposes that a spatial index exists for POINTS.geom. If you cannot have a spatial index AND table POINTS is really small, you can use where sdo_geom.relate(t.geom,'determine',p_geom)='EQUAL' - but it'll be slow...

Second, I agree with @Alex Poole in that such error handling is not only meaningless, but detrimental as well. The way it's written, you'll get the error (which you would have gotten anyway without the exception) but you will lose e.g. where this error happened. You should firstly get rid of it, run the code and see if you get a better description of the error (CHAR MDSYS.SDO_GEOMETRY? what "CHAR"? in what line?). If what you get doesn't shed any more light, we're here to help...

On a side note, I'm not sure that this function is indeed DETERMINISTIC - you have to make sure it is (and why declare it as such? what's the goal here?). Finally, it's best to declare geometry variables as "MDSYS.SDO_GEOMETRY", not just "SDO_GEOMETRY" - old bugs may come back to bite you...

HTH, let me know if you need anything else.

Body:
I am attempting to create a function (at the database level) that is to be called from a web map. The function is to enable that when a user clicks on a point the associated region (polygon) is also selected/highlighted. Points and regions are associated at the attribute level via the value in a column called code (eks. not spatially).

I have created the below code but it returns the error:

ORA-00932: inconsistent datatypes: expected CHAR MDSYS.SDO_GEOMETRY (?)

Code:

create or replace function region_select
  (
      p_geom in sdo_geometry
  )

RETURN SDO_GEOMETRY
DETERMINISTIC

IS
  v_pointId number;
  v_code number;
  geom_out sdo_geometry;

BEGIN

select point_id into v_pointId from points where geom = p_geom;
select code into v_code from points where point_id = v_pointId;

    if (v_pointId is not null)
    then
    select geom into geom_out from regions where code  = v_code;
    RETURN geom_out;
    end if;

-- error handling
exception
when others then
    raise_application_error(-20001,'An error was encountered - '||
sqlcode ||' -error- '|| sqlerrm);
    rollback;
end;


问:
How to redirect to a Sitecore page with Data from Controller action?
I am submitting a form in Sitecore MVC using Html.Sitecore().FormHandler(). My requirement upon validation in the action, it should be redirected to another Sitecore page with some of the form data (I am using Linkmanager for that). How to achieve the same from a Controller action?

答:
You can use RedirectToRoute()and pass parameters between actions as below

```<code>Item item = Sitecore.Context.Database.GetItem(Sitecore.Data.ID.Parse("{GUID_OF_ITEM_WHERE_YOU_WANT_TO_REDIRECT}"));
var pathInfo = LinkManager.GetItemUrl(item, UrlOptions.DefaultOptions);
return RedirectToRoute(MvcSettings.SitecoreRouteName, new { pathInfo = pathInfo.TrimStart(new char[] { '/' }), param1 = actionParam });
</code>```

It works as standard HTTP GET with URL params appended by "?" to your URL, therefore, you can't pass complex models between your actions, only simple types.

Body:
You can use RedirectToRoute()and pass parameters between actions as below

Item item = Sitecore.Context.Database.GetItem(Sitecore.Data.ID.Parse("{GUID_OF_ITEM_WHERE_YOU_WANT_TO_REDIRECT}"));
var pathInfo = LinkManager.GetItemUrl(item, UrlOptions.DefaultOptions);
return RedirectToRoute(MvcSettings.SitecoreRouteName, new { pathInfo = pathInfo.TrimStart(new char[] { '/' }), param1 = actionParam });

It works as standard HTTP GET with URL params appended by "?" to your URL, therefore, you can't pass complex models between your actions, only simple types.


问:
tensorflow.python.framework.errors_impl.ResourceExhaustedError
I'm using an object detection module for classifying images. My specs are as follows:

OS: Ubuntu 18.04 LTS

Python: 3.6.7

VirtualEnv: Version: 16.4.3

Pip3 version inside virtualenv: 19.0.3

TensorFlow Version: 1.13.1

Protoc Version: 3.0.0-9

I'm working on Windows virtualenv and google-colab. This is the error message I get:

```<code>python3 legacy/train.py --logtostderr --train_dir=training/ --pipeline_config_path=training/ssd_mobilenet_v1_pets.config

INFO:tensorflow:global step 1: loss = 18.5013 (48.934 sec/step)
INFO:tensorflow:Finished training! Saving model to disk.
/home/priyank/venv/lib/python3.6/site-packages/tensorflow/python/summary/writer/writer.py:386: UserWarning: Attempting to use a closed FileWriter. The operation will be a noop unless the FileWriter is explicitly reopened.
  warnings.warn("Attempting to use a closed FileWriter. "
Traceback (most recent call last):
  File "legacy/train.py", line 184, in <module>
    tf.app.run()
  File "/home/priyank/venv/lib/python3.6/site-packages/tensorflow/python/platform/app.py", line 125, in run
    _sys.exit(main(argv))
  File "/home/priyank/venv/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py", line 324, in new_func
    return func(*args, **kwargs)
  File "legacy/train.py", line 180, in main
    graph_hook_fn=graph_rewriter_fn)
  File "/home/priyank/venv/models-master/research/object_detection/legacy/trainer.py", line 416, in train
    saver=saver)
  File "/home/priyank/venv/lib/python3.6/site-packages/tensorflow/contrib/slim/python/slim/learning.py", line 785, in train
    ignore_live_threads=ignore_live_threads)
  File "/home/priyank/venv/lib/python3.6/site-packages/tensorflow/python/training/supervisor.py", line 832, in stop
    ignore_live_threads=ignore_live_threads)
  File "/home/priyank/venv/lib/python3.6/site-packages/tensorflow/python/training/coordinator.py", line 389, in join
    six.reraise(*self._exc_info_to_raise)
  File "/home/priyank/venv/lib/python3.6/site-packages/six.py", line 693, in reraise
    raise value
  File "/home/priyank/venv/lib/python3.6/site-packages/tensorflow/python/training/queue_runner_impl.py", line 257, in _run
    enqueue_callable()
  File "/home/priyank/venv/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1257, in _single_operation_run
    self._call_tf_sessionrun(None, {}, [], target_list, None)
  File "/home/priyank/venv/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1407, in _call_tf_sessionrun
    run_metadata)
<b>tensorflow.python.framework.errors_impl.ResourceExhaustedError: OOM when allocating tensor with shape[15,1,1755,2777,3] and type float on /job:localhost/replica:0/task:0/device:CPU:0 by allocator cpu
     [[{{node batch}}]]
Hint: If you want to see a list of allocated tensors when OOM happens, add report_tensor_allocations_upon_oom to RunOptions for current allocation info.</b>
</code>```

答:
You can try the following fixes:

 1. Reducing the image dimension in case you are using very high image resolution

 2. Try reducing the batch size

 3. Check if any other process is using up your memory

Could you also please share your config file

Body:
I'm using an object detection module for classifying images. My specs are as follows:

OS: Ubuntu 18.04 LTS

Python: 3.6.7

VirtualEnv: Version: 16.4.3

Pip3 version inside virtualenv: 19.0.3

TensorFlow Version: 1.13.1

Protoc Version: 3.0.0-9

I'm working on Windows virtualenv and google-colab. This is the error message I get:

python3 legacy/train.py --logtostderr --train_dir=training/ --pipeline_config_path=training/ssd_mobilenet_v1_pets.config

INFO:tensorflow:global step 1: loss = 18.5013 (48.934 sec/step)
INFO:tensorflow:Finished training! Saving model to disk.
/home/priyank/venv/lib/python3.6/site-packages/tensorflow/python/summary/writer/writer.py:386: UserWarning: Attempting to use a closed FileWriter. The operation will be a noop unless the FileWriter is explicitly reopened.
  warnings.warn("Attempting to use a closed FileWriter. "
Traceback (most recent call last):
  File "legacy/train.py", line 184, in <module>
    tf.app.run()
  File "/home/priyank/venv/lib/python3.6/site-packages/tensorflow/python/platform/app.py", line 125, in run
    _sys.exit(main(argv))
  File "/home/priyank/venv/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py", line 324, in new_func
    return func(*args, **kwargs)
  File "legacy/train.py", line 180, in main
    graph_hook_fn=graph_rewriter_fn)
  File "/home/priyank/venv/models-master/research/object_detection/legacy/trainer.py", line 416, in train
    saver=saver)
  File "/home/priyank/venv/lib/python3.6/site-packages/tensorflow/contrib/slim/python/slim/learning.py", line 785, in train
    ignore_live_threads=ignore_live_threads)
  File "/home/priyank/venv/lib/python3.6/site-packages/tensorflow/python/training/supervisor.py", line 832, in stop
    ignore_live_threads=ignore_live_threads)
  File "/home/priyank/venv/lib/python3.6/site-packages/tensorflow/python/training/coordinator.py", line 389, in join
    six.reraise(*self._exc_info_to_raise)
  File "/home/priyank/venv/lib/python3.6/site-packages/six.py", line 693, in reraise
    raise value
  File "/home/priyank/venv/lib/python3.6/site-packages/tensorflow/python/training/queue_runner_impl.py", line 257, in _run
    enqueue_callable()
  File "/home/priyank/venv/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1257, in _single_operation_run
    self._call_tf_sessionrun(None, {}, [], target_list, None)
  File "/home/priyank/venv/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1407, in _call_tf_sessionrun
    run_metadata)
tensorflow.python.framework.errors_impl.ResourceExhaustedError: OOM when allocating tensor with shape[15,1,1755,2777,3] and type float on /job:localhost/replica:0/task:0/device:CPU:0 by allocator cpu
     [[{{node batch}}]]
Hint: If you want to see a list of allocated tensors when OOM happens, add report_tensor_allocations_upon_oom to RunOptions for current allocation info.


问:
Should I call BigQuery for every row insert or should I insert a bulk?
I have a NodeJs service (build on Express) that has 100M requests per day and for every request a new data row is being sent to BigQuery.
Is it better, performance wise, to keep sending the rows separately or should I gather rows and every X seconds/minutes send them to BigQuery as a bulk? (the calls are done asynchronously)

My BigQuery repository class looks something like this: (on Express service launch the repository is initialised by calling .init() and for every row insert the service call .add())

```<code>function BQRepository() {
}

BQRepository.prototype.init = async function() {
    this.bigQueryClient = new BigQuery({ projectId: ..., keyFilename: ... });
}

BQRepository.prototype.add = async function(tableName, obj) {
    this.bigQueryClient
        .dataset(...)
        .table(tableName)
        .insert(obj)
        .then(() => {
          logger.debug(`object added`)
        })
        .catch(err => {
                    logger.error('error occurred')
        });
}

var bqRepo = new BQRepository()
module.exports = bqRepo;
</code>```

答:
I'm not sure there is enough information in the question to provide a cut-and-dry answer to this since you do not appear to be hitting any hard limits with your current transaction per request method. Gathering up requests to do bulk transactions may help limit network I/O at the cost of potentially losing transactions if the service fails in between each bulk transaction. I would recommend doing performance testing to provide a direct comparison of each method and understand their pros & cons for your use case.

One last thing that you neglected could be cost, depending on the size of an individual row. Based off of the BigQuery cost projections:

Individual rows are calculated using a 1 KB minimum size

Depending on the size of your objects, if you have sufficiently small rows you may be being overcharged unless you bundle them up into bulk transactions.

Body:
I have a NodeJs service (build on Express) that has 100M requests per day and for every request a new data row is being sent to BigQuery.
Is it better, performance wise, to keep sending the rows separately or should I gather rows and every X seconds/minutes send them to BigQuery as a bulk? (the calls are done asynchronously)

My BigQuery repository class looks something like this: (on Express service launch the repository is initialised by calling .init() and for every row insert the service call .add())

function BQRepository() {
}

BQRepository.prototype.init = async function() {
    this.bigQueryClient = new BigQuery({ projectId: ..., keyFilename: ... });
}

BQRepository.prototype.add = async function(tableName, obj) {
    this.bigQueryClient
        .dataset(...)
        .table(tableName)
        .insert(obj)
        .then(() => {
          logger.debug(`object added`)
        })
        .catch(err => {
                    logger.error('error occurred')
        });
}

var bqRepo = new BQRepository()
module.exports = bqRepo;


问:
Sending an event on creating a new file in azure data lake gen 1
I want to send an event or a notification to external NIFI flow once a new file has been added to azure data lake gen 1.

Any one worked or has any information about this use case?

答: I found a solution to this problem by using Azure Data Lake Gen 2 we can trigger different kind of events like "Azure Function", and make this function send notification with the path to the file that just added to NIFI flow, which starts with one of the listeners processors like "ListenHttp or HandleHttpRequest" processors. After that we can use any processor fetch this file from your storage.</p>


问:
Moving up a directory
I'm creating a directory in a php script, moving into that directory and doing some stuff. This part works fine.

Now, I want to move out of this directory and delete it.
Any pointers on how to do this?

I have tried moving up 1 level, but it doesnt work

```<code>chdir("../");
chdir("..")
system("cd ..");
</code>```

none of the above have any effect on the present working directory

答:
Don't chdir into that directory once you create it, modify files from outside it, and then remove it.

i.e. instead of doing something like:

```<code>mkdir("dir");
chdir("dir");
write_file("one");
write_file("two");
</code>```

structure your code as:

```<code>mkdir("dir");
write_file("dir/one");
write_file("dir/two");
</code>```

You then don't need to walk the directory hierarchy.

Title: Moving up a directory

Body:
I'm creating a directory in a php script, moving into that directory and doing some stuff. This part works fine.

Now, I want to move out of this directory and delete it.
Any pointers on how to do this?

I have tried moving up 1 level, but it doesnt work

chdir("../");
chdir("..")
system("cd ..");

none of the above have any effect on the present working directory

Body:
Don't chdir into that directory once you create it, modify files from outside it, and then remove it.

i.e. instead of doing something like:

mkdir("dir");
chdir("dir");
write_file("one");
write_file("two");

structure your code as:

mkdir("dir");
write_file("dir/one");
write_file("dir/two");

You then don't need to walk the directory hierarchy.


问:
Can I check if user email verification was successful using Django automated testing?
My AccountActivationView expecting a GET request to path('email/confirm/', if the key exists, AccountActivationView invokes activation function and toggles is_active in user profile.
I'm trying to implement a test for this feature using Django TestCase, but it does not produce the results I'm expecting. The view class redirects Client to the right location, but is_active state of the user account does not change.
Can anyone point me in the right direction, please?</p>

```<code>class TestUserAccounts(TestCase):

    def setUp(self):
        self.client = Client()

        # Initial user data
        self.username = 'TestTest'
        self.email = 'test@test.com'
        self.password = 'test123test'

        # Creating user
        User.objects.create_user(
            email=self.email, username=self.username, password=self.password)

    def test_activating_user(self):
        '''Activating user account using link in the email'''

        user_email_activation_status = EmailActivation.objects.get(
            email=self.email).activated
        user = User.objects.get(email=self.email).is_active
        activation_key = EmailActivation.objects.get(
            email=self.email).key

        # The initial state of account and email should be inactive
        self.assertEqual(user_email_activation_status, False)
        self.assertEqual(user, False)

        # Activating the account with get request to email/confirm/<key>
        activation = self.client.get(
            reverse('accounts:email-activate', kwargs={'key': activation_key}))
        print(activation)

        # Checking if activation was successful
        self.assertEqual(user_email_activation_status, True)
        self.assertEqual(user, True)
</code>```

答:
You just need to rerun the query to check the status of user after you hit the URL to activate the user</p>

```<code>class TestUserAccounts(TestCase):

    def setUp(self):
        self.client = Client()

        # Initial user data
        self.username = 'TestTest'
        self.email = 'test@test.com'
        self.password = 'test123test'

        # Creating user
        User.objects.create_user(
            email=self.email, username=self.username, password=self.password)

    def test_activating_user(self):
        '''Activating user account using link in the email'''
        activation_key = EmailActivation.objects.get(
            email=self.email).key
        user_email_activation_status = EmailActivation.objects.get(
            email=self.email).activated
        user = User.objects.get(email=self.email).is_active
        # The initial state of account and email should be inactive
        self.assertEqual(user_email_activation_status, False)
        self.assertEqual(user, False)

        # Activating the account with get request to email/confirm/<key>
        activation = self.client.get(
            reverse('accounts:email-activate', kwargs={'key': activation_key}))
        print(activation)

        # Checking if activation was successful
        # get the value again after calling the route to activate the user
        user_email_activation_status = EmailActivation.objects.get(
            email=self.email).activated
        user = User.objects.get(email=self.email).is_active
        self.assertEqual(user_email_activation_status, True)
        self.assertEqual(user, True)
</code>```

Body:
My AccountActivationView expecting a GET request to path('email/confirm/', if the key exists, AccountActivationView invokes activation function and toggles is_active in user profile.
I'm trying to implement a test for this feature using Django TestCase, but it does not produce the results I'm expecting. The view class redirects Client to the right location, but is_active state of the user account does not change.
Can anyone point me in the right direction, please?

class TestUserAccounts(TestCase):

    def setUp(self):
        self.client = Client()

        # Initial user data
        self.username = 'TestTest'
        self.email = 'test@test.com'
        self.password = 'test123test'

        # Creating user
        User.objects.create_user(
            email=self.email, username=self.username, password=self.password)

    def test_activating_user(self):
        '''Activating user account using link in the email'''

        user_email_activation_status = EmailActivation.objects.get(
            email=self.email).activated
        user = User.objects.get(email=self.email).is_active
        activation_key = EmailActivation.objects.get(
            email=self.email).key

        # The initial state of account and email should be inactive
        self.assertEqual(user_email_activation_status, False)
        self.assertEqual(user, False)

        # Activating the account with get request to email/confirm/<key>
        activation = self.client.get(
            reverse('accounts:email-activate', kwargs={'key': activation_key}))
        print(activation)

        # Checking if activation was successful
        self.assertEqual(user_email_activation_status, True)
        self.assertEqual(user, True)

Body:
You just need to rerun the query to check the status of user after you hit the URL to activate the user

class TestUserAccounts(TestCase):

    def setUp(self):
        self.client = Client()

        # Initial user data
        self.username = 'TestTest'
        self.email = 'test@test.com'
        self.password = 'test123test'

        # Creating user
        User.objects.create_user(
            email=self.email, username=self.username, password=self.password)

    def test_activating_user(self):
        '''Activating user account using link in the email'''
        activation_key = EmailActivation.objects.get(
            email=self.email).key
        user_email_activation_status = EmailActivation.objects.get(
            email=self.email).activated
        user = User.objects.get(email=self.email).is_active
        # The initial state of account and email should be inactive
        self.assertEqual(user_email_activation_status, False)
        self.assertEqual(user, False)

        # Activating the account with get request to email/confirm/<key>
        activation = self.client.get(
            reverse('accounts:email-activate', kwargs={'key': activation_key}))
        print(activation)

        # Checking if activation was successful
        # get the value again after calling the route to activate the user
        user_email_activation_status = EmailActivation.objects.get(
            email=self.email).activated
        user = User.objects.get(email=self.email).is_active
        self.assertEqual(user_email_activation_status, True)
        self.assertEqual(user, True)


问:
Xcode build failure "Undefined symbols for architecture x86_64"
An Xcode beginner's question:

It is my first experience with Xcode 4.6.3.

I am trying to write a very simple console program, that searches for paired BT devices and prints them to an NSLog.

It builds with the following error:

```<code>Undefined symbols for architecture x86_64:
  "_OBJC_CLASS_$_IOBluetoothDevice", referenced from:
      objc-class-ref in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

I searched like crazy. The common problem should be a reference to a file, of which only the header files are imported and no implementation (*.m-file) is found by the linker. The IOBluetooth library is however, a standard Framework like the Foundation Framework.

What am I missing in my above statement?

I also have tried building it for a 32-bit machine (build fails again). It is clearly a linker error, however I have no idea, to what it relates, except that there is an issue with finding the implementation for IOBluetoothDevice, on both x86 and x64 architecture, while the header files are from a standard included Framework, called IOBluetooth?

For your information my main code "main.m" being:

```<code>#import <Foundation/Foundation.h>
#import <IOBluetooth/objc/IOBluetoothDevice.h>          // Note the import for bluetooth
#import <IOBluetooth/objc/IOBluetoothDeviceInquiry.h>   // Note the import for bluetooth

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        IOBluetoothDevice *currentDevice;
        NSArray *devices = [ IOBluetoothDevice pairedDevices];

        for (id currentDevice in devices){
          NSLog(@"%i : %@",[ currentDevice classOfDevice ], [ currentDevice name ]);
        }
    }
    return 0;
}
</code>```

Thanks for any help or pointers to the right direction.

答:
in my case, removing selection of target membership and then select again fix the issue.

Check William Cerniuk answer with the attachment photo.

Body:
An Xcode beginner's question:

It is my first experience with Xcode 4.6.3.

I am trying to write a very simple console program, that searches for paired BT devices and prints them to an NSLog.

It builds with the following error:

Undefined symbols for architecture x86_64:
  "_OBJC_CLASS_$_IOBluetoothDevice", referenced from:
      objc-class-ref in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I searched like crazy. The common problem should be a reference to a file, of which only the header files are imported and no implementation (*.m-file) is found by the linker. The IOBluetooth library is however, a standard Framework like the Foundation Framework.

What am I missing in my above statement?

I also have tried building it for a 32-bit machine (build fails again). It is clearly a linker error, however I have no idea, to what it relates, except that there is an issue with finding the implementation for IOBluetoothDevice, on both x86 and x64 architecture, while the header files are from a standard included Framework, called IOBluetooth?

For your information my main code "main.m" being:

#import <Foundation/Foundation.h>
#import <IOBluetooth/objc/IOBluetoothDevice.h>          // Note the import for bluetooth
#import <IOBluetooth/objc/IOBluetoothDeviceInquiry.h>   // Note the import for bluetooth

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        IOBluetoothDevice *currentDevice;
        NSArray *devices = [ IOBluetoothDevice pairedDevices];

        for (id currentDevice in devices){
          NSLog(@"%i : %@",[ currentDevice classOfDevice ], [ currentDevice name ]);
        }
    }
    return 0;
}

Thanks for any help or pointers to the right direction.


问:
How do you balance working for a living and contributing to open source projects?
I have been a working programmer since the turn of the century and I have always been fascinated by the open source world. I have wanted to contribute to these projects but I find it difficult to find the time that I think these projects would require.

I find professional software development to be a huge time sink. Almost every project I have worked on has a familiar litany inflexible deadlines and inevitable round the clock last minute pushes that eat up your nights and weekends and everything else in sight. Even in the project that don't have this - the typical work day is 10 to 12 hours and after that one has errands and chores, reading up on the latest stuff, etc...

Since this happens with a fair amount of regularity - I am hesitant to join projects since I can't promise to devote a regular number of hours every week.

My question is how do you people do it?

Do you work at open source companies? Am I exaggerating the amount of time I need to spend (I am thinking a couple of hours everyday)? Am I way off base and simply not managing my time efficiently? How do you manage your time?

答:
1) Go to http://code.google.com/  or a similar website
2) Find a few project you like and email the owner
3) Each week dedicating some time, say 5-10 hours.
4) Have fun </p>

OwnerDisplayName: Nikhil

OwnerDisplayName: Sasha


问:
Flutter : Where is the title of Material App used?
The flutter app name is shown by the package name, the AppBar title is shown on the AppBar of the home page, so where does the title MaterialApp(title: 'Rectangle App',); is used in flutter projects.

```<code>import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Rectangle App',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Rectangle App Home Page'),
        ),
        body: HelloRectangle(),
      ),
    );
  }
}
</code>```

答: In "Flutter for Web", it's used in browser-tabs, which corresponds to the web app's 'title' property.</p>

Body:
The flutter app name is shown by the package name, the AppBar title is shown on the AppBar of the home page, so where does the title MaterialApp(title: 'Rectangle App',); is used in flutter projects.

import 'package:flutter/material.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Rectangle App',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Rectangle App Home Page'),
        ),
        body: HelloRectangle(),
      ),
    );
  }
}


问:
How to number of entries in one column that satisfy condition from another column?
I have a data frame like this:

```<code>head(m,20)

         snp1      snp2    r2
1   rs7278528 rs7278528 1.000
2    rs234750 rs7278528 0.841
3    rs413621 rs7278528 0.841
4    rs413624 rs7278528 0.568
5   rs4920017 rs7278528 0.841
6    rs393280 rs7278528 0.821
7   rs1788470 rs7278528 0.568
8  rs10887972 rs7278528 0.568
9    rs439861 rs7278528 0.568
10  rs1672133 rs7278528 0.841
11   rs370994 rs7278528 0.841
12   rs442981 rs7278528 0.841
...
</code>```

I would like to calculate and output in a separate column for each unique value in snp2, how many snp1 have r2 > 0.8

I tired doing this but no success:

```<code>m %>%
  group_by(snp1) %>%
  summarize(sumR2 = sumRows(snp1[r2>0.8]))
</code>```

UPDATE

this solved my problem:

```<code>t <- filter(m, r2 >= 0.8) %>% group_by(snp1) %>% mutate(ldbuds = length(r2))
</code>```

答:
Based on the description, we may need to group by 'snp2', extract the 'snp1' that corresponds to where 'r2' is greater than 0.8 and get the length of unique elements of 'snp1'

```<code>library(tidyverse)
m %>%
  group_by(snp2) %>%
  summarize(sumR2 = n_distinct(snp1[r2>0.8]))
</code>```

Or it could be

```<code>m %>%
   group_by(snp2) %>%
   summarise(sumR2 =  sum(r2 > 0.8, na.rm = TRUE))
</code>```

Body:
I have a data frame like this:

head(m,20)

         snp1      snp2    r2
1   rs7278528 rs7278528 1.000
2    rs234750 rs7278528 0.841
3    rs413621 rs7278528 0.841
4    rs413624 rs7278528 0.568
5   rs4920017 rs7278528 0.841
6    rs393280 rs7278528 0.821
7   rs1788470 rs7278528 0.568
8  rs10887972 rs7278528 0.568
9    rs439861 rs7278528 0.568
10  rs1672133 rs7278528 0.841
11   rs370994 rs7278528 0.841
12   rs442981 rs7278528 0.841
...

I would like to calculate and output in a separate column for each unique value in snp2, how many snp1 have r2 > 0.8

I tired doing this but no success:

m %>%
  group_by(snp1) %>%
  summarize(sumR2 = sumRows(snp1[r2>0.8]))

UPDATE

this solved my problem:

t <- filter(m, r2 >= 0.8) %>% group_by(snp1) %>% mutate(ldbuds = length(r2))

Body:
Based on the description, we may need to group by 'snp2', extract the 'snp1' that corresponds to where 'r2' is greater than 0.8 and get the length of unique elements of 'snp1'

library(tidyverse)
m %>%
  group_by(snp2) %>%
  summarize(sumR2 = n_distinct(snp1[r2>0.8]))

Or it could be

m %>%
   group_by(snp2) %>%
   summarise(sumR2 =  sum(r2 > 0.8, na.rm = TRUE))


问:
Is there a good way to edit images with php?
I'm currently trying to set up a html gallery with a php script that automaticaly resizes them an puts them into the gallery. My problem now is that there are around 30 pictures and:

It takes forever to load the site.

The images don't load properly. The string thats looks like binary? I don't know

Thats the only php code I'm running:

```<code><?php
            $directory = "images/gallery/feet";
            $images = glob($directory . "/*.jpg");

            foreach ($images as $image) {

              //getting the image dimensions
              list($width, $height) = getimagesize($image);

              //saving the image into memory (for manipulation with GD Library)
              $image = imagecreatefromjpeg($image);

              // calculating the part of the image to use for thumbnail
              if ($width > $height) {
                $y = 0;
                $x = ($width - $height) / 2;
                $smallestSide = $height;
              } else {
                $x = 0;
                $y = ($height - $width) / 2;
                $smallestSide = $width;
              }
              $thumbSize = 500;
              $thumb = imagecreatetruecolor($thumbSize, $thumbSize);
              imagecopyresampled($thumb, $image, 0, 0, $x, $y, $thumbSize, $thumbSize, $smallestSide, $smallestSide);

              imagejpeg($thumb, null, 100);

              echo "<div class=\"carousel-item\">";
              echo "<img class=\"d-block w-100\" src=\"${thumb}\" />";
              echo "</div>";
            }
            ?>
</code>```

Do you know what I can do?

答:
Don't try to run the resizing algorithm for every image with every page load, that's a stupidly expensive process.

Run it once - EVER - for each file, and stick the thumbnails in a child directory.

Then just give the link to the thumbnail image file and let your web server handle your headers so that the image is properly rendered, instead of getting the base64 string.

Something like

```<code><?php
$directory = "images/gallery/feet";
$thmb_dir = $directory . "/thumbnail";
$images = glob($directory . "/*.jpg");

foreach ($images as $image) {

    if (/*thumbnail doesn't already exist*/) {

        //getting the image dimensions
        list($width, $height) = getimagesize($image);

        //saving the image into memory (for manipulation with GD Library)
        $image = imagecreatefromjpeg($image);

        // calculating the part of the image to use for thumbnail
        if ($width > $height) {
            $y = 0;
            $x = ($width - $height) / 2;
            $smallestSide = $height;
        } else {
            $x = 0;
            $y = ($height - $width) / 2;
            $smallestSide = $width;
        }
        $thumbSize = 500;
        $thumb = imagecreatetruecolor($thumbSize, $thumbSize);
        imagecopyresampled($thumb, $image, 0, 0, $x, $y, $thumbSize, $thumbSize, $smallestSide, $smallestSide);

        imagejpeg($thumb, null, 100);

        // Save this image w/ the same name in /thumbnails - I just made up this function name
        saveThumb($thumb, $thmb_dir);
    }

    // Grab the thumbnail with the right name - another made-up function name
    $thumb_link = getThumbLink($image)

    echo "<div class=\"carousel-item\">";
    echo "<img class=\"d-block w-100\" src=\"${thumb_link}\" />";
    echo "</div>";
}
</code>```

?>

Body:
I'm currently trying to set up a html gallery with a php script that automaticaly resizes them an puts them into the gallery. My problem now is that there are around 30 pictures and:

It takes forever to load the site.

The images don't load properly. The string thats looks like binary? I don't know

Thats the only php code I'm running:

<?php
            $directory = "images/gallery/feet";
            $images = glob($directory . "/*.jpg");

            foreach ($images as $image) {

              //getting the image dimensions
              list($width, $height) = getimagesize($image);

              //saving the image into memory (for manipulation with GD Library)
              $image = imagecreatefromjpeg($image);

              // calculating the part of the image to use for thumbnail
              if ($width > $height) {
                $y = 0;
                $x = ($width - $height) / 2;
                $smallestSide = $height;
              } else {
                $x = 0;
                $y = ($height - $width) / 2;
                $smallestSide = $width;
              }
              $thumbSize = 500;
              $thumb = imagecreatetruecolor($thumbSize, $thumbSize);
              imagecopyresampled($thumb, $image, 0, 0, $x, $y, $thumbSize, $thumbSize, $smallestSide, $smallestSide);

              imagejpeg($thumb, null, 100);

              echo "
";
              echo "";
              echo "
";
            }
            ?>

Do you know what I can do?

Body:
Don't try to run the resizing algorithm for every image with every page load, that's a stupidly expensive process.

Run it once - EVER - for each file, and stick the thumbnails in a child directory.

Then just give the link to the thumbnail image file and let your web server handle your headers so that the image is properly rendered, instead of getting the base64 string.

Something like

<?php
$directory = "images/gallery/feet";
$thmb_dir = $directory . "/thumbnail";
$images = glob($directory . "/*.jpg");

foreach ($images as $image) {

    if (/*thumbnail doesn't already exist*/) {

        //getting the image dimensions
        list($width, $height) = getimagesize($image);

        //saving the image into memory (for manipulation with GD Library)
        $image = imagecreatefromjpeg($image);

        // calculating the part of the image to use for thumbnail
        if ($width > $height) {
            $y = 0;
            $x = ($width - $height) / 2;
            $smallestSide = $height;
        } else {
            $x = 0;
            $y = ($height - $width) / 2;
            $smallestSide = $width;
        }
        $thumbSize = 500;
        $thumb = imagecreatetruecolor($thumbSize, $thumbSize);
        imagecopyresampled($thumb, $image, 0, 0, $x, $y, $thumbSize, $thumbSize, $smallestSide, $smallestSide);

        imagejpeg($thumb, null, 100);

        // Save this image w/ the same name in /thumbnails - I just made up this function name
        saveThumb($thumb, $thmb_dir);
    }

    // Grab the thumbnail with the right name - another made-up function name
    $thumb_link = getThumbLink($image)

    echo "<div class=\"carousel-item\">";
    echo "<img class=\"d-block w-100\" src=\"${thumb_link}\" />";
    echo "</div>";
}

?>


问:
Result id from database by mysql?
I have a column in database saved as id like 1,12,10 and I want to return only one id like 1 or 12 or 10 when use like will return wrong data? What can I do?</p>

答:
You can use LIMIT.

```<code>SELECT col FROM table_name LIMIT 1
</code>```

This will only return one result.

However you are claiming that it is returning the wrong results, which we can't help if you don't post more.

Update

as per your comment, you want to use IN

```<code>SELECT col FROM table_name WHERE id IN (10, 12, 1)
</code>```

Title: Result id from database by mysql?

Body:
You can use LIMIT.

SELECT col FROM table_name LIMIT 1

This will only return one result.

However you are claiming that it is returning the wrong results, which we can't help if you don't post more.

Update

as per your comment, you want to use IN

SELECT col FROM table_name WHERE id IN (10, 12, 1)


问:
Load login page without Sidebar, Navbar and Dashboard in React
How to load login page without sidebar, navbar and dashboard?

答:
Well, I will suggest that you should have separate container for Credentials and Login and Signup should be the components.

That page should have public routing, which means it could be viewed by general public. Your Navbar, Sidebar and Dashboard should be other components and should not be included in Login and Signup components.