问:
Can't update from php 5.5.12 - Ubuntu 16.04
I'm trying to update php. When I check my php version, it returns:

```<code>php -v
PHP 5.5.12 (cli) (built: Mar 10 2017 16:27:17)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies
</code>```

So I added ondrej's repository

```<code>sudo add-apt-repository ppa:ondrej/php
sudo apt-get update
sudo apt-get install php7.0
</code>```

But STILL:

```<code>php -v
PHP 5.5.12 (cli) (built: Mar 10 2017 16:27:17)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies
</code>```

I don't know what to do anymore... Already tried purge, everything... this php doesn't upgrade, it remains this version. Any ideas?

答:
If you have this problem while upgrading from PHP5 to PHP7 on Ubuntu 16.04

with Apache, here's what helped me (credit goes here):

Disable PHP5 module on Apache:

```<code>sudo a2dismod php5
</code>```

Now enable PHP7:

```<code>sudo a2enmod php7.1
</code>```

To reflect changes Apache restart is required:

```<code>sudo systemctl restart apache2
</code>```

By the way run phpinfo() in your script take a look which version is this running. Command line php is a complete separate system

Body:
I'm trying to update php. When I check my php version, it returns:

php -v
PHP 5.5.12 (cli) (built: Mar 10 2017 16:27:17)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies

So I added ondrej's repository

sudo add-apt-repository ppa:ondrej/php
sudo apt-get update
sudo apt-get install php7.0

But STILL:

php -v
PHP 5.5.12 (cli) (built: Mar 10 2017 16:27:17)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies

I don't know what to do anymore... Already tried purge, everything... this php doesn't upgrade, it remains this version. Any ideas?

Body:
If you have this problem while upgrading from PHP5 to PHP7 on Ubuntu 16.04

with Apache, here's what helped me (credit goes here):

Disable PHP5 module on Apache:

sudo a2dismod php5

Now enable PHP7:

sudo a2enmod php7.1

To reflect changes Apache restart is required:

sudo systemctl restart apache2

By the way run phpinfo() in your script take a look which version is this running. Command line php is a complete separate system


来源: stackexchange

答:
Try to run First :

```<code>sudo apt-get upgrade
</code>```

And then : For PHP 5.5, PHP 5.6 and PHP 7.0:

```<code>sudo apt-add-repository ppa:ondrej/php
</code>```

You have flipped "apt" and "add". Please take a look at your command.

Then the other steps that you made.

ContentLicense: CC BY-SA 3.0

Title: Can't update from php 5.5.12 - Ubuntu 16.04

Body:
Try to run First :

sudo apt-get upgrade

And then : For PHP 5.5, PHP 5.6 and PHP 7.0:

sudo apt-add-repository ppa:ondrej/php

You have flipped "apt" and "add". Please take a look at your command.

Then the other steps that you made.


问:
Conditional where statement in T-SQL
I've got a table that returns the history of a value, as well as the current one, each with a date.

The oldest date is the main record.  If the value is changed, a new record is created, with the old value, and the main record is updated with the new value.  If this happens again, a third record is created, which contains the now old value.

So if the value starts at 4, changes to 2, then again changes to 1.  The records will go

```<code>1
4
2
</code>```

I'm currently creating an inner join on the table to itself as follows, which gets the max date of the 3 above records, which would be 2.. The actual value I need is the 4.  The easiest way to tell if a record is a historical one is that the TriageEndDateTime is NULL.

```<code>INNER JOIN (SELECT EmergencyAttendanceId,MIN(SourceCreateDateTime) as Max_Date
                FROM FactEmergencyAttendanceTriageDetail
                GROUP BY EmergencyAttendanceId) AS EAiD
                ON EAiD.EmergencyAttendanceId = FactEmergencyAttendanceTriageDetail.EmergencyAttendanceId
                AND EAiD.Max_Date = FactEmergencyAttendanceTriageDetail.SourceCreateDateTime
</code>```

What I need to do is select the second record, but only if it exists.  So something along the lines of this.

```<code> SELECT EmergencyAttendanceId,MIN(SourceCreateDateTime) as Max_Date
    FROM FactEmergencyAttendanceTriageDetail
    WHERE IF COUNT(EmergencyAttendanceId) > 1 THEN TriageEndDateTime Is NULL ELSE NOT NULL
    GROUP BY EmergencyAttendanceId
    inside the INNER JOIN.
</code>```

Can anyone help me with this?

Sample data

In the above case, record 2 is the one I'm after.

答:
Try this:</p>

```<code>    SELECT EmergencyAttendanceId

    case when count(EmergencyAttendanceId) > 1 then
          MIN
          (
          case when TriageDateTime is null then SourceCreateDateTime end
          )
    else
          min(SourceCreateDateTime)
    end as max_date

    FROM FactEmergencyAttendanceTriageDetail
    GROUP BY EmergencyAttendanceId
</code>```

Title: Conditional where statement in T-SQL

Body:
I've got a table that returns the history of a value, as well as the current one, each with a date.

The oldest date is the main record.  If the value is changed, a new record is created, with the old value, and the main record is updated with the new value.  If this happens again, a third record is created, which contains the now old value.

So if the value starts at 4, changes to 2, then again changes to 1.  The records will go

1
4
2

I'm currently creating an inner join on the table to itself as follows, which gets the max date of the 3 above records, which would be 2.. The actual value I need is the 4.  The easiest way to tell if a record is a historical one is that the TriageEndDateTime is NULL.

INNER JOIN (SELECT EmergencyAttendanceId,MIN(SourceCreateDateTime) as Max_Date
                FROM FactEmergencyAttendanceTriageDetail
                GROUP BY EmergencyAttendanceId) AS EAiD
                ON EAiD.EmergencyAttendanceId = FactEmergencyAttendanceTriageDetail.EmergencyAttendanceId
                AND EAiD.Max_Date = FactEmergencyAttendanceTriageDetail.SourceCreateDateTime

What I need to do is select the second record, but only if it exists.  So something along the lines of this.

 SELECT EmergencyAttendanceId,MIN(SourceCreateDateTime) as Max_Date
    FROM FactEmergencyAttendanceTriageDetail
    WHERE IF COUNT(EmergencyAttendanceId) > 1 THEN TriageEndDateTime Is NULL ELSE NOT NULL
    GROUP BY EmergencyAttendanceId
    inside the INNER JOIN.

Can anyone help me with this?

Sample data

In the above case, record 2 is the one I'm after.

Body:
Try this:

    SELECT EmergencyAttendanceId

    case when count(EmergencyAttendanceId) > 1 then
          MIN
          (
          case when TriageDateTime is null then SourceCreateDateTime end
          )
    else
          min(SourceCreateDateTime)
    end as max_date

    FROM FactEmergencyAttendanceTriageDetail
    GROUP BY EmergencyAttendanceId

ContentLicense: CC BY-SA 2.5


问:
add_row and do some calculations
Say I have a data.frame that looks like the below:

```<code>df <- data.frame(group = c("group1","group1", "group2", "group2"),
                 year = c(2000, 2001, 2000, 2001),
                 value = c(10, 13, 2, 5))
</code>```

And I want to group by each group, then add a row, then do a calculation on column 3. So for example, the new data frame would look like this (the calculation was simply value(-1)+value(-2))

```<code>df <- data.frame(group = c("group1","group1", "group1", "group2", "group2", "group2"),
                 year = c(2000, 2001, 2002, 2000, 2001, 2002),
                 value = c(10, 13, 23, 2, 5, 7))
</code>```

I've tried using dplyr, but I cant seem to figure it out. So I am open to any solution, although if there is a dplyr one that would be great!

Further, I want to be able to do this ten periods into the future so year would be the sequence from 2000 to 2011 in the final data.frame.

答:
This is the sort of Fibonacci-like calculation that is really simple to write with a for loop, and not so much with vectorized operations. for loops should be used with caution in R, as using them incorrectly can render your code shockingly slow, but if you preallocate memory by expanding your data.frame with tidyr::complete beforehand, you can code a function to contain the loop easily enough:

library(tidyverse)

df <- data.frame(group = c("group1","group1", "group2", "group2"),
                 year = c(2000, 2001, 2000, 2001),
                 value = c(10, 13, 2, 5))

fibonacci <- function(x){
    for(i in seq(3, length(x))){
        x[i] <- x[i-1] + x[i-2]
    }
    x
}

df2 <- df %>%
    group_by(group) %>%
    complete(year = 2000:2005) %>%
    mutate(value = fibonacci(value))

df2
#> # A tibble: 12 x 3
#> # Groups:   group [2]
#>     group  year value
#>    <fctr> <dbl> <dbl>
#>  1 group1  2000    10
#>  2 group1  2001    13
#>  3 group1  2002    23
#>  4 group1  2003    36
#>  5 group1  2004    59
#>  6 group1  2005    95
#>  7 group2  2000     2
#>  8 group2  2001     5
#>  9 group2  2002     7
#> 10 group2  2003    12
#> 11 group2  2004    19
#> 12 group2  2005    31
```

<p>If you want to avoid the loop and vectorize, use a formulaic expressions of the Fibonacci sequence. From Wikipedia,</p>

<pre class="lang-r prettyprint-override"><code>fibonacci2 <- function(u0, u1, n){
    phi <- (1 + sqrt(5)) / 2
    psi <- 1 - phi
    a <- (u1 - u0 * psi) / sqrt(5)
    b <- (u0 * phi - u1) / sqrt(5)
    a * phi^n + b * psi^n
}

df3 <- df %>%
    group_by(group) %>%
    complete(year = 2000:2005) %>%
    mutate(value = fibonacci2(value[1], value[2], seq.int(0L, length(value) - 1)))

df3
#> # A tibble: 12 x 3
#> # Groups:   group [2]
#>     group  year value
#>    <fctr> <dbl> <dbl>
#>  1 group1  2000    10
#>  2 group1  2001    13
#>  3 group1  2002    23
#>  4 group1  2003    36
#>  5 group1  2004    59
#>  6 group1  2005    95
#>  7 group2  2000     2
#>  8 group2  2001     5
#>  9 group2  2002     7
#> 10 group2  2003    12
#> 11 group2  2004    19
#> 12 group2  2005    31
</code>```

