问:
Can't find my source file even it's already in the pythonpath directory
On Windows 10, Python 3.6.1, after I added E:\learning python exercise  in PYTHONPATH  by the GUI or through .pth file.  Ihen C checked the os.sys.path, it reads:

But when I want to run a file through the cmd prompt, it pops out error:

答:
Python does not use PYTHONPATH for scripts - it uses them for modules.  So you could try:

```<code>python -m script1
</code>```

but that is not the way scripts should be run.  You should supply the path name to python or assume it is in the current directory. For example:

python "E:\learning python exercise\script1.py"

The double quotes are required because you have elected to have spaces in your directory name - I suggest that you might want to stop doing that, spaces in path names just makes life more difficult.

Alternatively, change your current directory, either using the cd command or by setting the "start in" properties to your cmd.exe shortcut.  For example:

```<code>cd "E:\learning python exercise"
python script1.py
</code>```

You only have to do the cd once in each cmd.exe session.

If you have setup the filename association for python (should have been done at installation time), then you should only need:

```<code>cd "E:\learning python exercise"
script1.py
</code>```

Body:
Python does not use PYTHONPATH for scripts - it uses them for modules.  So you could try:

python -m script1

but that is not the way scripts should be run.  You should supply the path name to python or assume it is in the current directory. For example:

python "E:\learning python exercise\script1.py"

The double quotes are required because you have elected to have spaces in your directory name - I suggest that you might want to stop doing that, spaces in path names just makes life more difficult.

Alternatively, change your current directory, either using the cd command or by setting the "start in" properties to your cmd.exe shortcut.  For example:

cd "E:\learning python exercise"
python script1.py

You only have to do the cd once in each cmd.exe session.

If you have setup the filename association for python (should have been done at installation time), then you should only need:

cd "E:\learning python exercise"
script1.py


来源: stackexchange

问:
Android simultaneous db operations -- "database is locked"
I'm writing an application with an "online mode", that is, data is downloaded, parsed and inserted into a SQLite database as needed. All this is performed by a service. The app consists of several activities that ask the service for a data update (different data depending on the activity).

When the user navigates through the activities (without waiting for the service to finish), it's very easy to get SQLiteExceptions (message: database is locked).

I thought about using synchronized blocks, but that would force the user to wait while loading a new activity (that needs database access to load) while the service finishes updating. So that seems a dead end.

Another option might be to stop the update when in the onStop method of each activity. Of course, the update will be interrupted, but that's not a big issue. Problem with this is that I'm not sure how to approach it.

My question is, how can/should I handle this?

答:
If your activity is only going to read and not write to database like my case, this is what i did as a workaround:

