问:
How to reduce Eclipse's memory usage?
The memory usage of Eclipse 3.4 is through the roof to the point where it's becoming an issue.

I have a simple BlackBerry project loaded and the usage skyrockets to nearly 400 MB, sometimes higher.  Is there something that can be done to bring it down?

答:
Checking General -> Show heap status will enable this

in the bottom bar.
This way you can manually run the garbage collector whenever you want by clicking on the trash can. It's not a fix, more like a workaround, but it helped reduce massively my RAM / CPU usage.

Title: How to reduce Eclipse's memory usage?


来源: stackexchange

问:
android how to download PDF fie in web view

i have to use webview to show asp.net rdlc report using http url.

now i can download PDF file in web view show option in bellow image

答:
You should create WebViewClient and set it to your webview.

every time you click a link WebViewClient's shouldOverrideUrlLoading method will be called.

You can get the PDF url, now call async task and download the file in device.

```<code>webView.setWebViewClient(new WebViewClient() {
    public boolean shouldOverrideUrlLoading (WebView view, String url) {
        if (url.endsWith(".pdf")) {
          // call Asynctask and download pdf file
          return true;
        }
        return false;
    }
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You should create WebViewClient and set it to your webview.

every time you click a link WebViewClient's shouldOverrideUrlLoading method will be called.

You can get the PDF url, now call async task and download the file in device.

webView.setWebViewClient(new WebViewClient() {
    public boolean shouldOverrideUrlLoading (WebView view, String url) {
        if (url.endsWith(".pdf")) {
          // call Asynctask and download pdf file
          return true;
        }
        return false;
    }
});


问:
Read a Google Sheet with Python using API Key instead of OAuth Client ID [Python]
While there are several useful articles on how to use OAuth Client IDs to generate credentials needed for reading and writing to Google Sheets, I have been unable to make sense of how one would use the alternative API Key (token) in such a context.

I've blindly attempted to simply pass the token string into gspread.authorize(TOKEN) but, not surprisingly, received an error: AttributeError: 'str' object has no attribute 'access_token'

Thanks in advance for any advice

答: Every method in the Sheets API need authorization using the OAuth. Refer to Python Quickstart to get started.</p>


问:
ANTLR4 Building in Visual Studio 2017 (C++)
I'm trying to build ANTLR4 in Visual Studio (C++).

These are the errors:
Error trying to build

The unresolved externals are virtual destructors.

Why it is implemented like that? Pure virtual destructors must have a function body. How can I fix it and build ANTLR4?

Thanks in advance

答:
Although not related to destructors, there are other challenges if you haven't overcome them already.  Getting ANTLR4 solutions to build in VS was a challenge.  Other than several nuget installs, I remember having to do some manipulations to the project file as in:

```<code><ItemGroup>
    <Antlr4 Include="YOURGRAMMAR.g4">
      <Generator>MSBuild:Compile</Generator>
      <Listener>True</Listener>
      <Visitor>True</Visitor>
    </Antlr4>
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="Antlr4" Version="4.5.3 YOUR VERSION" />
</ItemGroup>
</code>```

And after all that I still don't have syntax highlighting in the .g4 grammar files.  But the change above at least set up the build actions and let the background ANTLR classes rebuild when necessary.

Body:
Although not related to destructors, there are other challenges if you haven't overcome them already.  Getting ANTLR4 solutions to build in VS was a challenge.  Other than several nuget installs, I remember having to do some manipulations to the project file as in:

<ItemGroup>
    <Antlr4 Include="YOURGRAMMAR.g4">
      <Generator>MSBuild:Compile</Generator>
      <Listener>True</Listener>
      <Visitor>True</Visitor>
    </Antlr4>
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="Antlr4" Version="4.5.3 YOUR VERSION" />
</ItemGroup>

And after all that I still don't have syntax highlighting in the .g4 grammar files.  But the change above at least set up the build actions and let the background ANTLR classes rebuild when necessary.


问:
Passing bitwise operation as argument to function in C
What will be the argument value if we call function with the following argument

```<code>void func((0x1 | 0x3))
</code>```

Is it true that if the result of this operation is >0 it gives true, and for the opposite it gives false, or we get 0x3 as a return value of this operation?

答:
From a boolean perspective, a value of 0 is false and any non-zero value is evaluated as true.

Because you're using the bitwise-OR operator |, the expression (0x1 | 0x3) has the value 0x3:

```<code>  00000001 = 0x1
| 00000011 = 0x3
----------
  00000011 = 0x3
</code>```

If this value is passed to a function expecting a _Bool (or equivalently bool), it is converted as per section 6.3.1.2 of the C standard:

When any scalar value is converted to _Bool, the result is 0 if the
  value compares equal to 0; otherwise, the result is 1.

If the function is expecting an int, the value is not converted.

Body:
What will be the argument value if we call function with the following argument

void func((0x1 | 0x3))

Is it true that if the result of this operation is >0 it gives true, and for the opposite it gives false, or we get 0x3 as a return value of this operation?

Body:
From a boolean perspective, a value of 0 is false and any non-zero value is evaluated as true.

Because you're using the bitwise-OR operator |, the expression (0x1 | 0x3) has the value 0x3:

  00000001 = 0x1
| 00000011 = 0x3
----------
  00000011 = 0x3

If this value is passed to a function expecting a _Bool (or equivalently bool), it is converted as per section 6.3.1.2 of the C standard:

When any scalar value is converted to _Bool, the result is 0 if the
  value compares equal to 0; otherwise, the result is 1.

If the function is expecting an int, the value is not converted.


问:
How to attach directives served on request by server to running angular application
I have a number of angularJs directives generated using velocity template engine

Based on request i want to serve respective directive and attach it to angular.

Basically i dont want to bundle up all directives instead i want to use only the one which is required (serve that and use)

答:
You can use $compile method to bind scope of a controller to the HTML block in run time.
Try https://www.w3schools.com/code/tryit.asp?filename=FH0A46GZB2UV

In the above example, a directive is added to DOM in run time on an event. Similarly in your case, you can add the tag of the directive which has to be loaded, based on the response of an ajax call.


问:
Get Dell KACE to run a script outside of the normal interval
Is it possible to get Dell KACE to run a script on a client machine immediately when some condition happens?

I need the script to run on the agent machine within 1 minute of the condition happening (like a file appearing). This is because I need an application to update to a newer version only when a user action happens.

If I set the inventory interval very low and use a custom condition it might affect the general performance of KACE, since there are many client machines.

答:
It's impossible to do this.

I can send an inventory via the API even without admin rights. But the inventory checks/results cannot be linked to scripts in KACE, so that gets me nowhere.


问:
start and stop tomcat via command prompt
Im currently using tomcat 6.0.18.  I have installed tomcat server and set the CATALINA_HOME variable in the environment variables. Inside the tomcat installation location under the bin folder, there is no startup.bat or shutdown.bat file available. There are only two exe files: tomcat6.exe & tomcat6w.exe. I would like to know how to start the tomcat server via command prompt.

I tried executing the below command

```<code>C:\Apache Software Foundation\Tomcat6.0\bin>tomcat6.exe start
</code>```

The start command works fine. But I'm unable to stop the server using the command

```<code>C:\Apache Software Foundation\Tomcat6.0\bin>tomcat6.exe stop
</code>```

But the stop command does not stop the server. It only starts the tomcat server.

Both the commands 'tomcat6.exe start' & 'tomcat6.exe stop' starts the tomcat server. I would like to know what options should I use to stop the tomcat server via command prompt.

Any help on this is much appreciated. Thanks in Advance.

答: In your bin directory there is a file called startup which is an executable. Please execute that.After you have run that please check the following url http://localhost:8080/. If you have installed tomcat successfully then you will get a message.</p>

Body:
Im currently using tomcat 6.0.18.  I have installed tomcat server and set the CATALINA_HOME variable in the environment variables. Inside the tomcat installation location under the bin folder, there is no startup.bat or shutdown.bat file available. There are only two exe files: tomcat6.exe & tomcat6w.exe. I would like to know how to start the tomcat server via command prompt.

I tried executing the below command

C:\Apache Software Foundation\Tomcat6.0\bin>tomcat6.exe start

The start command works fine. But I'm unable to stop the server using the command

C:\Apache Software Foundation\Tomcat6.0\bin>tomcat6.exe stop

But the stop command does not stop the server. It only starts the tomcat server.

Both the commands 'tomcat6.exe start' & 'tomcat6.exe stop' starts the tomcat server. I would like to know what options should I use to stop the tomcat server via command prompt.

Any help on this is much appreciated. Thanks in Advance.


问:
koa-views nunjucks: Error: template not found: master
Structure:

```<code>|-server.js
|-views/
    |-master.njk
    |-index.njk
</code>```

Koa-views configuration:

```<code>logit("Koa-views : subfolder used: /views");
var views = views('./views', { //note that I removed the __dirname to test if it was the cause
    extension: 'njk',
    map: {
        njk: 'nunjucks'
    },
    options: {
        helpers: {
            uppercase: (str) => str.toUpperCase(),
            lowercase: (str) => str.toLowerCase(),
        },

    }
});
koa.use(views);
</code>```

index.njk

```<code>{% extends "master" %}
{% block content %}
    <h1>Pretty lame content...</h1>
{% endblock %}
</code>```

master.njk

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        "Master page here" => {% block content %}{% endblock %}
    </body>
</html>
</code>```

Log output:

```<code>NodeJS server started, it is running on port 3000

  Template render error: (unknown path)
    Error: template not found: master
      at Object.exports.prettifyError (/srv/NodesProjects/AnotherNodeTry/node_modules/nunjucks/src/lib.js:34:15)
      at /srv/NodesProjects/AnotherNodeTry/node_modules/nunjucks/src/environment.js:489:31
      at eval (eval at _compile (/srv/NodesProjects/AnotherNodeTry/node_modules/nunjucks/src/environment.js:568:24), <anonymous>:9:11)
      at createTemplate (/srv/NodesProjects/AnotherNodeTry/node_modules/nunjucks/src/environment.js:213:25)
      at next (/srv/NodesProjects/AnotherNodeTry/node_modules/nunjucks/src/lib.js:210:13)
      at handle (/srv/NodesProjects/AnotherNodeTry/node_modules/nunjucks/src/environment.js:253:25)
      at /srv/NodesProjects/AnotherNodeTry/node_modules/nunjucks/src/environment.js:264:21
      at next (/srv/NodesProjects/AnotherNodeTry/node_modules/nunjucks/src/lib.js:207:13)
      at Object.exports.asyncIter (/srv/NodesProjects/AnotherNodeTry/node_modules/nunjucks/src/lib.js:214:5)
      at new_cls.getTemplate (/srv/NodesProjects/AnotherNodeTry/node_modules/nunjucks/src/environment.js:243:17)
      at new_cls.root [as rootRenderFunc] (eval at _compile (/srv/NodesProjects/AnotherNodeTry/node_modules/nunjucks/src/environment.js:568:24), <anonymous>:8:5)
      at new_cls.render (/srv/NodesProjects/AnotherNodeTry/node_modules/nunjucks/src/environment.js:482:15)
      at new_cls.renderString (/srv/NodesProjects/AnotherNodeTry/node_modules/nunjucks/src/environment.js:328:21)
      at Object.module.exports.renderString (/srv/NodesProjects/AnotherNodeTry/node_modules/nunjucks/index.js:80:14)
      at /srv/NodesProjects/AnotherNodeTry/node_modules/consolidate/lib/consolidate.js:1174:11
      at /srv/NodesProjects/AnotherNodeTry/node_modules/consolidate/lib/consolidate.js:144:5
</code>```