Somewhat curiously (likely due to proper preallocation and R's addition of JIT compilation for loops), there's little time differential between the two. Benchmarking is tricky, as the series tends exceed .Machine$double.xmax and turn to Inf at about the 1475th term, but replicated on new inputs to 1,475,000 calculations with each method,

microbenchmark::microbenchmark(
    fibonacci = replicate(1000, {
        x <- double(1475);
        x[1:2] <- rnorm(2);
        fibonacci(x)
    }),
    fibonacci2 = replicate(1000, {
        x <- double(1475);
        x[1:2] <- rnorm(2);
        fibonacci2(x[1], x[2], seq.int(0L, length(x) - 1L))
    })
)
#> Unit: milliseconds
#>        expr      min       lq     mean   median       uq      max neval
#>   fibonacci 249.4110 255.9866 264.2625 261.6491 272.0018 295.3266   100
#>  fibonacci2 202.3588 209.0647 219.0509 214.2429 223.5476 375.7604   100
```

Title: add_row and do some calculations

Body:
Say I have a data.frame that looks like the below:

df <- data.frame(group = c("group1","group1", "group2", "group2"),
                 year = c(2000, 2001, 2000, 2001),
                 value = c(10, 13, 2, 5))

And I want to group by each group, then add a row, then do a calculation on column 3. So for example, the new data frame would look like this (the calculation was simply value(-1)+value(-2))

df <- data.frame(group = c("group1","group1", "group1", "group2", "group2", "group2"),
                 year = c(2000, 2001, 2002, 2000, 2001, 2002),
                 value = c(10, 13, 23, 2, 5, 7))

I've tried using dplyr, but I cant seem to figure it out. So I am open to any solution, although if there is a dplyr one that would be great!

Further, I want to be able to do this ten periods into the future so year would be the sequence from 2000 to 2011 in the final data.frame.

Body:
This is the sort of Fibonacci-like calculation that is really simple to write with a for loop, and not so much with vectorized operations. for loops should be used with caution in R, as using them incorrectly can render your code shockingly slow, but if you preallocate memory by expanding your data.frame with tidyr::complete beforehand, you can code a function to contain the loop easily enough:

library(tidyverse)

df <- data.frame(group = c("group1","group1", "group2", "group2"),
                 year = c(2000, 2001, 2000, 2001),
                 value = c(10, 13, 2, 5))

fibonacci <- function(x){
    for(i in seq(3, length(x))){
        x[i] <- x[i-1] + x[i-2]
    }
    x
}

df2 <- df %>%
    group_by(group) %>%
    complete(year = 2000:2005) %>%
    mutate(value = fibonacci(value))

df2
#> # A tibble: 12 x 3
#> # Groups:   group [2]
#>     group  year value
#>    <fctr> <dbl> <dbl>
#>  1 group1  2000    10
#>  2 group1  2001    13
#>  3 group1  2002    23
#>  4 group1  2003    36
#>  5 group1  2004    59
#>  6 group1  2005    95
#>  7 group2  2000     2
#>  8 group2  2001     5
#>  9 group2  2002     7
#> 10 group2  2003    12
#> 11 group2  2004    19
#> 12 group2  2005    31

If you want to avoid the loop and vectorize, use a formulaic expressions of the Fibonacci sequence. From Wikipedia,

fibonacci2 <- function(u0, u1, n){
    phi <- (1 + sqrt(5)) / 2
    psi <- 1 - phi
    a <- (u1 - u0 * psi) / sqrt(5)
    b <- (u0 * phi - u1) / sqrt(5)
    a * phi^n + b * psi^n
}

df3 <- df %>%
    group_by(group) %>%
    complete(year = 2000:2005) %>%
    mutate(value = fibonacci2(value[1], value[2], seq.int(0L, length(value) - 1)))

df3
#> # A tibble: 12 x 3
#> # Groups:   group [2]
#>     group  year value
#>    <fctr> <dbl> <dbl>
#>  1 group1  2000    10
#>  2 group1  2001    13
#>  3 group1  2002    23
#>  4 group1  2003    36
#>  5 group1  2004    59
#>  6 group1  2005    95
#>  7 group2  2000     2
#>  8 group2  2001     5
#>  9 group2  2002     7
#> 10 group2  2003    12
#> 11 group2  2004    19
#> 12 group2  2005    31

Somewhat curiously (likely due to proper preallocation and R's addition of JIT compilation for loops), there's little time differential between the two. Benchmarking is tricky, as the series tends exceed .Machine$double.xmax and turn to Inf at about the 1475th term, but replicated on new inputs to 1,475,000 calculations with each method,

microbenchmark::microbenchmark(
    fibonacci = replicate(1000, {
        x <- double(1475);
        x[1:2] <- rnorm(2);
        fibonacci(x)
    }),
    fibonacci2 = replicate(1000, {
        x <- double(1475);
        x[1:2] <- rnorm(2);
        fibonacci2(x[1], x[2], seq.int(0L, length(x) - 1L))
    })
)
#> Unit: milliseconds
#>        expr      min       lq     mean   median       uq      max neval
#>   fibonacci 249.4110 255.9866 264.2625 261.6491 272.0018 295.3266   100
#>  fibonacci2 202.3588 209.0647 219.0509 214.2429 223.5476 375.7604   100


问:
Stop setInterval() without global variables
I am looking to start then later stop a setInterval, all examples that I've come across do this with a global variable, but I'd rather not use one if I can.

I have a button to start the setInterval and another to stop it. I can start it just fine, but I am unable to stop it without using a global variable.

This is what I have:

```<code>function counter() {
  function stop() {
    clearInterval(timer);
  }
  var timer = setInterval(function() {
    console.log(new Date());
  }, 1000);
  return stop;
}
$('#start').click(function() {
  counter();
});
$('#stop').click(function() {
  stop(); // this of course doesn't work
});
</code>```

答:
You will need a global variable, but you can do it in many ways so here an approach, the HTML part:

```<code><button id="start">Start</button>
<button id="stop">Stop</button>
</code>```

and the JS part:

```<code>function timer() {
    var timer = null;
    function stop() {
    clearTimeout(timer);
  }

  function start() {
    timer  = setInterval(function(){
      console.log("repeat it");
    }, 500);
  }

  return {
      stop,
    start
  };
}

var t = timer();

var startBtn = document.getElementById("start");
var stopBtn = document.getElementById("stop");

startBtn.addEventListener("click", function(){
    t.start();
}, false);

stopBtn.addEventListener("click", function(){
    t.stop();
}, false);
</code>```

Here you have a demo

Body:
I am looking to start then later stop a setInterval, all examples that I've come across do this with a global variable, but I'd rather not use one if I can.

I have a button to start the setInterval and another to stop it. I can start it just fine, but I am unable to stop it without using a global variable.

This is what I have:

function counter() {
  function stop() {
    clearInterval(timer);
  }
  var timer = setInterval(function() {
    console.log(new Date());
  }, 1000);
  return stop;
}
$('#start').click(function() {
  counter();
});
$('#stop').click(function() {
  stop(); // this of course doesn't work
});

Body:
You will need a global variable, but you can do it in many ways so here an approach, the HTML part:

<button id="start">Start</button>
<button id="stop">Stop</button>

and the JS part:

function timer() {
    var timer = null;
    function stop() {
    clearTimeout(timer);
  }

  function start() {
    timer  = setInterval(function(){
      console.log("repeat it");
    }, 500);
  }

  return {
      stop,
    start
  };
}

var t = timer();

var startBtn = document.getElementById("start");
var stopBtn = document.getElementById("stop");

startBtn.addEventListener("click", function(){
    t.start();
}, false);

stopBtn.addEventListener("click", function(){
    t.stop();
}, false);

Here you have a demo


问:
Can I implement phone specific sizing with XAML in Xamarin Forms?
I have this XAML

```<code><Grid x:Name="scoreFaveGrid" Grid.Row="0" Grid.Column="0" Padding="5,0,0,0"
                HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
</code>```

I understand that with C# I can make the padding sizes etc change depending on if I am using iOS or Android.

Can I do the same with XAML and if so how is that done?

答:
Yes, you can use the <OnPlatform> tag in XAML. Here's how it would work for Padding in your sample above.

```<code><Grid x:Name="scoreFaveGrid" Grid.Row="0" Grid.Column="0" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
    <Grid.Padding>
        <OnPlaform x:TypeArguments="x:Thickness">
            <On Platform="iOS" Value="15,0,15,0" />
            <On Platform="Android" Value="5,0,5,0"/>
        </OnPlaform>
    </Grid.Padding>
</Grid>
</code>```

Body:
I have this XAML

<Grid x:Name="scoreFaveGrid" Grid.Row="0" Grid.Column="0" Padding="5,0,0,0"
                HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">

I understand that with C# I can make the padding sizes etc change depending on if I am using iOS or Android.

Can I do the same with XAML and if so how is that done?

Body:
Yes, you can use the <OnPlatform> tag in XAML. Here's how it would work for Padding in your sample above.

<Grid x:Name="scoreFaveGrid" Grid.Row="0" Grid.Column="0" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
    <Grid.Padding>
        <OnPlaform x:TypeArguments="x:Thickness">
            <On Platform="iOS" Value="15,0,15,0" />
            <On Platform="Android" Value="5,0,5,0"/>
        </OnPlaform>
    </Grid.Padding>
</Grid>


问:
How to select multiple values in a bidirectional many to many relationship based on input array
How to make the select statement below handle multiple inputs (a list) at once and still return a similar resulting list as to that of a single input

It's been hours, and I'm stuck - I need help writing a mysql statement to retrieve a list of ids from a table where a "link" is found.

The idea behind this question is to feed the query an array of id values, and have it return all other id's that are linked, from both sides of the table, to each of the id's passed in from the array into a single comma delineated list.

table structure "team_permissions"

```<code>first_teamID  |  second_teamID
  113         |     112
  114         |     112
  118         |     117
  119         |     112
  119         |     113
  119         |     114
</code>```

Working "get permissions per single team" sql statement -- need to feed a list into this

```<code>SELECT first_teamID AS team_permissions
FROM team_permissions
WHERE second_teamID = ?

UNION ALL

SELECT second_teamID AS team_permissions
FROM team_permissions
WHERE first_teamID = ?
</code>```

Expected Single Input -> Output Examples - this works

(? = 112) will yield the result: [113,
114, 119]

(? = 113) will yield the
result: [112, 119]

(? = 117) will
yield the result: [118]

(? = 119) will
yield the result: [112, 113, 114]

Expected Multiple Input -> Output Examples

(? = [112, 113] ) will yield the result: [112, 113,
114, 119]

(? = [113, 119] ) will yield the result: [112, 113, 114, 119]

(? = [112, 114, 118] ) will yield the result: [112, 113, 114, 117, 119]

team_permissions table structure

答:
Just use WHERE IN, e.g.:

```<code>SELECT first_teamID AS team_permissions
FROM team_permissions
WHERE second_teamID IN (113, 119)
UNION ALL
SELECT second_teamID AS team_permissions
FROM team_permissions
WHERE first_teamID IN (113, 119)
</code>```

Body:
How to make the select statement below handle multiple inputs (a list) at once and still return a similar resulting list as to that of a single input

It's been hours, and I'm stuck - I need help writing a mysql statement to retrieve a list of ids from a table where a "link" is found.

The idea behind this question is to feed the query an array of id values, and have it return all other id's that are linked, from both sides of the table, to each of the id's passed in from the array into a single comma delineated list.

table structure "team_permissions"

first_teamID  |  second_teamID
  113         |     112
  114         |     112
  118         |     117
  119         |     112
  119         |     113
  119         |     114

Working "get permissions per single team" sql statement -- need to feed a list into this

SELECT first_teamID AS team_permissions
FROM team_permissions
WHERE second_teamID = ?

UNION ALL

SELECT second_teamID AS team_permissions
FROM team_permissions
WHERE first_teamID = ?

Expected Single Input -> Output Examples - this works

(? = 112) will yield the result: [113,
114, 119]

(? = 113) will yield the
result: [112, 119]

(? = 117) will
yield the result: [118]

(? = 119) will
yield the result: [112, 113, 114]

Expected Multiple Input -> Output Examples

(? = [112, 113] ) will yield the result: [112, 113,
114, 119]

(? = [113, 119] ) will yield the result: [112, 113, 114, 119]

(? = [112, 114, 118] ) will yield the result: [112, 113, 114, 117, 119]

team_permissions table structure

Body:
Just use WHERE IN, e.g.:

SELECT first_teamID AS team_permissions
FROM team_permissions
WHERE second_teamID IN (113, 119)
UNION ALL
SELECT second_teamID AS team_permissions
FROM team_permissions
WHERE first_teamID IN (113, 119)


问:
Git svn work flow, making branchs in git-svn
```<code>git version 1.7.3.3
</code>```

I had a project that was using git.

Our company changed its policy and wanted everyone to switch to svn.

So I imported my project in subversion using the standard layout (trunk, branchs, and tags).

So my current workflow is the following:

Make some changes, put them in the staging area, then commit them to git. However, I get a little confused when it comes to svn. First I rebase to get the latest changes from subversion. Then I do a dcommit.

i.e.

Stage the change files

```<code>git stage app_driver.c
</code>```

Commit them to git

```<code>git commit -m"Added some changes"
</code>```

Get the latest changes from svn

```<code>git svn rebase
</code>```

commit the my latest changes to svn

```<code>git svn dcommit
</code>```

push the changes to my git repository

```<code>git push upstream my_project
</code>```

However, the real confusion comes when I make a new branch in git, and how I can commit to that branch in subversion.

```<code>git checkout -b add_new_feature
</code>```

Then how do I make the new branch in svn and commit it?

Many thanks for any suggestions,

答:
I'd make the branch in subversion first in this case, since it sounds like you want to have a long-term development branch which is merged in later with the contents of /trunk.

When I want to do a short term fix to whatever is in /trunk I do what you want to do:

```<code>git checkout -b add_quick_change
</code>```

and change away.

Then when I want to put it in /trunk:

```<code>git checkout master
git pull --no-squash . add_quick_change
git svn dcommit
</code>```

This should copy all the history into master so it ends up in subversion after the dcommit.

Body:
git version 1.7.3.3

I had a project that was using git.

Our company changed its policy and wanted everyone to switch to svn.

So I imported my project in subversion using the standard layout (trunk, branchs, and tags).

So my current workflow is the following:

Make some changes, put them in the staging area, then commit them to git. However, I get a little confused when it comes to svn. First I rebase to get the latest changes from subversion. Then I do a dcommit.

i.e.

Stage the change files

git stage app_driver.c

Commit them to git

git commit -m"Added some changes"

Get the latest changes from svn

git svn rebase

commit the my latest changes to svn

git svn dcommit

push the changes to my git repository

git push upstream my_project

However, the real confusion comes when I make a new branch in git, and how I can commit to that branch in subversion.

git checkout -b add_new_feature

Then how do I make the new branch in svn and commit it?

Many thanks for any suggestions,

Body:
I'd make the branch in subversion first in this case, since it sounds like you want to have a long-term development branch which is merged in later with the contents of /trunk.

When I want to do a short term fix to whatever is in /trunk I do what you want to do:

git checkout -b add_quick_change

and change away.

Then when I want to put it in /trunk:

git checkout master
git pull --no-squash . add_quick_change
git svn dcommit

This should copy all the history into master so it ends up in subversion after the dcommit.


问:
How to print in a QDialog the output of a function? With pyqt
I have a problem displaying the output of a function in a qdialog of pyqt.

My code is as follows:

```<code>import sys
import os
import glob
import shutil
import json
import datetime
import time
import requests
from multiprocessing import Queue

start_time = time.time()

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QDialog, QPushButton, QLabel, QScrollArea, QProgressBar, QTextEdit

noreports = len(glob.glob('*.txt'))

class Dialogo(QDialog):
    def __init__(self):
        QDialog.__init__(self)
        self.resize(400, 380)
        self.nombre = QLabel(self)
        self.nombre.setGeometry(QtCore.QRect(30, 20, 171, 17))
        self.nombre.setObjectName("nombre")
        self.label = QLabel(self)
        self.label.setGeometry(QtCore.QRect(30, 50, 121, 17))
        self.label.setObjectName("label")
        self.pushButton = QPushButton(self)
        self.pushButton.setGeometry(QtCore.QRect(260, 310, 86, 28))
        self.pushButton.setObjectName("pushButton")
        self.scrollArea = QScrollArea(self)
        self.scrollArea.setGeometry(QtCore.QRect(30, 120, 341, 171))
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setObjectName("scrollArea")
        self.scrollAreaWidgetContents = QtWidgets.QWidget()
        self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 337, 167))
        self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
        self.scrollArea.setWidget(self.scrollAreaWidgetContents)
        self.progressBar = QProgressBar(self)
        self.progressBar.setGeometry(QtCore.QRect(30, 80, 341, 23))
        self.progressBar.setProperty("value", 0)
        self.progressBar.setObjectName("progressBar")
        self.textEdit = QTextEdit(self)
        self.scrollArea.setWidget(self.textEdit)

        self.retranslateUi(self)
        QtCore.QMetaObject.connectSlotsByName(self)

    def retranslateUi(self, Dialogo):
        global noreports
        _translate = QtCore.QCoreApplication.translate
        self.setWindowTitle(_translate("Dialog", "Process..."))
        self.label.setText(_translate("Dialog", "Files:" + str(noreports)))
        self.pushButton.setText(_translate("Dialog", "Terminate"))

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(321, 247)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("../../../../api-server/favicon.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        Form.setWindowIcon(icon)
        Form.setWindowOpacity(0.98)
        Form.setProperty("sunrise", QtGui.QPixmap("../../../../api-server/ejemplo.png"))
        self.lineEdit = QtWidgets.QLineEdit(Form)
        self.lineEdit.setGeometry(QtCore.QRect(20, 130, 281, 51))
        self.lineEdit.setAutoFillBackground(True)
        self.lineEdit.setObjectName("lineEdit")
        self.DescriptLbl = QtWidgets.QLabel(Form)
        self.DescriptLbl.setGeometry(QtCore.QRect(20, 100, 281, 20))
        self.DescriptLbl.setObjectName("DescriptLbl")
        self.showinformBtn = QtWidgets.QPushButton(Form)
        self.showinformBtn.setGeometry(QtCore.QRect(30, 190, 161, 31))
        self.showinformBtn.setStyleSheet("background:rgb(110, 175, 255);\n"
"color:rgb(36, 36, 36);\n"
"border-radius:3px;\n"
"border-color:black;")
        self.showinformBtn.setObjectName("showinformBtn")
        self.dialogo = Dialogo()
        self.showinformBtn.clicked.connect(self.abrirDialogo)
        #self.showinformBtn.clicked.connect(self.showinform)
        self.CancelarBtn = QtWidgets.QPushButton(Form)
        self.CancelarBtn.setGeometry(QtCore.QRect(220, 190, 75, 31))
        self.CancelarBtn.setStyleSheet("background:rgb(226, 76, 31);\n"
"color:rgb(36, 36, 36);\n"
"border-radius:3px;\n"
"border-color:black;")
        self.CancelarBtn.setObjectName("CancelarBtn")
        self.label_2 = QtWidgets.QLabel(Form)
        self.label_2.setGeometry(QtCore.QRect(20, 220, 311, 20))
        self.label_2.setTextFormat(QtCore.Qt.RichText)
        self.label_2.setScaledContents(True)
        self.label_2.setOpenExternalLinks(True)
        self.label_2.setTextInteractionFlags(QtCore.Qt.LinksAccessibleByKeyboard|QtCore.Qt.LinksAccessibleByMouse|QtCore.Qt.TextBrowserInteraction|QtCore.Qt.TextEditable|QtCore.Qt.TextEditorInteraction|QtCore.Qt.TextSelectableByKeyboard|QtCore.Qt.TextSelectableByMouse)
        self.label_2.setObjectName("label_2")
        self.showinformLbl = QtWidgets.QLabel(Form)
        self.showinformLbl.setGeometry(QtCore.QRect(20, 30, 281, 41))
        font = QtGui.QFont()
        font.setPointSize(22)
        self.showinformLbl.setFont(font)
        self.showinformLbl.setObjectName("showinformLbl")
        self.imagen = QtWidgets.QLabel(Form)
        self.imagen.setGeometry(QtCore.QRect(-80, 0, 221, 231))
        self.imagen.setText("")
        self.imagen.setPixmap(QtGui.QPixmap("max.png"))
        self.imagen.setScaledContents(False)
        self.imagen.setIndent(-1)
        self.imagen.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
        self.imagen.setObjectName("imagen")
        self.imagen.raise_()
        self.lineEdit.raise_()
        self.DescriptLbl.raise_()
        self.showinformBtn.raise_()
        self.CancelarBtn.raise_()
        self.label_2.raise_()
        self.showinformLbl.raise_()

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "api-server"))
        self.lineEdit.setToolTip(_translate("Form", "<html><head/><body><p>write.</p></body></html>"))
        self.lineEdit.setWhatsThis(_translate("Form", "<html><head/><body><p>write.</p></body></html>"))
        self.DescriptLbl.setText(_translate("Form", "descrip inform."))
        self.showinformBtn.setToolTip(_translate("Form", "<html><head/><body><p>Create report.</p></body></html>"))
        self.showinformBtn.setText(_translate("Form", "show inform"))
        self.CancelarBtn.setToolTip(_translate("Form", "<html><head/><body><p>Cancel.</p></body></html>"))
        self.CancelarBtn.setText(_translate("Form", "Cancel"))
        self.label_2.setText(_translate("Form", "<html><head/><body><p>Visit api-server.  ;)</p></body></html>"))
        self.showinformLbl.setText(_translate("Form", "show inform."))

    def abrirDialogo(self):
        nombreinform = self.lineEdit.text()
        self.dialogo.nombre.setText('inform:' + nombreinform)
        self.dialogo.show()
        self.showinform()

    def showinform(self):
        current_time = datetime.datetime.today().strftime("%Y-%b-%dT%H_%M")

        alle = glob.glob('*.txt')
        counterfile = noreports
        porcentotal = 0
        suma = 100/counterfile
        counterbien = 0
        for file in alle:
            porcentotal += float(suma)
            avance = round(float(porcentotal), 0)
            self.dialogo.progressBar.setProperty("value", format(avance))
            self.dialogo.textEdit.setText(file + format(avance))
            print ('{!r} %'.format(avance))
            dict = '{!r} %'.format(avance)
            f = open(file,'w')
            f.write('result = ' + repr(dict) + '\n')

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())
</code>```

The code is executed but not displayed in Dialog, only the labels but not the progress bar.

Why does this happen?

答:
The problem is that you are using the format function badly, this is used when you have a string and you want to insert data with a certain format.

The setProperty function requires as first parameter the property you want to assign, and a second value of the type that requires the property, in your case value requires an integer value so you can pass the percentage directly without needing to change it to string.

If you read many files this can block the main thread where the GUI is drawn, to solve this you must use QApplication.processEvents()

```<code>def showinform(self):
    current_time = datetime.datetime.today().strftime("%Y-%b-%dT%H_%M")

    alle = glob.glob('*.txt')
    counterfile = noreports
    porcentotal = 0
    suma = 100/counterfile
    counterbien = 0
    for file in alle:
        porcentotal += float(suma)
        avance = round(float(porcentotal), 0)
        self.dialogo.progressBar.setProperty("value", avance)
        self.dialogo.textEdit.append("{}{}".format(file, avance))
        print ('{!r} %'.format(avance))
        dict = '{!r} %'.format(avance)
        QApplication.processEvents()
        f = open(file,'w')
        f.write('result = ' + repr(dict) + '\n')