create a service ( i.e DatabaseService 0 and use it as a central point to access database (i.e open a database connection) to ensure you only have one dbhelper at a time.

all activity and service which need to access database have to establish a connection to DatabaseService

ensure that only your DownloadService's thread is able to write to database and it should use transaction

after that, you can use getReadable database to read / use the connection to stop the download service , etc.

Just make sure that you only use 1 dbhelper.

ContentLicense: CC BY-SA 2.5


问:
ORA-00979: not a GROUP BY expression when I execute my sql
When I execute my SQL, I get the below error:

My exception is:

```<code>[SQL]select bd.name aaa
from bd_material_v m ,bd_marbasclass bd
where m.creator='1001A210000000000IIQ'
and bd.code=substr(m.code,0,4)
group by bd.name
order by substr(m.code,0,4)
[Err] ORA-00979: not a GROUP BY expression
</code>```

My SQL is below:

```<code>select bd.name aaa
  from bd_material_v m ,bd_marbasclass bd
    where m.creator='1001A210000000000IIQ'
      and bd.code=substr(m.code,0,4)
      group by bd.name
      order by substr(m.code,0,4)
</code>```

Addtional

If I annotation this line group by bd.name, I will query out the result, without the issue.

EDIT

My table:

bd_marbasclass

bd_material_v

答:
Even though your join syntax is unconventional, the problem in your code is order by. Remove it and you will not get the not a group by error.

But I strongly suggest to correct the join syntax. use inner join on appropriate column.

```<code>select bd.name aaa
  from bd_material_v m ,bd_marbasclass bd
    where m.creator='1001A210000000000IIQ'
      and bd.code=substr(m.code,0,4)
      group by bd.name
</code>```

So this will not give you error

```<code>with tbl(col1,col2) as
(select 1,1 from dual union all
select 1,3 from dual )
select col1 as col1
from tbl
group by col1
</code>```

But this will

```<code>with tbl(col1,col2) as
(select 1,1 from dual union all
select 1,3 from dual )
select col1 as col1
from tbl
group by col1
order by col2
</code>```

ContentLicense: CC BY-SA 3.0

Body:
When I execute my SQL, I get the below error:

My exception is:

[SQL]select bd.name aaa
from bd_material_v m ,bd_marbasclass bd
where m.creator='1001A210000000000IIQ'
and bd.code=substr(m.code,0,4)
group by bd.name
order by substr(m.code,0,4)
[Err] ORA-00979: not a GROUP BY expression

My SQL is below:

select bd.name aaa
  from bd_material_v m ,bd_marbasclass bd
    where m.creator='1001A210000000000IIQ'
      and bd.code=substr(m.code,0,4)
      group by bd.name
      order by substr(m.code,0,4)

Addtional

If I annotation this line group by bd.name, I will query out the result, without the issue.

EDIT

My table:

bd_marbasclass

bd_material_v

Body:
Even though your join syntax is unconventional, the problem in your code is order by. Remove it and you will not get the not a group by error.

But I strongly suggest to correct the join syntax. use inner join on appropriate column.

select bd.name aaa
  from bd_material_v m ,bd_marbasclass bd
    where m.creator='1001A210000000000IIQ'
      and bd.code=substr(m.code,0,4)
      group by bd.name

So this will not give you error

with tbl(col1,col2) as
(select 1,1 from dual union all
select 1,3 from dual )
select col1 as col1
from tbl
group by col1

But this will

with tbl(col1,col2) as
(select 1,1 from dual union all
select 1,3 from dual )
select col1 as col1
from tbl
group by col1
order by col2


问:
On click how can I get the closet getAttribute('data-name') with the same id
When I click on #tag-list-item it should get the closet data-name

How ever it works fine for the first one but if I click on the second #tag-list-item it gets the first data-name and not the closet one.

Question when I click on my #tag-list-item how can I make sure it gets
  the correct getAttribute('data-name') with same id?

```<code><script type="text/javascript">
$(document).on('click', '#tag-list-item', function(e){
    var taglistitem = document.getElementById("tag-list-item");

    var tagbar = document.getElementById("tag-menu");

    var tagmenuitem = document.createElement("li");
    tagmenuitem.id = "tag-menu-item";
    tagbar.appendChild(tagmenuitem);

    var label = document.createElement("span");
    label.className = "label label-default";
    label.innerHTML = taglistitem.getAttribute('data-name');
    tagmenuitem.appendChild(label);
});
</script>
</code>```

Full View

```<code><div id="tag">
<?php if ($tags) {?>
<div id="tag-list-group">
<?php foreach (array_chunk($tags, 4) as $tag) { ?>
<div class="row">
<?php foreach ($tag as $tag) {?>
<div class="col-sm-3 col-xs-6 text-center">
<a>
<span id="tag-list-item" data-id="<?php echo $tag['tag_id'];?>" data-name="<?php echo $tag['name'];?>"><?php echo $tag['tag_name'];?></span>
</a>
</div>
<?php }?>
</div>
<?php }?>
</div>
<?php }?>

<div id="tagbar"><ul id="tag-menu" class="list-inline"></ul></div>
</div>

<script type="text/javascript">
$(document).on('click', '#tag-list-item', function(e){
    var taglistitem = document.getElementById("tag-list-item");

    var tagbar = document.getElementById("tag-menu");

    var tagmenuitem = document.createElement("li");
    tagmenuitem.id = "tag-menu-item";
    tagbar.appendChild(tagmenuitem);

    var label = document.createElement("span");
    label.className = "label label-default";
    label.innerHTML = taglistitem.getAttribute('data-name');
    tagmenuitem.appendChild(label);
});
</script>
</code>```

答:
I don't recommend you to use id but class if you have multiple items.

But in all case, you can use this instead of select ID.

$(document).on('click', '.tag-list-item', function(e){
    $('#result').html(this.getAttribute('data-name'));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="tag-list-item" data-name="First">Click me</button>
<button class="tag-list-item" data-name="Second">Click me</button>
<button class="tag-list-item" data-name="Third">Click me</button>

<div id="result"></div></code>```

Body:
When I click on #tag-list-item it should get the closet data-name

How ever it works fine for the first one but if I click on the second #tag-list-item it gets the first data-name and not the closet one.

Question when I click on my #tag-list-item how can I make sure it gets
  the correct getAttribute('data-name') with same id?

Full View

<?php if ($tags) {?>

<?php foreach (array_chunk($tags, 4) as $tag) { ?>

<?php foreach ($tag as $tag) {?>

<span id="tag-list-item" data-id="<?php echo $tag['tag_id'];?>" data-name="<?php echo $tag['name'];?>"><?php echo $tag['tag_name'];?>

<?php }?>

<?php }?>

<?php }?>

Body:
I don't recommend you to use id but class if you have multiple items.

But in all case, you can use this instead of select ID.

$(document).on('click', '.tag-list-item', function(e){
    $('#result').html(this.getAttribute('data-name'));
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="tag-list-item" data-name="First">Click me</button>
<button class="tag-list-item" data-name="Second">Click me</button>
<button class="tag-list-item" data-name="Third">Click me</button>

<div id="result"></div>


问:
Sharing variable globally
In my main controller I have a user service that returns the current user.

```<code>// Curr user
userService.getCurrentUser().then(user => {
    mainCtrl.currUser = user;
});
</code>```

Is there any way to be able to use the currUser variable in other controllers without injecting my service and calling this method over and over again in maybe 50 controllers?

Ex.

```<code>// My other awesome controller
console.log(currUser.fullName);
</code>```

答:
you can use $rootScope like bellow:

```<code>mainCtrl.$rootScope.currUser = user;
</code>```

and the other controller, you can recover this as bellow:

```<code>console.log(yourContrl.$rootScope.currUser.fullName);
</code>```

Title: Sharing variable globally

Body:
In my main controller I have a user service that returns the current user.

// Curr user
userService.getCurrentUser().then(user => {
    mainCtrl.currUser = user;
});

Is there any way to be able to use the currUser variable in other controllers without injecting my service and calling this method over and over again in maybe 50 controllers?

Ex.

// My other awesome controller
console.log(currUser.fullName);

Body:
you can use $rootScope like bellow:

mainCtrl.$rootScope.currUser = user;

and the other controller, you can recover this as bellow:

console.log(yourContrl.$rootScope.currUser.fullName);


问:
jQuery get meta content in div
I need to get some data stored in a div and in a meta tag.

Here the div:

```<code><div id="qtip-0" class="qtip simcal-default-calendar simcal-event-bubble qtip-pos-tc qtip-fixed qtip-focus" tracking="false" role="alert" aria-live="polite" aria-atomic="false" aria-describedby="qtip-0-content" aria-hidden="false" data-qtip-id="0" >
<div class="qtip-tip">
    <canvas width="16" height="16" style="background-color: transparent !important; border: 0px !important; width: 8px; height: 8px;"></canvas>
</div>
<div class="qtip-content" id="qtip-0-content" aria-atomic="true">
    <div class="simcal-event-details simcal-tooltip-content" style="display: block; visibility: visible;">
        <div class="col-xs-12 title-event-container">
            <span class="simcal-event-title" itemprop="name">Riunione intenra Scali ferroviari</span>
        </div>
        <p><label>Luogo:</label><br>
        <span class="simcal-event-address simcal-event-start-location" itemprop="location" itemscope="" itemtype="http://schema.org/Place"><meta itemprop="name" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia"><meta itemprop="address" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia">Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia</span></p>
        <div id="map">Mappa</div>
        <p>
            <a href="//maps.google.com?q=Palazzo+Marino+-+Comune+di+MilanoPiazza+della+Scala+2%2C+20121+Milano%2C+Italia" target="_blank">Vedi mappa ingrandita</a>
        </p>
    </div>
</div>
</code>```

I need to access to:

```<code><meta itemprop="address" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia">
</code>```

to get the content attribute.

Here what I have tried:

```<code>var currentEventAddress = $('#qtip-0 span').find('meta[itemprop="address"]').attr('content');

console.log(currentEventAddress);
</code>```

But I get undefined

答:
var currentEventAddress = $('#qtip-0').find('meta[itemprop="address"]').attr('content');

console.log(currentEventAddress);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="qtip-0" class="qtip simcal-default-calendar simcal-event-bubble qtip-pos-tc qtip-fixed qtip-focus" tracking="false" role="alert" aria-live="polite" aria-atomic="false" aria-describedby="qtip-0-content" aria-hidden="false" data-qtip-id="0">
  <div class="qtip-tip">
    <canvas width="16" height="16" style="background-color: transparent !important; border: 0px !important; width: 8px; height: 8px;"></canvas>
  </div>
  <div class="qtip-content" id="qtip-0-content" aria-atomic="true">
    <div class="simcal-event-details simcal-tooltip-content" style="display: block; visibility: visible;">
      <div class="col-xs-12 title-event-container">
        <span class="simcal-event-title" itemprop="name">Riunione intenra Scali ferroviari</span>
      </div>
      <p><label>Luogo:</label><br>
        <span class="simcal-event-address simcal-event-start-location" itemprop="location" itemscope="" itemtype="http://schema.org/Place"><meta itemprop="name" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia"><meta itemprop="address" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia">Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia</span></p>
      <div id="map">Mappa</div>
      <p>
        Vedi mappa ingrandita
      </p>
    </div>
  </div></code>```

Use this $('#qtip-0').find('meta[itemprop="address"]').attr('content') if you want to add span use $('#qtip-0 span.simcal-event-address')

Because the span that contains the meta is the span with class simcal-event-address

var currentEventAddress = $('#qtip-0 span.simcal-event-address').find('meta[itemprop="address"]').attr('content');

console.log(currentEventAddress);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="qtip-0" class="qtip simcal-default-calendar simcal-event-bubble qtip-pos-tc qtip-fixed qtip-focus" tracking="false" role="alert" aria-live="polite" aria-atomic="false" aria-describedby="qtip-0-content" aria-hidden="false" data-qtip-id="0">
  <div class="qtip-tip">
    <canvas width="16" height="16" style="background-color: transparent !important; border: 0px !important; width: 8px; height: 8px;"></canvas>
  </div>
  <div class="qtip-content" id="qtip-0-content" aria-atomic="true">
    <div class="simcal-event-details simcal-tooltip-content" style="display: block; visibility: visible;">
      <div class="col-xs-12 title-event-container">
        <span class="simcal-event-title" itemprop="name">Riunione intenra Scali ferroviari</span>
      </div>
      <p><label>Luogo:</label><br>
        <span class="simcal-event-address simcal-event-start-location" itemprop="location" itemscope="" itemtype="http://schema.org/Place"><meta itemprop="name" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia"><meta itemprop="address" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia">Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia</span></p>
      <div id="map">Mappa</div>
      <p>
        Vedi mappa ingrandita
      </p>
    </div>
  </div></code>```

Title: jQuery get meta content in div

Body:
I need to get some data stored in a div and in a meta tag.

Here the div:

    <canvas width="16" height="16" style="background-color: transparent !important; border: 0px !important; width: 8px; height: 8px;"></canvas>

            Riunione intenra Scali ferroviari

Luogo:

        <meta itemprop="name" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia"><meta itemprop="address" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia">Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia

Mappa

            Vedi mappa ingrandita

I need to access to:

<meta itemprop="address" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia">

to get the content attribute.

Here what I have tried:

var currentEventAddress = $('#qtip-0 span').find('meta[itemprop="address"]').attr('content');

console.log(currentEventAddress);

But I get undefined

Body:
var currentEventAddress = $('#qtip-0').find('meta[itemprop="address"]').attr('content');

console.log(currentEventAddress);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="qtip-0" class="qtip simcal-default-calendar simcal-event-bubble qtip-pos-tc qtip-fixed qtip-focus" tracking="false" role="alert" aria-live="polite" aria-atomic="false" aria-describedby="qtip-0-content" aria-hidden="false" data-qtip-id="0">
  <div class="qtip-tip">
    <canvas width="16" height="16" style="background-color: transparent !important; border: 0px !important; width: 8px; height: 8px;"></canvas>
  </div>
  <div class="qtip-content" id="qtip-0-content" aria-atomic="true">
    <div class="simcal-event-details simcal-tooltip-content" style="display: block; visibility: visible;">
      <div class="col-xs-12 title-event-container">
        <span class="simcal-event-title" itemprop="name">Riunione intenra Scali ferroviari</span>
      </div>
      <p><label>Luogo:</label><br>
        <span class="simcal-event-address simcal-event-start-location" itemprop="location" itemscope="" itemtype="http://schema.org/Place"><meta itemprop="name" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia"><meta itemprop="address" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia">Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia</span></p>
      <div id="map">Mappa</div>
      <p>
        <a href="//maps.google.com?q=Palazzo+Marino+-+Comune+di+MilanoPiazza+della+Scala+2%2C+20121+Milano%2C+Italia" target="_blank">Vedi mappa ingrandita</a>
      </p>
    </div>
  </div>

Use this $('#qtip-0').find('meta[itemprop="address"]').attr('content') if you want to add span use $('#qtip-0 span.simcal-event-address')

Because the span that contains the meta is the span with class simcal-event-address

var currentEventAddress = $('#qtip-0 span.simcal-event-address').find('meta[itemprop="address"]').attr('content');

console.log(currentEventAddress);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="qtip-0" class="qtip simcal-default-calendar simcal-event-bubble qtip-pos-tc qtip-fixed qtip-focus" tracking="false" role="alert" aria-live="polite" aria-atomic="false" aria-describedby="qtip-0-content" aria-hidden="false" data-qtip-id="0">
  <div class="qtip-tip">
    <canvas width="16" height="16" style="background-color: transparent !important; border: 0px !important; width: 8px; height: 8px;"></canvas>
  </div>
  <div class="qtip-content" id="qtip-0-content" aria-atomic="true">
    <div class="simcal-event-details simcal-tooltip-content" style="display: block; visibility: visible;">
      <div class="col-xs-12 title-event-container">
        <span class="simcal-event-title" itemprop="name">Riunione intenra Scali ferroviari</span>
      </div>
      <p><label>Luogo:</label><br>
        <span class="simcal-event-address simcal-event-start-location" itemprop="location" itemscope="" itemtype="http://schema.org/Place"><meta itemprop="name" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia"><meta itemprop="address" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia">Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia</span></p>
      <div id="map">Mappa</div>
      <p>
        <a href="//maps.google.com?q=Palazzo+Marino+-+Comune+di+MilanoPiazza+della+Scala+2%2C+20121+Milano%2C+Italia" target="_blank">Vedi mappa ingrandita</a>
      </p>
    </div>
  </div>


问:
Why does Azure SDK for PHP not working well with Azure General-purpose Storage
Is Azure SDK for PHP Blob Storage method works only on a Blob Storage account? Because whenever I tried to use it on an Azure General-purpose Storage account (which gives you access to Azure Storage services such as Tables, Queues, Files, Blobs and Azure virtual machine disks under a single account), my php program stops at an specific process in an inconsistent manner. At times it processes completely but when I re-run it, it stops again in a random point.

My goal is to get all blobs under my Azure subscription using foreach loop, given that I have an array variable that holds connection strings for each storage accounts. It works well with a Blob Storage account but whenever I include the General-purpose Storage account, the problem starts to occur.

I already tried overriding my php memory limit and still it does not solve the issue.

Any advise guys? Thank you in advance.

答:
```<code>//And this is the powershell script that generates the csv file accessed by my php

    Get-AzureStorageAccount | foreach-object {
    Get-AzureStorageKey -StorageAccountName $_.StorageAccountName
    } | Select-object StorageAccountName, Primary, Secondary | Export-CSV "..csv\bs_asm.csv" -Encoding ascii -NoTypeInformation
    Start-Sleep 1
    Get-AzureRmStorageAccount | foreach-object {
    $Primary = (Get-AzureRmStorageAccountKey -Name $_.StorageAccountName -ResourceGroupName $_.ResourceGroupName).Value[0]
    $Secondary = (Get-AzureRmStorageAccountKey -Name $_.StorageAccountName -ResourceGroupName $_.ResourceGroupName).Value[1]
    New-Object -TypeName PSObject -Property @{
    StorageAccountName = $_.StorageAccountName
    Primary = $Primary
    Secondary = $Secondary
    } | Select-Object StorageAccountName, Primary, Secondary
    } | Export-CSV "..csv\bs_arm.csv" -Encoding ascii -NoTypeInformation
    $directory = "..csv\*.*";
    $csvFiles = Get-ChildItem -Path $directory -Filter *.csv;
    $content =@();
    foreach ($csv in $csvFiles) {
    $content += Import-Csv $csv;
    }
    $content | Export-Csv -Path "..csv\azureblobstorages.csv" -Encoding ascii -NoTypeInformation;
</code>```


问:
Clicked 2 Button At Once
Hello :) I Actually want to ask something
So my aim here is "If I click the button 1, the button 2 will be clicked too "

"Is it possible ? Click a one button so the other button will be clicked ?"

Here is my Code:

```<code>Button btn1 = sender as Button;

if (btn1 == button1){
    button2.PerformClick();
}
</code>```

It actually does not work it seems there is something wrong

答:
It is very simple.</p>

```<code>   private void button1_Click(object sender, EventArgs e)
    {
        if ((sender as Button) == button1)
        {
            button2_Click(sender, e);
        }
    }

    private void button2_Click(object sender, EventArgs e)
    {

    }
</code>```

Title: Clicked 2 Button At Once

Body:
Hello :) I Actually want to ask something
So my aim here is "If I click the button 1, the button 2 will be clicked too "

"Is it possible ? Click a one button so the other button will be clicked ?"

Here is my Code:

Button btn1 = sender as Button;

if (btn1 == button1){
    button2.PerformClick();
}

It actually does not work it seems there is something wrong

Body:
It is very simple.

   private void button1_Click(object sender, EventArgs e)
    {
        if ((sender as Button) == button1)
        {
            button2_Click(sender, e);
        }
    }

    private void button2_Click(object sender, EventArgs e)
    {

    }


问:
Angular2 & RxJS multiple HTTP calls - display as soon as first response returned
I'm trying to use RxJS and Angular2 to build a search field. I have a simple text input field that I'm observing for valueChanges.

I then use the inputted value to call a first REST service which returns a search results object that contains a list of customers.

Then for each customer returned I call a second REST service to get the customer details and store the returned details in the customer object.

My screen then loops over the customers to display them.

But I have two problems that I can't seem to figure out:

I want the results to appear as soon as the first service returns
and then update the screen when the second service returns but at
the moment nothing displays until all the service calls are
completed.

When someone changes the input field I want the results to disappear
immediately but for some reason that is no happening and I can't
figure out why e.g. if I enter in a search term that returns no
matches, the results from the previous search remain on screen.

My code looks like:

this.customers = this.term.valueChanges
            .filter(term => {
                return term !== null;
            })
            .switchMap(term => {
                return this.customerService.search(term)
            })
            .map(searchResults => {
                return searchResults.customers;
            })
            .flatMap(customers => {
                if (customers.length > 0) {
                    // this.customers = customers;
                    return Observable.forkJoin(
                        customers.map((customer: Customer) => {
                            return this.customerDetailService.getDetails(customer)
                                .map((details: any) => {
                                    customer.details = details;
                                    return customer;
                                });
                        }));
                }
                return customers;
            });
```

<p>And the screen looks like:</p>

<pre class="lang-html prettyprint-override"><code><div *ngIf="customers|async; let customers">

    <ul>
        <li *ngFor="let customer of customers">

           {{customer.name}}
           {{customer.details.age}}
        </li>
    </ul>
</div>
</code>```

Any help would be appreciated.

Thanks,
Kevin.

答:
What is this.customers ? A combination of the initial fetch and every update that comes later. So this should work :

let search = this.term.valueChanges
  .filter(term => term !== null)
  .switchMap(term => this.customerService.search(term))
  .map(searchResults => searchResults.customers);

let details = search.switchMap(customers => {
  if (customers.length > 0) {
    // this.customers = customers;
    return Observable.forkJoin(
      customers.map((customer: Customer) => {
        return this.customerDetailService.getDetails(customer)
          .map((details: any) => {
            customer.details = details;
            return customer;
          });
      }));
  }
  return customers;
});

this.customers = Observable.merge(search, details);
```

Body:
I'm trying to use RxJS and Angular2 to build a search field. I have a simple text input field that I'm observing for valueChanges.

I then use the inputted value to call a first REST service which returns a search results object that contains a list of customers.

Then for each customer returned I call a second REST service to get the customer details and store the returned details in the customer object.

My screen then loops over the customers to display them.

But I have two problems that I can't seem to figure out:

I want the results to appear as soon as the first service returns
and then update the screen when the second service returns but at
the moment nothing displays until all the service calls are
completed.

When someone changes the input field I want the results to disappear
immediately but for some reason that is no happening and I can't
figure out why e.g. if I enter in a search term that returns no
matches, the results from the previous search remain on screen.

My code looks like:

this.customers = this.term.valueChanges
            .filter(term => {
                return term !== null;
            })
            .switchMap(term => {
                return this.customerService.search(term)
            })
            .map(searchResults => {
                return searchResults.customers;
            })
            .flatMap(customers => {
                if (customers.length > 0) {
                    // this.customers = customers;
                    return Observable.forkJoin(
                        customers.map((customer: Customer) => {
                            return this.customerDetailService.getDetails(customer)
                                .map((details: any) => {
                                    customer.details = details;
                                    return customer;
                                });
                        }));
                }
                return customers;
            });

And the screen looks like:

           {{customer.name}}
           {{customer.details.age}}

Any help would be appreciated.

Thanks,
Kevin.


问:
WebDriverIO: waitFor <title> to be X
Is there a pattern with the current 2.0 library that would allow me to wait until the current Page's title is X? For the purpose of pausing the WebDriver until I am on the page I wish to be after several redirects?

This would be easy if I could do driver.waitFor('title:contains("Google")');

答:
With webdriver 3.0+ you can also add a browser custom command somewhere in a module shared across all your tests:

browser.addCommand('waitForTitle', function (title, timeout) {
    browser.waitUntil(function () {
        return browser.getTitle() === title;
    }, timeout | 3000);
});
```

<p>Then call it from you test code:</p>

<pre class="lang-js prettyprint-override"><code>it('should navigate to login page', function () {
    browser.click('.login-button');
    browser.waitForTitle('Login');
});
</code>```

Title: WebDriverIO: waitFor <title> to be X

Body:
With webdriver 3.0+ you can also add a browser custom command somewhere in a module shared across all your tests:

browser.addCommand('waitForTitle', function (title, timeout) {
    browser.waitUntil(function () {
        return browser.getTitle() === title;
    }, timeout | 3000);
});

Then call it from you test code:

it('should navigate to login page', function () {
    browser.click('.login-button');
    browser.waitForTitle('Login');
});


问:
Docker Error : no space left on device on windows
I'm using docker on windows 7 and trying to download an image from cloud. After downloading while extraction i'm getting an error. Below is log snippet

```<code>cba922442da5: Downloading 5.866 GB/5.866 GB
10d186ab9b98: Download complete
89c26a498cda: Download complete
write /mnt/sda1/var/lib/docker/tmp/GetImageBlob601918967: no space left on devic
e

 Tools docker image has been downloaded or upgraded to the newer version success
fully if already exist
</code>```

There are already several thread related to this issue & i have tried solution provided by them but they didn't work. i have tried to delete all the images using below command but got certificate error

```<code>$ docker ps -a -q
time="2017-03-30T13:09:16+05:30" level=info msg="Unable to use system certificat
e pool: crypto/x509: system root pool is not available on Windows"
</code>```

Docker config file

```<code>{
    "ConfigVersion": 3,
    "Driver": {
        "IPAddress": "192.234.345.231",
        "MachineName": "default",
        "SSHUser": "docker",
        "SSHPort": 53944,
        "SSHKeyPath": "C:\\Users\\sbha5\\.docker\\machine\\machines\\default\\id_rsa",
        "StorePath": "C:\\Users\\sbha5\\.docker\\machine",
        "SwarmMaster": false,
        "SwarmHost": "tcp://0.0.0.0:3326",
        "SwarmDiscovery": "",
        "VBoxManager": {},
        "HostInterfaces": {},
        "CPU": 1,
        "Memory": 1024,
        "DiskSize": 60000,
        "NatNicType": "82540EM",
        "Boot2DockerURL": "",
        "Boot2DockerImportVM": "",
        "HostDNSResolver": false,
        "HostOnlyCIDR": "192.134.77.1/24",
        "HostOnlyNicType": "82540EM",
        "HostOnlyPromiscMode": "deny",
        "UIType": "headless",
        "HostOnlyNoDHCP": false,
        "NoShare": false,
        "DNSProxy": true,
        "NoVTXCheck": false,
        "ShareFolder": ""
    },
    "DriverName": "virtualbox",
    "HostOptions": {
        "Driver": "",
        "Memory": 0,
        "Disk": 0,
        "EngineOptions": {
            "ArbitraryFlags": [],
            "Dns": null,
            "GraphDir": "",
            "Env": [],
            "Ipv6": false,
            "InsecureRegistry": [],
            "Labels": [],
            "LogLevel": "",
            "StorageDriver": "",
            "SelinuxEnabled": false,
            "TlsVerify": true,
            "RegistryMirror": [],
            "InstallURL": "https://get.docker.com"
        },
        "SwarmOptions": {
            "IsSwarm": false,
            "Address": "",
            "Discovery": "",
            "Agent": false,
            "Master": false,
            "Host": "tcp://0.0.0.0:3326",
            "Image": "swarm:latest",
            "Strategy": "spread",
            "Heartbeat": 0,
            "Overcommit": 0,
            "ArbitraryFlags": [],
            "ArbitraryJoinFlags": [],
            "Env": null,
            "IsExperimental": false
        },
        "AuthOptions": {
            "CertDir": "C:\\Users\\sbha5\\.docker\\machine\\certs",
            "CaCertPath": "C:\\Users\\sbha5\\.docker\\machine\\certs\\ca.pem",
            "CaPrivateKeyPath": "C:\\Users\\sbha5\\.docker\\machine\\certs\\ca-key.pem",
            "CaCertRemotePath": "",
            "ServerCertPath": "C:\\Users\\sbha5\\.docker\\machine\\machines\\default\\server.pem",
            "ServerKeyPath": "C:\\Users\\sbha5\\.docker\\machine\\machines\\default\\server-key.pem",
            "ClientKeyPath": "C:\\Users\\sbha5\\.docker\\machine\\certs\\key.pem",
            "ServerCertRemotePath": "",
            "ServerKeyRemotePath": "",
            "ClientCertPath": "C:\\Users\\sbha5\\.docker\\machine\\certs\\cert.pem",
            "ServerCertSANs": [],
            "StorePath": "C:\\Users\\sbha5\\.docker\\machine\\machines\\default"
        }
    },
    "Name": "default"
}
</code>```

Docker info

```<code>$ docker info
time="2017-03-30T13:13:35+05:30" level=info msg="Unable to use system certificat
e pool: crypto/x509: system root pool is not available on Windows"
Containers: 0
 Running: 0
 Paused: 0
 Stopped: 0
Images: 0
Server Version: 17.03.1-ce
Storage Driver: aufs
 Root Dir: /mnt/sda1/var/lib/docker/aufs
 Backing Filesystem: extfs
 Dirs: 0
 Dirperm1 Supported: true
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
 Volume: local
 Network: bridge host macvlan null overlay
Swarm: inactive
Runtimes: runc
Default Runtime: runc
Init Binary: docker-init
containerd version: 4ab9917febca54791c5f071a9d1f404867857fcc
runc version: 54296cf40ad8143b62dbcaa1d90e520a2136ddfe
init version: 949e6fa
Security Options:
 seccomp
  Profile: default
Kernel Version: 4.4.57-boot2docker
Operating System: Boot2Docker 17.03.1-ce (TCL 7.2); HEAD : 4c264fa - Tue Mar 28
21:11:51 UTC 2017
OSType: linux
Architecture: x86_64
CPUs: 1
Total Memory: 995.8 MiB
Name: default
ID: WVD7:APIY:7JVZ:HEY7:TJKR:UH3U:PQLR:PTSK:OIOY:ERF3:UIPR:FRE3
Docker Root Dir: /mnt/sda1/var/lib/docker
Debug Mode (client): false
Debug Mode (server): true
 File Descriptors: 15
 Goroutines: 23
 System Time: 2017-03-30T07:43:35.782810077Z
 EventsListeners: 0
Username: cartdocker
Registry: https://index.docker.io/v1/
Labels:
 provider=virtualbox
Experimental: false
Insecure Registries:
 127.0.0.0/8
Live Restore Enabled: false
</code>```

If it's memory or storage issue please let me know how to increase memory. I'm using windows 7.

答:
Start by doing some cleaning of the unused/stopped images and containers.

```<code>$ docker ps -a
$ docker images -a
$ docker container prune
$ docker image prune
</code>```

You may also log in to boot2docker and inspect filesystem usage:

```<code>> boot2docker ssh
$ df -kh
</code>```

Additionally you may consider increasing boot2docker's volume size, although I didn't find it in live documentation (just this md).

Body:
I'm using docker on windows 7 and trying to download an image from cloud. After downloading while extraction i'm getting an error. Below is log snippet

cba922442da5: Downloading 5.866 GB/5.866 GB
10d186ab9b98: Download complete
89c26a498cda: Download complete
write /mnt/sda1/var/lib/docker/tmp/GetImageBlob601918967: no space left on devic
e

 Tools docker image has been downloaded or upgraded to the newer version success
fully if already exist

There are already several thread related to this issue & i have tried solution provided by them but they didn't work. i have tried to delete all the images using below command but got certificate error

$ docker ps -a -q
time="2017-03-30T13:09:16+05:30" level=info msg="Unable to use system certificat
e pool: crypto/x509: system root pool is not available on Windows"

Docker config file

{
    "ConfigVersion": 3,
    "Driver": {
        "IPAddress": "192.234.345.231",
        "MachineName": "default",
        "SSHUser": "docker",
        "SSHPort": 53944,
        "SSHKeyPath": "C:\\Users\\sbha5\\.docker\\machine\\machines\\default\\id_rsa",
        "StorePath": "C:\\Users\\sbha5\\.docker\\machine",
        "SwarmMaster": false,
        "SwarmHost": "tcp://0.0.0.0:3326",
        "SwarmDiscovery": "",
        "VBoxManager": {},
        "HostInterfaces": {},
        "CPU": 1,
        "Memory": 1024,
        "DiskSize": 60000,
        "NatNicType": "82540EM",
        "Boot2DockerURL": "",
        "Boot2DockerImportVM": "",
        "HostDNSResolver": false,
        "HostOnlyCIDR": "192.134.77.1/24",
        "HostOnlyNicType": "82540EM",
        "HostOnlyPromiscMode": "deny",
        "UIType": "headless",
        "HostOnlyNoDHCP": false,
        "NoShare": false,
        "DNSProxy": true,
        "NoVTXCheck": false,
        "ShareFolder": ""
    },
    "DriverName": "virtualbox",
    "HostOptions": {
        "Driver": "",
        "Memory": 0,
        "Disk": 0,
        "EngineOptions": {
            "ArbitraryFlags": [],
            "Dns": null,
            "GraphDir": "",
            "Env": [],
            "Ipv6": false,
            "InsecureRegistry": [],
            "Labels": [],
            "LogLevel": "",
            "StorageDriver": "",
            "SelinuxEnabled": false,
            "TlsVerify": true,
            "RegistryMirror": [],
            "InstallURL": "https://get.docker.com"
        },
        "SwarmOptions": {
            "IsSwarm": false,
            "Address": "",
            "Discovery": "",
            "Agent": false,
            "Master": false,
            "Host": "tcp://0.0.0.0:3326",
            "Image": "swarm:latest",
            "Strategy": "spread",
            "Heartbeat": 0,
            "Overcommit": 0,
            "ArbitraryFlags": [],
            "ArbitraryJoinFlags": [],
            "Env": null,
            "IsExperimental": false
        },
        "AuthOptions": {
            "CertDir": "C:\\Users\\sbha5\\.docker\\machine\\certs",
            "CaCertPath": "C:\\Users\\sbha5\\.docker\\machine\\certs\\ca.pem",
            "CaPrivateKeyPath": "C:\\Users\\sbha5\\.docker\\machine\\certs\\ca-key.pem",
            "CaCertRemotePath": "",
            "ServerCertPath": "C:\\Users\\sbha5\\.docker\\machine\\machines\\default\\server.pem",
            "ServerKeyPath": "C:\\Users\\sbha5\\.docker\\machine\\machines\\default\\server-key.pem",
            "ClientKeyPath": "C:\\Users\\sbha5\\.docker\\machine\\certs\\key.pem",
            "ServerCertRemotePath": "",
            "ServerKeyRemotePath": "",
            "ClientCertPath": "C:\\Users\\sbha5\\.docker\\machine\\certs\\cert.pem",
            "ServerCertSANs": [],
            "StorePath": "C:\\Users\\sbha5\\.docker\\machine\\machines\\default"
        }
    },
    "Name": "default"
}

Docker info

$ docker info
time="2017-03-30T13:13:35+05:30" level=info msg="Unable to use system certificat
e pool: crypto/x509: system root pool is not available on Windows"
Containers: 0
 Running: 0
 Paused: 0
 Stopped: 0
Images: 0
Server Version: 17.03.1-ce
Storage Driver: aufs
 Root Dir: /mnt/sda1/var/lib/docker/aufs
 Backing Filesystem: extfs
 Dirs: 0
 Dirperm1 Supported: true
Logging Driver: json-file
Cgroup Driver: cgroupfs
Plugins:
 Volume: local
 Network: bridge host macvlan null overlay
Swarm: inactive
Runtimes: runc
Default Runtime: runc
Init Binary: docker-init
containerd version: 4ab9917febca54791c5f071a9d1f404867857fcc
runc version: 54296cf40ad8143b62dbcaa1d90e520a2136ddfe
init version: 949e6fa
Security Options:
 seccomp
  Profile: default
Kernel Version: 4.4.57-boot2docker
Operating System: Boot2Docker 17.03.1-ce (TCL 7.2); HEAD : 4c264fa - Tue Mar 28
21:11:51 UTC 2017
OSType: linux
Architecture: x86_64
CPUs: 1
Total Memory: 995.8 MiB
Name: default
ID: WVD7:APIY:7JVZ:HEY7:TJKR:UH3U:PQLR:PTSK:OIOY:ERF3:UIPR:FRE3
Docker Root Dir: /mnt/sda1/var/lib/docker
Debug Mode (client): false
Debug Mode (server): true
 File Descriptors: 15
 Goroutines: 23
 System Time: 2017-03-30T07:43:35.782810077Z
 EventsListeners: 0
Username: cartdocker
Registry: https://index.docker.io/v1/
Labels:
 provider=virtualbox
Experimental: false
Insecure Registries:
 127.0.0.0/8
Live Restore Enabled: false

If it's memory or storage issue please let me know how to increase memory. I'm using windows 7.

Body:
Start by doing some cleaning of the unused/stopped images and containers.

$ docker ps -a
$ docker images -a
$ docker container prune
$ docker image prune

You may also log in to boot2docker and inspect filesystem usage:

> boot2docker ssh
$ df -kh

Additionally you may consider increasing boot2docker's volume size, although I didn't find it in live documentation (just this md).


问:
Mininet's CLI get error:Error setting resource limits. Mininet's performance may be affected
I'm new to mininet,I try two ways to install the lastest mininet:

sudo apt-get install mininet

install mininet by source code

I get this message: Error setting resource limits. Mininet's performance may be affected when I using sudo mn command to start the mininet CLI.

what is the message mean,I'm not limit any resource or my machine is not good enough?I see the issue like this,but I'm not docker.

答:
I get the anwser,because my ubuntu version is 3.0.13-100,a bug in this version.if you want to solve this problem,you need to update your kernl version

the bug is when you run the command like this:

$ sudo sysctl -w net.ipv4.neigh.default.gc_thresh1=128

get this error message:

error: "Invalid argument" setting key "net.ipv4.neigh.default.gc_thresh1"

this bug in version 3.0.13-96 to 3.0.13-100,the detail view this link

when mininet start,It will run the fixLimits() function:

def fixLimits():
    "Fix ridiculously small resource limits."
    debug( "*** Setting resource limits\n" )
    try:
        rlimitTestAndSet( RLIMIT_NPROC, 8192 )
        rlimitTestAndSet( RLIMIT_NOFILE, 16384 )
        #Increase open file limit
        sysctlTestAndSet( 'fs.file-max', 10000 )
        #Increase network buffer space
        sysctlTestAndSet( 'net.core.wmem_max', 16777216 )
        sysctlTestAndSet( 'net.core.rmem_max', 16777216 )
        sysctlTestAndSet( 'net.ipv4.tcp_rmem', '10240 87380 16777216' )
        sysctlTestAndSet( 'net.ipv4.tcp_wmem', '10240 87380 16777216' )
        sysctlTestAndSet( 'net.core.netdev_max_backlog', 5000 )
        #Increase arp cache size
        sysctlTestAndSet( 'net.ipv4.neigh.default.gc_thresh1', 4096 )
        sysctlTestAndSet( 'net.ipv4.neigh.default.gc_thresh2', 8192 )
        sysctlTestAndSet( 'net.ipv4.neigh.default.gc_thresh3', 16384 )
        #Increase routing table size
        sysctlTestAndSet( 'net.ipv4.route.max_size', 32768 )
        #Increase number of PTYs for nodes
        sysctlTestAndSet( 'kernel.pty.max', 20000 )
    # pylint: disable=broad-except
    except Exception:
        warn( "*** Error setting resource limits. "
              "Mininet's performance may be affected.\n" )
    # pylint: enable=broad-except


问:
On your very first program, which construct hooked you on programming?
To me it was the If statement, I'm psyched up, since then I believed that computers are very intelligent, or I can at least make it appear intelligent because of it.</p>

答:
For many of us who were introduced to computers in the late 70's or early 80's, the first program we saw looked like this:

```<code>10 PRINT "Commodore sucks!  "
20 GOTO 10
</code>```

("Commodore" could be replaced with "Apple", "Atari" or "TRS-80").

GOTO is awesome.

OwnerDisplayName: Michael Buen

LastEditorDisplayName: Triptych

Body:
For many of us who were introduced to computers in the late 70's or early 80's, the first program we saw looked like this:

10 PRINT "Commodore sucks!  "
20 GOTO 10

("Commodore" could be replaced with "Apple", "Atari" or "TRS-80").

GOTO is awesome.

OwnerDisplayName: Kristopher Johnson

LastEditorDisplayName: Kristopher Johnson


问:
How can I save an object to a file?
I would like to save an object to a file, and then read it from the file easily. As a simple example, lets say I have the following 3d array:

```<code>m = [[[0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]],
[[0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]]]
</code>```

Is there an easy Ruby API that I can use to achieve this without programming a parser to interpret the data from the file? In the example I give it is easy, but as the objects become more complicated, it gets annoying to make objects persistent.

答:
YAML and Marshal are the most obvious answers, but depending on what you're planning to do with the data, sqlite3 may be a useful option too. </p>

```<code>require 'sqlite3'

m = [[[0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]],
[[0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]]]

db=SQLite3::Database.new("demo.out")
db.execute("create table data (x,y,z,value)")
inserter=db.prepare("insert into data (x,y,z,value) values (?,?,?,?)")
m.each_with_index do |twod,z|
  twod.each_with_index do |row,y|
    row.each_with_index do |val,x|
      inserter.execute(x,y,z,val)
    end
  end
end
</code>```

Title: How can I save an object to a file?

Body:
I would like to save an object to a file, and then read it from the file easily. As a simple example, lets say I have the following 3d array:

m = [[[0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]],
[[0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]]]

Is there an easy Ruby API that I can use to achieve this without programming a parser to interpret the data from the file? In the example I give it is easy, but as the objects become more complicated, it gets annoying to make objects persistent.

Body:
YAML and Marshal are the most obvious answers, but depending on what you're planning to do with the data, sqlite3 may be a useful option too.

require 'sqlite3'

m = [[[0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]],
[[0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]]]

db=SQLite3::Database.new("demo.out")
db.execute("create table data (x,y,z,value)")
inserter=db.prepare("insert into data (x,y,z,value) values (?,?,?,?)")
m.each_with_index do |twod,z|
  twod.each_with_index do |row,y|
    row.each_with_index do |val,x|
      inserter.execute(x,y,z,val)
    end
  end
end


问:
iOS: How to prevent table from updating if row is currently being swiped?
I have a table that is being populated by a Firebase database. The user can swipe each row left and right, which causes the row to disappear. This is coming from this library: https://github.com/alikaragoz/MCSwipeTableViewCell

If I'm in the middle of swiping a row and the table updates with new data, my swipe gesture resets and the row that I was swiping gets pushed down.

Is there a way to prevent updates on the table while one of the rows is currently being interacted with?

答:
Probably, the reason of the issue is that you are -somehow- calling tableView.reloadData() after getting new data (which sounds ok), the updating of the table view causes to edit the number of its rows which leads to push the current swiped cell.

The solution is to check if there is a cell swiping currently happening to prevent the calling of tableView.reloadData(), this should be done after the swiping finished. Fortunately, after checking the used MCSwipeTableViewCell library, I found how to check such a functionality, by conforming to MCSwipeTableViewCellDelegate as follows:

Implement swipeTableViewCellDidStartSwiping: to prevent tableView.reloadData().

Implement swipeTableViewCell:didEndSwipingSwipingWithState:mode: to make sure that the swiping ended and then calling tableView.reloadData().

Of course the logic of how you will do the checking is up to you, but -hopefully- this guides you to solve the issue.

Hope this helped.


问:
What physical resources will I need for web application built on java + tomcat + mysql?
I want to create dynamic website using java + tomcat + mysql. I want to buy some space on linode.com or digitalocean but I want to know what resources will application need to run normal way ( I am not expecting many users at all, 2-5 at the same time maximum).

Also I do not know which linux distro should I use to minimize cost.

答:
RAM:

for the system like Ubuntu you need 512Mo

for Tomcat you need 256Mo--->512Mo  (small applications),

for Mysql you need 256Mo,

and if you use Plesk you will need 512Mo

ROM:

also it depends on your application and your database

I'm using a 2 GB RAM vps to host one java application for dialysis center, 2 wordpress website , plesk and mysql


问:
c++ class-to-class data transfer
I am working in c++, i want to input from text file then transfer to the variables in the class. I have 2 classes: class A and class B which are present by:

```<code>class A
{
   public:
   double i;
   double r;

   double function(double s)
   {
      i = s*s+r;
      return i;
   };

class B: public A
{
  public:
     A A;
     int c;
     double e;
     e = A.r;
     c = A.function(c);
     double h;
     h=e+c;
};

int main()
{
   ifstream data;

   double f[3];

   data.open("A.txt", ios::in);

   for (int i = 0; i <3; i++)
   {
     data>> f[i];
   }
   A A;
   A.r = f[0];
};
</code>```

the r that I input in class A didn't remain values when I use it in class B. I don't know how to deal with this problem. please help me!! thank you co much!!!

答: I think you are confused by the fact that your class B contains two instances of class A: first is inhered public A and the second is a field A A; So every instance of class B will have b.r field and b.A.r field. This is allowed by language, but in this case you probably need only one of them.</p>

Title: c++ class-to-class data transfer

Body:
I am working in c++, i want to input from text file then transfer to the variables in the class. I have 2 classes: class A and class B which are present by:

class A
{
   public:
   double i;
   double r;

   double function(double s)
   {
      i = s*s+r;
      return i;
   };

class B: public A
{
  public:
     A A;
     int c;
     double e;
     e = A.r;
     c = A.function(c);
     double h;
     h=e+c;
};

int main()
{
   ifstream data;

   double f[3];

   data.open("A.txt", ios::in);

   for (int i = 0; i <3; i++)
   {
     data>> f[i];
   }
   A A;
   A.r = f[0];
};

the r that I input in class A didn't remain values when I use it in class B. I don't know how to deal with this problem. please help me!! thank you co much!!!


问:
HTML5 save Canvas image every few seconds
How can I save every few seconds a canvas Image to a Folder.

I have a Basic canvas drawing function and a download function to save the image like this:

```<code><canvas></canvas>

var link = document.createElement('a');
    link.innerHTML = 'download image';
link.addEventListener('click', function(ev) {
    link.href = canvas.toDataURL();
    link.download = "mypainting.png";
}, false);
document.body.appendChild(link);
</code>```

I want to implemente a button named start / stop.

If the user clicks on that button I want to save every second the canvas Image.

Every Image shall be saved as a new file.

How would this be possible?
Is it even possible?

答:
Yes it is possible. Browser will ask the user to allow multiple file download. It will only download multiple images if user clicks confirms that he/she want to allow multiple file download.

var canvas = document.getElementById('canvas'),
    ctx = canvas.getContext('2d');

function doCanvas() {
    ctx.fillStyle = '#f90';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = '#fff';
    ctx.font = '30px sans-serif';
    ctx.fillText('Code Project', 10, canvas.height / 2 - 15);
    ctx.font = '13px sans-serif';
    ctx.fillText('Click start to download images', 15, canvas.height / 2 + 35);
}

function downloadCanvas(link, canvasId, filename) {
  link.href = document.getElementById(canvasId).toDataURL();
  link.download = filename;
}

document.getElementById('download').addEventListener('click', function() {
    downloadCanvas(this, 'canvas', 'test.png');
}, false);

doCanvas();

$( document ).ready(function() {
  $('#start').on('click', function() {
    if( confirm('This will continue download image every 2 second, do you want to proceed?') ) {
      setInterval(function() {
          $('#download')[0].click();
        }, 2000);
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background-color:#555557;
  padding:0;
  margin:0;
  overflow:hidden;
  font-family:sans-serif;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
canvas {
  border:1px solid #000;
  float:left;
  clear:both;
}
#download {
  float:left;
  cursor:pointer;
  color:#ccc;
  padding:3px;
}
#download:hover {
  color:#fff;
}</code>```

<canvas width="250" height="150" id="canvas">Sorry, no canvas available</canvas>

Make sure you have not blocked multiple file downloads.

<button id="start">Start</button>```

SOURCE

Body:
How can I save every few seconds a canvas Image to a Folder.

I have a Basic canvas drawing function and a download function to save the image like this:

<canvas></canvas>

var link = document.createElement('a');
    link.innerHTML = 'download image';
link.addEventListener('click', function(ev) {
    link.href = canvas.toDataURL();
    link.download = "mypainting.png";
}, false);
document.body.appendChild(link);

I want to implemente a button named start / stop.

If the user clicks on that button I want to save every second the canvas Image.

Every Image shall be saved as a new file.

How would this be possible?
Is it even possible?

Body:
Yes it is possible. Browser will ask the user to allow multiple file download. It will only download multiple images if user clicks confirms that he/she want to allow multiple file download.

var canvas = document.getElementById('canvas'),
    ctx = canvas.getContext('2d');

function doCanvas() {
    ctx.fillStyle = '#f90';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = '#fff';
    ctx.font = '30px sans-serif';
    ctx.fillText('Code Project', 10, canvas.height / 2 - 15);
    ctx.font = '13px sans-serif';
    ctx.fillText('Click start to download images', 15, canvas.height / 2 + 35);
}

function downloadCanvas(link, canvasId, filename) {
  link.href = document.getElementById(canvasId).toDataURL();
  link.download = filename;
}

document.getElementById('download').addEventListener('click', function() {
    downloadCanvas(this, 'canvas', 'test.png');
}, false);

doCanvas();

$( document ).ready(function() {
  $('#start').on('click', function() {
    if( confirm('This will continue download image every 2 second, do you want to proceed?') ) {
      setInterval(function() {
          $('#download')[0].click();
        }, 2000);
    }
  });
});

body {
  background-color:#555557;
  padding:0;
  margin:0;
  overflow:hidden;
  font-family:sans-serif;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
canvas {
  border:1px solid #000;
  float:left;
  clear:both;
}
#download {
  float:left;
  cursor:pointer;
  color:#ccc;
  padding:3px;
}
#download:hover {
  color:#fff;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas width="250" height="150" id="canvas">Sorry, no canvas available</canvas>
<p>Make sure you have not blocked multiple file downloads.</p>
<a id="download"> </a>
<button id="start">Start</button>

SOURCE


问:
HTML5 Polymer custom element styling with attributes
I'm trying out Polymer and custom elements. Trying to make a
 inside the element a certain colour by passing the attribute value. So my element code looks like this:

```<code><polymer-element name="test-element" attributes="nameColor">
  <template>
    Hello! My name is <span style="color:{{nameColor}}">Robert</span>
    <h1> oioioi </h1>

  <style>
  h1 {
    color:{{nameColor}};
  }
  </style>

  </template>
  <script>

    Polymer('test-element', {
      nameColor: "blue"
    });

  </script>
</polymer-element>
</code>```

So, then I use the element like this:

```<code><test-element nameColor="red"></test-element>
</code>```

The thing is, my name (Robert) is now red. Which is good. But the h1 element is not red. Why not? If I change color:{{nameColor}}; within the style tag to color:red; it works, but I don't want that obviously. So does the attribute value not get passed to the style? Any hints on why this is happening and where I should look for more info? I've read some blogs but don't find any specific info on this.

Thanks. :-)

答:
You can change:

```<code><span style="color:{{nameColor}}">Robert</span>
</code>```

to

```<code><span style$="color:{{nameColor}};">Robert</span>
</code>```

and remove it form the  block and it should work.

//edit

You probably have to change:

```<code>Polymer('test-element', {
  nameColor: "blue"
});
</code>```

to:

```<code>Polymer('test-element', {
  properties:{
    nameColor: {
      type: String,
      value: "blue"
    }
  }
});
</code>```

Body:
I'm trying out Polymer and custom elements. Trying to make a
 inside the element a certain colour by passing the attribute value. So my element code looks like this:

<polymer-element name="test-element" attributes="nameColor">
  <template>
    Hello! My name is Robert

 oioioi

  </template>

</polymer-element>

So, then I use the element like this:

<test-element nameColor="red"></test-element>

The thing is, my name (Robert) is now red. Which is good. But the h1 element is not red. Why not? If I change color:{{nameColor}}; within the style tag to color:red; it works, but I don't want that obviously. So does the attribute value not get passed to the style? Any hints on why this is happening and where I should look for more info? I've read some blogs but don't find any specific info on this.

Thanks. :-)

Body:
You can change:

<span style="color:{{nameColor}}">Robert</span>

to

<span style$="color:{{nameColor}};">Robert</span>

and remove it form the  block and it should work.

//edit

You probably have to change:

Polymer('test-element', {
  nameColor: "blue"
});

to:

Polymer('test-element', {
  properties:{
    nameColor: {
      type: String,
      value: "blue"
    }
  }
});


答:
Smallest answer to above is:</p>

```<code>df$GDP <- substring(df$GDP, 2)
</code>```

Title: How to remover certain caracters from each row of a column

Body:
I have this data table:

Year    GDP
1998–99 1,668,739
1999–00 1,858,205
2000–01 2,000,743
2001–02 2,175,260
2002–03 2,343,864
2003–04 2,625,819
2004–05 2,971,464
2005–06 3,390,503
2006–07 3,953,276
2007–08 4,582,086
2008–09 5,303,567
2009–10 6,108,903
2010–11 7,248,860
2011–12 8,391,691
2012–13 9,388,876

What I want to do is to remove "" from all of the rows. How can I do it?

I was trying with grepl and grep, but did not work for me:

df[!grepl("", df$GDP),]

df[ grep("REVERSE", df$Name, invert = TRUE) , ]

These do not work for me...

What I want is something like this:

Year    GDP
1998–99 1,668,739
1999–00 1,858,205
2000–01 2,000,743
2001–02 2,175,260
2002–03 2,343,864
2003–04 2,625,819
2004–05 2,971,464
2005–06 3,390,503
2006–07 3,953,276
2007–08 4,582,086
2008–09 5,303,567
2009–10 6,108,903
2010–11 7,248,860
2011–12 8,391,691
2012–13 9,388,876

I also tried using below solution but did not work for me either...
How to identify/delete non-UTF-8 characters in R

x <- ""
Encoding(x) <- "UTF-8"
iconv(x, "UTF-8", "UTF-8",sub='')

returns me "" as it is...

Body:
Smallest answer to above is:

df$GDP <- substring(df$GDP, 2)


问:
How to convert RDD of Avro's GenericData.Record to DataFrame?
Perhaps this question may seem a bit abstract, here it is:

```<code>val originalAvroSchema : Schema   = // read from a file
val rdd : RDD[GenericData.Record] = // From some streaming source

// Looking for a handy:
val df: DataFrame   = rdd.toDF(schema)
</code>```

I explore spark-avro but it has support only to read from a file, not from existing RDD.

答:
```<code>import com.databricks.spark.avro._

val sqlContext = new SQLContext(sc)
val rdd : RDD[MyAvroRecord] = ...
val df = rdd.toAvroDF(sqlContext)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Perhaps this question may seem a bit abstract, here it is:

val originalAvroSchema : Schema   = // read from a file
val rdd : RDD[GenericData.Record] = // From some streaming source

// Looking for a handy:
val df: DataFrame   = rdd.toDF(schema)

I explore spark-avro but it has support only to read from a file, not from existing RDD.


问:
Call a method of the object which is created in another class
I have a little problem.

I have a 3 classes looks "like" this:

```<code>public class Gun{
    public void Shot(){
        // shoot code
    }

    public void RenderGun()
    {
        // render code
    }

    // more methods
}

public class GameManager
{
    Gun gun;

    public GameManager()
    {
        gun = new Gun();
    }

    // methods using GunClass methods.
}

public class HudScreen
{
    Gun gun;

    public HudScreen()
    {
        gun = new Gun();
    }

    public void GunShotButton()
    {
        gun.Shoot();
    }
}
</code>```

The problem is I have two Gun objects and i want to have one but use it in both classes HudScreen and GameManager.

So, if I create a new Gun object in GameManager, how to "call" this object from the HudScreen class?

Thanks, MM.

答:
Change constructors in that way:

```<code>public GameManager(Gun gun) {
   this.gun = gun;
}
</code>```

and the same in HudScreen class.
Then in some Main class:

```<code>class Main {
   public static void main(String[] args) {
      Gun gun = new Gun();
      HudScreen hudScreen = new HudScreen(gun);
      GameManager gameManager = new GameManager(gun)
   }
}
</code>```

Currently main method is assumed to be the top level method doing the initilization. This may be some other method as well where objects of Gun , GunManager and HudScreen are created.

Body:
I have a little problem.

I have a 3 classes looks "like" this:

public class Gun{
    public void Shot(){
        // shoot code
    }

    public void RenderGun()
    {
        // render code
    }

    // more methods
}

public class GameManager
{
    Gun gun;

    public GameManager()
    {
        gun = new Gun();
    }

    // methods using GunClass methods.
}

public class HudScreen
{
    Gun gun;

    public HudScreen()
    {
        gun = new Gun();
    }

    public void GunShotButton()
    {
        gun.Shoot();
    }
}

The problem is I have two Gun objects and i want to have one but use it in both classes HudScreen and GameManager.

So, if I create a new Gun object in GameManager, how to "call" this object from the HudScreen class?

Thanks, MM.

Body:
Change constructors in that way:

public GameManager(Gun gun) {
   this.gun = gun;
}

and the same in HudScreen class.
Then in some Main class:

class Main {
   public static void main(String[] args) {
      Gun gun = new Gun();
      HudScreen hudScreen = new HudScreen(gun);
      GameManager gameManager = new GameManager(gun)
   }
}

Currently main method is assumed to be the top level method doing the initilization. This may be some other method as well where objects of Gun , GunManager and HudScreen are created.


问:
Change order of custom attachments in Worpdress
I have to change the order of the image attachments that I add to my custom post types. They use the plugin called "WP Better Attachments" but there is no option to change the order in the backend (dragging, changing the title or time of upload does not change the order).

I searched for the code and this is what I found:

```<code><?php
                        $id = icl_object_id(get_the_ID(), 'momenten', true, 'nl');
                        $attachments = get_posts( array(

                            'post_type' => 'attachment',

                            'posts_per_page' => -1,

                            'post_parent' => $id ,

                            'exclude'     => get_post_thumbnail_id()

                        ) );

                        if ( $attachments ) {

                            foreach ( $attachments as $attachment ) {

                                $thumbimg = wp_get_attachment_image_src( $attachment->ID, 'bs-tumb', true );

                                $thumbimgbig = wp_get_attachment_image_src( $attachment->ID, 'large', true );

                                echo '<div class="small-12 medium-4 large-4 columns vxf"  itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">

                                <a href="'.$thumbimgbig[0].'" class="gallery-item" title="'.get_field('titel_afbeelding_'.ICL_LANGUAGE_CODE, $attachment->ID).'"  itemprop="contentUrl" data-size="'.$thumbimgbig[1].'x'.$thumbimgbig[2].'"><img src="' . $thumbimg[0] . '" class="thumbnail"  alt="'.get_post($attachment->ID)->post_title.'" temprop="thumbnail" ></a><div class="descrip" itemprop="caption description">'.get_field('titel_afbeelding_'.ICL_LANGUAGE_CODE, $attachment->ID).'</div></div>';

                            }

                        }

                    ?>
</code>```

Sadly my knowledge of php is limited so any kind of help will be greatly appreciated.

答:
The Wordpress get_posts function can take arguments in an array that help with sorting. Some arguments are already being passed - eg the post_parent argument.

You don't mention how you want the posts to be ordered, but there are quite a few options. For example, to sort by attachment name, in descending order, you can add:

```<code>$attachments = get_posts( array(
    'post_type' => 'attachment',
    'posts_per_page' => -1,
    'post_parent' => $id ,
    'exclude'     => get_post_thumbnail_id()
    'orderby'     => 'date',
    'order'       => 'DESC',
 ) );
</code>```

You can see the full list of available options in the WP docs.

Be aware that if you add custom code to the plugin, it might get overwritten when you upgrade the plugin. For some plugins, there is a special file that is preserved between upgrades, but using it would require you integrate your custom sorting code with the plugin, which is a little more complex than the solution here.

Body:
I have to change the order of the image attachments that I add to my custom post types. They use the plugin called "WP Better Attachments" but there is no option to change the order in the backend (dragging, changing the title or time of upload does not change the order).

I searched for the code and this is what I found:

<?php
                        $id = icl_object_id(get_the_ID(), 'momenten', true, 'nl');
                        $attachments = get_posts( array(

                            'post_type' => 'attachment',

                            'posts_per_page' => -1,

                            'post_parent' => $id ,

                            'exclude'     => get_post_thumbnail_id()

                        ) );

                        if ( $attachments ) {

                            foreach ( $attachments as $attachment ) {

                                $thumbimg = wp_get_attachment_image_src( $attachment->ID, 'bs-tumb', true );

                                $thumbimgbig = wp_get_attachment_image_src( $attachment->ID, 'large', true );

                                echo '

                                ID).'"  itemprop="contentUrl" data-size="'.$thumbimgbig[1].'x'.$thumbimgbig[2].'">ID)->post_title.'" temprop="thumbnail" >
'.get_field('titel_afbeelding_'.ICL_LANGUAGE_CODE, $attachment->ID).'

';

                            }

                        }

                    ?>

Sadly my knowledge of php is limited so any kind of help will be greatly appreciated.

Body:
The Wordpress get_posts function can take arguments in an array that help with sorting. Some arguments are already being passed - eg the post_parent argument.

You don't mention how you want the posts to be ordered, but there are quite a few options. For example, to sort by attachment name, in descending order, you can add:

$attachments = get_posts( array(
    'post_type' => 'attachment',
    'posts_per_page' => -1,
    'post_parent' => $id ,
    'exclude'     => get_post_thumbnail_id()
    'orderby'     => 'date',
    'order'       => 'DESC',
 ) );

You can see the full list of available options in the WP docs.

Be aware that if you add custom code to the plugin, it might get overwritten when you upgrade the plugin. For some plugins, there is a special file that is preserved between upgrades, but using it would require you integrate your custom sorting code with the plugin, which is a little more complex than the solution here.


问:
PHP - limit the file size but somehow got Warning: POST Content-Length exceeds the limit
I wanted to test out the file upload code. This is an upload file code and it has the option whether the user has the file to upload or just submit it blankly. I added the error message to limit the file extension. It works.

Then, I added an error message to notify the user about the limit file size. But somehow got the Warning: POST Content-Length of 681075903 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

instead of the error message of "Sorry, your file is too large. Only 3MB allowed"  from the php code.

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

<form method="post" action="" enctype="multipart/form-data">

    Upload File:
    <input type="file" name="upload" /><br>
    <input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>

<?php
include("config.php");
if(isset($_POST['submit'])  ){

//user has the option whether to upload the file or not
if ($_FILES['upload']['size'] != 0 ){

$filename = $con->real_escape_string($_FILES['upload']['name']);
$filedata= $con->real_escape_string(file_get_contents($_FILES['upload']['tmp_name']));
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);

$allowed =  array('zip','rar', 'pdf', 'doc', 'docx');
$ext = pathinfo($filename, PATHINFO_EXTENSION);

if(in_array($ext, $allowed)){

            if($filesize > 3000000) {
                $query = "INSERT INTO contracts(`filename`,`filedata`, `filetype`,`filesize`) VALUES ('$filename','$filedata','$filetype','$filesize')" ;

                if ($con->query($query) == TRUE) {
                echo "<br><br> New record created successfully";
                } else {
                echo "Error:<br>" . $con->error;
                }

                }
            else{
                echo "Sorry, your file is too large. Only 3MB allowed";
            }
        }
        else{
            echo "Sorry, only zip, rar, pdf, doc & docs files are allowed.";
        }

//if user has no file to upload then proceed to this else statement
} else {

$filename = $con->real_escape_string($_FILES['upload']['name']);
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);

$query = "INSERT INTO contracts(`filename`, `filetype`,`filesize`) VALUES ('$filename','$filetype','$filesize')" ;

if ($con->query($query) == TRUE) {
echo "<br><br> New record created successfully";
} else {
echo "Error:<br>" . $con->error;
}

}
$con->close();
}

?>
</code>```

I don't get it. What did I do wrong in this code?

I think it is the if ($_FILES['upload']['size'] != 0 ){ part that gave the problem but I still want my user to have it optional to upload.

答:
Can you post the form HTML code ?

The problem is, php has a directive (post_max_size) that limits the size of what he allows in POST - before any execution of your script. So, if this limit is reached, the warning is emitted before your script is called, and $_POST is not filled in.

It would deserves additional testing, but be sure :

to include MAX_FILE_SIZE hidden field in your form (see http://php.net/manual/en/features.file-upload.post-method.php).

to set post_max_size to something largely greater to what you want to accept

to set upload_max_filesize to (at first sight) the value you want.

In addition, it would also be intersting to try setting the maxlength attributes on the input, as this is is stated in the RFC-1867.

If the INPUT tag includes the attribute MAXLENGTH, the user agent should consider its value to represent the maximum Content-Length which the server will accept for transferred files.

In this way, servers can hint to the client how much space they have available for a file upload, before that upload takes place.  It is important to note, however, that this is only a hint, and the actual requirements of the server may change between form creation and file submission.

This would allow to forbid the upload directly in the browser that respect the RFC.

Body:
I wanted to test out the file upload code. This is an upload file code and it has the option whether the user has the file to upload or just submit it blankly. I added the error message to limit the file extension. It works.

Then, I added an error message to notify the user about the limit file size. But somehow got the Warning: POST Content-Length of 681075903 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

instead of the error message of "Sorry, your file is too large. Only 3MB allowed"  from the php code.

<form method="post" action="" enctype="multipart/form-data">

    Upload File:
    <input type="file" name="upload" />

    <input type="submit" name="submit" value="Submit"/>
</form>

<?php
include("config.php");
if(isset($_POST['submit'])  ){

//user has the option whether to upload the file or not
if ($_FILES['upload']['size'] != 0 ){

$filename = $con->real_escape_string($_FILES['upload']['name']);
$filedata= $con->real_escape_string(file_get_contents($_FILES['upload']['tmp_name']));
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);

$allowed =  array('zip','rar', 'pdf', 'doc', 'docx');
$ext = pathinfo($filename, PATHINFO_EXTENSION);

if(in_array($ext, $allowed)){

            if($filesize > 3000000) {
                $query = "INSERT INTO contracts(`filename`,`filedata`, `filetype`,`filesize`) VALUES ('$filename','$filedata','$filetype','$filesize')" ;

                if ($con->query($query) == TRUE) {
                echo "

 New record created successfully";
                } else {
                echo "Error:
" . $con->error;
                }

                }
            else{
                echo "Sorry, your file is too large. Only 3MB allowed";
            }
        }
        else{
            echo "Sorry, only zip, rar, pdf, doc & docs files are allowed.";
        }

//if user has no file to upload then proceed to this else statement
} else {

$filename = $con->real_escape_string($_FILES['upload']['name']);
$filetype = $con->real_escape_string($_FILES['upload']['type']);
$filesize = intval($_FILES['upload']['size']);

$query = "INSERT INTO contracts(`filename`, `filetype`,`filesize`) VALUES ('$filename','$filetype','$filesize')" ;

if ($con->query($query) == TRUE) {
echo "

 New record created successfully";
} else {
echo "Error:
" . $con->error;
}

}
$con->close();
}

?>

I don't get it. What did I do wrong in this code?

I think it is the if ($_FILES['upload']['size'] != 0 ){ part that gave the problem but I still want my user to have it optional to upload.


问:
How to separate letters and digits from a string in php
I have a string which is combination of letters and digits. For my application i have to separate a string with letters and digits:  ex:If my string is "12jan" i hav to get "12" "jan" separately..</p>

答:
Try This :</p>

```<code>$string="12jan";
$chars = '';
$nums = '';
for ($index=0;$index<strlen($string);$index++) {
    if(isNumber($string[$index]))
        $nums .= $string[$index];
    else
        $chars .= $string[$index];
}
echo "Chars: -$chars-<br>Nums: -$nums-";

function isNumber($c) {
    return preg_match('/[0-9]/', $c);
}
</code>```

Body:
Try This :

$string="12jan";
$chars = '';
$nums = '';
for ($index=0;$index<strlen($string);$index++) {
    if(isNumber($string[$index]))
        $nums .= $string[$index];
    else
        $chars .= $string[$index];
}
echo "Chars: -$chars-<br>Nums: -$nums-";

function isNumber($c) {
    return preg_match('/[0-9]/', $c);
}


问:
Set router link for select list in vue js2.0
I want to set for select drop down list

<select name="educationOption" class="form-control">
          <option>
            Search for SSC Course
          </option>
          <option v-link="'/higherEducationDetails/'+ user_id">
              Search for Higher Education
          </option>
</select>```
</div>
</div>
</p>

<p>I tried this also, but not working</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> <select name="educationOption" class="form-control">
          <option>
            Search for SSC Course
          </option>
          <option>
            <router-link :to="'/higherEducationDetails/'+ $route.params.id">
              Search for Higher Education
            </router-link>
          </option>
        </select></code>```

Any suggestion

答:
Edit :

router-link by default is not gonna work inside select tags however we can do some trick for example:

we can define a normal option tag :

```<code><option>
   educationOption
</option>
</code>```

and add event listener on change select value:

```<code> <select name="educationOption" class="form-control" v-on:change="changeRoute">
</code>```

and then add changeRoute method to our vue:

```<code>export default {
        data() {
            return {
                id: 1
            }
        },
        methods: {
            changeRout() {
                this.$router.push({path:'/educationOption/' + this.id })
            }
        }
    }
</code>```

Body:
I want to set for select drop down list

<select name="educationOption" class="form-control">
          <option>
            Search for SSC Course
          </option>
          <option v-link="'/higherEducationDetails/'+ user_id">
              Search for Higher Education
          </option>
</select>

I tried this also, but not working

 <select name="educationOption" class="form-control">
          <option>
            Search for SSC Course
          </option>
          <option>
            <router-link :to="'/higherEducationDetails/'+ $route.params.id">
              Search for Higher Education
            </router-link>
          </option>
        </select>

Any suggestion

Body:
Edit :

router-link by default is not gonna work inside select tags however we can do some trick for example:

we can define a normal option tag :

<option>
   educationOption
</option>

and add event listener on change select value:

 <select name="educationOption" class="form-control" v-on:change="changeRoute">

and then add changeRoute method to our vue:

export default {
        data() {
            return {
                id: 1
            }
        },
        methods: {
            changeRout() {
                this.$router.push({path:'/educationOption/' + this.id })
            }
        }
    }


问:
\r character in shell script
I get the below error while trying to execute a shell script,

```<code>$'\r': command not found: line 2:
</code>```

Please suggest a solution for the same.

Below are the intial lines used in the script,

```<code>#!/bin/sh

if [[ $# -lt 1 ]]; then
   echo "ERROR Environment argument missing <dev,test,qa,prod>"
   export RC=50
   exit $RC
fi
</code>```

答:
I had the same error and what I did was to transform the characters '\r' to '\n'. using this line:

```<code>tr '\r' '\n' < oldfile.sh > newfile.sh
mv newfile.sh oldfile.sh
chmod +x oldfile.sh
./oldfile.sh
</code>```

I think you could also delete the '\r' characters by using:

```<code>tr -d '\r' < oldfile.sh > newfile.sh
</code>```

tr is the command trasnform, and the -d is delete the following character.

I think the shell actually doesn't like '\r' character.

Title: \r character in shell script

Body:
I get the below error while trying to execute a shell script,

$'\r': command not found: line 2:

Please suggest a solution for the same.

Below are the intial lines used in the script,

#!/bin/sh

if [[ $# -lt 1 ]]; then
   echo "ERROR Environment argument missing <dev,test,qa,prod>"
   export RC=50
   exit $RC
fi

Body:
I had the same error and what I did was to transform the characters '\r' to '\n'. using this line:

tr '\r' '\n' < oldfile.sh > newfile.sh
mv newfile.sh oldfile.sh
chmod +x oldfile.sh
./oldfile.sh

I think you could also delete the '\r' characters by using:

tr -d '\r' < oldfile.sh > newfile.sh

tr is the command trasnform, and the -d is delete the following character.

I think the shell actually doesn't like '\r' character.


问:
Naming of word combination
Assuming "A B C D" to be a sentence, is there any dedicated name for two following string deconstructions :

1)

size:3 <=> {"ABC", "BCD"}

size:2 <=> {"AB","BC", "CD"}

2)

size:3 <=> {"ABC", "ABD", "BCD"}

size:2 <=> {"AB","AC", "AD", "BC", "BD", "CD"}

Please, note that we never permute elements...

Thank you in advance,

-Bast

答:
Like java code</p>

```<code>String sequence = "A B C D";

public List createConventions(String sequence,int mode) {
    List<String> result = new ArrayList<>();
    String[] elements = sequence.split(" ");
    for (int i = 0; i < elements.length; i++) {
        for (int j = i + 1; j < elements.length; j++) {
            if (mode == 1) {
                result.add(elements[i] + elements[j]);
            } else if (mode == 2) {
                for (int k = j + 1; k < elements.length; k++) {
                    result.add(elements[i] + elements[j] + elements[k]);
                }
            }
        }
    }
    return result;
}
</code>```

Title: Naming of word combination

Body:
Like java code

String sequence = "A B C D";

public List createConventions(String sequence,int mode) {
    List<String> result = new ArrayList<>();
    String[] elements = sequence.split(" ");
    for (int i = 0; i < elements.length; i++) {
        for (int j = i + 1; j < elements.length; j++) {
            if (mode == 1) {
                result.add(elements[i] + elements[j]);
            } else if (mode == 2) {
                for (int k = j + 1; k < elements.length; k++) {
                    result.add(elements[i] + elements[j] + elements[k]);
                }
            }
        }
    }
    return result;
}


问:
Who sent you?
I have a series of input forms, all of them take a different form action. Each of those validates input. If ok, they go to different success pages. If fail, I want the form action/validation pages to set $_SESSION['error_messages'] and go to a common page which displays the errors and has a "resubmit" button.

Question ... how to get error form the resubmit button back to one of many possible input forms?

Edit: I don't see how $_SERVER['HTTP_REFERER'] is going to work. Again: form --> validation --> error_page

So, I guess that validation has to set  a session variable from $_SERVER['HTTP_REFERER']

答:
You can use the HTTP_REFERER header, but this is not always reliable as the browser needs to set this.

A more reliable way would be to set a hidden field in each form with the url to redirect back to.

Title: Who sent you?


问:
Standard or Legacy SQL for Google Analytics Data in BigQuery?
we are just starting to use Google Analytics data in BigQuery and previously used just the MSSQL Server in the work environment. We would like to move some of the analysis to the GCP and BigQuery, but could not decide on what is the better option to use - standard or legacy SQL?<br>
In both cases we would have to adjust to the new language version, but the real question is what is the best choice when it comes to Google Analytics data analysis? Is there something that from the technical point of view should make us choose legacy over standard, or the other way around?
It is very misleading for us that there are two versions, because legacy seems to be more developed now, but perphaps standard will be the main version for SQL in the future in BQ? </p>

答: Standard SQL is the preferred SQL dialect for use in BigQuery, as stated in the migration guide. While legacy SQL has been around for quite some time--and is still the default at the time of this writing--there is no active development work on it. If you are evaluating which to use, you should pick standard SQL, since in addition to being more similar to T-SQL (SQL Server's dialect) it is more expressive, has fewer surprising edge cases, and generally has more features.</p>

Body:
we are just starting to use Google Analytics data in BigQuery and previously used just the MSSQL Server in the work environment. We would like to move some of the analysis to the GCP and BigQuery, but could not decide on what is the better option to use - standard or legacy SQL?

In both cases we would have to adjust to the new language version, but the real question is what is the best choice when it comes to Google Analytics data analysis? Is there something that from the technical point of view should make us choose legacy over standard, or the other way around?
It is very misleading for us that there are two versions, because legacy seems to be more developed now, but perphaps standard will be the main version for SQL in the future in BQ?


问:
Regex: match words between certain characters, but not between other certain characters (in .NET)
I want to match all the words in brackets, including brackets, which are not between simple quotation marks (in .NET):

```<code>"[field1] = 'id1'" -> match "[field1]"
"[field1] = '[field2]'" -> match "[field1]"
"[ field1 ] = '[ field2 ]'" -> match "[ field1 ]"
"[ field1 ] = '[ field2 ] field3'" -> match "[ field1 ]"
"[field1] = ' [field2] ' And [field3] = '[field4] '' [field5]'" -> match "[field1]" and "[field3]"
</code>```

Any suggestion would be greatly appreciated!

答:
As @horcrux also pointed out, you can use negative lookbehind and lookahead. Since apparently C# supports infinite repetition, you could get away with:

```<code>"(?<!(')\s*)" + "\[[^\[\]]+\]" + "(?!\s*$1)
</code>```

Separated the three parts, the negative lookbehind, the capturing match and the negative lookahead.

Note also that since the lookarounds are non-capturing, you don't even need parenthesis around the middle part.

In Java this would be something like:

```<code>"(?<!(')\s{0,1000})" + "\[[^\[\]]+\]" + "(?!\s{0,1000}$1)
</code>```

but it's kinda' hacky, as it would only work for 1000 spaces between the two.

Body:
I want to match all the words in brackets, including brackets, which are not between simple quotation marks (in .NET):

"[field1] = 'id1'" -> match "[field1]"
"[field1] = '[field2]'" -> match "[field1]"
"[ field1 ] = '[ field2 ]'" -> match "[ field1 ]"
"[ field1 ] = '[ field2 ] field3'" -> match "[ field1 ]"
"[field1] = ' [field2] ' And [field3] = '[field4] '' [field5]'" -> match "[field1]" and "[field3]"

Any suggestion would be greatly appreciated!

Body:
As @horcrux also pointed out, you can use negative lookbehind and lookahead. Since apparently C# supports infinite repetition, you could get away with:

"(?<!(')\s*)" + "\[[^\[\]]+\]" + "(?!\s*$1)

Separated the three parts, the negative lookbehind, the capturing match and the negative lookahead.

Note also that since the lookarounds are non-capturing, you don't even need parenthesis around the middle part.

In Java this would be something like:

"(?<!(')\s{0,1000})" + "\[[^\[\]]+\]" + "(?!\s{0,1000}$1)

but it's kinda' hacky, as it would only work for 1000 spaces between the two.


问:
Xcode - how to change the name of the programmer into company?
I have app in iTune store but it shows my private name, app was made for a company, how can i show company instead of my name?

Like Google apps show Google inc but not programmers name.

Here Team: my name shows
Signing certificate: shows my name

答:
You need to create a developer account for your company.
Say ABC Company

Setup abcdevelopment@abc.com apple developer account

Create certificates and profiles (Provisioning and Distribution) for the new account.

Then use this account in your Xcode, you will able to see company name in the Team option.

Transfer app between accounts

Go to your app in iTunes

Additional Information

See also in the official apple docs:
https://developer.apple.com/library/content/documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/Chapters/TransferringAndDeletingApps.html

EDIT: LINK


问:
Cocoon link_to_add_association not working
Have followed video tutorials, searched over and over, don't get it. Would appreciate help.

My main issue is that the link_to_add_association isn't working and I keep getting a missing template error.

"ActionView::MissingTemplate in Applications#new"

It says:
Missing partial applications/_question_fields, application/_question_fields with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :coffee, :jbuilder]}. Searched in:
  * "/Users/AndyAir/projects/friends-app/app/views"
  * "/Users/AndyAir/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/devise-4.2.1/app/views"

model

```<code>class Application < ApplicationRecord
 belongs_to :user

 has_many :questions

 accepts_nested_attributes_for :questions, reject_if: :all_blank, allow_destroy: true

 validates :name, :description, presence: true
end
</code>```

controller

```<code>class ApplicationsController < ApplicationController
 before_action :find_application, only: [:show, :edit, :update, :destroy]
 before_action :authenticate_user!

 def index
    @applications = Application.all.order("created_at DESC").limit(3)
 end

 def new
  @application = Application.new
  @application.questions.build
 end

 def create
    @application = Application.new(application_params)

    if @application.save
        redirect_to @application
    else
        render 'new'
    end
 end

 def show
 end

 def edit
 end

 def update
    if @application.update(application_params)
        redirect_to @application
    else
        render 'edit'
    end
 end

 def destroy
    @application.destroy
    redirect_to root_path
 end

 private

 def find_application
    @application = Application.find(params[:id])
 end

 def application_params
    params.require(:application).permit(:name, :description, questions_attributes: [:id, :name, :_destroy])
 end

 def after_sign_out_path_for(resource_or_scope)
  redirect_to root_path
 end
end
</code>```

views/applications/new

```<code><%= form_for @application do |f| %>
    <% if @application.errors.any? %>
      <div id="errors">
        <p><%= @application.errors.count %> Prevented this application from saving</p>
        <ul>
          <% @application.errors.full_messages.each do |msg| %>
            <li><%= msg %></li>
          <% end %>
        </ul>
      </div>
    <% end %>
    <div class="field">
        <%= f.label :title %><br>
        <%= f.text_field :name, placeholder: "Name of Your Friend Test", class: "form-control" %><br>
        <%= f.label :description %><br>
        <%= f.text_field :description, placeholder: "Write a witty tagline for your test.", class: "form-control" %><br>
    </div>
    <h3>Questions</h3>
        <%= f.fields_for :questions do |question| %>
            <div id="questions">
                <div class="field">
                <%= render 'questions_fields', f: question %>
             <div class="links">
                <%= link_to_add_association 'Add Question', f, :questions %>
               </div>
              </div>
            </div>
        <% end %>
    <br>
    <div class="form-actions">
        <%= f.button :submit %>
    </div>
<% end %>
</code>```

views/applications/_questions_fields.html.erb

```<code><div class="nested-fields">
  <%= f.text_field :question %>
  <%= link_to_remove_association "remove task", f %>
</div>
</code>```

答:
Your view is named incorrectly for cocoon to deduce automatically. It is looking for _question_fields (singular) while you have _questions_fields.

Either you rename the partial (it only contains a single question, so imho it seems more logical), but you can also overrule the default partial name as follows:

```<code><%= link_to_add_association 'Add Question', f, :questions, partial: 'questions_fields' %>
</code>```

Body:
Have followed video tutorials, searched over and over, don't get it. Would appreciate help.

My main issue is that the link_to_add_association isn't working and I keep getting a missing template error.

"ActionView::MissingTemplate in Applications#new"

It says:
Missing partial applications/_question_fields, application/_question_fields with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :coffee, :jbuilder]}. Searched in:
  * "/Users/AndyAir/projects/friends-app/app/views"
  * "/Users/AndyAir/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/devise-4.2.1/app/views"

model

class Application < ApplicationRecord
 belongs_to :user

 has_many :questions

 accepts_nested_attributes_for :questions, reject_if: :all_blank, allow_destroy: true

 validates :name, :description, presence: true
end

controller

class ApplicationsController < ApplicationController
 before_action :find_application, only: [:show, :edit, :update, :destroy]
 before_action :authenticate_user!

 def index
    @applications = Application.all.order("created_at DESC").limit(3)
 end

 def new
  @application = Application.new
  @application.questions.build
 end

 def create
    @application = Application.new(application_params)

    if @application.save
        redirect_to @application
    else
        render 'new'
    end
 end

 def show
 end

 def edit
 end

 def update
    if @application.update(application_params)
        redirect_to @application
    else
        render 'edit'
    end
 end

 def destroy
    @application.destroy
    redirect_to root_path
 end

 private

 def find_application
    @application = Application.find(params[:id])
 end

 def application_params
    params.require(:application).permit(:name, :description, questions_attributes: [:id, :name, :_destroy])
 end

 def after_sign_out_path_for(resource_or_scope)
  redirect_to root_path
 end
end

views/applications/new

<%= form_for @application do |f| %>
    <% if @application.errors.any? %>

<%= @application.errors.count %> Prevented this application from saving

          <% @application.errors.full_messages.each do |msg| %>

<%= msg %>

          <% end %>

    <% end %>

        <%= f.label :title %>

        <%= f.text_field :name, placeholder: "Name of Your Friend Test", class: "form-control" %>

        <%= f.label :description %>

        <%= f.text_field :description, placeholder: "Write a witty tagline for your test.", class: "form-control" %>

Questions

        <%= f.fields_for :questions do |question| %>

                <%= render 'questions_fields', f: question %>

                <%= link_to_add_association 'Add Question', f, :questions %>

        <% end %>

        <%= f.button :submit %>

<% end %>

views/applications/_questions_fields.html.erb

  <%= f.text_field :question %>
  <%= link_to_remove_association "remove task", f %>

Body:
Your view is named incorrectly for cocoon to deduce automatically. It is looking for _question_fields (singular) while you have _questions_fields.

Either you rename the partial (it only contains a single question, so imho it seems more logical), but you can also overrule the default partial name as follows:

<%= link_to_add_association 'Add Question', f, :questions, partial: 'questions_fields' %>