I verify that every file have chmod 777 and same user.
If I replace with only 1 variable and try to pass it with the render function it works. But includes and extends seems off.

I tried on another project with another backend and it's working - but I'm not good enough to go through all the source code and figure it out :(

I wish the traceback was more detailed, no complete path :(

Edit
I forgot, this is how I call the templace

```<code>router.get('/', async function (ctx, next) {
    await ctx.render('index', {test: 'Hello'})
})
</code>```

Edit 2
I tried using koaNunjucks2 lib, it works when I put the .njk at the end of my extends, must be related to the package koa-views.

答:
Try this.

```<code>const Koa = require('koa');
const views = require('koa-views');
const nunjucks = require('nunjucks');
const nunjucksEnvironment = new nunjucks.Environment(
    new nunjucks.FileSystemLoader(path.join(__dirname, './views'))
);

const koa = new Koa();

koa.use(views(path.join(__dirname, './views'), {
    extension: 'njk',
    options: {
        nunjucksEnv: nunjucksEnvironment
    },
    map: { njk: 'nunjucks' }
}));
</code>```

Reference: https://github.com/queckezz/koa-views/blob/6994e23e0f02a83d30b3ab9bea56ae79b37a07fa/test/index.js#L252

Body:
Structure:

|-server.js
|-views/
    |-master.njk
    |-index.njk

Koa-views configuration:

logit("Koa-views : subfolder used: /views");
var views = views('./views', { //note that I removed the __dirname to test if it was the cause
    extension: 'njk',
    map: {
        njk: 'nunjucks'
    },
    options: {
        helpers: {
            uppercase: (str) => str.toUpperCase(),
            lowercase: (str) => str.toLowerCase(),
        },

    }
});
koa.use(views);

index.njk

{% extends "master" %}
{% block content %}

Pretty lame content...

{% endblock %}

master.njk

<!DOCTYPE html>

        <meta charset="utf-8">
        <title></title>

        "Master page here" => {% block content %}{% endblock %}

Log output:

NodeJS server started, it is running on port 3000

  Template render error: (unknown path)
    Error: template not found: master
      at Object.exports.prettifyError (/srv/NodesProjects/AnotherNodeTry/node_modules/nunjucks/src/lib.js:34:15)
      at /srv/NodesProjects/AnotherNodeTry/node_modules/nunjucks/src/environment.js:489:31
      at eval (eval at _compile (/srv/NodesProjects/AnotherNodeTry/node_modules/nunjucks/src/environment.js:568:24), <anonymous>:9:11)
      at createTemplate (/srv/NodesProjects/AnotherNodeTry/node_modules/nunjucks/src/environment.js:213:25)
      at next (/srv/NodesProjects/AnotherNodeTry/node_modules/nunjucks/src/lib.js:210:13)
      at handle (/srv/NodesProjects/AnotherNodeTry/node_modules/nunjucks/src/environment.js:253:25)
      at /srv/NodesProjects/AnotherNodeTry/node_modules/nunjucks/src/environment.js:264:21
      at next (/srv/NodesProjects/AnotherNodeTry/node_modules/nunjucks/src/lib.js:207:13)
      at Object.exports.asyncIter (/srv/NodesProjects/AnotherNodeTry/node_modules/nunjucks/src/lib.js:214:5)
      at new_cls.getTemplate (/srv/NodesProjects/AnotherNodeTry/node_modules/nunjucks/src/environment.js:243:17)
      at new_cls.root [as rootRenderFunc] (eval at _compile (/srv/NodesProjects/AnotherNodeTry/node_modules/nunjucks/src/environment.js:568:24), <anonymous>:8:5)
      at new_cls.render (/srv/NodesProjects/AnotherNodeTry/node_modules/nunjucks/src/environment.js:482:15)
      at new_cls.renderString (/srv/NodesProjects/AnotherNodeTry/node_modules/nunjucks/src/environment.js:328:21)
      at Object.module.exports.renderString (/srv/NodesProjects/AnotherNodeTry/node_modules/nunjucks/index.js:80:14)
      at /srv/NodesProjects/AnotherNodeTry/node_modules/consolidate/lib/consolidate.js:1174:11
      at /srv/NodesProjects/AnotherNodeTry/node_modules/consolidate/lib/consolidate.js:144:5

I verify that every file have chmod 777 and same user.
If I replace with only 1 variable and try to pass it with the render function it works. But includes and extends seems off.

I tried on another project with another backend and it's working - but I'm not good enough to go through all the source code and figure it out :(

I wish the traceback was more detailed, no complete path :(

Edit
I forgot, this is how I call the templace

router.get('/', async function (ctx, next) {
    await ctx.render('index', {test: 'Hello'})
})

Edit 2
I tried using koaNunjucks2 lib, it works when I put the .njk at the end of my extends, must be related to the package koa-views.

Body:
Try this.

const Koa = require('koa');
const views = require('koa-views');
const nunjucks = require('nunjucks');
const nunjucksEnvironment = new nunjucks.Environment(
    new nunjucks.FileSystemLoader(path.join(__dirname, './views'))
);

const koa = new Koa();

koa.use(views(path.join(__dirname, './views'), {
    extension: 'njk',
    options: {
        nunjucksEnv: nunjucksEnvironment
    },
    map: { njk: 'nunjucks' }
}));

Reference: https://github.com/queckezz/koa-views/blob/6994e23e0f02a83d30b3ab9bea56ae79b37a07fa/test/index.js#L252


问:
display dynamic tags in meta tag
On my index.php, i am trying to implode an array of meta tags loaded from MYSQL db. I am trying to echo it in <meta> tag. But it shows the last tag only. Why is it so?

html

```<code>$meta_t=mysqli_query($con,"select * from tags");
while($row1=mysqli_fetch_array($meta_t,MYSQLI_ASSOC)){
    $meta_tags=array();
    $meta_tags[]=$row1['tag_name'];
    $comma_separated = implode($meta_tags);
   }
?>

<!DOCTYPE html>
<html lang="en">
<head>

    <meta charset="utf-8" />
    <title>GripOffers</title>
    <meta name="keywords" content="<?php echo $comma_separated;?>">
</code>```

答:
Three corrections:

1) Define array outside loop. Your code every time defines a new array. Therefore, you are getting only latest value.

2) Move implode() outside loop. You need to implode() whole array, not the latest iteration value.

3) implode(): First parameter missing, I placed ,.

Corrected code:

```<code>$meta_t=mysqli_query($con,"select * from tags");
$meta_tags=array();
while($row1=mysqli_fetch_array($meta_t,MYSQLI_ASSOC)){
 $meta_tags[]=$row1['tag_name'];
}
$comma_separated = implode(', ', $meta_tags);
</code>```

Title: display dynamic tags in meta tag

Body:
On my index.php, i am trying to implode an array of meta tags loaded from MYSQL db. I am trying to echo it in <meta> tag. But it shows the last tag only. Why is it so?

html

$meta_t=mysqli_query($con,"select * from tags");
while($row1=mysqli_fetch_array($meta_t,MYSQLI_ASSOC)){
    $meta_tags=array();
    $meta_tags[]=$row1['tag_name'];
    $comma_separated = implode($meta_tags);
   }
?>

<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>GripOffers</title>
    <meta name="keywords" content="<?php echo $comma_separated;?>">

Body:
Three corrections:

1) Define array outside loop. Your code every time defines a new array. Therefore, you are getting only latest value.

2) Move implode() outside loop. You need to implode() whole array, not the latest iteration value.

3) implode(): First parameter missing, I placed ,.

Corrected code:

$meta_t=mysqli_query($con,"select * from tags");
$meta_tags=array();
while($row1=mysqli_fetch_array($meta_t,MYSQLI_ASSOC)){
 $meta_tags[]=$row1['tag_name'];
}
$comma_separated = implode(', ', $meta_tags);


问:
Automation : After file upload in phantomJS (Headless) browser through selenium, Processing Pop-up remain on screen for infinite seconds
In my c# code I am performing a file upload action through phantomJS browser.

```<code>public void ImportFileNew(String importType, String fileNamePath)
    {
        Thread.Sleep(30000);
        switch (importType)
        {
            case "Currency Rates":
                ((OpenQA.Selenium.PhantomJS.PhantomJSDriver)_driver).ExecutePhantomJS("var page = this; page.uploadFile('input[type=file]', '"+fileNamePath+"');");
                break;
            default:
                throw new Exception(importType + "Name is not correct please check in options");
        }
    }
</code>```

Note: This code is working fine. But issue is after uploading file a processing pop-up comes for infinite seconds. If I run the script for other browser like chrome, then pop-up appears for fraction of seconds and then go.

答:
After digging on to this I found that there is some issue in PhantomJs in file uploading scenario. Refer this link:
PhantomJS issue | File Upload

I think presently there is no any concrete solution/workaround on this present. So I am marking it closed for now.

Body:
In my c# code I am performing a file upload action through phantomJS browser.

public void ImportFileNew(String importType, String fileNamePath)
    {
        Thread.Sleep(30000);
        switch (importType)
        {
            case "Currency Rates":
                ((OpenQA.Selenium.PhantomJS.PhantomJSDriver)_driver).ExecutePhantomJS("var page = this; page.uploadFile('input[type=file]', '"+fileNamePath+"');");
                break;
            default:
                throw new Exception(importType + "Name is not correct please check in options");
        }
    }

Note: This code is working fine. But issue is after uploading file a processing pop-up comes for infinite seconds. If I run the script for other browser like chrome, then pop-up appears for fraction of seconds and then go.


问:
Why mySQL table won't export properly as HTML table
I use bootstrap 3 template and connect to a mysql database, sort the table and export some datas as HTML table in order to display it on bootstrap webpage.

Here is the mySQL look like :

The following code won't get expected results:

```<code><div class="well">

<?php

//MySQL Database Connect
include '/includes/dbconnect.php';

$result = mysqli_query($conn,"SELECT * FROM webpilot ORDER BY NEXT_EVENT ASC");

if(mysqli_num_rows($result) >= 1) {

    echo '<table class="table table-striped table-bordered table-hover">';
    echo "<tr><th>ID</th><th>NAME:</th><th>EPOCH</th></tr>";
    while($row = mysqli_fetch_array($results)) {
        echo "<tr><td>";
        echo $row['ID'];
        echo "</td><td>";
        echo $row['NAME'];
        echo "</td><td>";
        echo $row['NEXT_EVENT'];
        echo "</td></tr>";
    }
    echo "</table>";
}
?>
</div>  <!-- well -->
</code>```

dbconnect.php :