</code>```

Note: I have changed the setText function to append in QTextEdit so that it is added and not overwritten.

Instead of using setProperty you could use the setValue function of QProgressBar:

```<code>self.dialogo.progressBar.setValue(avance)
</code>```

Another recommendation is to verify that the counterfile is non-zero since it could generate an exception for the division.

Body:
I have a problem displaying the output of a function in a qdialog of pyqt.

My code is as follows:

import sys
import os
import glob
import shutil
import json
import datetime
import time
import requests
from multiprocessing import Queue

start_time = time.time()

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QDialog, QPushButton, QLabel, QScrollArea, QProgressBar, QTextEdit

noreports = len(glob.glob('*.txt'))

class Dialogo(QDialog):
    def __init__(self):
        QDialog.__init__(self)
        self.resize(400, 380)
        self.nombre = QLabel(self)
        self.nombre.setGeometry(QtCore.QRect(30, 20, 171, 17))
        self.nombre.setObjectName("nombre")
        self.label = QLabel(self)
        self.label.setGeometry(QtCore.QRect(30, 50, 121, 17))
        self.label.setObjectName("label")
        self.pushButton = QPushButton(self)
        self.pushButton.setGeometry(QtCore.QRect(260, 310, 86, 28))
        self.pushButton.setObjectName("pushButton")
        self.scrollArea = QScrollArea(self)
        self.scrollArea.setGeometry(QtCore.QRect(30, 120, 341, 171))
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setObjectName("scrollArea")
        self.scrollAreaWidgetContents = QtWidgets.QWidget()
        self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 337, 167))
        self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
        self.scrollArea.setWidget(self.scrollAreaWidgetContents)
        self.progressBar = QProgressBar(self)
        self.progressBar.setGeometry(QtCore.QRect(30, 80, 341, 23))
        self.progressBar.setProperty("value", 0)
        self.progressBar.setObjectName("progressBar")
        self.textEdit = QTextEdit(self)
        self.scrollArea.setWidget(self.textEdit)

        self.retranslateUi(self)
        QtCore.QMetaObject.connectSlotsByName(self)

    def retranslateUi(self, Dialogo):
        global noreports
        _translate = QtCore.QCoreApplication.translate
        self.setWindowTitle(_translate("Dialog", "Process..."))
        self.label.setText(_translate("Dialog", "Files:" + str(noreports)))
        self.pushButton.setText(_translate("Dialog", "Terminate"))

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(321, 247)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("../../../../api-server/favicon.ico"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        Form.setWindowIcon(icon)
        Form.setWindowOpacity(0.98)
        Form.setProperty("sunrise", QtGui.QPixmap("../../../../api-server/ejemplo.png"))
        self.lineEdit = QtWidgets.QLineEdit(Form)
        self.lineEdit.setGeometry(QtCore.QRect(20, 130, 281, 51))
        self.lineEdit.setAutoFillBackground(True)
        self.lineEdit.setObjectName("lineEdit")
        self.DescriptLbl = QtWidgets.QLabel(Form)
        self.DescriptLbl.setGeometry(QtCore.QRect(20, 100, 281, 20))
        self.DescriptLbl.setObjectName("DescriptLbl")
        self.showinformBtn = QtWidgets.QPushButton(Form)
        self.showinformBtn.setGeometry(QtCore.QRect(30, 190, 161, 31))
        self.showinformBtn.setStyleSheet("background:rgb(110, 175, 255);\n"
"color:rgb(36, 36, 36);\n"
"border-radius:3px;\n"
"border-color:black;")
        self.showinformBtn.setObjectName("showinformBtn")
        self.dialogo = Dialogo()
        self.showinformBtn.clicked.connect(self.abrirDialogo)
        #self.showinformBtn.clicked.connect(self.showinform)
        self.CancelarBtn = QtWidgets.QPushButton(Form)
        self.CancelarBtn.setGeometry(QtCore.QRect(220, 190, 75, 31))
        self.CancelarBtn.setStyleSheet("background:rgb(226, 76, 31);\n"
"color:rgb(36, 36, 36);\n"
"border-radius:3px;\n"
"border-color:black;")
        self.CancelarBtn.setObjectName("CancelarBtn")
        self.label_2 = QtWidgets.QLabel(Form)
        self.label_2.setGeometry(QtCore.QRect(20, 220, 311, 20))
        self.label_2.setTextFormat(QtCore.Qt.RichText)
        self.label_2.setScaledContents(True)
        self.label_2.setOpenExternalLinks(True)
        self.label_2.setTextInteractionFlags(QtCore.Qt.LinksAccessibleByKeyboard|QtCore.Qt.LinksAccessibleByMouse|QtCore.Qt.TextBrowserInteraction|QtCore.Qt.TextEditable|QtCore.Qt.TextEditorInteraction|QtCore.Qt.TextSelectableByKeyboard|QtCore.Qt.TextSelectableByMouse)
        self.label_2.setObjectName("label_2")
        self.showinformLbl = QtWidgets.QLabel(Form)
        self.showinformLbl.setGeometry(QtCore.QRect(20, 30, 281, 41))
        font = QtGui.QFont()
        font.setPointSize(22)
        self.showinformLbl.setFont(font)
        self.showinformLbl.setObjectName("showinformLbl")
        self.imagen = QtWidgets.QLabel(Form)
        self.imagen.setGeometry(QtCore.QRect(-80, 0, 221, 231))
        self.imagen.setText("")
        self.imagen.setPixmap(QtGui.QPixmap("max.png"))
        self.imagen.setScaledContents(False)
        self.imagen.setIndent(-1)
        self.imagen.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
        self.imagen.setObjectName("imagen")
        self.imagen.raise_()
        self.lineEdit.raise_()
        self.DescriptLbl.raise_()
        self.showinformBtn.raise_()
        self.CancelarBtn.raise_()
        self.label_2.raise_()
        self.showinformLbl.raise_()

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "api-server"))
        self.lineEdit.setToolTip(_translate("Form", "
write.
"))
        self.lineEdit.setWhatsThis(_translate("Form", "
write.
"))
        self.DescriptLbl.setText(_translate("Form", "descrip inform."))
        self.showinformBtn.setToolTip(_translate("Form", "
Create report.
"))
        self.showinformBtn.setText(_translate("Form", "show inform"))
        self.CancelarBtn.setToolTip(_translate("Form", "
Cancel.
"))
        self.CancelarBtn.setText(_translate("Form", "Cancel"))
        self.label_2.setText(_translate("Form", "
Visit api-server.  ;)
"))
        self.showinformLbl.setText(_translate("Form", "show inform."))

    def abrirDialogo(self):
        nombreinform = self.lineEdit.text()
        self.dialogo.nombre.setText('inform:' + nombreinform)
        self.dialogo.show()
        self.showinform()

    def showinform(self):
        current_time = datetime.datetime.today().strftime("%Y-%b-%dT%H_%M")

        alle = glob.glob('*.txt')
        counterfile = noreports
        porcentotal = 0
        suma = 100/counterfile
        counterbien = 0
        for file in alle:
            porcentotal += float(suma)
            avance = round(float(porcentotal), 0)
            self.dialogo.progressBar.setProperty("value", format(avance))
            self.dialogo.textEdit.setText(file + format(avance))
            print ('{!r} %'.format(avance))
            dict = '{!r} %'.format(avance)
            f = open(file,'w')
            f.write('result = ' + repr(dict) + '\n')

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())

The code is executed but not displayed in Dialog, only the labels but not the progress bar.

Why does this happen?

Body:
The problem is that you are using the format function badly, this is used when you have a string and you want to insert data with a certain format.

The setProperty function requires as first parameter the property you want to assign, and a second value of the type that requires the property, in your case value requires an integer value so you can pass the percentage directly without needing to change it to string.

If you read many files this can block the main thread where the GUI is drawn, to solve this you must use QApplication.processEvents()

def showinform(self):
    current_time = datetime.datetime.today().strftime("%Y-%b-%dT%H_%M")

    alle = glob.glob('*.txt')
    counterfile = noreports
    porcentotal = 0
    suma = 100/counterfile
    counterbien = 0
    for file in alle:
        porcentotal += float(suma)
        avance = round(float(porcentotal), 0)
        self.dialogo.progressBar.setProperty("value", avance)
        self.dialogo.textEdit.append("{}{}".format(file, avance))
        print ('{!r} %'.format(avance))
        dict = '{!r} %'.format(avance)
        QApplication.processEvents()
        f = open(file,'w')
        f.write('result = ' + repr(dict) + '\n')

Note: I have changed the setText function to append in QTextEdit so that it is added and not overwritten.

Instead of using setProperty you could use the setValue function of QProgressBar:

self.dialogo.progressBar.setValue(avance)

Another recommendation is to verify that the counterfile is non-zero since it could generate an exception for the division.


问:
How does one read a .dif file with Python
I am working on a project that requires me to read a file with a .dif extension. Dif stands for data information exchange. The file opens nicely in Open Office Calc. Then you can easily save as a csv file, however when I open in Python all I get are random characters that don't make sense. Here is the last code that I tried just to see if I could read.

```<code>txt = open('C:\myfile.dif', 'rb').read()
print txt
</code>```

I would even be open to programatically converting the file to csv first.  before opening if someone knows how to do that. As always, any help is much appreciated. Below is a partial screenshot of what I get when I run the code.

答:
Hadn't heard of this file format. Went and got a sample here.

I tested your method and it works fine:

```<code>>>> content = open(r"E:\sample.dif", 'rb').read()
>>> print (content)
b'TABLE\r\n0,1\r\n"EXCEL"\r\nVECTORS\r\n0,8\r\n""\r\nTUPLES\r\n0,3\r\n""\r\nDATA\r\n0,0\r\n""\r\n-1,0\r\nBOT\r\n1,0\r\n"Welcome to File Extension FYI Center!"\r\n1,0\r\n""\r\n1,0\r\n""\r\n-1,0\r\nBOT\r\n1,0\r\n""\r\n1,0\r\n""\r\n1,0\r\n""\r\n-1,0\r\nBOT\r\n1,0\r\n"ID"\r\n1,0\r\n"Type"\r\n1,0\r\n"Description"\r\n-1,0\r\nBOT\r\n0,1\r\nV\r\n1,0\r\n"ASP"\r\n1,0\r\n"Active Server Pages"\r\n-1,0\r\nBOT\r\n0,2\r\nV\r\n1,0\r\n"JSP"\r\n1,0\r\n"JavaServer Pages"\r\n-1,0\r\nBOT\r\n0,3\r\nV\r\n1,0\r\n"PNG"\r\n1,0\r\n"Portable Network Graphics"\r\n-1,0\r\nBOT\r\n0,4\r\nV\r\n1,0\r\n"GIF"\r\n1,0\r\n"Graphics Interchange Format"\r\n-1,0\r\nBOT\r\n0,5\r\nV\r\n1,0\r\n"WMV"\r\n1,0\r\n"Windows Media Video"\r\n-1,0\r\nEOD\r\n'
>>>
</code>```

The question is what is in the file and how do you want to handle it. Personally I liked:

```<code>with open(r"E:\sample.dif", 'rb') as f:
    for line in f:
        print (line)
