问:
Combine all values of a map where each value is a dataframe
In Scala using Spark, I have a Map where the key is a String, and the value is a DataFrame.

Schema looks like this:

```<code>scala.collection.immutable.Map[String,org.apache.spark.sql.DataFrame] = Map(Key_A -> [value_col1: string, value_col2: string ... 1 more field], Key_B -> [value_col1: string, value_col2: string ... 1 more field])
</code>```

I do not care about the keys here. I want a dataframe that combines all the values and would look like this.

```<code>value_col1     value_col2
    1               2
    1.1             2.2
</code>```

I am looking to see how to do this using simple as well as recommended/efficient approaches.

答:
You can use map to iterate among the map values and merge the dataframes. If your schema remains identical for all the dataframes you can use a union to merge the data:

val mapping = Map("df1" -> df1, "df2" -> df)

val finalDF = mapping.values.map{df =>
  df.select("*")
}.reduce((d0, d1) => d0.union(d1))
```

<p>Otherwise, if the dataframes have different schema then replace the <code>union</code> with an <code>inner join</code>:</p>

<pre class="lang-scala prettyprint-override"><code>val finalDF = mapping.values.map{df =>
  df.select("*")
}.reduce((d0, d1) => d0.join(d1, "id"))
</code>```

Here we assume that the dataframes share the same id field.

Body:
In Scala using Spark, I have a Map where the key is a String, and the value is a DataFrame.

Schema looks like this:

scala.collection.immutable.Map[String,org.apache.spark.sql.DataFrame] = Map(Key_A -> [value_col1: string, value_col2: string ... 1 more field], Key_B -> [value_col1: string, value_col2: string ... 1 more field])

I do not care about the keys here. I want a dataframe that combines all the values and would look like this.

value_col1     value_col2
    1               2
    1.1             2.2

I am looking to see how to do this using simple as well as recommended/efficient approaches.

Body:
You can use map to iterate among the map values and merge the dataframes. If your schema remains identical for all the dataframes you can use a union to merge the data:

val mapping = Map("df1" -> df1, "df2" -> df)

val finalDF = mapping.values.map{df =>
  df.select("*")
}.reduce((d0, d1) => d0.union(d1))

Otherwise, if the dataframes have different schema then replace the union with an inner join:

val finalDF = mapping.values.map{df =>
  df.select("*")
}.reduce((d0, d1) => d0.join(d1, "id"))

Here we assume that the dataframes share the same id field.


来源: stackexchange

问:
azure data factory v2 copy data activity recursive
I am new to azure Data factory v2

I have a folder having 2 files F1.csv and F2.csv in a blob storage.

I have a created a copy data pipeline activity to load the data from file to a table in azure DWH with 3 parameters and copy recursively was made to false.

Parameter1: container

Parameter2: directory

Parameter3: F1.csv

executed successfully when used the above parameters for the copy data activity.

But the data has been loaded from two files, only one file has given as parameter for the activity

答:
Can you please check the "wildcard file name" parameter ( Select the pipeline and look under the source tab )  ?

If it is set as  .  please remove that and it should work .

ContentLicense: CC BY-SA 4.0


问:
Import file from one directory up
I am working to import a file from one directory up.

```<code>Fitv/
  __init__.py
  BrowserPool.py
  FitvTests/
    __init__.py
    environment.py
</code>```

So with the above file structure, I want to import BrowserPool into environment.

I started with:

```<code>from Fitv.BrowserPool import BrowserPool
</code>```

And got this:

```<code>  File "..\environment.py", line 4, in <module>
    from Fitv.BrowserPool import BrowserPool
ModuleNotFoundError: No module named 'Fitv'
</code>```

Looking at various sources I tried:

```<code>from .. import BrowserPool
</code>```

I got this:

```<code>  File "..\environment.py", line 3, in <module>
    from .. import BrowserPool
KeyError: "'__name__' not in globals"
</code>```

Tried (used absolute path):

```<code>import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath('D:/Dev/Python/Fitv-master-new/Fitv/'))))
from Fitv.BrowserPool import BrowserPool
</code>```

Got:

```<code>  File "..\environment.py", line 3, in <module>
    from Fitv.BrowserPool import BrowserPool
ModuleNotFoundError: No module named 'Fitv'
</code>```

Tried (used relative path):

```<code>import sys
sys.path.append('/Fitv-master-new/Fitv/')
from Fitv import BrowserPool
</code>```

Got:

```<code>  File "..\environment.py", line 8, in <module>
    from Fitv import BrowserPool
ModuleNotFoundError: No module named 'Fitv'
</code>```

What am I doing wrong and how do I fix it?

答:
Imports in Python are always relative to the path that the Python interpreter runs from, and from the path to environment.py shown in your trackback that includes a ..:

```<code>File "..\environment.py", line 8, in <module>
</code>```

it is apparent that you are running environment.py from a sub-directory under the FitvTests, rather than the same directory where environment.py is located, in which case the .. in your import statement would simply refer to the FitvTests directory rather than its parent directory, Fitv.

You should either run environment.py from the FitvTests directory, or if you have a good reason to run it from the sub-directory you currently run it from, use ... instead to refer to the directory 2 levels up:

```<code>from ...BrowserPool import BrowserPool
</code>```

Title: Import file from one directory up

Body:
I am working to import a file from one directory up.

Fitv/
  __init__.py
  BrowserPool.py
  FitvTests/
    __init__.py
    environment.py

So with the above file structure, I want to import BrowserPool into environment.

I started with:

from Fitv.BrowserPool import BrowserPool

And got this:

  File "..\environment.py", line 4, in <module>
    from Fitv.BrowserPool import BrowserPool
ModuleNotFoundError: No module named 'Fitv'

Looking at various sources I tried:

from .. import BrowserPool

I got this:

  File "..\environment.py", line 3, in <module>
    from .. import BrowserPool
KeyError: "'__name__' not in globals"

Tried (used absolute path):

import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath('D:/Dev/Python/Fitv-master-new/Fitv/'))))
from Fitv.BrowserPool import BrowserPool

Got:

  File "..\environment.py", line 3, in <module>
    from Fitv.BrowserPool import BrowserPool
ModuleNotFoundError: No module named 'Fitv'

Tried (used relative path):

import sys
sys.path.append('/Fitv-master-new/Fitv/')
from Fitv import BrowserPool

Got:

  File "..\environment.py", line 8, in <module>
    from Fitv import BrowserPool
ModuleNotFoundError: No module named 'Fitv'

What am I doing wrong and how do I fix it?

Body:
Imports in Python are always relative to the path that the Python interpreter runs from, and from the path to environment.py shown in your trackback that includes a ..:

File "..\environment.py", line 8, in <module>

it is apparent that you are running environment.py from a sub-directory under the FitvTests, rather than the same directory where environment.py is located, in which case the .. in your import statement would simply refer to the FitvTests directory rather than its parent directory, Fitv.

You should either run environment.py from the FitvTests directory, or if you have a good reason to run it from the sub-directory you currently run it from, use ... instead to refer to the directory 2 levels up:

from ...BrowserPool import BrowserPool


问:
Issues with POST and PUT in table with comma separated numeric values
I am running into issues with POST and PUT for my backend. The relevant table structure can be seen here

```<code>DROP TABLE IF EXISTS coordinate;
CREATE TABLE coordinate
(
   id                    int(10) NOT NULL auto_increment,
   longitude             double(8,4) NOT NULL,
   latitude              double(8,4) NOT NULL,
   measurementId         int(10) default NULL,
   PRIMARY KEY (id),
   FOREIGN KEY (measurementId)
        REFERENCES measurement (id)
        ON DELETE CASCADE
);
</code>```

It has a corresponding Model, which looks like this

```<code>public class Coordinate
{
    public Coordinate()
    {

    }

    public int ID { get; set; }

    public double Latitude { get; set; }

    public double Longitude { get; set; }

    public int MeasurementId { get; set; }

    ...
}
</code>```

I am trying to insert numeric values into coordinate like so:

```<code>sql = "UPDATE coordinate SET longitude = '" + coordinate.Longitude + "," + " latitude = " + coordinate.Latitude + "," + " measurementId = " + coordinate.MeasurementId + "' WHERE id = " + id.ToString();
</code>```

Notice the inclusion of the single bracket before the double bracket after longitude = '" and + "' WHERE ...

When I run this with a debugger the string sql is constructed like so:

```<code>sql = "UPDATE coordinate SET longitude = '55,6, latitude = 70,33, measurementId = 2' WHERE id = 2'
</code>```

And my backend throws the following error:

```<code>{
 "Message": "An error has occurred.",
 "ExceptionMessage": "Data truncated for column 'longitude' at row 1",
 "ExceptionType": "MySql.Data.MySqlClient.MySqlException",
 ...
}
</code>```

My hunch is that the sql string is not constructed properly because of the inclusion of the single bracket, so I remove it like and construct a new sql string like so:

```<code>sql = "UPDATE coordinate SET longitude = " + coordinate.Longitude + "," + " latitude = " + coordinate.Latitude + "," + " measurementId = " + coordinate.MeasurementId + " WHERE id = " + id.ToString();
</code>```