```<code><?php

$localhost="xxx.xx.xxx.com";
$username="dboxxxxxxx";
$password="xxxxxx";
$database="dbxxxxxx";

$conn = mysqli_connect($localhost,$username,$password,$database);

//test if connection failed
if(mysqli_connect_errno()){
    die("connection failed: "
        . mysqli_connect_error()
        . " (" . mysqli_connect_errno()
        . ")");
}
?>
</code>```

original page link can be found here : http://s529471052.onlinehome.fr/bs3/gpio/dyntable.htm

答:
Its just a simple typo

```<code>$result = mysqli_query($conn,"SELECT * FROM webpilot ORDER BY NEXT_EVENT ASC");

if(mysqli_num_rows($result) >= 1) {

    echo '<table class="table table-striped table-bordered table-hover">';
    echo "<tr><th>ID</th><th>NAME:</th><th>EPOCH</th></tr>";
    //while($row = mysqli_fetch_array($results)) {
                                      ^^^^^^^^
    while($row = mysqli_fetch_array($result)) {
</code>```

While testing Add

```<code>ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); `
</code>```

to the top of your script. This will force any mysqli_ errors to
  generate an Exception that you can see on the browser and other errors will also be visible on your browser.

Answer for additional info provided in a comment

From your comment below, it appears you are trying to run PHP code from a web page with a .htm extension. That wont work unless you have configured Apache to do this

Change the web page file name to have a .php extension and then Apache will pass the PHP code to the PHP interpreter for compilation and execution.

Body:
I use bootstrap 3 template and connect to a mysql database, sort the table and export some datas as HTML table in order to display it on bootstrap webpage.

Here is the mySQL look like :

The following code won't get expected results:

<?php

//MySQL Database Connect
include '/includes/dbconnect.php';

$result = mysqli_query($conn,"SELECT * FROM webpilot ORDER BY NEXT_EVENT ASC");

if(mysqli_num_rows($result) >= 1) {

    echo '
';
    echo "
ID	NAME:	EPOCH
";
    while($row = mysqli_fetch_array($results)) {
        echo "
";
        echo $row['ID'];
        echo "	";
        echo $row['NAME'];
        echo "	";
        echo $row['NEXT_EVENT'];
        echo "
";
    }
    echo "
";
}
?>

dbconnect.php :

<?php

$localhost="xxx.xx.xxx.com";
$username="dboxxxxxxx";
$password="xxxxxx";
$database="dbxxxxxx";

$conn = mysqli_connect($localhost,$username,$password,$database);

//test if connection failed
if(mysqli_connect_errno()){
    die("connection failed: "
        . mysqli_connect_error()
        . " (" . mysqli_connect_errno()
        . ")");
}
?>

original page link can be found here : http://s529471052.onlinehome.fr/bs3/gpio/dyntable.htm

Body:
Its just a simple typo

$result = mysqli_query($conn,"SELECT * FROM webpilot ORDER BY NEXT_EVENT ASC");

if(mysqli_num_rows($result) >= 1) {

    echo '<table class="table table-striped table-bordered table-hover">';
    echo "<tr><th>ID</th><th>NAME:</th><th>EPOCH</th></tr>";
    //while($row = mysqli_fetch_array($results)) {
                                      ^^^^^^^^
    while($row = mysqli_fetch_array($result)) {

While testing Add

ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); `

to the top of your script. This will force any mysqli_ errors to
  generate an Exception that you can see on the browser and other errors will also be visible on your browser.

Answer for additional info provided in a comment

From your comment below, it appears you are trying to run PHP code from a web page with a .htm extension. That wont work unless you have configured Apache to do this

Change the web page file name to have a .php extension and then Apache will pass the PHP code to the PHP interpreter for compilation and execution.


问:
Search for string within a List with Dictionaries
-- EDIT:

Okay thanks to you guys, and especially randomir I adjusted the loop as follows:

```<code>while buy_active > 0 or balance_available > 0 or i <= 0:
        print('Selling {0} {1} for {2:.8f} {3}. Volume: {4} It {5}'.format(balance_available, currency, coinprice_sell, trade, coinvolume, i))
        api.selllimit(market, balance_available, coinprice_sell)

        open_order = api.getopenorders(market)
        buy_active = len(list(filter(partial(eq, "LIMIT_BUY"),
                                map(itemgetter("OrderType"), open_order)))) > 0

        coinbalance = api.getbalance(currency)
        balance_available = coinbalance['Available']  # You still have some coins available
        coinsummary = api.getmarketsummary(market)
        coinprice = coinsummary[0]['Last']
        coinvolume = coinsummary[0]['Volume'] * coinprice
        i += 1
else:
        print('No open Buy order or remaining quantity')
</code>```