</code>```

In the first code block, that long line that has a b'' (for bytes!) in front of it can be iterated on \r\n:

```<code>b'TABLE\r\n'
b'0,1\r\n'
b'"EXCEL"\r\n'
b'VECTORS\r\n'
b'0,8\r\n'
b'""\r\n'
b'TUPLES\r\n'
b'0,3\r\n'
b'""\r\n'
b'DATA\r\n'
b'0,0\r\n'
.
.
.
b'"Windows Media Video"\r\n'
b'-1,0\r\n'
b'EOD\r\n'
</code>```

Body:
I am working on a project that requires me to read a file with a .dif extension. Dif stands for data information exchange. The file opens nicely in Open Office Calc. Then you can easily save as a csv file, however when I open in Python all I get are random characters that don't make sense. Here is the last code that I tried just to see if I could read.

txt = open('C:\myfile.dif', 'rb').read()
print txt

I would even be open to programatically converting the file to csv first.  before opening if someone knows how to do that. As always, any help is much appreciated. Below is a partial screenshot of what I get when I run the code.

Body:
Hadn't heard of this file format. Went and got a sample here.

I tested your method and it works fine:

>>> content = open(r"E:\sample.dif", 'rb').read()
>>> print (content)
b'TABLE\r\n0,1\r\n"EXCEL"\r\nVECTORS\r\n0,8\r\n""\r\nTUPLES\r\n0,3\r\n""\r\nDATA\r\n0,0\r\n""\r\n-1,0\r\nBOT\r\n1,0\r\n"Welcome to File Extension FYI Center!"\r\n1,0\r\n""\r\n1,0\r\n""\r\n-1,0\r\nBOT\r\n1,0\r\n""\r\n1,0\r\n""\r\n1,0\r\n""\r\n-1,0\r\nBOT\r\n1,0\r\n"ID"\r\n1,0\r\n"Type"\r\n1,0\r\n"Description"\r\n-1,0\r\nBOT\r\n0,1\r\nV\r\n1,0\r\n"ASP"\r\n1,0\r\n"Active Server Pages"\r\n-1,0\r\nBOT\r\n0,2\r\nV\r\n1,0\r\n"JSP"\r\n1,0\r\n"JavaServer Pages"\r\n-1,0\r\nBOT\r\n0,3\r\nV\r\n1,0\r\n"PNG"\r\n1,0\r\n"Portable Network Graphics"\r\n-1,0\r\nBOT\r\n0,4\r\nV\r\n1,0\r\n"GIF"\r\n1,0\r\n"Graphics Interchange Format"\r\n-1,0\r\nBOT\r\n0,5\r\nV\r\n1,0\r\n"WMV"\r\n1,0\r\n"Windows Media Video"\r\n-1,0\r\nEOD\r\n'
>>>

The question is what is in the file and how do you want to handle it. Personally I liked:

with open(r"E:\sample.dif", 'rb') as f:
    for line in f:
        print (line)

In the first code block, that long line that has a b'' (for bytes!) in front of it can be iterated on \r\n:

b'TABLE\r\n'
b'0,1\r\n'
b'"EXCEL"\r\n'
b'VECTORS\r\n'
b'0,8\r\n'
b'""\r\n'
b'TUPLES\r\n'
b'0,3\r\n'
b'""\r\n'
b'DATA\r\n'
b'0,0\r\n'
.
.
.
b'"Windows Media Video"\r\n'
b'-1,0\r\n'
b'EOD\r\n'


问:
Dropdown menu not showing in Bootstrap
I'm trying to get a basic dropdown menu in Bootstrap:

```<code><!DOCTYPE html>
<html>
  <head>
    <title>Bootstrap 101 Template</title>
    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
  </head>
  <body>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script src="js/bootstrap.min.js"></script>

    <div class="dropdown">
      <!-- Link or button to toggle dropdown -->
      <ul class="dropdown-menu" role="menu" aria-labelledby="dLabel">
        <li><a tabindex="-1" href="#">Action</a></li>
        <li><a tabindex="-1" href="#">Another action</a></li>
        <li><a tabindex="-1" href="#">Something else here</a></li>
        <li class="divider"></li>
        <li><a tabindex="-1" href="#">Separated link</a></li>
      </ul>
    </div>

  </body>