Notice the removal of the single bracket ' in the places it was present before. Now, in the debugger, the string sql is constructed like so:

```<code>sql = "UPDATE coordinate SET longitude 55,6 latitude = 70,33, measurementId = 2 WHERE id = 2"
</code>```

It's my impression that the numeric values should be separated by a . and not a ,, which could by why the backend now throws this error:

```<code>{
 "Message": "An error has occurred.",
 "ExceptionMessage": "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 '6, latitude = 70,33, measurementId = 2 WHERE id = 2' at line 1",
}
</code>```

I am a bit at a loss on how to then handle the insertion of numeric values in my database. Any help is much appreciated.

答:
As pointed out by in the comments to my question, using a parameterized query solved the issue with the added benefit of securing the SQL query. While DubDub's answer was an okay workaround, the following solves it in a more scalable, secure way.

The SQL query now looks like this:

```<code> string sql = "UPDATE coordinate SET longitude = @Longitude, latitude = @Latitude, measurementId = @MeasurementId WHERE id = @ID";

 List<MySqlParameter> parameters = SqlFactory.CreateParametersFor(coordinate);

 cmd = SqlFactory.CreateParameterizedQuery(sql, parameters, conn);

 cmd.Parameters.Add(ID);

 await cmd.ExecuteNonQueryAsync();
</code>```

Where the CreateParametersFor() and CreateParameterizedQuery() are implemented like so:

```<code>public static MySqlCommand CreateParameterizedQuery(string sql, List<MySqlParameter> parameters, MySqlConnection connection)
    {
        MySqlCommand cmd = new MySqlCommand(sql, connection);
        foreach (MySqlParameter parameter in parameters) cmd.Parameters.Add(parameter);
        return cmd;
    }

    public static List<MySqlParameter> CreateParametersFor(Coordinate coordinate)
    {
        List<MySqlParameter> parameters = new List<MySqlParameter>();

        MySqlParameter latitude = new MySqlParameter()
        {
            ParameterName = "@Latitude",
            Value = coordinate.Latitude
        };

        MySqlParameter longitude = new MySqlParameter()
        {
            ParameterName = "@Longitude",
            Value = coordinate.Longitude
        };

        MySqlParameter measurementId = new MySqlParameter()
        {
            ParameterName = "@MeasurementId",
            Value = coordinate.MeasurementId
        };

        parameters.Add(latitude);
        parameters.Add(longitude);
        parameters.Add(measurementId);

        return parameters;
    }
</code>```

Body:
I am running into issues with POST and PUT for my backend. The relevant table structure can be seen here

DROP TABLE IF EXISTS coordinate;
CREATE TABLE coordinate
(
   id                    int(10) NOT NULL auto_increment,
   longitude             double(8,4) NOT NULL,
   latitude              double(8,4) NOT NULL,
   measurementId         int(10) default NULL,
   PRIMARY KEY (id),
   FOREIGN KEY (measurementId)
        REFERENCES measurement (id)
        ON DELETE CASCADE
);

It has a corresponding Model, which looks like this

public class Coordinate
{
    public Coordinate()
    {

    }

    public int ID { get; set; }

    public double Latitude { get; set; }

    public double Longitude { get; set; }

    public int MeasurementId { get; set; }

    ...
}

I am trying to insert numeric values into coordinate like so:

sql = "UPDATE coordinate SET longitude = '" + coordinate.Longitude + "," + " latitude = " + coordinate.Latitude + "," + " measurementId = " + coordinate.MeasurementId + "' WHERE id = " + id.ToString();

Notice the inclusion of the single bracket before the double bracket after longitude = '" and + "' WHERE ...

When I run this with a debugger the string sql is constructed like so:

sql = "UPDATE coordinate SET longitude = '55,6, latitude = 70,33, measurementId = 2' WHERE id = 2'

And my backend throws the following error:

{
 "Message": "An error has occurred.",
 "ExceptionMessage": "Data truncated for column 'longitude' at row 1",
 "ExceptionType": "MySql.Data.MySqlClient.MySqlException",
 ...
}

My hunch is that the sql string is not constructed properly because of the inclusion of the single bracket, so I remove it like and construct a new sql string like so:

sql = "UPDATE coordinate SET longitude = " + coordinate.Longitude + "," + " latitude = " + coordinate.Latitude + "," + " measurementId = " + coordinate.MeasurementId + " WHERE id = " + id.ToString();

Notice the removal of the single bracket ' in the places it was present before. Now, in the debugger, the string sql is constructed like so:

sql = "UPDATE coordinate SET longitude 55,6 latitude = 70,33, measurementId = 2 WHERE id = 2"

It's my impression that the numeric values should be separated by a . and not a ,, which could by why the backend now throws this error:

{
 "Message": "An error has occurred.",
 "ExceptionMessage": "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 '6, latitude = 70,33, measurementId = 2 WHERE id = 2' at line 1",
}

I am a bit at a loss on how to then handle the insertion of numeric values in my database. Any help is much appreciated.

Body:
As pointed out by in the comments to my question, using a parameterized query solved the issue with the added benefit of securing the SQL query. While DubDub's answer was an okay workaround, the following solves it in a more scalable, secure way.

The SQL query now looks like this:

 string sql = "UPDATE coordinate SET longitude = @Longitude, latitude = @Latitude, measurementId = @MeasurementId WHERE id = @ID";

 List<MySqlParameter> parameters = SqlFactory.CreateParametersFor(coordinate);

 cmd = SqlFactory.CreateParameterizedQuery(sql, parameters, conn);

 cmd.Parameters.Add(ID);

 await cmd.ExecuteNonQueryAsync();

Where the CreateParametersFor() and CreateParameterizedQuery() are implemented like so:

public static MySqlCommand CreateParameterizedQuery(string sql, List<MySqlParameter> parameters, MySqlConnection connection)
    {
        MySqlCommand cmd = new MySqlCommand(sql, connection);
        foreach (MySqlParameter parameter in parameters) cmd.Parameters.Add(parameter);
        return cmd;
    }

    public static List<MySqlParameter> CreateParametersFor(Coordinate coordinate)
    {
        List<MySqlParameter> parameters = new List<MySqlParameter>();

        MySqlParameter latitude = new MySqlParameter()
        {
            ParameterName = "@Latitude",
            Value = coordinate.Latitude
        };

        MySqlParameter longitude = new MySqlParameter()
        {
            ParameterName = "@Longitude",
            Value = coordinate.Longitude
        };

        MySqlParameter measurementId = new MySqlParameter()
        {
            ParameterName = "@MeasurementId",
            Value = coordinate.MeasurementId
        };

        parameters.Add(latitude);
        parameters.Add(longitude);
        parameters.Add(measurementId);

        return parameters;
    }


问:
How can i check if the function exists in my class
i started using Javascript OOP i'm still beginner,
i created a class and i want to know if the deleteQuote function exists in my class ?

This is my Class code

```<code>class Quote{

deleteQuote(callback){
    $('tr#'+callback.quoteid).hide('slow', function(){
        $(this).remove();
    });
}}

var quote = new Quote();
var y = quote.deleteQuote();
console.log(typeof y);
</code>```

Thank you

答:
You should use its typeof like this:

class Quote {

  deleteQuote(callback) {
    $('tr#' + callback.quoteid).hide('slow', function() {
      $(this).remove();
    });
  }
}

var quote = new Quote();
let exists = typeof quote.deleteQuote !== "undefined";
console.log(exists);```

typeof returns the variable type of the element you provide. In this case, when it returns undefined, it means that the object, method, property, function, etc. of what you are searching, is not defined.

Body:
i started using Javascript OOP i'm still beginner,
i created a class and i want to know if the deleteQuote function exists in my class ?

This is my Class code

class Quote{

deleteQuote(callback){
    $('tr#'+callback.quoteid).hide('slow', function(){
        $(this).remove();
    });
}}

var quote = new Quote();
var y = quote.deleteQuote();
console.log(typeof y);

Thank you

Body:
You should use its typeof like this:

class Quote {

  deleteQuote(callback) {
    $('tr#' + callback.quoteid).hide('slow', function() {
      $(this).remove();
    });
  }
}

var quote = new Quote();
let exists = typeof quote.deleteQuote !== "undefined";
console.log(exists);

typeof returns the variable type of the element you provide. In this case, when it returns undefined, it means that the object, method, property, function, etc. of what you are searching, is not defined.


问:
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

答:
You need to use backticks instead of single quotes for column names:

```<code>`Nome`
</code>```

this is the reason for the syntax error. It is also possible to use no quotes at all.

Also, your code is vulnerable to SQL injection. Read up on the issue, it's essential for security.

To fix the vulnerability at hand, do the following on every variable:

```<code>$Nome = mysql_real_escape_string($_POST["Nome"]);
</code>```

and then insert the escaped variable:

```<code>SET `Nome` = '$Nome',
</code>```

ContentLicense: CC BY-SA 3.0

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

Body:
You need to use backticks instead of single quotes for column names:

`Nome`

this is the reason for the syntax error. It is also possible to use no quotes at all.

Also, your code is vulnerable to SQL injection. Read up on the issue, it's essential for security.

To fix the vulnerability at hand, do the following on every variable:

$Nome = mysql_real_escape_string($_POST["Nome"]);

and then insert the escaped variable:

SET `Nome` = '$Nome',


问:
Firebase InAppMessaging crashing my project with "-[NSBundle initWithURL:]: nil URL argument"
I recently added Firebase In-App Messaging to my project via cocoapods. After following the setup process in the documentation, I'm getting the error below. If it helps, I also have recently installed Admob but this error didn't show up until I installed in-app messaging. The thing that baffles me is: there is hardly any code to set this up, so where could I be getting a nil URL error?

At first, I wasn't sure it was Firebase I.A.M. causing the problem, but after deleting and reinstalling it, the issue went away then reappeared. So, I'll describe how I installed Firebase IAM. I used this link for reference:

https://firebase.google.com/docs/in-app-messaging/get-started?authuser=0

Added it to my Podfile, with cocoapods 1.4.0

Added the "-FIRDebugEnabled" to my schemes

Got my instance ID, and added it to my campaign in the console

Double checked my schemes

Error:

```<code>    Terminating app due to uncaught exception
    'NSInvalidArgumentException', reason: ' -[NSBundle initWithURL:]: nil URL argument'
    First throw call stack:
    (0x234b8cec4 0x233d5da40 0x234a93594 0x23554f6a8 0x23554f62c
    0x10027a1b8 0x10248cdc8 0x10248ee28 0x10027a0f8 0x10027a2c0
    0x10027b518 0x100267038 0x100260888 0x100266e44 0x100267328
    0x100264bd0 0x10248b824 0x10248cdc8 0x10248fc90 0x10249e1dc
    0x10249ebc8 0x2347a917c 0x2347abcec)
    libc++abi.dylib: terminating with uncaught exception of type NSException