Now this codes runs almost all the time perfectly but once in a while I receive an error (which I do not know how to replicate, since it probably depends on what the API transmits to the program.

The error says:

```<code>Traceback (most recent call last):
  File "test.py", line 76, in <module>
    while buy_active > 0 or balance_available > 0 or i <= 0:
TypeError: '>' not supported between instances of 'NoneType' and 'int'
</code>```

So I interpret the error that sometimes the variable buy_active has no type and hence cannot be interpreted with ">". However, I do not see how this can happen. It probably has something to do with the len(list(filter(... approach. I also tried to define buy_active = 1 so it enters the loop at least once. But this does not solve the problem. Hence I guess this operator sometimes deliveres a NoneType character.

Does anybody has a suggestion what the problem could be?

Best
SaltyJ

Original:

I just started programming in python 2.7 (for this particular code I would like to stay on 2.7) where I encountered a problem. Since I am very new to programming, I cannot figure out how to solve my problem. I hope you can help.

I want to handle some input from an API about my open orders at an online exchange.

Over the API I receive a list with nested dictionnaries. One Example (for 2 orders is below).

```<code>{
    "success" : true,
    "message" : "",
    "result" : [{
            "Uuid" : null,
            "OrderUuid" : "09aa5bb6-8232-41aa-9b78-a5a1093e0211",
            "Exchange" : "BTC-LTC",
            "OrderType" : "LIMIT_SELL",
            "Quantity" : 5.00000000,
            "QuantityRemaining" : 5.00000000,
            "Limit" : 2.00000000,
            "CommissionPaid" : 0.00000000,
            "Price" : 0.00000000,
            "PricePerUnit" : null,
            "Opened" : "2014-07-09T03:55:48.77",
            "Closed" : null,
            "CancelInitiated" : false,
            "ImmediateOrCancel" : false,
            "IsConditional" : false,
            "Condition" : null,
            "ConditionTarget" : null
        }, {
            "Uuid" : null,
            "OrderUuid" : "8925d746-bc9f-4684-b1aa-e507467aaa99",
            "Exchange" : "BTC-LTC",
            "OrderType" : "LIMIT_BUY",
            "Quantity" : 100000.00000000,
            "QuantityRemaining" : 100000.00000000,
            "Limit" : 0.00000001,
            "CommissionPaid" : 0.00000000,
            "Price" : 0.00000000,
            "PricePerUnit" : null,
            "Opened" : "2014-07-09T03:55:48.583",
            "Closed" : null,
            "CancelInitiated" : false,
            "ImmediateOrCancel" : false,
            "IsConditional" : false,
            "Condition" : null,
            "ConditionTarget" : null
        }
    ]
}
</code>```

The API produces a list with one dictionnary for every open order.

Now I want to basically make my code go through all dic. looking for the string "LIMIT_BUY".

My current code does this for up to 2 orders. But it is probably highly inefficient and also cannot cope with orders > 2:

At the end of the loop the buy_active variable should  be "1" if there is any buy order or 0 if there is no order or only selling orders.

```<code>if len(open_order) == 2:
            order_type_1 = open_order[0]['OrderType']
            order_type_2 = open_order[1]['OrderType']
            if order_type_1 == 'LIMIT_BUY' or order_type_2 == 'LIMIT_BUY':
                buy_active = 1
            else:
                buy_active = 0

        elif len(open_order) == 1:
            order_type_1 = open_order[0]['OrderType']
            if order_type_1 == 'LIMIT_BUY':
                buy_active = 1
            else:
                buy_active = 0
        else:
            buy_active = 0
</code>```

What I would like is a most efficient (in terms of time) code to look through the list with any number of entries.

Can somebody help me?:)

Thanks alot! I just started coding 4 days ago, so please be nice :)

Best
SaltyJ

答:
This would be the imperative programming approach, simply looping over values in open_order list:

```<code>buy_active = False
for order in open_order:
    if order.get("OrderType") == "LIMIT_BUY":
        buy_active = True
        break
</code>```

We use a for loop to iterate over items in the list, and then we safely inspect each item (which is a dictionary) - to see if it contains a key OrderType, and if does, is it equal to LIMIT_BUY. When we find the first such item, we set buy_active to True, and abort any further processing (we know there is at least one item, so no point in looping over other items).

And this would be the functional programming approach:

```<code>from operator import itemgetter, eq
from functools import partial

buy_active = len(filter(partial(eq, "LIMIT_BUY"),
                        map(itemgetter("OrderType"), open_order))) > 0
</code>```

The boolean variable buy_active will be True if at least one LIMIT_BUY was found as a value for OrderType, same as in previous approach.

Here we use the built-in function called map to evaluate function itemgetter("OrderType") over each item in open_order collection of dictionaries. The itemgetter will extract "OrderType" from each dictionary, and the result of the mapping will be a list of all OrderTypes, like this: ["LIMIT_SELL", "LIMIT_BUY", ...].

We now apply filter on that list, and with partially applied eq operator we check if any of the items is equal to "LIMIT_BUY". That filters-out all that are not, producing a list: ["LIMIT_BUY", ...].

After that, we simply check the length of the list, and declare buy_active is True if the list is not empty.

Body:
-- EDIT:

Okay thanks to you guys, and especially randomir I adjusted the loop as follows:

while buy_active > 0 or balance_available > 0 or i <= 0:
        print('Selling {0} {1} for {2:.8f} {3}. Volume: {4} It {5}'.format(balance_available, currency, coinprice_sell, trade, coinvolume, i))
        api.selllimit(market, balance_available, coinprice_sell)

        open_order = api.getopenorders(market)
        buy_active = len(list(filter(partial(eq, "LIMIT_BUY"),
                                map(itemgetter("OrderType"), open_order)))) > 0

        coinbalance = api.getbalance(currency)
        balance_available = coinbalance['Available']  # You still have some coins available
        coinsummary = api.getmarketsummary(market)
        coinprice = coinsummary[0]['Last']
        coinvolume = coinsummary[0]['Volume'] * coinprice
        i += 1
else:
        print('No open Buy order or remaining quantity')

Now this codes runs almost all the time perfectly but once in a while I receive an error (which I do not know how to replicate, since it probably depends on what the API transmits to the program.

The error says:

Traceback (most recent call last):
  File "test.py", line 76, in <module>
    while buy_active > 0 or balance_available > 0 or i <= 0:
TypeError: '>' not supported between instances of 'NoneType' and 'int'

So I interpret the error that sometimes the variable buy_active has no type and hence cannot be interpreted with ">". However, I do not see how this can happen. It probably has something to do with the len(list(filter(... approach. I also tried to define buy_active = 1 so it enters the loop at least once. But this does not solve the problem. Hence I guess this operator sometimes deliveres a NoneType character.

Does anybody has a suggestion what the problem could be?

Best
SaltyJ

Original:

I just started programming in python 2.7 (for this particular code I would like to stay on 2.7) where I encountered a problem. Since I am very new to programming, I cannot figure out how to solve my problem. I hope you can help.

I want to handle some input from an API about my open orders at an online exchange.

Over the API I receive a list with nested dictionnaries. One Example (for 2 orders is below).

{
    "success" : true,
    "message" : "",
    "result" : [{
            "Uuid" : null,
            "OrderUuid" : "09aa5bb6-8232-41aa-9b78-a5a1093e0211",
            "Exchange" : "BTC-LTC",
            "OrderType" : "LIMIT_SELL",
            "Quantity" : 5.00000000,
            "QuantityRemaining" : 5.00000000,
            "Limit" : 2.00000000,
            "CommissionPaid" : 0.00000000,
            "Price" : 0.00000000,
            "PricePerUnit" : null,
            "Opened" : "2014-07-09T03:55:48.77",
            "Closed" : null,
            "CancelInitiated" : false,
            "ImmediateOrCancel" : false,
            "IsConditional" : false,
            "Condition" : null,
            "ConditionTarget" : null
        }, {
            "Uuid" : null,
            "OrderUuid" : "8925d746-bc9f-4684-b1aa-e507467aaa99",
            "Exchange" : "BTC-LTC",
            "OrderType" : "LIMIT_BUY",
            "Quantity" : 100000.00000000,
            "QuantityRemaining" : 100000.00000000,
            "Limit" : 0.00000001,
            "CommissionPaid" : 0.00000000,
            "Price" : 0.00000000,
            "PricePerUnit" : null,
            "Opened" : "2014-07-09T03:55:48.583",
            "Closed" : null,
            "CancelInitiated" : false,
            "ImmediateOrCancel" : false,
            "IsConditional" : false,
            "Condition" : null,
            "ConditionTarget" : null
        }
    ]
}

The API produces a list with one dictionnary for every open order.

Now I want to basically make my code go through all dic. looking for the string "LIMIT_BUY".

My current code does this for up to 2 orders. But it is probably highly inefficient and also cannot cope with orders > 2:

At the end of the loop the buy_active variable should  be "1" if there is any buy order or 0 if there is no order or only selling orders.

if len(open_order) == 2:
            order_type_1 = open_order[0]['OrderType']
            order_type_2 = open_order[1]['OrderType']
            if order_type_1 == 'LIMIT_BUY' or order_type_2 == 'LIMIT_BUY':
                buy_active = 1
            else:
                buy_active = 0

        elif len(open_order) == 1:
            order_type_1 = open_order[0]['OrderType']
            if order_type_1 == 'LIMIT_BUY':
                buy_active = 1
            else:
                buy_active = 0
        else:
            buy_active = 0

What I would like is a most efficient (in terms of time) code to look through the list with any number of entries.

Can somebody help me?:)

Thanks alot! I just started coding 4 days ago, so please be nice :)

Best
SaltyJ

Body:
This would be the imperative programming approach, simply looping over values in open_order list:

buy_active = False
for order in open_order:
    if order.get("OrderType") == "LIMIT_BUY":
        buy_active = True
        break

We use a for loop to iterate over items in the list, and then we safely inspect each item (which is a dictionary) - to see if it contains a key OrderType, and if does, is it equal to LIMIT_BUY. When we find the first such item, we set buy_active to True, and abort any further processing (we know there is at least one item, so no point in looping over other items).

And this would be the functional programming approach:

from operator import itemgetter, eq
from functools import partial

buy_active = len(filter(partial(eq, "LIMIT_BUY"),
                        map(itemgetter("OrderType"), open_order))) > 0

The boolean variable buy_active will be True if at least one LIMIT_BUY was found as a value for OrderType, same as in previous approach.

Here we use the built-in function called map to evaluate function itemgetter("OrderType") over each item in open_order collection of dictionaries. The itemgetter will extract "OrderType" from each dictionary, and the result of the mapping will be a list of all OrderTypes, like this: ["LIMIT_SELL", "LIMIT_BUY", ...].

We now apply filter on that list, and with partially applied eq operator we check if any of the items is equal to "LIMIT_BUY". That filters-out all that are not, producing a list: ["LIMIT_BUY", ...].

After that, we simply check the length of the list, and declare buy_active is True if the list is not empty.


问:
Close a ionic modal in a service
I'm working with Ionic 3 (Angular 4) and I would like to close a ionic modal in a service, it's possible ?

Screen of DataService.ts

I would like call a close() function in another function of my DataService.ts to close my modal deleteconfirm.ts

答:
By the looks of your code, seems to me like your service will have to know about the view.

What you can do is add an instance of the modal to your service whenever the modal is opened, so that you can refer to that instance to be able to close it as well in the service.

Example (just a made up example as the code in your example is too brief):

```<code>// Example component
export class MyComponent implements OnInit {
    modal: Modal;

    constructor(private modalService: ModalService) {}

    ngOnInit() {
        this.modalService.modal = this.modal;
    }

    close() {
        this.modalService.close();
    }
}

// Example service
export class ModalService {
    _modal: Modal;

    set modal(modal: Modal) {
        this._modal = modal;
    }

    close() {
        if (this._modal) {
            this._modal.close();
            this._modal = null;
        }
    }
}
</code>```

This approach allows portability, in that you can close the modal from any component you wish by just injecting the ModalService.

Title: Close a ionic modal in a service

Body:
By the looks of your code, seems to me like your service will have to know about the view.

What you can do is add an instance of the modal to your service whenever the modal is opened, so that you can refer to that instance to be able to close it as well in the service.

Example (just a made up example as the code in your example is too brief):

// Example component
export class MyComponent implements OnInit {
    modal: Modal;

    constructor(private modalService: ModalService) {}

    ngOnInit() {
        this.modalService.modal = this.modal;
    }

    close() {
        this.modalService.close();
    }
}

// Example service
export class ModalService {
    _modal: Modal;

    set modal(modal: Modal) {
        this._modal = modal;
    }

    close() {
        if (this._modal) {
            this._modal.close();
            this._modal = null;
        }
    }
}

This approach allows portability, in that you can close the modal from any component you wish by just injecting the ModalService.


问:
Special characters to UTF-8 byte in r
I am working with a vector of text, which contains odd characters such as:
í, ã, ú etc.

I am working with an api to translate them from Portuguese to English, but the problem is that the encoding of the API prefers it to be UTF-8 hex encoded. This means that the text that I send through needs to be as follow:

```<code>Província: Prov%C3%ADncia
</code>```

I can use iconv in R, in the follow manner:

```<code>iconv("Província", "UTF-8", sub = "byte")
[1] "Prov<ed>ncia"
</code>```

But it provides a different result. Is there a way in R to do this?

答:
To read special characters you need : </p>

```<code>x <- enc2utf8(as("Província", "character"))
y <- iconv("Província", "LATIN2", "UTF-8")
[1] "Província"

Encoding(x) <- "bytes"
Encoding(y) <- "bytes"
cat(y,"\n");cat(x)

> Prov\xc3\xadncia
> Prov\xc3\xadncia
</code>```

Title: Special characters to UTF-8 byte in r

Body:
I am working with a vector of text, which contains odd characters such as:
í, ã, ú etc.

I am working with an api to translate them from Portuguese to English, but the problem is that the encoding of the API prefers it to be UTF-8 hex encoded. This means that the text that I send through needs to be as follow:

Província: Prov%C3%ADncia

I can use iconv in R, in the follow manner:

iconv("Província", "UTF-8", sub = "byte")
[1] "Prov<ed>ncia"

But it provides a different result. Is there a way in R to do this?

Body:
To read special characters you need :

x <- enc2utf8(as("Província", "character"))
y <- iconv("Província", "LATIN2", "UTF-8")
[1] "Província"

Encoding(x) <- "bytes"
Encoding(y) <- "bytes"
cat(y,"\n");cat(x)

> Prov\xc3\xadncia
> Prov\xc3\xadncia


问:
How to enhance-iterate by reference over an array element that's of type set (STL) of user-defined objects?
necklace is a c-array consisting of elements that are std::set<Pearl>, where Pearl is a user-defined type.

necklace is defined as follows

```<code>std::set<Pearl> necklace[NUM_CIRC] = { };
</code>```

After this the elements are populated with the Pearl's.

The following snippet

```<code>for (Pearl &p : necklace[circular_coordinate]) {
    p.set_color("white");
}
</code>```

results in a compile error

invalid initialization of reference of type 'Pearl&' from
  expression of type 'const Pearl'

How can I access necklace[circular_coordinate] in a non-const fashion?

答:
Unfortunately, std::set elements are immutable. This means, you can't change them by design.

The reason for this is the same as with immutable keys in std::set and std::map - changing the key might result in changed order between keys, which is not supported by associative containers.

Body:
necklace is a c-array consisting of elements that are std::set<Pearl>, where Pearl is a user-defined type.

necklace is defined as follows

std::set<Pearl> necklace[NUM_CIRC] = { };

After this the elements are populated with the Pearl's.

The following snippet

for (Pearl &p : necklace[circular_coordinate]) {
    p.set_color("white");
}

results in a compile error

invalid initialization of reference of type 'Pearl&' from
  expression of type 'const Pearl'

How can I access necklace[circular_coordinate] in a non-const fashion?


问:
how to debug requests with a client certificate C#
I am currently trying to make a secure request (HTTPS) via client certificate, but I'm having issues understanding if the client is actually sending the certificate itself.

I already tried fiddler for checking the traffic, but I was not able to find any filter or any doc about it (and the official docs of fiddler seems also down atm)

Cheers in advance

答: As far, I know you cannot use fiddler because it captures only HTTP(S) traffic, but SSL negotiation happens on transport (TCP) level. You can use wireshark traffic analyzer and this guide or this.</p>


问:
jQuery post and .NET MVC action - returning partial results to end user
I have a question in regards to a concept that I haven't had a chance to encounter before, but I have been thinking about it for a long time and I wanted to see if it's doable in .NET MVC 5 using jQuery...

So let's say we have an action  in controller which looks like this:

```<code>[ActionName("OurTestAction")]
[HttpPost]
public ActionResult OurTestAction()
{
 Method1();
//returning some sort of "signal" here to client side to notify that the method1 finished processing data.. ?
 Method2();
 Method3();
 return Json("Ok");
}
</code>```

Where the action was triggered like this:

```<code>$(document).ready(function(){
$.post("/Controller/OurTestAction").done(function(response){
// displaying the result here
});
}):
</code>```

So the idea that I had with this piece of code is that I could be able to tell end user when was the Method1() called and ended it's life cycle. Once the Method1(); finishes what it was supposed to do, I'd like to be able to tell the end user in his browser something like this (via jQuery): Method1() finished processing the data , moving onto the method2();

Is something like this doable with jQuery and .NET, and if so how?

Can someone help me out ?

答:
Break your controller methods into different actions.

Controller

```<code>[HttpPost]
public ActionResult Method1()
{
  Method1();
  return Json("Ok");
}

[HttpPost]
public ActionResult Method2()
{
  Method2();
  return Json("Ok");
}

[HttpPost]
public ActionResult Method3()
{
  Method3();
  return Json("Ok");
}
</code>```

Javascript

```<code>$.ajax({
    type: 'POST',
    url: 'controller/method1'
}).done(function(resp) {
   //do stuff to notify users method 1 is complete
    $.ajax({
        type: 'POST',
        url: 'controller/method2'
    }).done(function(resp2) {
        //do stuff to notify users method 2 is complete
    });
});
</code>```

Body:
I have a question in regards to a concept that I haven't had a chance to encounter before, but I have been thinking about it for a long time and I wanted to see if it's doable in .NET MVC 5 using jQuery...

So let's say we have an action  in controller which looks like this:

[ActionName("OurTestAction")]
[HttpPost]
public ActionResult OurTestAction()
{
 Method1();
//returning some sort of "signal" here to client side to notify that the method1 finished processing data.. ?
 Method2();
 Method3();
 return Json("Ok");
}

Where the action was triggered like this:

$(document).ready(function(){
$.post("/Controller/OurTestAction").done(function(response){
// displaying the result here
});
}):

So the idea that I had with this piece of code is that I could be able to tell end user when was the Method1() called and ended it's life cycle. Once the Method1(); finishes what it was supposed to do, I'd like to be able to tell the end user in his browser something like this (via jQuery): Method1() finished processing the data , moving onto the method2();

Is something like this doable with jQuery and .NET, and if so how?

Can someone help me out ?

Body:
Break your controller methods into different actions.

Controller

[HttpPost]
public ActionResult Method1()
{
  Method1();
  return Json("Ok");
}

[HttpPost]
public ActionResult Method2()
{
  Method2();
  return Json("Ok");
}

[HttpPost]
public ActionResult Method3()
{
  Method3();
  return Json("Ok");
}

Javascript

$.ajax({
    type: 'POST',
    url: 'controller/method1'
}).done(function(resp) {
   //do stuff to notify users method 1 is complete
    $.ajax({
        type: 'POST',
        url: 'controller/method2'
    }).done(function(resp2) {
        //do stuff to notify users method 2 is complete
    });
});


问:
Haskell Declare empty list, but which is actually not empty?
I'm new to Haskell and are playing around a bit. I created a recursive function with guards. See function below:

```<code>filterAge :: [Person] -> [String]
filterAge (x:xs)
 | (x:xs) == []                        = []
 | (getAge x) < 30 || (getAge x) > 40  = [] ++ filterAge xs
 | otherwise                           = [getName x] ++ filterAge xs
</code>```

I have a data set created with 10 Persons which I use in this method. When I tried this function it gave all the right people, but after that it got a Non-exhaustive patterns error:
["Lise","Jaap","Elle","Ebba"*** Exception: D:\...:(44,1)-(47,77): Non-exhaustive patterns in function filterAge

I found out that it never reaches the first guard. So I played around a bit and found out something really strange (in my opinion):

```<code>*Main> let (x:xs) = []
*Main> (x:xs) == []
False
</code>```

Now my main question is: Why does (x:xs) == [] return False?

If anyone has a better way for me of doing the function that'd be great, but it's not very important.

Thanks in advance!

EDIT

Thanks to Willem Van Onsem and Lambda.xy.x I got a quick answer to my question. This resulted in the following function which works perfectly:

```<code>filterAge :: [Person] -> [String]
filterAge []                           = []
filterAge (x:xs)
 | (getAge x) < 30 || (getAge x) > 40  = [] ++ filterAge xs
 | otherwise                           = [getName x] ++ filterAge xs
</code>```

But for the best version you'd have to check the answer of Willem Van Onsem.

答:
To answer your "main" question,

*Main> let (x:xs) = []      -- (1)

means, when x's or xs's value is required, match (x:xs) with [] and use the resulting bindings. The match will never succeed, and any such attempt will always result in patter-matching failure error.

So why wasn't it?

*Main> (x:xs) == []         -- (2)

Now this means, try to compare (x:xs) and []. Both are lists; comparing lists involves pattern matching the top structure and then proceeding recursively  comparing the components, on success -- returning False on failure (not actually failing). Thus a match between (_:_) and [] is tried, and fails, resulting in an immediate return of the False value as the result of the comparison.

Note that values bound to x and xs were not requested at any point; hence there was no error because the matching of (x:xs) and [] in (1) was never triggered.

Body:
I'm new to Haskell and are playing around a bit. I created a recursive function with guards. See function below:

filterAge :: [Person] -> [String]
filterAge (x:xs)
 | (x:xs) == []                        = []
 | (getAge x) < 30 || (getAge x) > 40  = [] ++ filterAge xs
 | otherwise                           = [getName x] ++ filterAge xs

I have a data set created with 10 Persons which I use in this method. When I tried this function it gave all the right people, but after that it got a Non-exhaustive patterns error:
["Lise","Jaap","Elle","Ebba"*** Exception: D:\...:(44,1)-(47,77): Non-exhaustive patterns in function filterAge

I found out that it never reaches the first guard. So I played around a bit and found out something really strange (in my opinion):

*Main> let (x:xs) = []
*Main> (x:xs) == []
False

Now my main question is: Why does (x:xs) == [] return False?

If anyone has a better way for me of doing the function that'd be great, but it's not very important.

Thanks in advance!

EDIT

Thanks to Willem Van Onsem and Lambda.xy.x I got a quick answer to my question. This resulted in the following function which works perfectly:

filterAge :: [Person] -> [String]
filterAge []                           = []
filterAge (x:xs)
 | (getAge x) < 30 || (getAge x) > 40  = [] ++ filterAge xs
 | otherwise                           = [getName x] ++ filterAge xs

But for the best version you'd have to check the answer of Willem Van Onsem.


问:
Test simple code too?
I've tried unit testing and I'm not a big fan; it's been much more of a burden than a boon. So what tests should I have for this simple 2D point class?

```<code>public class Point{
    int x;
    int y;

    public Point(int px, int py) {
        x = px;
        y = py;
    }

    public double distanceTo(Point other) {
        // Pythagorean theorem
    }

    public ArrayList<Point> lineTo(Point other) {
        // Bresenham's line algorithm. The same thing I've
        // implemented a dozen times in differnt languages
        // and can type from memory....
    }
}
</code>```

How many tests do I need for each method? The other point could be at the same place as the first, or one of it's four quadrants, or null. So six unit tests for each method?

Is it possible to have code so simple and obvious that unit tests provide so little value that they aren't worth it?

(The responses so far say: tests should be written for any parameter that can be null, any parameter that can be the object itself (ie this.distanceTo(this)), any parameter that may possibly cause an overflow, and any parameter that may possibly cause floating point loss of precision. At least four things to write tests for.)

答: Since you put TDD tag, then that consider that you write your unit tests before you write your code. Under code I consider even the interface. Your tests should define what the class does.</p>

ContentLicense: CC BY-SA 2.5

Title: Test simple code too?

Body:
I've tried unit testing and I'm not a big fan; it's been much more of a burden than a boon. So what tests should I have for this simple 2D point class?

public class Point{
    int x;
    int y;

    public Point(int px, int py) {
        x = px;
        y = py;
    }

    public double distanceTo(Point other) {
        // Pythagorean theorem
    }

    public ArrayList<Point> lineTo(Point other) {
        // Bresenham's line algorithm. The same thing I've
        // implemented a dozen times in differnt languages
        // and can type from memory....
    }
}

How many tests do I need for each method? The other point could be at the same place as the first, or one of it's four quadrants, or null. So six unit tests for each method?

Is it possible to have code so simple and obvious that unit tests provide so little value that they aren't worth it?

(The responses so far say: tests should be written for any parameter that can be null, any parameter that can be the object itself (ie this.distanceTo(this)), any parameter that may possibly cause an overflow, and any parameter that may possibly cause floating point loss of precision. At least four things to write tests for.)


问:
Compare two integers doesn't work correctly in Android
I have a method that have to compare an integer with an Arraylist and if the number on the integer is on the arraylist, I recieve a false. If the integer number is not on the arraylist I recieve a true.

I need this, because I'm making a quiz game that have some questions on a BBDD and I can't show the same question twice. Also this questions are in three categories: E, I and A. I have to show five E questions, then five I questions and then five A questions.

So I have to show questions without repeat them, and also 5 of each category. I make this methods but I don't know why it repeats some questions.

The only thing works correctly is the category questions. I have always 5 E questions, then 5 I questions and at least 5 A questions.

The method that told me if the questions is on the ArrayList:

```<code>private boolean checkRandom()
{
    for(int i = 0; i < listRandom.size(); i++)
    {
        if(questionPosition == listRandom.get(i))
        {
            return false;
        }
    }

    return true;
}
</code>```

I also try with "equals", but I have the same result.

The method that check if the question is in the correct category and is not showed before:

```<code>private void loadPhase() {

    if (numQuestion < 15)
    {
        r = new Random();
        questionPosition = r.nextInt(listQuestions.size());

        if(numQuestion < 5)
        {
            while(!listPhase.get(questionPosition).equals("E") && (!listPhase.get(questionPosition).equals("E")|| !checkRandom()))
            {
                r = new Random();
                questionPosition = r.nextInt(listQuestions.size());
            }
        }
        else if(numQuestion > 4 && numQuestion < 10)
        {
            while(!listPhase.get(questionPosition).equals("I") && (!listPhase.get(questionPosition).equals("I")|| !checkRandom()))
            {
                r = new Random();
                questionPosition = r.nextInt(listQuestions.size());
            }
        }
        else if(numQuestion > 9)
        {
            while(!listPhase.get(questionPosition).equals("A") && (!listPhase.get(questionPosition).equals("A")|| !checkRandom()))
            {
                r = new Random();
                questionPosition = r.nextInt(listQuestions.size());
            }
        }

        listRandom.add(questionPosition);

        header4questions.setText(listQuestions.get(questionPosition));

        answer1.setText(listAnswers.get(questionPosition * 4));
        answer2.setText(listAnswers.get((questionPosition * 4) + 1));
        answer3.setText(listAnswers.get((questionPosition * 4) + 2));
        answer4.setText(listAnswers.get((questionPosition * 4) + 3));

        numQuestion++;
    }
    else {
        Toast.makeText(getApplicationContext(), "You have finished the quiz!", Toast.LENGTH_SHORT).show();

        uploadPoints();
    }
}
</code>```

So, what I have is all the questions on the correct category, but it repeat the questions and I don't know why.

Can anyone help me?

Thanks!

答:
I solve it! I have to change the while condition like this:</p>

```<code>while(!listPhase.get(questionPosition).equals("E") || (listPhase.get(questionPosition).equals("E") && !checkRandom()))
</code>```

Body:
I have a method that have to compare an integer with an Arraylist and if the number on the integer is on the arraylist, I recieve a false. If the integer number is not on the arraylist I recieve a true.

I need this, because I'm making a quiz game that have some questions on a BBDD and I can't show the same question twice. Also this questions are in three categories: E, I and A. I have to show five E questions, then five I questions and then five A questions.

So I have to show questions without repeat them, and also 5 of each category. I make this methods but I don't know why it repeats some questions.

The only thing works correctly is the category questions. I have always 5 E questions, then 5 I questions and at least 5 A questions.

The method that told me if the questions is on the ArrayList:

private boolean checkRandom()
{
    for(int i = 0; i < listRandom.size(); i++)
    {
        if(questionPosition == listRandom.get(i))
        {
            return false;
        }
    }

    return true;
}

I also try with "equals", but I have the same result.

The method that check if the question is in the correct category and is not showed before:

private void loadPhase() {

    if (numQuestion < 15)
    {
        r = new Random();
        questionPosition = r.nextInt(listQuestions.size());

        if(numQuestion < 5)
        {
            while(!listPhase.get(questionPosition).equals("E") && (!listPhase.get(questionPosition).equals("E")|| !checkRandom()))
            {
                r = new Random();
                questionPosition = r.nextInt(listQuestions.size());
            }
        }
        else if(numQuestion > 4 && numQuestion < 10)
        {
            while(!listPhase.get(questionPosition).equals("I") && (!listPhase.get(questionPosition).equals("I")|| !checkRandom()))
            {
                r = new Random();
                questionPosition = r.nextInt(listQuestions.size());
            }
        }
        else if(numQuestion > 9)
        {
            while(!listPhase.get(questionPosition).equals("A") && (!listPhase.get(questionPosition).equals("A")|| !checkRandom()))
            {
                r = new Random();
                questionPosition = r.nextInt(listQuestions.size());
            }
        }

        listRandom.add(questionPosition);

        header4questions.setText(listQuestions.get(questionPosition));

        answer1.setText(listAnswers.get(questionPosition * 4));
        answer2.setText(listAnswers.get((questionPosition * 4) + 1));
        answer3.setText(listAnswers.get((questionPosition * 4) + 2));
        answer4.setText(listAnswers.get((questionPosition * 4) + 3));

        numQuestion++;
    }
    else {
        Toast.makeText(getApplicationContext(), "You have finished the quiz!", Toast.LENGTH_SHORT).show();

        uploadPoints();
    }
}

So, what I have is all the questions on the correct category, but it repeat the questions and I don't know why.

Can anyone help me?

Thanks!

Body:
I solve it! I have to change the while condition like this:

while(!listPhase.get(questionPosition).equals("E") || (listPhase.get(questionPosition).equals("E") && !checkRandom()))


问:
Runtime Error 3011 in Access
I just try to import a .csv file with vba.
I use the DoCmd.TransferText method with custom specs. I tried to import the file with the wizard, with the same specs and it works perfectly fine.

But when I start the vba I get this error Message:

Sorry, it is in german, but I think one can read the essentials

Here is the part of my code, where I call up the method:

```<code>Public Function ImportFileToTable(params As ImportFileToTableParams) As ImportFileToTableResult
    'TODO: Import a CSV File into the selected table
    Dim result As New ImportFileToTableResult

    On Error GoTo ImportFail
    DoCmd.TransferText acImportDelim, params.SpecificationName, params.TableName, params.FileName, params.HasFieldNames

    result.Success = True
    Set ImportFileToTable = result
    Exit Function

ImportFail:
    result.Success = False
    result.ErrorMessage = "There was an error importing the File"
    Set ImportFileToTable = result
End Function
</code>```

My Database is on a Network-Drive, but I tried to copy it on my local drive and it had the same otcome. I also experimented with the File Location.

The Software I am using is:
    -Microsoft Access 2013

Thank you all in adnvance :)

答:
A more full answer:

The filename contained non-ASCII characters. Multiple Access functions can't handle this properly. The solution is to rename any file with non-ASCII characters to something that doesn't include these characters.

Some useful helper functions:

Test if a string contains non-ASCII characters and return true if it does, false if it doesn't (can be used to throw descriptive errors in this case).

```<code>Public Function StringContainsNonASCII(str As String) As Boolean
    Dim i As Integer
    'Default is false
    StringContainsNonASCII = False
    'Remove question marks
    str = Replace(str, "?", "")
    For i = 1 To Len(str)
        'Search for question marks
        If Asc(Mid(str, i, 1)) = 63 Then
            StringContainsNonASCII = True
            Exit Function
        End If
    Next i
End Function
</code>```

Strip non-ASCII characters from a string

```<code>Public Function RemoveNonASCII(str As String) As String
    Dim i As Integer
    For i = 1 To Len(str)
        'Append the question marks
        If Mid(str, i, 1) = "?" Then
            RemoveNonASCII = RemoveNonASCII & "?"
        End If
        'Append anything that isn't a questionmark
        If Asc(Mid(str, i, 1)) <> 63 Then
            RemoveNonASCII = RemoveNonASCII & Chr(Asc(Mid(str, i, 1)))
        End If
    Next i
End Function
</code>```

Title: Runtime Error 3011 in Access

Body:
I just try to import a .csv file with vba.
I use the DoCmd.TransferText method with custom specs. I tried to import the file with the wizard, with the same specs and it works perfectly fine.

But when I start the vba I get this error Message:

Sorry, it is in german, but I think one can read the essentials

Here is the part of my code, where I call up the method:

Public Function ImportFileToTable(params As ImportFileToTableParams) As ImportFileToTableResult
    'TODO: Import a CSV File into the selected table
    Dim result As New ImportFileToTableResult

    On Error GoTo ImportFail
    DoCmd.TransferText acImportDelim, params.SpecificationName, params.TableName, params.FileName, params.HasFieldNames

    result.Success = True
    Set ImportFileToTable = result
    Exit Function

ImportFail:
    result.Success = False
    result.ErrorMessage = "There was an error importing the File"
    Set ImportFileToTable = result
End Function

My Database is on a Network-Drive, but I tried to copy it on my local drive and it had the same otcome. I also experimented with the File Location.

The Software I am using is:
    -Microsoft Access 2013

Thank you all in adnvance :)

Body:
A more full answer:

The filename contained non-ASCII characters. Multiple Access functions can't handle this properly. The solution is to rename any file with non-ASCII characters to something that doesn't include these characters.

Some useful helper functions:

Test if a string contains non-ASCII characters and return true if it does, false if it doesn't (can be used to throw descriptive errors in this case).

Public Function StringContainsNonASCII(str As String) As Boolean
    Dim i As Integer
    'Default is false
    StringContainsNonASCII = False
    'Remove question marks
    str = Replace(str, "?", "")
    For i = 1 To Len(str)
        'Search for question marks
        If Asc(Mid(str, i, 1)) = 63 Then
            StringContainsNonASCII = True
            Exit Function
        End If
    Next i
End Function

Strip non-ASCII characters from a string

Public Function RemoveNonASCII(str As String) As String
    Dim i As Integer
    For i = 1 To Len(str)
        'Append the question marks
        If Mid(str, i, 1) = "?" Then
            RemoveNonASCII = RemoveNonASCII & "?"
        End If
        'Append anything that isn't a questionmark
        If Asc(Mid(str, i, 1)) <> 63 Then
            RemoveNonASCII = RemoveNonASCII & Chr(Asc(Mid(str, i, 1)))
        End If
    Next i
End Function


问:
Fabric JS - Split Multiple Lines IText
I am using Fabric JS for my project, I want to split multiple lines IText like image below:

split multiple lines on IText

Here is my code:

```<code>var canvas = new fabric.Canvas("canvas", { preserveObjectStacking: true
});

var text = new fabric.IText("Hello!\nSplit Me\nPlease....", {
  fontSize: 20,
  top: 80,
  left: 100,
  fontFamily: "Arial"
});

canvas.add(text);
canvas.renderAll();

$('#split').click(function() {

    var object = canvas.getActiveObject();

    if(!object) return false;

    if ((object.get('type') == 'i-text') && (object.getText().indexOf( "\n" ) > 0)) {

        var splitText = object.getText().split("\n");
        var group = new fabric.Group();
        var cloneObj = [];

        for(var i=0;i<=splitText.length-1;i++) {
            cloneObj[i] = fabric.util.object.clone(object);
            cloneObj[i].setText(splitText[i]);
            canvas.add(group);
            canvas.add(cloneObj[i]);
            group.addWithUpdate(cloneObj[i]);
            canvas.renderAll();
        }

        object.remove();
        canvas.setActiveGroup(group);
        group.setCoords();
        canvas.renderAll();

    }
});
</code>```

Here is the jsfiddle: https://jsfiddle.net/m74ruzwq/2/

Any help would be appreciated. Thanks in advance.

答:
The best way is to take any textLine from fabric has it already split, generate a new object for each line, fix the top value, render at the end.

var canvas = new fabric.Canvas("canvas", { preserveObjectStacking: true });

var text = new fabric.IText("Hello!\nSplit Me\nPlease....", {
  fontSize: 20,
  top: 80,
  left: 100,
  fontFamily: "Arial"
});

canvas.add(text);
canvas.renderAll();

$('#split').click(function() {

  var object = canvas.getActiveObject();

    if(!object) return false;

  if (object._textLines && object._textLines.length > 1) {
      canvas.renderOnAddRemove = false;
   var group = new fabric.Group();
   var cloneObj = [];
      var options = object.toObject();
      group.canvas = canvas;
      delete options.text;
   for(var i=0; i < object._textLines.length; i++) {
    var newObj = new fabric.IText(object._textLines[i], options);
        newObj.top += i * object.fontSize * object.lineHeight;
    canvas.add(newObj);
        group.addWithUpdate(newObj);
   }
   object.remove();
      group.setCoords();
      canvas.renderOnAddRemove = true;
   canvas.setActiveGroup(group);
      canvas.renderAll();
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.14/fabric.min.js"></script>
<button id="split">Split</button>
<canvas id="canvas" width="400" height="300" style="border: 1px solid #ccc"></canvas></code>```

Title: Fabric JS - Split Multiple Lines IText

Body:
I am using Fabric JS for my project, I want to split multiple lines IText like image below:

split multiple lines on IText

Here is my code:

var canvas = new fabric.Canvas("canvas", { preserveObjectStacking: true
});

var text = new fabric.IText("Hello!\nSplit Me\nPlease....", {
  fontSize: 20,
  top: 80,
  left: 100,
  fontFamily: "Arial"
});

canvas.add(text);
canvas.renderAll();

$('#split').click(function() {

    var object = canvas.getActiveObject();

    if(!object) return false;

    if ((object.get('type') == 'i-text') && (object.getText().indexOf( "\n" ) > 0)) {

        var splitText = object.getText().split("\n");
        var group = new fabric.Group();
        var cloneObj = [];

        for(var i=0;i<=splitText.length-1;i++) {
            cloneObj[i] = fabric.util.object.clone(object);
            cloneObj[i].setText(splitText[i]);
            canvas.add(group);
            canvas.add(cloneObj[i]);
            group.addWithUpdate(cloneObj[i]);
            canvas.renderAll();
        }

        object.remove();
        canvas.setActiveGroup(group);
        group.setCoords();
        canvas.renderAll();

    }
});

Here is the jsfiddle: https://jsfiddle.net/m74ruzwq/2/

Any help would be appreciated. Thanks in advance.

Body:
The best way is to take any textLine from fabric has it already split, generate a new object for each line, fix the top value, render at the end.

var canvas = new fabric.Canvas("canvas", { preserveObjectStacking: true });

var text = new fabric.IText("Hello!\nSplit Me\nPlease....", {
  fontSize: 20,
  top: 80,
  left: 100,
  fontFamily: "Arial"
});

canvas.add(text);
canvas.renderAll();

$('#split').click(function() {

  var object = canvas.getActiveObject();

    if(!object) return false;

  if (object._textLines && object._textLines.length > 1) {
      canvas.renderOnAddRemove = false;
   var group = new fabric.Group();
   var cloneObj = [];
      var options = object.toObject();
      group.canvas = canvas;
      delete options.text;
   for(var i=0; i < object._textLines.length; i++) {
    var newObj = new fabric.IText(object._textLines[i], options);
        newObj.top += i * object.fontSize * object.lineHeight;
    canvas.add(newObj);
        group.addWithUpdate(newObj);
   }
   object.remove();
      group.setCoords();
      canvas.renderOnAddRemove = true;
   canvas.setActiveGroup(group);
      canvas.renderAll();
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.14/fabric.min.js"></script>
<button id="split">Split</button>
<canvas id="canvas" width="400" height="300" style="border: 1px solid #ccc"></canvas>


问:
Send mail with output of a Filter Array data in Logic Apps
Is it possible to send the output of a Filter Array in an e-mail body or as attachment?

I'm testing some error handling and want to send the error that occurred in a previous scope in my Logic App.

答: Solved it by using and Action: "Parse JSON" with the output Body from the Filter array and then using the values I was interested of when sending an e-mail.</p>


问:
Custom directive is overriding scope
I have a custom directive as defined below (if you need controller let me know)

```<code>module.exports = angular.module('aah-yes-no-directive-module', [
  require('./yes-no.controller').name,
]).directive('aahYesNo', [function YesNoDirective() {

  return {
    restrict: 'A',
    templateUrl: 'partials/yes-no.template.html',
    require: ['aahYesNo', 'ngModel'],
    controller: 'aahYesNoController',
    controllerAs: 'ctrl',
    link: (scope, el, attrs, ctrls) => {
      let ctrl = ctrls[0],
        ngModelCtrl = ctrls[1];

      ctrl.init(ngModelCtrl, attrs.onValue, attrs.offValue);

      angular.element(el).children().addClass(attrs.size || '');
    },
    scope: {}
  };
}]);
</code>```

Why question is, why does it not update the $modelValue when it changes in the parent controller, or when $viewValue changes?

it is always undefined?

if i take out scope: {} it works, but seems to override the entire parent scope (?!)

答:
Because scope: {} creates an isolated scope,

You can tell directive to inherit parent scope by setting scope: true or by not defining scope property.

Check this article for more details about scope in directives

Title: Custom directive is overriding scope

Body:
I have a custom directive as defined below (if you need controller let me know)

module.exports = angular.module('aah-yes-no-directive-module', [
  require('./yes-no.controller').name,
]).directive('aahYesNo', [function YesNoDirective() {

  return {
    restrict: 'A',
    templateUrl: 'partials/yes-no.template.html',
    require: ['aahYesNo', 'ngModel'],
    controller: 'aahYesNoController',
    controllerAs: 'ctrl',
    link: (scope, el, attrs, ctrls) => {
      let ctrl = ctrls[0],
        ngModelCtrl = ctrls[1];

      ctrl.init(ngModelCtrl, attrs.onValue, attrs.offValue);

      angular.element(el).children().addClass(attrs.size || '');
    },
    scope: {}
  };
}]);

Why question is, why does it not update the $modelValue when it changes in the parent controller, or when $viewValue changes?

it is always undefined?

if i take out scope: {} it works, but seems to override the entire parent scope (?!)


问:
Parameter defaults for ALTER FUNCTION?
I'm trying to migrate one of my oracle databases to Postgres 9.5. I`m currently trying to create the next function:

```<code>-- Generated by Ora2Pg, the Oracle database Schema converter, version 18.1
-- Copyright 2000-2017 Gilles DAROLD. All rights reserved.
-- DATASOURCE: dbi:Oracle:oralab

SET client_encoding TO 'UTF8';
SET search_path = repdev,public,oracle,utl_file,extensions;
show search_path;

CREATE OR REPLACE FUNCTION Bl_Create_Flat_File_Pg.set_charset (file_id
utl_file.file_type, p_title text DEFAULT NULL) RETURNS VOID AS $body$
BEGIN
.....
End;
--
$body$
LANGUAGE PLPGSQL
SECURITY DEFINER
STABLE;
ALTER FUNCTION Bl_Create_Flat_File_Pg.set_charset (file_id
utl_file.file_type, p_title text DEFAULT NOT NULL ) OWNER TO repdev;
</code>```

but when I`m running it in psql iget the next error:

```<code>ERROR:  syntax error at or near "DEFAULT"
LINE 1: ...charset (file_id utl_file.file_type, p_title text DEFAULT NU...
</code>```

答:
For the ALTER FUNCTION you only need to repeat the parameter definitions (actually only the parameter types are required), not the default clause of a parameter:

```<code>ALTER FUNCTION Bl_Create_Flat_File_Pg.set_charset(file_id utl_file.file_type, p_title text)
OWNER TO repdev;
</code>```

or shorter:

```<code>ALTER FUNCTION Bl_Create_Flat_File_Pg.set_charset(utl_file.file_type, text)
OWNER TO repdev;
</code>```

If you compare the documentation of the CREATE FUNCTION statement, which is:

```<code>CREATE [ OR REPLACE ] FUNCTION
name ( [ [ argmode ] [ argname ] argtype [ { DEFAULT | = } default_expr ] [, ...] ] )
</code>```

to the ALTER FUNCTION documentation:

```<code>ALTER FUNCTION name ( [ [ argmode ] [ argname ] argtype [, ...] ] )
</code>```

you will notice that ALTER FUNCTION does not allow the DEFAULT clause.

If the code you have shown us really was generated by Ora2Pg then you should report that as an error to the Ora2Pg authors.

Title: Parameter defaults for ALTER FUNCTION?

Body:
I'm trying to migrate one of my oracle databases to Postgres 9.5. I`m currently trying to create the next function:

-- Generated by Ora2Pg, the Oracle database Schema converter, version 18.1
-- Copyright 2000-2017 Gilles DAROLD. All rights reserved.
-- DATASOURCE: dbi:Oracle:oralab

SET client_encoding TO 'UTF8';
SET search_path = repdev,public,oracle,utl_file,extensions;
show search_path;

CREATE OR REPLACE FUNCTION Bl_Create_Flat_File_Pg.set_charset (file_id
utl_file.file_type, p_title text DEFAULT NULL) RETURNS VOID AS $body$
BEGIN
.....
End;
--
$body$
LANGUAGE PLPGSQL
SECURITY DEFINER
STABLE;
ALTER FUNCTION Bl_Create_Flat_File_Pg.set_charset (file_id
utl_file.file_type, p_title text DEFAULT NOT NULL ) OWNER TO repdev;

but when I`m running it in psql iget the next error:

ERROR:  syntax error at or near "DEFAULT"
LINE 1: ...charset (file_id utl_file.file_type, p_title text DEFAULT NU...

Body:
For the ALTER FUNCTION you only need to repeat the parameter definitions (actually only the parameter types are required), not the default clause of a parameter:

ALTER FUNCTION Bl_Create_Flat_File_Pg.set_charset(file_id utl_file.file_type, p_title text)
OWNER TO repdev;

or shorter:

ALTER FUNCTION Bl_Create_Flat_File_Pg.set_charset(utl_file.file_type, text)
OWNER TO repdev;

If you compare the documentation of the CREATE FUNCTION statement, which is:

CREATE [ OR REPLACE ] FUNCTION
name ( [ [ argmode ] [ argname ] argtype [ { DEFAULT | = } default_expr ] [, ...] ] )

to the ALTER FUNCTION documentation:

ALTER FUNCTION name ( [ [ argmode ] [ argname ] argtype [, ...] ] )

you will notice that ALTER FUNCTION does not allow the DEFAULT clause.

If the code you have shown us really was generated by Ora2Pg then you should report that as an error to the Ora2Pg authors.


答:
Welcome to the wonderful art of coding!

You've encountered your first repetitive task so it seems. This might be the time to look into for-loops or while-loops. They allow you to repeat tasks.

For example, though greatly simplified:

```<code>mylist = [1,2,3]
# Your way:
print mylist[0]
print mylist[1]
print mylist[2]
# This works, but gets tedious if your list grows.

# This is way more concise:
for i in mylist:
    print i
</code>```

Title: Search for string within a List with Dictionaries

Body:
-- EDIT:

Okay thanks to you guys, and especially randomir I adjusted the loop as follows:

while buy_active > 0 or balance_available > 0 or i <= 0:
        print('Selling {0} {1} for {2:.8f} {3}. Volume: {4} It {5}'.format(balance_available, currency, coinprice_sell, trade, coinvolume, i))
        api.selllimit(market, balance_available, coinprice_sell)

        open_order = api.getopenorders(market)
        buy_active = len(list(filter(partial(eq, "LIMIT_BUY"),
                                map(itemgetter("OrderType"), open_order)))) > 0

        coinbalance = api.getbalance(currency)
        balance_available = coinbalance['Available']  # You still have some coins available
        coinsummary = api.getmarketsummary(market)
        coinprice = coinsummary[0]['Last']
        coinvolume = coinsummary[0]['Volume'] * coinprice
        i += 1
else:
        print('No open Buy order or remaining quantity')

Now this codes runs almost all the time perfectly but once in a while I receive an error (which I do not know how to replicate, since it probably depends on what the API transmits to the program.

The error says:

Traceback (most recent call last):
  File "test.py", line 76, in <module>
    while buy_active > 0 or balance_available > 0 or i <= 0:
TypeError: '>' not supported between instances of 'NoneType' and 'int'

So I interpret the error that sometimes the variable buy_active has no type and hence cannot be interpreted with ">". However, I do not see how this can happen. It probably has something to do with the len(list(filter(... approach. I also tried to define buy_active = 1 so it enters the loop at least once. But this does not solve the problem. Hence I guess this operator sometimes deliveres a NoneType character.

Does anybody has a suggestion what the problem could be?

Best
SaltyJ

Original:

I just started programming in python 2.7 (for this particular code I would like to stay on 2.7) where I encountered a problem. Since I am very new to programming, I cannot figure out how to solve my problem. I hope you can help.

I want to handle some input from an API about my open orders at an online exchange.

Over the API I receive a list with nested dictionnaries. One Example (for 2 orders is below).

{
    "success" : true,
    "message" : "",
    "result" : [{
            "Uuid" : null,
            "OrderUuid" : "09aa5bb6-8232-41aa-9b78-a5a1093e0211",
            "Exchange" : "BTC-LTC",
            "OrderType" : "LIMIT_SELL",
            "Quantity" : 5.00000000,
            "QuantityRemaining" : 5.00000000,
            "Limit" : 2.00000000,
            "CommissionPaid" : 0.00000000,
            "Price" : 0.00000000,
            "PricePerUnit" : null,
            "Opened" : "2014-07-09T03:55:48.77",
            "Closed" : null,
            "CancelInitiated" : false,
            "ImmediateOrCancel" : false,
            "IsConditional" : false,
            "Condition" : null,
            "ConditionTarget" : null
        }, {
            "Uuid" : null,
            "OrderUuid" : "8925d746-bc9f-4684-b1aa-e507467aaa99",
            "Exchange" : "BTC-LTC",
            "OrderType" : "LIMIT_BUY",
            "Quantity" : 100000.00000000,
            "QuantityRemaining" : 100000.00000000,
            "Limit" : 0.00000001,
            "CommissionPaid" : 0.00000000,
            "Price" : 0.00000000,
            "PricePerUnit" : null,
            "Opened" : "2014-07-09T03:55:48.583",
            "Closed" : null,
            "CancelInitiated" : false,
            "ImmediateOrCancel" : false,
            "IsConditional" : false,
            "Condition" : null,
            "ConditionTarget" : null
        }
    ]
}

The API produces a list with one dictionnary for every open order.

Now I want to basically make my code go through all dic. looking for the string "LIMIT_BUY".

My current code does this for up to 2 orders. But it is probably highly inefficient and also cannot cope with orders > 2:

At the end of the loop the buy_active variable should  be "1" if there is any buy order or 0 if there is no order or only selling orders.

if len(open_order) == 2:
            order_type_1 = open_order[0]['OrderType']
            order_type_2 = open_order[1]['OrderType']
            if order_type_1 == 'LIMIT_BUY' or order_type_2 == 'LIMIT_BUY':
                buy_active = 1
            else:
                buy_active = 0

        elif len(open_order) == 1:
            order_type_1 = open_order[0]['OrderType']
            if order_type_1 == 'LIMIT_BUY':
                buy_active = 1
            else:
                buy_active = 0
        else:
            buy_active = 0

What I would like is a most efficient (in terms of time) code to look through the list with any number of entries.

Can somebody help me?:)

Thanks alot! I just started coding 4 days ago, so please be nice :)

Best
SaltyJ

Body:
Welcome to the wonderful art of coding!

You've encountered your first repetitive task so it seems. This might be the time to look into for-loops or while-loops. They allow you to repeat tasks.

For example, though greatly simplified:

mylist = [1,2,3]
# Your way:
print mylist[0]
print mylist[1]
print mylist[2]
# This works, but gets tedious if your list grows.

# This is way more concise:
for i in mylist:
    print i


问:
angular includes not working after applying base tag to remove # in url
I have been working on Single Page Application in Angularjs. When index page loads I have loaded other pages into index page by using Angular ng-include.
Now it's working, But in the URL it's showing like http://localhost:8080/Index.html#/Home.html, I want to remove "#". I applied , after applying the base tag in the head tag "ng-include" not working. I tried other online stuff but I couldn't find any solution. I am using xampp server.</p>

```<code>Thanks in Advance friends
<body ng-app="mainApp" ng-controller="mainCtrl">
    <header ng-include="'navigation.html'" ng-controller="headerCtrl">

    </header>
    <div class="container">
        <h3>{{Title}}</h3>
        <div ng-include="'leftNavigation.html'" ng-controller="leftDivCtrl">

        </div>

        <div ng-include="'rightPage.html'" ng-controller="rightDivCtrl">

        </div>
        <div class="clearfix"></div>
        <ng-view></ng-view>
    </div>
</body>

var app = angular.module("mainApp", ["ngRoute"])
    // Navigating external pages
    .config(function($routeProvider, $locationProvider){
        $routeProvider

         // $routeProvider .when( '/', { redirectTo: '/home' })
        .when("/Home", {
            templateUrl: "partials/Home.html",
            controller:"homeCtrl",
        })
        .when("/Aboutus", {
            templateUrl: "partials/Aboutus.html",
            controller:"AboutusCtrl",
        })
        .when("/Courses", {
            templateUrl: "partials/Courses.html",
            controller:"CoursesCtrl",
        })
        .when("/Contactus", {
            templateUrl: "partials/Contactus.html",
            controller:"ContactusCtrl",
        })
        .otherwise({
            redirectTo:"Index.html"
        })
        //$locationProvider.hashPrefix('')
        $locationProvider.html5Mode({
            enabled:true,
            //requireBase:false
        })
    })
    .controller("homeCtrl", function($scope){
        $scope.msg = "Home Page";
    })
    .controller("AboutusCtrl", function($scope){
        $scope.msg = "Aboutus Page";
    })
    .controller("CoursesCtrl", function($scope){
        $scope.msg = "Courses Page";
    })
    .controller("ContactusCtrl", function($scope){
        $scope.msg = "Contactus Page";
    })

    app.controller("mainCtrl", ["$scope", function($scope){
        $scope.Title = "Single Page Application";
    }]);

    // loading external pages as includes, when index page loads
    app.controller("headerCtrl", ["$scope", function($scope){

    }]);
    app.controller("leftDivCtrl", ["$scope", function($scope){

    }]);
    app.controller("rightDivCtrl", ["$scope", function($scope){

    }]);
</code>```

答:
Sounds like you need to define the $locationProvider to use html5 mode.
So in your config phase just add this line:

```<code> $locationProvider.html5Mode(true);
</code>```

Body:
I have been working on Single Page Application in Angularjs. When index page loads I have loaded other pages into index page by using Angular ng-include.
Now it's working, But in the URL it's showing like http://localhost:8080/Index.html#/Home.html, I want to remove "#". I applied , after applying the base tag in the head tag "ng-include" not working. I tried other online stuff but I couldn't find any solution. I am using xampp server.

Thanks in Advance friends

{{Title}}

        <ng-view></ng-view>

var app = angular.module("mainApp", ["ngRoute"])
    // Navigating external pages
    .config(function($routeProvider, $locationProvider){
        $routeProvider

         // $routeProvider .when( '/', { redirectTo: '/home' })
        .when("/Home", {
            templateUrl: "partials/Home.html",
            controller:"homeCtrl",
        })
        .when("/Aboutus", {
            templateUrl: "partials/Aboutus.html",
            controller:"AboutusCtrl",
        })
        .when("/Courses", {
            templateUrl: "partials/Courses.html",
            controller:"CoursesCtrl",
        })
        .when("/Contactus", {
            templateUrl: "partials/Contactus.html",
            controller:"ContactusCtrl",
        })
        .otherwise({
            redirectTo:"Index.html"
        })
        //$locationProvider.hashPrefix('')
        $locationProvider.html5Mode({
            enabled:true,
            //requireBase:false
        })
    })
    .controller("homeCtrl", function($scope){
        $scope.msg = "Home Page";
    })
    .controller("AboutusCtrl", function($scope){
        $scope.msg = "Aboutus Page";
    })
    .controller("CoursesCtrl", function($scope){
        $scope.msg = "Courses Page";
    })
    .controller("ContactusCtrl", function($scope){
        $scope.msg = "Contactus Page";
    })

    app.controller("mainCtrl", ["$scope", function($scope){
        $scope.Title = "Single Page Application";
    }]);

    // loading external pages as includes, when index page loads
    app.controller("headerCtrl", ["$scope", function($scope){

    }]);
    app.controller("leftDivCtrl", ["$scope", function($scope){

    }]);
    app.controller("rightDivCtrl", ["$scope", function($scope){

    }]);

Body:
Sounds like you need to define the $locationProvider to use html5 mode.
So in your config phase just add this line:

 $locationProvider.html5Mode(true);


问:
C# MongoDB driver trouble( NORM)
I have used NORM driver in production. New year holidays - it is pretty cool, so my project get high loading and i want to set up a replication set, but have a problem - Norm does not support replication set :( . as far as i understand sharding too? </p>

<p>Help me :) Who did use mongodb csharp or official 10gen driver with replset? Is there any problem on production? If i choose another driver I'll have to rewrite the repository, but I do not want it to be in vain. Is there some issues? </p>

答:
Sharding should not depend on driver-specific support. When you shard, you connect to a router application mongos and this router behaves exactly like mongod.

So you should be able to shard. But you will probably need to change the "connection string". The suggested setup is to have one mongos per application server (instead of your current single mongod).

Title: C# MongoDB driver trouble( NORM)

Body:
I have used NORM driver in production. New year holidays - it is pretty cool, so my project get high loading and i want to set up a replication set, but have a problem - Norm does not support replication set :( . as far as i understand sharding too?

Help me :) Who did use mongodb csharp or official 10gen driver with replset? Is there any problem on production? If i choose another driver I'll have to rewrite the repository, but I do not want it to be in vain. Is there some issues?


问:
Stored procedure to select column from table and insert to multiple table in mysql
I want to select values from basic2 and insert into basic3 and basic4 using stored procedure.

These are the table definitions:

```<code>create table basic2(
    id int AUTO_INCREMENT,
    name varchar(50),
    address varchar(50),
    PRIMARY KEY (id)
);

create table basic3(
    id int AUTO_INCREMENT,
    name varchar(50),
    address varchar(50),
    PRIMARY KEY (id)
);

create table basic4(
    id int AUTO_INCREMENT,
    name varchar(50),
    address varchar(50),
    PRIMARY KEY (id)
);
</code>```

this is the new_person store procedure

```<code>drop procedure if exists new_person;
DELIMITER //
CREATE PROCEDURE new_person
    select (id, name,address)
    from basic2;
    BEGIN

        START TRANSACTION;
        INSERT INTO basic3 (id,name,address)
                VALUES(LAST_INSERT_ID(),bname,baddress);

        INSERT INTO basic4 (id,name,address)
                VALUES(LAST_INSERT_ID(),bname,baddress);

        COMMIT;
    END//

    DELIMITER;
</code>```

答:
We can do it by two way one for using cursor and another is using SELECT with insert i thing for you SELECT is better

Like this

INSERT INTO basic3 (name,address)
SELECT name, address FROM basic2;

Body:
I want to select values from basic2 and insert into basic3 and basic4 using stored procedure.

These are the table definitions:

create table basic2(
    id int AUTO_INCREMENT,
    name varchar(50),
    address varchar(50),
    PRIMARY KEY (id)
);

create table basic3(
    id int AUTO_INCREMENT,
    name varchar(50),
    address varchar(50),
    PRIMARY KEY (id)
);

create table basic4(
    id int AUTO_INCREMENT,
    name varchar(50),
    address varchar(50),
    PRIMARY KEY (id)
);

this is the new_person store procedure

drop procedure if exists new_person;
DELIMITER //
CREATE PROCEDURE new_person
    select (id, name,address)
    from basic2;
    BEGIN

        START TRANSACTION;
        INSERT INTO basic3 (id,name,address)
                VALUES(LAST_INSERT_ID(),bname,baddress);

        INSERT INTO basic4 (id,name,address)
                VALUES(LAST_INSERT_ID(),bname,baddress);

        COMMIT;
    END//

    DELIMITER;