</html>
</code>```

However, nothing shows up. I know the local CSS and JS files are being referred correctly. As far as I understand, the default JS includes all the plugins.

EDIT: Thanks to all for your feedback. I can only add, in case people find themselves in the same situation I am, to move further down in the tutorial before copying and pasting the snippets.

答: In my case I discovered the .dropdown-menu bootstrap class had set the top property to:top: 100%, that caused that the dropdown was shown outside the viewport.  I did override the top value with another class and now is working.

Title: Dropdown menu not showing in Bootstrap

Body:
I'm trying to get a basic dropdown menu in Bootstrap:

<!DOCTYPE html>

    <title>Bootstrap 101 Template</title>

    <link href="css/bootstrap.min.css" rel="stylesheet" media="screen">

Action

Another action

Something else here

Separated link

However, nothing shows up. I know the local CSS and JS files are being referred correctly. As far as I understand, the default JS includes all the plugins.

EDIT: Thanks to all for your feedback. I can only add, in case people find themselves in the same situation I am, to move further down in the tutorial before copying and pasting the snippets.


问:
aligning text to top of webpage in html code using css
I have this css code:

```<code>.post {
    margin-top: 0.5em;
    margin-left: 2em;
    margin-right: 2em;
    text-align: center;
}

.post p{
    max-width: 1200px;
    padding: .5em;
    text-align: justify;
    margin: 0;
    top: 1.25em;
}