</code>```

In the console, my instance ID appears, then some more information, then the error, So I have no clue as to what could be causing it to happen. Here is some of the output in my console:

```<code>     [Firebase/InAppMessaging][I-IAM700004] 1 messages were fetched successfully.
    [Firebase/InAppMessaging][I-IAM270005] No impression records update due to no change after applying the server message list
    [Firebase/InAppMessaging][I-IAM160010] There are analytics event trigger based messages, enable listening
    [Firebase/InAppMessaging][I-IAM160001] There are 0 test messages and 1 regular messages and 3 Firebase analytics events to watch after resetting the message cache
    [Firebase/InAppMessaging][I-IAM240002] Fetch is done. Start message rendering flow.
</code>```

For reference, I've looked through all these links and more when you google the error:

search 1

search 2

search 3

search 4

Any ideas?

答:
I started debugging app by placing breakpoint where the path for the resource was nil. when you hit a breakpoint, the value was nil & showed proj_name was compiled with optimization - stepping may behave oddly.. message.

This prevented us from watching real variable values because the in pod project setting optimization was different from main & target setting, so change to None.

Pods > Project Setting > Build Setting > Code Generation

Now I was able to see value/path for the main app bundle, but InAppMessagingDisplayResources.bundle was still missing from proj_name.app which gave a hint that there is a mistake while copying file. Found out that in Copy pod resource section flag for Run script only when installing was checked. Unchecked it, the app didn't crash for missing bundle.

Target Setting > Build Phases > Copy Pod Resources

Body:
I recently added Firebase In-App Messaging to my project via cocoapods. After following the setup process in the documentation, I'm getting the error below. If it helps, I also have recently installed Admob but this error didn't show up until I installed in-app messaging. The thing that baffles me is: there is hardly any code to set this up, so where could I be getting a nil URL error?

At first, I wasn't sure it was Firebase I.A.M. causing the problem, but after deleting and reinstalling it, the issue went away then reappeared. So, I'll describe how I installed Firebase IAM. I used this link for reference:

https://firebase.google.com/docs/in-app-messaging/get-started?authuser=0

Added it to my Podfile, with cocoapods 1.4.0

Added the "-FIRDebugEnabled" to my schemes

Got my instance ID, and added it to my campaign in the console

Double checked my schemes

Error:

    Terminating app due to uncaught exception
    'NSInvalidArgumentException', reason: ' -[NSBundle initWithURL:]: nil URL argument'
    First throw call stack:
    (0x234b8cec4 0x233d5da40 0x234a93594 0x23554f6a8 0x23554f62c
    0x10027a1b8 0x10248cdc8 0x10248ee28 0x10027a0f8 0x10027a2c0
    0x10027b518 0x100267038 0x100260888 0x100266e44 0x100267328
    0x100264bd0 0x10248b824 0x10248cdc8 0x10248fc90 0x10249e1dc
    0x10249ebc8 0x2347a917c 0x2347abcec)
    libc++abi.dylib: terminating with uncaught exception of type NSException

In the console, my instance ID appears, then some more information, then the error, So I have no clue as to what could be causing it to happen. Here is some of the output in my console:

     [Firebase/InAppMessaging][I-IAM700004] 1 messages were fetched successfully.
    [Firebase/InAppMessaging][I-IAM270005] No impression records update due to no change after applying the server message list
    [Firebase/InAppMessaging][I-IAM160010] There are analytics event trigger based messages, enable listening
    [Firebase/InAppMessaging][I-IAM160001] There are 0 test messages and 1 regular messages and 3 Firebase analytics events to watch after resetting the message cache
    [Firebase/InAppMessaging][I-IAM240002] Fetch is done. Start message rendering flow.

For reference, I've looked through all these links and more when you google the error:

search 1

search 2

search 3

search 4

Any ideas?


问:
"Show Item With No Data" function is not working after making relationship between two table. How to Fix This?
Power BI Desktop - I have two tables with Unique value.
Table one contains - Target for Each region.
e.g. APAC - 50, NA - 100, Europe - 200
Table two contains - Sales achievement for each region.
e.g. NA - 70, Europe - 90

Now Problem is - APAC region is not listed in 2nd Table. i created a matrix table and showing both table value in one table through relationship but after making the relationship, APAC region is not showing in third table list because its not there in 2nd table.

So please suggest how can i fix this?

I tried with "Show Items with No data" but it is also not working.

I want the unique list of regions from table 1 & 2 in 3rd table irrespective of value assigned to them or not.

答:
How about creating a third table from unique region-values with DAX?
Something like this:

```<code>UniquesTable = DISTINCT(UNION(VALUES(Table1[Region]),VALUES(Table2[Region])))
</code>```

You should connect Table1 and Table2 to UniquesTable in the Relationships-tab so that calculations with targets and achievements work as expected

Body:
How about creating a third table from unique region-values with DAX?
Something like this:

UniquesTable = DISTINCT(UNION(VALUES(Table1[Region]),VALUES(Table2[Region])))

You should connect Table1 and Table2 to UniquesTable in the Relationships-tab so that calculations with targets and achievements work as expected


问:
How to remove invisible chars in bash (tr and sed not working)
I want to remove invisible chars from a response:

Here is my code:

```<code>test_id=`clasp run testRunner`
echo "visible"
echo "$test_id"
echo "invisible"
echo "$test_id" | cat -v
echo "invisible2"
echo "$test_id" | tr -dc '[:print:]' | cat -v
echo "invisible3"
echo "$test_id" | sed 's/[^a-zA-Z0-9]//g' | cat -v
echo "invisible4"
printf '%q\n' "$test_id"
</code>```

Here's the output:

```<code>visible
1d5422fb
invisible
^[[2K^[[1G1d5422fb
invisible2
[2K[1G1d5422fbinvisible3
2K1G1d5422fb
invisible4
$'\E[2K\E[1G1d5422fb'
</code>```

答:
Instead of removing the escape sequences prevent them from being generated, which I guess you can do with</p>

```<code>test_id=$(TERM=dumb clasp run testRunner)
</code>```

Body:
I want to remove invisible chars from a response:

Here is my code:

test_id=`clasp run testRunner`
echo "visible"
echo "$test_id"
echo "invisible"
echo "$test_id" | cat -v
echo "invisible2"
echo "$test_id" | tr -dc '[:print:]' | cat -v
echo "invisible3"
echo "$test_id" | sed 's/[^a-zA-Z0-9]//g' | cat -v
echo "invisible4"
printf '%q\n' "$test_id"

Here's the output:

visible
1d5422fb
invisible
^[[2K^[[1G1d5422fb
invisible2
[2K[1G1d5422fbinvisible3
2K1G1d5422fb
invisible4
$'\E[2K\E[1G1d5422fb'

Body:
Instead of removing the escape sequences prevent them from being generated, which I guess you can do with

test_id=$(TERM=dumb clasp run testRunner)


问:
Missing number in array in C programming
Given an array C of size N-1 and given that there are numbers from 1 to N with one element missing, the missing number is to be found.

Input:
The first line of input contains an integer T denoting the number of test cases. For each test case first line contains N(size of array). The subsequent line contains N-1 array elements.

Output:
Print the missing number in array.

This problem is to find the missing number in a series of n integers. but, while using the below code I could not get the output as expected.

```<code>#include <stdio.h>

int main()
{
    //code
    int T,run,i;
    scanf("%d", &T);
    long N,res,C,en;
    long arra[1];
    for (run = 0;run <T; run++ )
    {
        long arra[T];
        scanf("%ld", &N);
        res =0;
        for (i = 0; i <N-1; i++)
        {
            scanf("%ld",&C);
            res = res + C;
        }
        en = ((N*(N+1))/2)- res; // subtracting the overall sum of array elements from N integers
        arra[run]=en; //saving it to array
    }
    for(run = 0; run < T; run++)
    {
        printf("%ld ",arra[run]);
    }
    return 0;
}
</code>```

I expected the below input and output:

```<code>Input:
2
5
1 2 3 5
10
1 2 3 4 5 6 7 8 10

Output:
4
9
</code>```

but actual output is

```<code>1 -8719623343620674816
</code>```

答:
You re-declared the variable arra inside the for loop. So when you assign to arra[run], you're assigning to the inner array, not the one in the main() function. So you get garbage when you try to print the contents of the array at the end.

You also declared the first array with only one element, rather than T elements.

Get rid of the second declaration, and change the first one from

```<code>long arra[1];
</code>```

to

```<code>long arra[T];
</code>```

Body:
Given an array C of size N-1 and given that there are numbers from 1 to N with one element missing, the missing number is to be found.

Input:
The first line of input contains an integer T denoting the number of test cases. For each test case first line contains N(size of array). The subsequent line contains N-1 array elements.

Output:
Print the missing number in array.

This problem is to find the missing number in a series of n integers. but, while using the below code I could not get the output as expected.

#include <stdio.h>

int main()
{
    //code
    int T,run,i;
    scanf("%d", &T);
    long N,res,C,en;
    long arra[1];
    for (run = 0;run <T; run++ )
    {
        long arra[T];
        scanf("%ld", &N);
        res =0;
        for (i = 0; i <N-1; i++)
        {
            scanf("%ld",&C);
            res = res + C;
        }
        en = ((N*(N+1))/2)- res; // subtracting the overall sum of array elements from N integers
        arra[run]=en; //saving it to array
    }
    for(run = 0; run < T; run++)
    {
        printf("%ld ",arra[run]);
    }
    return 0;
}

I expected the below input and output:

Input:
2
5
1 2 3 5
10
1 2 3 4 5 6 7 8 10

Output:
4
9

but actual output is

1 -8719623343620674816

Body:
You re-declared the variable arra inside the for loop. So when you assign to arra[run], you're assigning to the inner array, not the one in the main() function. So you get garbage when you try to print the contents of the array at the end.

You also declared the first array with only one element, rather than T elements.

Get rid of the second declaration, and change the first one from

long arra[1];

to

long arra[T];


问:
os.path.abspath is not producing the absolute path for the directory python
its a simple program which outputs the full file path using a given path that does not include the root. But It just prints out the given path. why?

operating system Ubutu18.04 Lts, IDE Pycharm , python 3.7
I've tried installing pathlib and path.py but it still does not work.

```<code>from os.path import abspath, relpath

x = '/python/100 exercises/24.py'

print(abspath(x))
</code>```

The expected output is

```<code>/home/tasif/Documents/python/100 exercises/24.py
</code>```

actual result is

```<code>/python/100 exercises/24.py
</code>```

答: By putting a / at the beginning of your path, your system is interpreting x as a root system path already. Instead, write your path as x = 'python/100 exercises/24.py' and try again.

Body:
its a simple program which outputs the full file path using a given path that does not include the root. But It just prints out the given path. why?

operating system Ubutu18.04 Lts, IDE Pycharm , python 3.7
I've tried installing pathlib and path.py but it still does not work.

from os.path import abspath, relpath

x = '/python/100 exercises/24.py'

print(abspath(x))

The expected output is

/home/tasif/Documents/python/100 exercises/24.py

actual result is

/python/100 exercises/24.py


问:
Google Colab Object detection notebook - NameError: name 'object_detection' is not defined
I'm trying to run this notebook on Google colab in cloud. I'm following these installation instructions linked there but I cannot figure out what am I doing wrong that object_detection is undefined. I do not get any errors while installing libraries or during COCO API installation. How do I import object_detection correctly?</p>

答: Are you sure that your object detection directory is in your drive and you are using the correct path while importing it?</p>


问:
Start an application at system start without login
We have a new server running and we got some new programs doing import routines. So far so good... But there is one program that is put into autostart folder. So it doesn't run until admin logs in and it stops if we logout.

I'd like to put this one into a seperate session so it may work without any interaction by simply starting it with the task scheduler at startup. Is this the right way to do this? Is it safe if I log in later and log out?

Many thanks!

Edit: The applications shows as a symbol in the task bar if running, it can be configured by this. Anything I must know about this if I change?

Edit: It is not my application, I cannot rewrite it as a service.

答:
it is a old question but I recently solved in another way...

(before I was using a scheduled-task for startup but this gave me diverse problems with lots software...)

Some programs also for diverse reasons must be run at a user level... or even inside a specific user session...

So the best way I found was to use a tool like Sysinternal/Autoruns to program the auto-logon to a specific user (it is a registry setting)... and in the startup-folder of that user (or any other "autorun/autolaunch" task)... run a script that first locks the screen... and next runs the other intended programs... that will run under that user profile...

so you can choose a standard user or a administrator... or even launch programs from a standard user in adminsitrator mode...

I hope will help...

This "hack" solved me many problems with startup apps...


问:
How do I change how Wagtail serves media over it's API?
I'm currently trying to create a web application that uses Django + Wagtail for its backend content, and React for the frontend. As of now, upon pageload, I request all of the 'articles' from Wagtail via an http GET request. I then display this data in my frontend components.

This has worked well, except for one issue that I have, which is that media within the article body is represented as an <embed /> tag with a local source. What I'd like instead is an  tag with the src pointing to the url that the image is stored in. How can I go about changing this on the backend? I can't seem to find any kind of documentation regarding this issue.

Here's what my get request response currently looks like:

```<code>{
    "id": 9,
    ...
    "title": "Child page",
    "date": null,
    "body": "<p>Here is a test image:</p><embed alt=\"testimg\" embedtype=\"image\" format=\"fullwidth\" id=\"5\"/><p></p>",
    "author": "Isaac"
}
</code>```

Here's what I'd like it to look like:

```<code>{
    "id": 9,
    ...
    "title": "Child page",
    "date": null,
    "body": "<p>Here is a test image:</p><img src="image-location-url"/><p></p>",
    "author": "Isaac"
}
</code>```

How should I go about this? Is this controllable with Wagtail settings configurations? Or should I be changing my Content model somehow? Thank you.

答:
Copied straight from a comment on the Github page (https://github.com/wagtail/wagtail/issues/2695#issuecomment-373002412):

```<code>from wagtail.wagtailcore.rich_text import expand_db_html

class APIRichTextField(APIField):
    def __init__(self, name):
        serializer = serializers.APIRichTextSerializer()
        super().__init__(name=name, serializer=serializer)

class APIRichTextSerializer(fields.CharField):
    def to_representation(self, instance):
        representation = super().to_representation(instance)
        return expand_db_html(representation)

class MyModel(Page):
    body = RichTextField()
    api_fields = [
        APIRichTextField('body'),
    ]
</code>```

Now my body is converted directly into the html that would be displayed on Wagtail's end. Thanks @solarissmoke for the guidance. If this answer/question doesn't follow guidelines please let me know and I'll happily delete this.

Body:
I'm currently trying to create a web application that uses Django + Wagtail for its backend content, and React for the frontend. As of now, upon pageload, I request all of the 'articles' from Wagtail via an http GET request. I then display this data in my frontend components.

This has worked well, except for one issue that I have, which is that media within the article body is represented as an <embed /> tag with a local source. What I'd like instead is an  tag with the src pointing to the url that the image is stored in. How can I go about changing this on the backend? I can't seem to find any kind of documentation regarding this issue.

Here's what my get request response currently looks like:

{
    "id": 9,
    ...
    "title": "Child page",
    "date": null,
    "body": "
Here is a test image:
<embed alt=\"testimg\" embedtype=\"image\" format=\"fullwidth\" id=\"5\"/>

",
    "author": "Isaac"
}

Here's what I'd like it to look like:

{
    "id": 9,
    ...
    "title": "Child page",
    "date": null,
    "body": "
Here is a test image:

",
    "author": "Isaac"
}

How should I go about this? Is this controllable with Wagtail settings configurations? Or should I be changing my Content model somehow? Thank you.

Body:
Copied straight from a comment on the Github page (https://github.com/wagtail/wagtail/issues/2695#issuecomment-373002412):

from wagtail.wagtailcore.rich_text import expand_db_html

class APIRichTextField(APIField):
    def __init__(self, name):
        serializer = serializers.APIRichTextSerializer()
        super().__init__(name=name, serializer=serializer)

class APIRichTextSerializer(fields.CharField):
    def to_representation(self, instance):
        representation = super().to_representation(instance)
        return expand_db_html(representation)

class MyModel(Page):
    body = RichTextField()
    api_fields = [
        APIRichTextField('body'),
    ]

Now my body is converted directly into the html that would be displayed on Wagtail's end. Thanks @solarissmoke for the guidance. If this answer/question doesn't follow guidelines please let me know and I'll happily delete this.


问:
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?

答:
There are two concepts one is Fail-Fast and another is Fail-Safe. All are not applicable in all situation, there is no rule of thumb that either one will be used. In some situations, Fail-Fast is perfectly ok and it is reasonable. Fail-Safe is also reasonable in some business use cases. So far your question is concerned, it brings two use cases.

First Validate and then Process
In this case, you have the reason not to process unwanted/undesired csv lines so that you can save memory and further processing. In this case, Strategy-1 is good as it is a case of Fail-Fast.

Process and Handle exception gracefully.
This is a case of Fail-Safe, if the requirement is is grab everything and maintain it even if the lines are not proper, then create another Strategy called Strategy-4 where you handle exception gracefully and maintain a list of valid objects for the next sub-system to process.

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?


问:
open file in "w" mode: IOError: [Errno 2] No such file or directory
When I try to open a file in write mode with the following code:

```<code>packetFile = open("%s/%s/%s/%s.mol2" % ("dir", "dir2", "dir3", "some_file"), "w")
</code>```

I get the following error:

```<code>IOError: [Errno 2] No such file or directory: 'dir/dir2/dir3/some_file.mol2'
</code>```

The w mode should create the file if it doesn't exist, right? So how can this error ever occur?

答:
I had the same issue, but my root cause was different than anyone's here.  Thought I'd share in case someone else ran into the same issue.

In my case, I had accidentally misplaced my parentheses on the 'with' line:

```<code>with (open(os.path.join(curpath, unique_name)), 'w') as fw:
</code>```

Gave the following error (modified to obscure company details and for clarity):

```<code>Traceback (most recent call last):
  File "./crap.py", line 60, in uniquify
    with (open(os.path.join(curpath, unique_name)), 'w') as fw:
IOError: [Errno 2] No such file or directory: '/<mypath>/bin/python/<filename>'
</code>```

These parentheses put the 'w' with the with() function, not with open() as intended.  I'm surprised it gives this IO Error, which implies it's something wrong with the open() call, which made this much harder to track down than if it obviously came from the with() call.

I didn't believe these results but just modified it again to replicate, and yes, I get the same error.

When I switch parentheses to the correct version:

```<code>with (open(os.path.join(curpath, unique_name), 'w')) as fw:
</code>```

it works as intended.

Body:
When I try to open a file in write mode with the following code:

packetFile = open("%s/%s/%s/%s.mol2" % ("dir", "dir2", "dir3", "some_file"), "w")

I get the following error:

IOError: [Errno 2] No such file or directory: 'dir/dir2/dir3/some_file.mol2'

The w mode should create the file if it doesn't exist, right? So how can this error ever occur?

Body:
I had the same issue, but my root cause was different than anyone's here.  Thought I'd share in case someone else ran into the same issue.

In my case, I had accidentally misplaced my parentheses on the 'with' line:

with (open(os.path.join(curpath, unique_name)), 'w') as fw:

Gave the following error (modified to obscure company details and for clarity):

Traceback (most recent call last):
  File "./crap.py", line 60, in uniquify
    with (open(os.path.join(curpath, unique_name)), 'w') as fw:
IOError: [Errno 2] No such file or directory: '/<mypath>/bin/python/<filename>'

These parentheses put the 'w' with the with() function, not with open() as intended.  I'm surprised it gives this IO Error, which implies it's something wrong with the open() call, which made this much harder to track down than if it obviously came from the with() call.

I didn't believe these results but just modified it again to replicate, and yes, I get the same error.

When I switch parentheses to the correct version:

with (open(os.path.join(curpath, unique_name), 'w')) as fw:

it works as intended.


问:
Attach Signed Documents in to Salesforce
I am suing Docusign Tool Kit to send the Documents for getting the esignature from Salesforce Oppurtunity Object. The documents are sent and are getting signed and goes to completed  state in DocuSign but it is not getting attached back to Salesforce after the signing is done/Docusign status is completed.

Below is the settings for Salesforce connect object

I dont see anything getting attached

The Document shows completed status in DocuSign

Am I missing something why it doesnt attach the signed document to Salesforce Object

答:
You'll likely want to open a case with DocuSign Support for troubleshooting. If you do, be sure to include an Envelope ID of a test send.

Things to check:

Is the DocuSign Status record being updated in Salesforce? If not, you'll first want to check the link from DS back to SF. Log in to DocuSign > Go to Admin > Connect > Reconfigure Login

are you sending from the same Opportunity the attachment should be writing back to?

Do you have Use Content Files checked in your DocuSign Connect configuration page? If so, check the Reconfigure Login panel and confirm that Salesforce SOAP Web Services API Version is 39


问:
ServerSocket how to receive multiple files
I have studies project. I my teacherd don't want to tell me how to solve problem with receive multiple files. I know I need to use function getInputStream() but I don't know how to split those files in this inputStream object. I need to split this inputStream beacuse I need to save each file in folder.

Thank you for your help and for explaining this problem to me.

答: The answer is that you probably need a transmission protocol like HTTP or FTP. But if you don't want something that high level, what you can do is tar and then gzip your files, which is what people did on unix back in the day. Tar is still basically a transmission protocol, but maybe not as heavyweight as HTTP or FTP</p>


问:
Export the events from third party web apps to linkedin and facebook
I have a webapp where users are asked to create events depending upon his/her requirements and I need to sync the same details of the event with linkedin and facebook events. I am using java/servlets along with jquery/js at the front event.Is there any libraries available or should I dirt my hands writing codes. </p>

答:
Start at http://developers.facebook.com/docs/ and
LinkedIn API http://developer.linkedin.com/docs/DOC-1002</p>

ContentLicense: CC BY-SA 2.5


问:
How data is fetched: max.poll.records and the offsets
As per my current understand of Kafka, data is stored and each "store location" is identified by "offset" (numerical value).

I came across this parameter --> max.poll.records

Suppose the value of max.poll.records is 5, what does this mean? Does it mean that it will read total of FIVE "store locations" in one go(for example, will it try to fetch data from offsets 101, 102, 103, 104, 105).

Can anyone help me understand this?

答:
First, you are correct, each record is assigned an offset in a partition.

The max.poll.records settings (docs) allows to define the maximum number of records that the consumer will return each time your application calls poll(). This is a maximum, it can return that or less.

Note that this does not directly controls how much data is fetched from the cluster as this settings is applied on the client side. This is just to control the number of records return by poll().

In the background, the consumer could have fetched more data, to be ready to be returned next time the application calls poll(). How much data is retrieved by the consumer is determined by fetch.min.bytes, max.partition.fetch.bytes and fetch.max.bytes.

This settings allows you to control the pace of your application as you can only have to process max.poll.records at once even if there's a large number of records available.


问:
How to extract contour of the front panel the washing machine?
I am looking a robust way to extract the contour of the front panel of a washing machine. Or just get 4 corner points of the front panel.
I've tried color masking but didn't find stable results.
Here some examples:

答:
Three potential options:

Get a bunch of images of the machines, manually determine a label saying where the door is, and then train a convolutional neural network to regress those parameters per image.

Treat each image as a separate optimization problem, where the goal is to estimate the parameters of the best rectangle most likely to correspond to the front panel. So our model is theta = (p_1, p_2, p_3, p_4), the four 2D locations of the panel in the image. We need an energy function E to minimize wrt theta (e.g., using gradient descent with momentum, or RANSAC). There are a number of terms you can use, just as some ideas:

a. At least some of the corners should be "corner-like": run a simple corner detector, and define an energy E_corner which penalizes distance to the closest corner.

b. At least some of the edges (between p_1 and p_2 or p_3, for example) should be "edge-like": compute the gradient magnitude of the image M = || \nabla I || and enforce that along the panel edge the values of M should be larger, using an energy E_edge. E.g., for x,y along an edge, let E_edge(x,y)=1/(1+M(x,y)) (Robust losses tend to be better here though).

c. Use the fact that each door is actually a projected 3D rectangle: e.g., see this question. An interesting idea is to start with a rectangle (representing the panel) and instead of regressing the p_i's, instead regress the parameters of an affine transform or even perspective projection transform (though this requires the algorithm estimate depth), that maps the starting rectangle to one in the image. You can then regularize the parameters of the estimated transform to prevent unlikely transforms from being output.

d. Use knowledge of what must be inside the rectangle. For instance, given the four corners, you can determine the ellipse defining the round door to the machine. The appearance statistics within that ellipse should be somewhat unique, as well as the edges/image gradient at the door boundary; hence you can define an energy term encouraging the model to choose corners such that the interior has a dark elliptical object on a white background.

Overall, this approach is similar to snakes, or active contour models, which might be worth looking into for you I think. However, energy-minimizing snakes tend not to consider the inside of the region they enclose; hence, some variant of the Mumford-Shah functional could be a useful addition (though note smoothness of the "door region" is not entirely desirable in your case).

If all your machines are very similar or nearly the same (as the ones you've posted are), it might actually be best to estimate a homography between the images. (See also here or here). Since the front of the machine is nearly planar, the fronts of different images must be related by a homography. Then knowing where the front panel is in one image will tell you where it is in all of them. For instance, check out the OpenCV tutorial for homographies, where they show how to undo the perspective transform of a planar surface allowing you to do a perspective warp of one image to another (here, one projected machine panel to another template one).


问:
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>```

答:
I have not used fmdb but I have used GRDB (https://github.com/groue/GRDB.swift) successfully in a recent project.  Usually, those libraries will allow you to retrieve an error code or log output whenever there is an error and this may prove really useful in solving your issue.

In the meantime, here's a Swift function I'm using to convert a filename into a full Documents user path:

```<code>    private static func path(for filename: String) -> String {
        let fm = FileManager.default
        let documentsDirectory = fm.urls(for: .documentDirectory, in: .userDomainMask).first
        return documentsDirectory?.appendingPathComponent(filename).absoluteString ?? filename
    }
</code>```

Note however, that files that are included as part of the build will typically not be in your Documents, it will be part of the bundle resources.  In which case this piece of code may be more useful:

```<code>    let path = Bundle.main.path(forResource: "mydatabase", ofType: "sqlite")
</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:
I have not used fmdb but I have used GRDB (https://github.com/groue/GRDB.swift) successfully in a recent project.  Usually, those libraries will allow you to retrieve an error code or log output whenever there is an error and this may prove really useful in solving your issue.

In the meantime, here's a Swift function I'm using to convert a filename into a full Documents user path:

    private static func path(for filename: String) -> String {
        let fm = FileManager.default
        let documentsDirectory = fm.urls(for: .documentDirectory, in: .userDomainMask).first
        return documentsDirectory?.appendingPathComponent(filename).absoluteString ?? filename
    }

Note however, that files that are included as part of the build will typically not be in your Documents, it will be part of the bundle resources.  In which case this piece of code may be more useful:

    let path = Bundle.main.path(forResource: "mydatabase", ofType: "sqlite")


问:
How many MySQL queries should I limit myself to on a page? PHP / MySQL
Okay, so I'm sure plenty of you have built crazy database intensive pages...

I am building a page that I'd like to pull all sorts of unrelated database information from.  Here are some sample different queries for this one page:

article content and info

IF the author is a registered user, their info

UPDATE the article's view counter

retrieve comments on the article

retrieve information for the authors of the comments

if the reader of the article is signed in, query for info on them

etc...

I know these are basically going to be pretty lightning quick, and that I could combine some; but I wanted to make sure that this isn't abnormal?

How many fairly normal and un-heavy queries would you limit yourself to on a page?

答:
In my experience, it is better to make two queries and post-process the results than to make one that takes ten times longer to run that you don't have to post-process. That said, it is also better to not repeat queries if you already have the result, and there are many different ways this can be achieved.

But all of that is oriented around performance optimization. So unless you really know what you're doing (hint: most people in this situation don't), just make the queries you need for the data you need and refactor it later.

OwnerDisplayName: johnnietheblack

OwnerDisplayName: staticsan


问:
Objective-C release is not called explicitly
```<code>NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

NSString * str = [[NSString alloc] initWithString:@"test"];
[str release];
int i = 999999999;
while(i-- > 0) {}
NSLog(@"%@", str);
[pool drain];
</code>```

Output: test

Why didn't release work?
How can I immediately delete the object from memory?

Xcode Version 4.0 iPhone Application

~SOLVED~

Thank's to all for answers.
I've got a lot of useful information about this question. I'm going to use NSString *str = @"text" instead of NSString *str = [[NSString alloc] initWithString:@"text"];

i've understood that release just "marks" memory as "willing to be freed", but not freeing it immediatly

答:
Release does work but what you are attempting to do has undefined behavior, and when using a NSString and a literal you may also get different behavior. What is happening is although your object is released the memory at that location is reclaimable and has not changed and when it goes to print it it is still valid. Since it is a NSString a message to description is not necessarily sent and that is why you are not getting an exception for attempting to message a deallocated object.

This question has some good information about NSString and NSLog.

Body:
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

NSString * str = [[NSString alloc] initWithString:@"test"];
[str release];
int i = 999999999;
while(i-- > 0) {}
NSLog(@"%@", str);
[pool drain];

Output: test

Why didn't release work?
How can I immediately delete the object from memory?

Xcode Version 4.0 iPhone Application

~SOLVED~

Thank's to all for answers.
I've got a lot of useful information about this question. I'm going to use NSString *str = @"text" instead of NSString *str = [[NSString alloc] initWithString:@"text"];

i've understood that release just "marks" memory as "willing to be freed", but not freeing it immediatly


问:
ASP.NET MVC: How to find Controllers with [Authorize] attributes using Reflection in C#? (or How to build Dynamic Site.Master Menus?)
Maybe I should back-up and widen the scope before diving into the title question...

I'm currently writing a web app in ASP.NET MVC 1.0 (although I do have MVC 2.0 installed on my PC, so I'm not exactly restricted to 1.0) -- I've started with the standard MVC project which has your basic "Welcome to ASP.NET MVC" and shows both the [Home] tab and [About] tab in the upper-right corner. Pretty standard, right?

I've added 4 new Controller classes, let's call them "Astronomer", "Biologist", "Chemist", and "Physicist". Attached to each new controller class is the [Authorize] attribute.

For example, for the BiologistController.cs

```<code>[Authorize(Roles = "Biologist,Admin")]
public class BiologistController : Controller
{
    public ActionResult Index() { return View(); }
}
</code>```

These [Authorize] tags naturally limit which user can access different controllers depending on Roles, but I want to dynamically build a Menu at the top of my website in the Site.Master Page based on the Roles the user is a part of. So for example, if "JoeUser" was a member of Roles "Astronomer" and "Physicist", the navigation menu would say:

[Home] [Astronomer] [Physicist]
[About]

And naturally, it would not list links to "Biologist" or "Chemist" controller Index page.

Or if "JohnAdmin" was a member of Role "Admin", links to all 4 controllers would show up in the navigation bar.

Ok, you prolly get the idea... Now for the real question...

Starting with the answer from this StackOverflow topic about Dynamic Menu building in ASP.NET, I'm trying to understand how I would fully implement this. (I'm a newbie and need a little more guidance, so please bare with me.)

The answer proposes Extending the Controller class (call it "ExtController") and then have each new WhateverController inherit from ExtController.

My conclusion is that I would need to use Reflection in this ExtController Constructor to determine which Classes and Methods have [Authorize] attributes attached to them to determine the Roles. Then using a Static Dictionary, store the Roles and Controllers/Methods in key-value pairs.

I imagine it something like this:

```<code>public class ExtController : Controller
{
    protected static Dictionary<Type,List<string>> ControllerRolesDictionary;

    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        // build list of menu items based on user's permissions, and add it to ViewData
        IEnumerable<MenuItem> menu = BuildMenu();
        ViewData["Menu"] = menu;
    }

    private IEnumerable<MenuItem> BuildMenu()
    {
        // Code to build a menu
        SomeRoleProvider rp = new SomeRoleProvider();
        foreach (var role in rp.GetRolesForUser(HttpContext.User.Identity.Name))
        {

        }
    }

    public ExtController()
    {
        // Use this.GetType() to determine if this Controller is already in the Dictionary
        if (!ControllerRolesDictionary.ContainsKey(this.GetType()))
        {
            // If not, use Reflection to add List of Roles to Dictionary
            // associating with Controller
        }
    }
}
</code>```

Is this doable? If so, how do I perform Reflection in the ExtController constructor to discover the [Authorize] attribute and related Roles (if any)

ALSO! Feel free to go out-of-scope on this question and suggest an alternate way of solving this "Dynamic Site.Master Menu based on Roles" problem. I'm the first to admit that this may not be the best approach.

EDIT

After much reading and experimenting, I came up with my own solution. See below for my answer. Any constructive feedback / criticism welcome!

答:
I met the same problem that requires the logic to stay in controller side. But I do like John's approach as it uses the system filter to decide if an action is authorized. In case it helps anyone, the following code removed the HtmlHelper from John's approach:

```<code>    protected bool HasActionPermission(string actionName, string controllerName)
    {
        if (string.IsNullOrWhiteSpace(controllerName))
            return false;

        var controller = GetControllerByName(ControllerContext.RequestContext, controllerName);
        var controllerDescriptor = new ReflectedControllerDescriptor(controller.GetType());
        var actionDescriptor = controllerDescriptor.FindAction(ControllerContext, actionName);
        return ActionIsAuthorized(ControllerContext, actionDescriptor);
    }

    private static bool ActionIsAuthorized(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
    {
        if (actionDescriptor == null)
            return false; // action does not exist so say yes - should we authorise this?!

        AuthorizationContext authContext = new AuthorizationContext(controllerContext, actionDescriptor);

        // run each auth filter until on fails
        // performance could be improved by some caching
        foreach (var filter in FilterProviders.Providers.GetFilters(controllerContext, actionDescriptor))
        {
            var authFilter = filter.Instance as IAuthorizationFilter;

            if (authFilter == null)
                continue;

            authFilter.OnAuthorization(authContext);

            if (authContext.Result != null)
                return false;
        }

        return true;
    }

    private static ControllerBase GetControllerByName(RequestContext context, string controllerName)
    {
        IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();

        IController controller = factory.CreateController(context, controllerName);

        if (controller == null)
        {
            throw new InvalidOperationException(

                String.Format(
                    CultureInfo.CurrentUICulture,
                    "Controller factory {0} controller {1} returned null",
                    factory.GetType(),
                    controllerName));
        }
        return (ControllerBase)controller;
    }
</code>```

Body:
Maybe I should back-up and widen the scope before diving into the title question...

I'm currently writing a web app in ASP.NET MVC 1.0 (although I do have MVC 2.0 installed on my PC, so I'm not exactly restricted to 1.0) -- I've started with the standard MVC project which has your basic "Welcome to ASP.NET MVC" and shows both the [Home] tab and [About] tab in the upper-right corner. Pretty standard, right?

I've added 4 new Controller classes, let's call them "Astronomer", "Biologist", "Chemist", and "Physicist". Attached to each new controller class is the [Authorize] attribute.

For example, for the BiologistController.cs

[Authorize(Roles = "Biologist,Admin")]
public class BiologistController : Controller
{
    public ActionResult Index() { return View(); }
}

These [Authorize] tags naturally limit which user can access different controllers depending on Roles, but I want to dynamically build a Menu at the top of my website in the Site.Master Page based on the Roles the user is a part of. So for example, if "JoeUser" was a member of Roles "Astronomer" and "Physicist", the navigation menu would say:

[Home] [Astronomer] [Physicist]
[About]

And naturally, it would not list links to "Biologist" or "Chemist" controller Index page.

Or if "JohnAdmin" was a member of Role "Admin", links to all 4 controllers would show up in the navigation bar.

Ok, you prolly get the idea... Now for the real question...

Starting with the answer from this StackOverflow topic about Dynamic Menu building in ASP.NET, I'm trying to understand how I would fully implement this. (I'm a newbie and need a little more guidance, so please bare with me.)

The answer proposes Extending the Controller class (call it "ExtController") and then have each new WhateverController inherit from ExtController.

My conclusion is that I would need to use Reflection in this ExtController Constructor to determine which Classes and Methods have [Authorize] attributes attached to them to determine the Roles. Then using a Static Dictionary, store the Roles and Controllers/Methods in key-value pairs.

I imagine it something like this:

public class ExtController : Controller
{
    protected static Dictionary<Type,List<string>> ControllerRolesDictionary;

    protected override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        // build list of menu items based on user's permissions, and add it to ViewData
        IEnumerable<MenuItem> menu = BuildMenu();
        ViewData["Menu"] = menu;
    }

    private IEnumerable<MenuItem> BuildMenu()
    {
        // Code to build a menu
        SomeRoleProvider rp = new SomeRoleProvider();
        foreach (var role in rp.GetRolesForUser(HttpContext.User.Identity.Name))
        {

        }
    }

    public ExtController()
    {
        // Use this.GetType() to determine if this Controller is already in the Dictionary
        if (!ControllerRolesDictionary.ContainsKey(this.GetType()))
        {
            // If not, use Reflection to add List of Roles to Dictionary
            // associating with Controller
        }
    }
}

Is this doable? If so, how do I perform Reflection in the ExtController constructor to discover the [Authorize] attribute and related Roles (if any)

ALSO! Feel free to go out-of-scope on this question and suggest an alternate way of solving this "Dynamic Site.Master Menu based on Roles" problem. I'm the first to admit that this may not be the best approach.

EDIT

After much reading and experimenting, I came up with my own solution. See below for my answer. Any constructive feedback / criticism welcome!

Body:
I met the same problem that requires the logic to stay in controller side. But I do like John's approach as it uses the system filter to decide if an action is authorized. In case it helps anyone, the following code removed the HtmlHelper from John's approach:

    protected bool HasActionPermission(string actionName, string controllerName)
    {
        if (string.IsNullOrWhiteSpace(controllerName))
            return false;

        var controller = GetControllerByName(ControllerContext.RequestContext, controllerName);
        var controllerDescriptor = new ReflectedControllerDescriptor(controller.GetType());
        var actionDescriptor = controllerDescriptor.FindAction(ControllerContext, actionName);
        return ActionIsAuthorized(ControllerContext, actionDescriptor);
    }

    private static bool ActionIsAuthorized(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
    {
        if (actionDescriptor == null)
            return false; // action does not exist so say yes - should we authorise this?!

        AuthorizationContext authContext = new AuthorizationContext(controllerContext, actionDescriptor);

        // run each auth filter until on fails
        // performance could be improved by some caching
        foreach (var filter in FilterProviders.Providers.GetFilters(controllerContext, actionDescriptor))
        {
            var authFilter = filter.Instance as IAuthorizationFilter;

            if (authFilter == null)
                continue;

            authFilter.OnAuthorization(authContext);

            if (authContext.Result != null)
                return false;
        }

        return true;
    }

    private static ControllerBase GetControllerByName(RequestContext context, string controllerName)
    {
        IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();

        IController controller = factory.CreateController(context, controllerName);

        if (controller == null)
        {
            throw new InvalidOperationException(

                String.Format(
                    CultureInfo.CurrentUICulture,
                    "Controller factory {0} controller {1} returned null",
                    factory.GetType(),
                    controllerName));
        }
        return (ControllerBase)controller;
    }


答:
Try to copy the local database file to the app's documents library if it's not exist there.

import FMDB

class DBService {
    // MARK: Properties
    static let shared = DBService()
    var database: FMDatabase!

    private let fileManager = FileManager.default
    private var documentsDBPath: String
    private var resourcesDBPath: String

    private let databaseFileName = "data"
    private let databaseFileName = "sqlite"

    // MARK: Initializers
    private init() {
        documentsDBPath = try! fileManager
            .url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
            .appendingPathComponent(databaseFileName)
            .appendingPathExtension(databaseFileExtension)
            .path

        resourcesDBPath = Bundle.main.path(forResource: databaseFileName,
                                           ofType: databaseFileExtension)!
    }

    // MARK: - Setup
    func isDatabaseOpen() -> Bool {
        if database == nil {
            initDatabase()
        }

        return database.open()
    }

    private func initDatabase() {
        if isFirstLaunch() {
            copyDatabase(from: resourcesDBPath, to: documentsDBPath)
        }

        database = FMDatabase(path: documentsDBPath)
    }

    private func isFirstLaunch() -> Bool {
        return !fileManager.fileExists(atPath: documentsDBPath)
    }

    private func copyDatabase(from source: String, to destination: String) {
        do {
            try fileManager.copyItem(atPath: source, toPath: destination)
        } catch {
            debugPrint(error)
        }
    }
}
```

Title: Load data from sqlite file Swift 4.2


问:
Find all parents for a child with lookthru path and other columns in python
I am really a newbie in python. Could you please help in the following problem

I have the following table:

```<code>Parent  Child   value 1 Value 2

a0      b1      0.2         5

b5      c1      0.3         2

a0      b2      0.5         6

a1      b3      0.6         3

a1      b4      0.7         58

a2      b5      0.5         63

f0      a0      0.6         9

f0      a1      0.8         5

f0      a2      0.5         5

a0      b0      0.2         6

b5      c0      0.6         4
</code>```

I need to do recursive parent child relationship and need to find all parents with a given child. However, I also need to multiply the values with each other for a give parent and child combination.

Expected output

```<code>Root    Parent  Child   Path              Value 3

f0      b5      c1      f0/a2/b5/c1       0.5 * 0.5 * 0.3  (f0->a2 * a2->b5 * b5->c1)

f0      a0      b0      f0/a0/b0          0.6 * 0.2  (f0->a0 * a0->b0)

f0      a1      b4      f0/a1/b4          ..and so on

f0      a1      b3      f0/a1/b3

f0      b5      c0      f0/a2/b5/c0

f0      a0      b2      f0/a0/b2

f0      a0      b1      f0/a0/b1
</code>```

I am using the following code which works perfectly fine. I got this code from this site only. However, I am not able to figure out how to get the value 3 by multiplying the value 1 as a recourse through the path.

```<code>parents = set() children = {} for c,p in ancestry:
    parents.add(p)
    children[c] = p

def ancestors(p):
    return (ancestors(children[p]) if p in children else []) + [p]
</code>```

for k in (set(children.keys()) - parents):
      print ('/'.join(ancestors(k)))

any help is greatly appreciated.

答:
I am not sure of how to solve this issue using recursion, but below solution may work for you. As you already pulled leaf nodes and traversing to parent node, I added a tuple "childvalues" to track the parent and it's value for each child. Then I traversed upward to get each parent one by one along with multiplication result </p>

```<code>def ancestor(child):
    child_weight = 1
    childpath = "/" + child
    while (child in childvalues):
        pathValue = childvalues[child][1]
        child_weight = child_weight * pathValue
        child = childvalues[child][0]
        childpath = childpath + "/" + child
    return (childpath, child_weight)
ancestry = [
    ('b1', 'a0', 0.1),
    ('c1', 'b5', 0.2),
    ('b2', 'a0', 0.3),
    ('b3', 'a1', 0.4),
    ('b4', 'a1', 0.5),
    ('b5', 'a2', 0.6),
    ('a0', 'f0', 0.7),
    ('a1', 'f0', 0.8),
    ('a2', 'f0', 0.9),
    ('b0', 'a0', 0.11),
    ('c0', 'b5', 0.12),
]
parents = set()
childvalues = {}
for child, parent, value in ancestry:
    parents.add(parent)
    childvalues[child] = (parent, value)
for leaf_node in (set(childvalues.keys()) - parents):
    print(ancestor(leaf_node))
</code>```

Body:
I am really a newbie in python. Could you please help in the following problem

I have the following table:

Parent  Child   value 1 Value 2

a0      b1      0.2         5

b5      c1      0.3         2

a0      b2      0.5         6

a1      b3      0.6         3

a1      b4      0.7         58

a2      b5      0.5         63

f0      a0      0.6         9

f0      a1      0.8         5

f0      a2      0.5         5

a0      b0      0.2         6

b5      c0      0.6         4

I need to do recursive parent child relationship and need to find all parents with a given child. However, I also need to multiply the values with each other for a give parent and child combination.

Expected output

Root    Parent  Child   Path              Value 3

f0      b5      c1      f0/a2/b5/c1       0.5 * 0.5 * 0.3  (f0->a2 * a2->b5 * b5->c1)

f0      a0      b0      f0/a0/b0          0.6 * 0.2  (f0->a0 * a0->b0)

f0      a1      b4      f0/a1/b4          ..and so on

f0      a1      b3      f0/a1/b3

f0      b5      c0      f0/a2/b5/c0

f0      a0      b2      f0/a0/b2

f0      a0      b1      f0/a0/b1

I am using the following code which works perfectly fine. I got this code from this site only. However, I am not able to figure out how to get the value 3 by multiplying the value 1 as a recourse through the path.

parents = set() children = {} for c,p in ancestry:
    parents.add(p)
    children[c] = p

def ancestors(p):
    return (ancestors(children[p]) if p in children else []) + [p]

for k in (set(children.keys()) - parents):
      print ('/'.join(ancestors(k)))

any help is greatly appreciated.

Body:
I am not sure of how to solve this issue using recursion, but below solution may work for you. As you already pulled leaf nodes and traversing to parent node, I added a tuple "childvalues" to track the parent and it's value for each child. Then I traversed upward to get each parent one by one along with multiplication result

def ancestor(child):
    child_weight = 1
    childpath = "/" + child
    while (child in childvalues):
        pathValue = childvalues[child][1]
        child_weight = child_weight * pathValue
        child = childvalues[child][0]
        childpath = childpath + "/" + child
    return (childpath, child_weight)
ancestry = [
    ('b1', 'a0', 0.1),
    ('c1', 'b5', 0.2),
    ('b2', 'a0', 0.3),
    ('b3', 'a1', 0.4),
    ('b4', 'a1', 0.5),
    ('b5', 'a2', 0.6),
    ('a0', 'f0', 0.7),
    ('a1', 'f0', 0.8),
    ('a2', 'f0', 0.9),
    ('b0', 'a0', 0.11),
    ('c0', 'b5', 0.12),
]
parents = set()
childvalues = {}
for child, parent, value in ancestry:
    parents.add(parent)
    childvalues[child] = (parent, value)
for leaf_node in (set(childvalues.keys()) - parents):
    print(ancestor(leaf_node))


问:
How to space two buttons
I am trying two put space between these two buttons

Tried style="margin-right: but it pushed the button down instead of keeping it even with the other button

<title>W3.CSS</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">

>>>Click Here to get Started Now<<<

>>>Schedule call and LEARN MORE <<<

```

答:
I've copied your code (below), and modified it.

I've added colors to the (focus) divs to show the containers and where they are displayed on the screen.
The only real thing I've done is, added a float:right to the second div with class="w3-bar".

I've also added a width:900px to the w3-container div, to control the horizontal distance of the container on the screen. You can change the width to see the results.

Note: if you set it to 'auto', it will be governed by its parent's width.

```<code><div class="w3-container" style="background-color: red;width:900px;">

  <div class="w3-show-inline-block" style="background-color:yellow;">
      <div class="w3-bar">
        <p style="text-align: left;"><a class="global-btn" style="margin-top: 0;" href="https://queencitylocal.com/contact/">>>>Click Here to get Started Now<<<</a></p>
      </div>
  </div>

  <div class="w3-show-inline-block" style="background-color: green;float:right;">
      <div class="w3-bar">
        <p style="text-align: right;"><a class="global-btn" style="margin-top: 0;" href="https://queencitylocal.com/contact/">>>>Schedule call and LEARN MORE <<<</a></p>
  </div>
  </div>
</div>
</code>```

Title: How to space two buttons

Body:
I've copied your code (below), and modified it.

I've added colors to the (focus) divs to show the containers and where they are displayed on the screen.
The only real thing I've done is, added a float:right to the second div with class="w3-bar".

I've also added a width:900px to the w3-container div, to control the horizontal distance of the container on the screen. You can change the width to see the results.

Note: if you set it to 'auto', it will be governed by its parent's width.

<div class="w3-container" style="background-color: red;width:900px;">

  <div class="w3-show-inline-block" style="background-color:yellow;">
      <div class="w3-bar">
        <p style="text-align: left;"><a class="global-btn" style="margin-top: 0;" href="https://queencitylocal.com/contact/">&gt;&gt;&gt;Click Here to get Started Now&lt;&lt;&lt;</a></p>
      </div>
  </div>

  <div class="w3-show-inline-block" style="background-color: green;float:right;">
      <div class="w3-bar">
        <p style="text-align: right;"><a class="global-btn" style="margin-top: 0;" href="https://queencitylocal.com/contact/">&gt;&gt;&gt;Schedule call and LEARN MORE &lt;&lt;&lt;</a></p>
  </div>
  </div>
</div>


问:
read a text file and remove all occurences of a duplicates
I have a text file called test1.txt I want to remove all occurences of the duplicates. that means only unique words will be there.
example.

test1.txt:

```<code>hello i am a businessman  i am also a student
</code>```

output should be:

```<code>hello businessman also student
</code>```

my approach was like this:

```<code>import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class main {

    public static void main(String[] args) throws FileNotFoundException {

        Scanner input = new Scanner(new File("test1.txt"));

        ArrayList<String> list1 = new ArrayList<String>();

        while (input.hasNext()) {
            list1.add(input.next());

        }

        for(int i=0;i<list1.size();i++){
        for(int j=i+1;j<list1.size();j++){
            if(list1.get(i).equals(list1.get(j))){
                list1.remove(j);
                j--;
               }
             }
         }

        System.out.println("List 1: " + list1);

    }

}
</code>```

but it's not what i am looking for. i want to remove all occurence of duplicate so that i can output only unique words.

答:
You can use a HashMap to track each word and its occurrence in the given text file.

Key -> word,  value -> word count

```<code>public static void main(String[] args) throws FileNotFoundException {

    Scanner input = new Scanner(new File("test1.txt"));

    ArrayList<String> list1 = new ArrayList<String>();

    HashMap<String, Integer> wordMap = new HashMap<String, Integer>();

    while (input.hasNext()) {
        list1.add(input.next());
    }

    for (String word : list1) {
        if (wordMap.get(word) == null) {
            wordMap.put(word, 1);
        } else {
            wordMap.put(word, wordMap.get(word) + 1);
        }
    }

    //If output order does not important just loop through wordMap
    for (String word : list1) {
        if(wordMap.get(word) == 1) {
            System.out.print(word + " ");
        }
    }
}
</code>```

Output:

hello businessman also student

Body:
I have a text file called test1.txt I want to remove all occurences of the duplicates. that means only unique words will be there.
example.

test1.txt:

hello i am a businessman  i am also a student

output should be:

hello businessman also student

my approach was like this:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class main {

    public static void main(String[] args) throws FileNotFoundException {

        Scanner input = new Scanner(new File("test1.txt"));

        ArrayList<String> list1 = new ArrayList<String>();

        while (input.hasNext()) {
            list1.add(input.next());

        }

        for(int i=0;i<list1.size();i++){
        for(int j=i+1;j<list1.size();j++){
            if(list1.get(i).equals(list1.get(j))){
                list1.remove(j);
                j--;
               }
             }
         }

        System.out.println("List 1: " + list1);

    }

}

but it's not what i am looking for. i want to remove all occurence of duplicate so that i can output only unique words.

Body:
You can use a HashMap to track each word and its occurrence in the given text file.

Key -> word,  value -> word count

public static void main(String[] args) throws FileNotFoundException {

    Scanner input = new Scanner(new File("test1.txt"));

    ArrayList<String> list1 = new ArrayList<String>();

    HashMap<String, Integer> wordMap = new HashMap<String, Integer>();

    while (input.hasNext()) {
        list1.add(input.next());
    }

    for (String word : list1) {
        if (wordMap.get(word) == null) {
            wordMap.put(word, 1);
        } else {
            wordMap.put(word, wordMap.get(word) + 1);
        }
    }

    //If output order does not important just loop through wordMap
    for (String word : list1) {
        if(wordMap.get(word) == 1) {
            System.out.print(word + " ");
        }
    }
}

Output:

hello businessman also student