.post h1{
    text-align: center;
}
</code>```

and have this in html:

```<code><div class="post">
 <h1>Title of Sample Work 2</h1>
 <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam dapibus id nisl ut suscipit. Nullam vel justo tellus. Suspendisse vehicula rhoncus nunc sed accumsan. In hac habitasse platea dictumst. Mauris vel dolor velit. Phasellus finibus massa mauris, at interdum nisl luctus at. Etiam porttitor, metus non dapibus pretium, orci arcu pretium nulla, eget congue augue libero at lectus. Mauris pretium urna tristique, laoreet enim rhoncus, euismod tortor.</p>
</div>
</code>```

And this is what I see:

Why there is so much margin at the top and the text title is so down?
You can see an example of the actual page on the web here:
http://www.nanogomo.com/sample1.html

It is interesting that if I add more content to it, it pushes the text up.

答:
Because the #wrapper has display:flex and has a before. You should you remove the following:

```<code>#wrapper::before {
    content: '';
    display: block;
}
</code>```

The flex container contained 3 elements home-back, post and before. Before is absolutely positioned so it is removed from the normal flow (doesn't take space). Before (with no width) and post are positioned on the main ax (vertical because direction is flex column) with justify-items: space-between (main ax is vertical).

Body:
I have this css code:

.post {
    margin-top: 0.5em;
    margin-left: 2em;
    margin-right: 2em;
    text-align: center;
}

.post p{
    max-width: 1200px;
    padding: .5em;
    text-align: justify;
    margin: 0;
    top: 1.25em;
}

.post h1{
    text-align: center;
}

and have this in html:

Title of Sample Work 2

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam dapibus id nisl ut suscipit. Nullam vel justo tellus. Suspendisse vehicula rhoncus nunc sed accumsan. In hac habitasse platea dictumst. Mauris vel dolor velit. Phasellus finibus massa mauris, at interdum nisl luctus at. Etiam porttitor, metus non dapibus pretium, orci arcu pretium nulla, eget congue augue libero at lectus. Mauris pretium urna tristique, laoreet enim rhoncus, euismod tortor.

And this is what I see:

Why there is so much margin at the top and the text title is so down?
You can see an example of the actual page on the web here:
http://www.nanogomo.com/sample1.html

It is interesting that if I add more content to it, it pushes the text up.

Body:
Because the #wrapper has display:flex and has a before. You should you remove the following:

#wrapper::before {
    content: '';
    display: block;
}

The flex container contained 3 elements home-back, post and before. Before is absolutely positioned so it is removed from the normal flow (doesn't take space). Before (with no width) and post are positioned on the main ax (vertical because direction is flex column) with justify-items: space-between (main ax is vertical).


问:
Simplest way to listen to another server?
I have server A (Windows, C#.NET), which  needs to send an alert/signal to server B (Linux, Java, Apache) everytime a certain process is done. I need to do this using a method call from .NET. What would be the easiest way to do this? I am thinking of setting up a web server on server B on some port which would listen to requests from server A. But how should I go about this? I am new to Java and have no experience with writing java web services, and I need to get this up quick, that is why I want to do this as easy as possible.</p>

答:
Look into Sockets. Instead of setting up an entire webserver, you can just have server B listen on a port and have server A allow connections, and send data on that same port. There are millions of examples online for sockets, and Java and .NET both have them (most languages do).

http://ondotnet.com/pub/a/dotnet/2002/10/21/sockets.htm

http://download.oracle.com/javase/tutorial/networking/sockets/


问:
vue-cli: How to reinitialize after closed development session?
This is probably a very basic question, but I'm trying to re-initialize a vue-cli development session after having closed my terminal window / restarted my computer, etc. So initially, I did:

```<code>$ vue init webpack my-project
</code>```

to build the first session, but after, for instance, restarting the computer, how can I come back to or reinitialize this session?

答:
Running vue init webpack my-project will generate a new webpack project.

To actually run the project (in development):

```<code>$ npm run dev
</code>```

Body:
This is probably a very basic question, but I'm trying to re-initialize a vue-cli development session after having closed my terminal window / restarted my computer, etc. So initially, I did:

$ vue init webpack my-project

to build the first session, but after, for instance, restarting the computer, how can I come back to or reinitialize this session?

Body:
Running vue init webpack my-project will generate a new webpack project.

To actually run the project (in development):

$ npm run dev


问:
Fatal error: Uncaught Error: Call to a member function format() on string
```<code><?php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "hello";

// Create connection

$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

echo "connected";

use Box\Spout\Reader\ReaderFactory;
use Box\Spout\Common\Type;

// Include Spout library
include ('spout-2.4.3\src\Spout\Autoloader\autoload.php');

// check file name is not empty
if (!empty($_FILES['file']['name'])) {

    // Get File extension eg. 'xlsx' to check file is excel sheet
    $pathinfo = pathinfo($_FILES["file"]["name"]);

    // check file has extension xlsx, xls and also check
    // file is not empty
   if (($pathinfo['extension'] == 'xlsx' || $pathinfo['extension'] == 'xls')
           && $_FILES['file']['size'] > 0 ) {

        // Temporary file name
        $inputFileName = $_FILES['file']['tmp_name'];

        // Read excel file by using ReadFactory object.
        $reader = ReaderFactory::create(Type::XLSX);

        // Open file
        $reader->open($inputFileName);
        $count = 1;
        $rows = array();

        // Number of sheet in excel file
        foreach ($reader->getSheetIterator() as $sheet) {

            // Number of Rows in Excel sheet
            foreach ($sheet->getRowIterator() as $row) {

                // It reads data after header. In the my excel sheet,
                // header is in the first row.
                if ($count> 1){

                $newDate = $row[4]-> format('d/m/Y');

                $result=mysqli_query($conn,"INSERT INTO stud VALUES                         ('NULL','$row[1]','$row[2]','$row[3]','$newDate','$row[5]','$row[6]','$row[7]')");

                }
                $count++;
            }

        }

        // Close excel file
        $reader->close();

    } else {

        echo "Please Select Valid Excel File";
    }

} else {

    echo "Please Select Excel File";

}
?>
</code>```

This is the php script am used to import excel file to mysql database ,i got an error while inserting date from excel to mysql table.

```<code>$newDate = $row[4]-> format('d/m/Y');
$result=mysqli_query($conn,"INSERT INTO stud VALUES           ('NULL','$row[1]','$row[2]','$row[3]','$newDate','$row[5]','$row[6]','$row[7]')");
</code>```

I try to format the row[4] ,but it shows "Uncaught Error: Call to a member function format() on string"  error.Any solution?

Excel file:
click to view excel which am working

答:
Please change ```<code>$newDate = $row[4]-> format('d/m/Y');</code>```
To ````</p>

```if(!empty($row[4])){
    $_newDate = new DateTime($row[4]);
}else{
    $_newDate = new DateTime();
}
$newDate = $_newDate->format('d/m/Y');
```

<p>````
Because $row[4] is string not object Date time.

Body:
<?php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "hello";

// Create connection

$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

echo "connected";

use Box\Spout\Reader\ReaderFactory;
use Box\Spout\Common\Type;

// Include Spout library
include ('spout-2.4.3\src\Spout\Autoloader\autoload.php');

// check file name is not empty
if (!empty($_FILES['file']['name'])) {

    // Get File extension eg. 'xlsx' to check file is excel sheet
    $pathinfo = pathinfo($_FILES["file"]["name"]);

    // check file has extension xlsx, xls and also check
    // file is not empty
   if (($pathinfo['extension'] == 'xlsx' || $pathinfo['extension'] == 'xls')
           && $_FILES['file']['size'] > 0 ) {

        // Temporary file name
        $inputFileName = $_FILES['file']['tmp_name'];

        // Read excel file by using ReadFactory object.
        $reader = ReaderFactory::create(Type::XLSX);

        // Open file
        $reader->open($inputFileName);
        $count = 1;
        $rows = array();

        // Number of sheet in excel file
        foreach ($reader->getSheetIterator() as $sheet) {

            // Number of Rows in Excel sheet
            foreach ($sheet->getRowIterator() as $row) {

                // It reads data after header. In the my excel sheet,
                // header is in the first row.
                if ($count> 1){

                $newDate = $row[4]-> format('d/m/Y');

                $result=mysqli_query($conn,"INSERT INTO stud VALUES                         ('NULL','$row[1]','$row[2]','$row[3]','$newDate','$row[5]','$row[6]','$row[7]')");

                }
                $count++;
            }

        }

        // Close excel file
        $reader->close();

    } else {

        echo "Please Select Valid Excel File";
    }

} else {

    echo "Please Select Excel File";

}
?>

This is the php script am used to import excel file to mysql database ,i got an error while inserting date from excel to mysql table.

$newDate = $row[4]-> format('d/m/Y');
$result=mysqli_query($conn,"INSERT INTO stud VALUES           ('NULL','$row[1]','$row[2]','$row[3]','$newDate','$row[5]','$row[6]','$row[7]')");

I try to format the row[4] ,but it shows "Uncaught Error: Call to a member function format() on string"  error.Any solution?

Excel file:
click to view excel which am working

Body:
Please change
$newDate = $row[4]-> format('d/m/Y');

To
`

if(!empty($row[4])){
    $_newDate = new DateTime($row[4]);
}else{
    $_newDate = new DateTime();
}
$newDate = $_newDate->format('d/m/Y');

`

Because $row[4] is string not object Date time.


问:
What is the best way to implement an interface at runtime in dotnet core?
I want to do something like this:

```<code>    interface IMyInterface
    {
        void DoSomething();
        string SaySomeWords(IEnumerable<string> words);
    }

    public class InterfaceImplFactory
    {
        public void RegisterInterface(Type type)
        {
            throw new NotImplementedException();
        }

        public InterfaceType GetInterfaceImpl<InterfaceType>()
        {
            throw new NotImplementedException();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var factory = new InterfaceImplFactory();
            factory.RegisterInterface(typeof(IMyInterface));

            var impl = factory.GetInterfaceImpl<IMyInterface>();

            impl.DoSomething();
            impl.SaySomeWords(new List<string>() { "HelloWorld", "thanks"});

            Console.ReadKey();
        }
    }
</code>```

After i googled How to implement an interface at runtime in c#, most articles are old. I want to solve this problem by using lambda, dynamic but not emit.Is there a way like this to work it out?

答:
Answering what you asked:

System.Reflection.Emit is the correct way to do what you are asking. dynamic and lambdas are C# language features. In other words, they are compiler magic, but under the hood, they are used to produce intermediate language (IL) at compile-time. System.Reflection.Emit is the best way to produce IL at run-time.

Now, guessing at what I think you meant to ask:

That said, in your sample above, it looked like what you're really asking for is type-lookup. Implementing an interface at runtime is difficult, but resolving an implementation from an interface is not difficult.

There are half a dozen dependency injection frameworks that will do this for you. For example, if you were to use Microsoft.Extensions.DependencyInjection, your code could look like this.

```<code>using Microsoft.Extensions.DependencyInjection;

interface IMyInterface
{
    void DoSomething();
}

class MyImplementation : IMyInterface
{
    public void DoSomething()
    {
        // implementation here
    }
}

class Program
{
    public static void Main()
    {
        var services = new ServiceCollection()
            .AddSingleton<IMyInterface, MyImplementation>()
            .BuildServiceProvider();

        IMyInterface impl = services.GetRequiredService<IMyInterface>();
        impl.DoSomething();
    }
}
</code>```

Body:
I want to do something like this:

    interface IMyInterface
    {
        void DoSomething();
        string SaySomeWords(IEnumerable<string> words);
    }

    public class InterfaceImplFactory
    {
        public void RegisterInterface(Type type)
        {
            throw new NotImplementedException();
        }

        public InterfaceType GetInterfaceImpl<InterfaceType>()
        {
            throw new NotImplementedException();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var factory = new InterfaceImplFactory();
            factory.RegisterInterface(typeof(IMyInterface));

            var impl = factory.GetInterfaceImpl<IMyInterface>();

            impl.DoSomething();
            impl.SaySomeWords(new List<string>() { "HelloWorld", "thanks"});

            Console.ReadKey();
        }
    }

After i googled How to implement an interface at runtime in c#, most articles are old. I want to solve this problem by using lambda, dynamic but not emit.Is there a way like this to work it out?

Body:
Answering what you asked:

System.Reflection.Emit is the correct way to do what you are asking. dynamic and lambdas are C# language features. In other words, they are compiler magic, but under the hood, they are used to produce intermediate language (IL) at compile-time. System.Reflection.Emit is the best way to produce IL at run-time.

Now, guessing at what I think you meant to ask:

That said, in your sample above, it looked like what you're really asking for is type-lookup. Implementing an interface at runtime is difficult, but resolving an implementation from an interface is not difficult.

There are half a dozen dependency injection frameworks that will do this for you. For example, if you were to use Microsoft.Extensions.DependencyInjection, your code could look like this.

using Microsoft.Extensions.DependencyInjection;

interface IMyInterface
{
    void DoSomething();
}

class MyImplementation : IMyInterface
{
    public void DoSomething()
    {
        // implementation here
    }
}

class Program
{
    public static void Main()
    {
        var services = new ServiceCollection()
            .AddSingleton<IMyInterface, MyImplementation>()
            .BuildServiceProvider();

        IMyInterface impl = services.GetRequiredService<IMyInterface>();
        impl.DoSomething();
    }
}


问:
How to get list of installed app that can sends notification in android?
I am developing an app in which i have to get list of apps which sends notifications in android. I searched a lot but didn't find any solution. So please let me know how do i get list of apps which sends notification.</p>

答:
To get the list of apps you can do it like this

```<code>Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent .addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> appList = context.getPackageManager().queryIntentActivities( intent , 0);
</code>```

Then to check if it has notification you can use this but I'm not sure how to use it for the app list.

```<code>NotificationManagerCompat.from(context).areNotificationsEnabled();
</code>```

Body:
To get the list of apps you can do it like this

Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent .addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> appList = context.getPackageManager().queryIntentActivities( intent , 0);

Then to check if it has notification you can use this but I'm not sure how to use it for the app list.

NotificationManagerCompat.from(context).areNotificationsEnabled();


问:
Why does Code::Blocks keep crashing when I try to run this code?
Code::Blocks keeps crashing when I enter the first score in this simple code. It is a perfectly type code to my understanding now I'm confused.</p>

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

int main() {
    float grade = 0;
    float scoreEntered = 0;
    float numtest = 0;
    float average = 0;

    printf("Press 0 when complete. \n\n");
    do {
        printf("Test: %.0f   Average: %.2f \n", numtest, average);
        printf("\nEnter test score ");
        scanf("%f", scoreEntered);
        grade += scoreEntered;
        numtest++;
        average = grade / numtest;
    } while (scoreEntered != 0);

    return 0;
}
</code>```

答:
Your error is in line 16

it should be

```<code>scanf("%f", &scoreEntered);
</code>```

Reason

"&"  is used to get the address of the variable and "scanf()" needs address of variable to store data

Body:
Code::Blocks keeps crashing when I enter the first score in this simple code. It is a perfectly type code to my understanding now I'm confused.

#include <stdio.h>
#include <stdlib.h>

int main() {
    float grade = 0;
    float scoreEntered = 0;
    float numtest = 0;
    float average = 0;

    printf("Press 0 when complete. \n\n");
    do {
        printf("Test: %.0f   Average: %.2f \n", numtest, average);
        printf("\nEnter test score ");
        scanf("%f", scoreEntered);
        grade += scoreEntered;
        numtest++;
        average = grade / numtest;
    } while (scoreEntered != 0);

    return 0;
}

Body:
Your error is in line 16

it should be

scanf("%f", &scoreEntered);

Reason

"&"  is used to get the address of the variable and "scanf()" needs address of variable to store data


问:
How can I inject ApplicationDbContext in another assembly?
I am trying to move some ViewComponents from the main web application to a separate class library (ASP.NET Core 1.1) which does NOT have the Entity Framework models or Identity stuff.

However, those view models depend on ApplicationDbContext to access the data (not all of what is available, just specific things). It kind of partially defeats the purpose of reusability (in other projects) if I have to leave the view component in the main web application.

答:
You can move ApplicationDbContext to a separate project.

Let say ApplicationDbContext locates in Data project, and ViewComponents locate in Common project.

Web project references both projects. Common project references Data project.


问:
Run JavaScript function at regular time interval
I am currently building a website to host software. What I want is to add to the project pages is a slideshow of screenshots cycling, changing images about every 5 seconds. Is there any way to a script triggered at a time interval using just JavaScript? ..or will I have to resort to alternative methods for achieving my desired functionality.
Thanks in advance for any help!</p>

答:
It Changes the date time in a div and time changes frequently after 1 sec.</p>

```<code>    setInterval(function(){
      var date=new Date();
      $('.class').html(date);
    },1000);
</code>```

Body:
It Changes the date time in a div and time changes frequently after 1 sec.

    setInterval(function(){
      var date=new Date();
      $('.class').html(date);
    },1000);


问:
Identifying which element invoked the event
I have following html code

```<code><input type="button"  id ="b1" value="Click me" onclick="msg()" />
<input type="button" id="b2"   value="Click me" onclick="msg()" />
</code>```

now in my javascript i want to identify whether button one was clicked or button 2. How can i do it?

答:
If you change your inline handler to use the .call() method, setting the context of the function to this:

```<code><input type="button"  id ="b1" value="Click me" onclick="msg.call( this )" />
</code>```

...then in your function, this will represent the one that received the event.

```<code>function msg() {
    alert( this.id );
}
</code>```

Otherwise, you could pass this as an argument:

```<code><input type="button"  id ="b1" value="Click me" onclick="msg( this )" />
</code>```

...and reference that argument:

```<code>function msg( elem ) {
    alert( elem.id );
}
</code>```

Body:
I have following html code

<input type="button"  id ="b1" value="Click me" onclick="msg()" />
<input type="button" id="b2"   value="Click me" onclick="msg()" />

now in my javascript i want to identify whether button one was clicked or button 2. How can i do it?

Body:
If you change your inline handler to use the .call() method, setting the context of the function to this:

<input type="button"  id ="b1" value="Click me" onclick="msg.call( this )" />

...then in your function, this will represent the one that received the event.

function msg() {
    alert( this.id );
}

Otherwise, you could pass this as an argument:

<input type="button"  id ="b1" value="Click me" onclick="msg( this )" />

...and reference that argument:

function msg( elem ) {
    alert( elem.id );
}


问:
What is wrong with this package structure in python?
I have the following structure:

```<code>/MyApp
   /Module_A
   __init__.py
   serviceFile.py
   /Module_B
   clientFile.py
</code>```

I am trying to call a function in ServiceFile.py from ClientFile.py

```<code>From MyApp.Module_a import ServiceFile
</code>```

but I am getting the error

ImportError: No module named MyApp.Module_a

Why?
BTW, When I run this from pyCharm it works fine only in CDM.
Both uses python 2.7

答:
There's potentially 2 sources of error. The first, like @TomCho has already pointed out is if the __init__.py file is not properly in your modules. However, since it works in PyCharm, I'm guessing it's the second.

The second is if your PYTHONPATH variable is not set up properly. There are a number of places which python will by default look for modules. This includes places like the Python install directory and the current working directory. To view a full list of places which Python looks, do..

```<code>import sys
print(sys.path)
</code>```

Python will then descend into each directory that has a __init__.py file, which is what makes that file so important. However, most likely you are not putting your code into the default places Python looks. And that's the whole purpose of the PYTHONPATH environment variable. You make it a list of paths where your packages are, and then those will be added to the sys.path seen above.

By default, PyCharm will add your project directory to the PYTHONPATH, which is why I'm guessing it worked in PyCharm, but not on the command line.

To set PYTHONPATH in Linux, go to the command line and type

```<code>export PYTHONPATH=/path/to/python/module
</code>```

If you have more than one path you need to add, you can keep appending with : so the more general case is

```<code>export PYTHONPATH=$PYTHONPATH:/path/to/python/module
</code>```

And you can keep doing that. I typically add that line to my ~/.bashrc file.

If you are in windows, modifying environment variables is different, but it's still pretty easy.

Body:
I have the following structure:

/MyApp
   /Module_A
   __init__.py
   serviceFile.py
   /Module_B
   clientFile.py

I am trying to call a function in ServiceFile.py from ClientFile.py

From MyApp.Module_a import ServiceFile

but I am getting the error

ImportError: No module named MyApp.Module_a

Why?
BTW, When I run this from pyCharm it works fine only in CDM.
Both uses python 2.7

Body:
There's potentially 2 sources of error. The first, like @TomCho has already pointed out is if the __init__.py file is not properly in your modules. However, since it works in PyCharm, I'm guessing it's the second.

The second is if your PYTHONPATH variable is not set up properly. There are a number of places which python will by default look for modules. This includes places like the Python install directory and the current working directory. To view a full list of places which Python looks, do..

import sys
print(sys.path)

Python will then descend into each directory that has a __init__.py file, which is what makes that file so important. However, most likely you are not putting your code into the default places Python looks. And that's the whole purpose of the PYTHONPATH environment variable. You make it a list of paths where your packages are, and then those will be added to the sys.path seen above.

By default, PyCharm will add your project directory to the PYTHONPATH, which is why I'm guessing it worked in PyCharm, but not on the command line.

To set PYTHONPATH in Linux, go to the command line and type

export PYTHONPATH=/path/to/python/module

If you have more than one path you need to add, you can keep appending with : so the more general case is

export PYTHONPATH=$PYTHONPATH:/path/to/python/module

And you can keep doing that. I typically add that line to my ~/.bashrc file.

If you are in windows, modifying environment variables is different, but it's still pretty easy.


问:
Increment value in one text file and write text to another
I have a HTML script of which contains a form, this form submits a Name value to a PHP script. In this PHP script I open two different text files, first file is to get the number inside and then increment it by 1. The other file is to open and then write the newly incremented number along with the Name value from the Post.
The first file of which only has a number inside starts on "0" and this is where I am having issues. When running the code, nothing happens, the form is submitted perfectly and the PHP script is called. But the only value inside the two different text files is "0" in both of them. Instead it should have "1" in the "amount.txt" file and "Text to appear:  1 Other text: Name" in the "textContent.txt" file.

I am not completely sure where I am wrong, to me it seems theoretically correct.

Underneath here is the PHP part, which is the part that isn't working.

```<code>$nam = $_POST['Name'];

$pastAmount = (int)file_get_contents('/user/site/amount.txt');
$fileOpen1 = '/user/site/amount.txt';
$newAmount = $pastAmount++;
file_put_contents($fileOpen1, $newAmount);

$fileOpen2 = '/user/site/textContent.txt';

$fileWrite2 = fopen($fileOpen2 , 'a');
$ordTxt = 'Text to appear:  ' + $newAmount + 'Other text: ' + $nam;
fwrite($fileWrite2, $ordTxt . PHP_EOL);
fclose($fileWrite2);
</code>```

答:
Instead of:

```<code>$newAmount = $pastAmount++;
</code>```

You should use:

```<code>$newAmount = $pastAmount + 1;
</code>```

Because $pastAmount++ will change the value of $pastAmount directly.

Then instead of

```<code>$ordTxt = 'Text to appear:  ' + $newAmount + 'Other text: ' + $nam;
</code>```

You should use :

```<code>$ordTxt = 'Text to appear:  '.$newAmount.' Other text: '.$nam;
</code>```

Because in PHP we are using the . for the concatenation.

PHP Code :

```<code><?php
$nam = $_POST['Name'];

// Read the value in the file amount
$filename = "./amount.txt";
$file = fopen($filename, "r");
$pastAmount = fread($file, filesize($filename));
$newAmount = $pastAmount + 1;
echo "Past amount: ".$pastAmount."-----New amount:".$newAmount;
fclose($file);

// Write the value in the file amount
$file = fopen($filename, "w+");
fwrite($file, $newAmount);
fclose($file);

// Write your second file
$fileOpen2 = './textContent.txt';
$fileWrite2 = fopen($fileOpen2 , 'w+  ');
$ordTxt = 'Text to appear:  '.$newAmount.' Other text: '.$nam;
fwrite($fileWrite2, $ordTxt . PHP_EOL);
fclose($fileWrite2);
?>
</code>```

Body:
I have a HTML script of which contains a form, this form submits a Name value to a PHP script. In this PHP script I open two different text files, first file is to get the number inside and then increment it by 1. The other file is to open and then write the newly incremented number along with the Name value from the Post.
The first file of which only has a number inside starts on "0" and this is where I am having issues. When running the code, nothing happens, the form is submitted perfectly and the PHP script is called. But the only value inside the two different text files is "0" in both of them. Instead it should have "1" in the "amount.txt" file and "Text to appear:  1 Other text: Name" in the "textContent.txt" file.

I am not completely sure where I am wrong, to me it seems theoretically correct.

Underneath here is the PHP part, which is the part that isn't working.

$nam = $_POST['Name'];

$pastAmount = (int)file_get_contents('/user/site/amount.txt');
$fileOpen1 = '/user/site/amount.txt';
$newAmount = $pastAmount++;
file_put_contents($fileOpen1, $newAmount);

$fileOpen2 = '/user/site/textContent.txt';

$fileWrite2 = fopen($fileOpen2 , 'a');
$ordTxt = 'Text to appear:  ' + $newAmount + 'Other text: ' + $nam;
fwrite($fileWrite2, $ordTxt . PHP_EOL);
fclose($fileWrite2);

Body:
Instead of:

$newAmount = $pastAmount++;

You should use:

$newAmount = $pastAmount + 1;

Because $pastAmount++ will change the value of $pastAmount directly.

Then instead of

$ordTxt = 'Text to appear:  ' + $newAmount + 'Other text: ' + $nam;

You should use :

$ordTxt = 'Text to appear:  '.$newAmount.' Other text: '.$nam;

Because in PHP we are using the . for the concatenation.

PHP Code :

<?php
$nam = $_POST['Name'];

// Read the value in the file amount
$filename = "./amount.txt";
$file = fopen($filename, "r");
$pastAmount = fread($file, filesize($filename));
$newAmount = $pastAmount + 1;
echo "Past amount: ".$pastAmount."-----New amount:".$newAmount;
fclose($file);

// Write the value in the file amount
$file = fopen($filename, "w+");
fwrite($file, $newAmount);
fclose($file);

// Write your second file
$fileOpen2 = './textContent.txt';
$fileWrite2 = fopen($fileOpen2 , 'w+  ');
$ordTxt = 'Text to appear:  '.$newAmount.' Other text: '.$nam;
fwrite($fileWrite2, $ordTxt . PHP_EOL);
fclose($fileWrite2);
?>


问:
How to stop fmincon after running an elapsed time of T sec?
I am running fmincon for a gird. For some points in the grid there is no solution, exit flag=-2, and it takes half an hour sometimes to return the flag and start the next point in the grid. However, for the other points the answer is revealed in less than a min.
  So I thought one possible solution to reduce the unnecessary running time is to define a stop criteria based on elapsed time for each point in the grid. In other words, How to stop fmincon after running  an elapsed time of T sec?

答:
You can use an output function:

```<code>tic
fmincon(.....,optimset('OutputFcn',@outfun,'MaxFunEval',20000))
</code>```

outfun.m :

```<code>function stop = outfun(x,optimValues,state)
stop = toc>T;
</code>```

Body:
You can use an output function:

tic
fmincon(.....,optimset('OutputFcn',@outfun,'MaxFunEval',20000))

outfun.m :

function stop = outfun(x,optimValues,state)
stop = toc>T;


问:
Doctrine: join one-to-one relation
Suppose we have two models: Post and ViewsCount. Relation type is 1:1.

Now I want to retrieve last 5 posts with their views stats:

```<code>$posts = PostTable::getInstance()->createQuery('p')
    ->leftJoin('p.ViewsCount') // relation name is "ViewsCount"
    ->orderBy('p.created_at DESC')
    ->limit(5)
    ->execute();
</code>```

But, there is no luck. It throws an error. If I remove joining - everything is ok.

So, my question is - How to automatically join/retrieve one-to-one relation in Doctrine to avoid lot's of additional queries?

答:
Is seems that you should define relations properly.
For each model define relations with type key (type:one).</p>

Title: Doctrine: join one-to-one relation

Body:
Suppose we have two models: Post and ViewsCount. Relation type is 1:1.

Now I want to retrieve last 5 posts with their views stats:

$posts = PostTable::getInstance()->createQuery('p')
    ->leftJoin('p.ViewsCount') // relation name is "ViewsCount"
    ->orderBy('p.created_at DESC')
    ->limit(5)
    ->execute();

But, there is no luck. It throws an error. If I remove joining - everything is ok.

So, my question is - How to automatically join/retrieve one-to-one relation in Doctrine to avoid lot's of additional queries?