问:
Close SideBar with Javascript
I need to close my sidebar with JavaScript. I try with the following code, but when I click on the icon that executes the opening of the sidebar, it simply does not open it anymore because the display:none is executed immediately.

This is my code with which I open and close the SideBar:

```<code>function openNavCategories() {
    const overlayContent = document.getElementById('overlayContent-categories');

    document.getElementById('nav-categories').style.width = '30%';
    overlayContent.style.display = 'block';
    overlayContent.style.width = '100%';
    document.getElementById('category-icon').style.display = 'none';
    document.getElementById('category-icon-open').style.display = 'block';
}

function closeNavCategories() {
    const navCategories = document.getElementById('nav-categories');
    navCategories.style.width = '0%';
    navCategories.style.transition = 'all 0.4s';
    document.getElementById('overlayContent-categories').style.display = 'none';
}
</code>```

And this one with which I try to verify that the click is outside of my SideBar but it does not even show it anymore:

```<code>window.addEventListener('mouseup', function(event) {
    var SideBar = document.getElementById('nav-categories');
    if(event.target != SideBar && event.target.parentNode != SideBar ) {
        SideBar.style.display = 'none';
    }
})
</code>```

And this is my HTML and SCSS:

```<code>    <a href="#" class="closeBtn-categories" onclick="closeNavCategories()">X</a>

    <div id="overlayContent-categories" class="overlay__content-categories">
        <h2>Categorías</h2>
        <a href="#" onclick="closeNavCategories()">Categoría 1</a>
        <a href="#" onclick="closeNavCategories()">Categoría 2</a>
        <a href="#" onclick="closeNavCategories()">Categoría 3</a>
        <a href="#" onclick="closeNavCategories()">Categoría 4</a>
    </div>
</div>
</code>```

SCSS:

```<code>    .overlay-categories {
      position: fixed;
      top:0;
      right:0; // de derecha
      width: 0%;
      height: 100%;
      background: rgba(0,0,0,.9);
      overflow-x: hidden;
      z-index: 10;
      transition: all 0.8s;

      h2 {
        color: #506a80;
        margin: .2rem 0 .5rem 0rem;
      }

      a {
        padding: 10px;
        color: #ccc;
        font-size: 1rem;
        text-decoration: none;
        display:block;

        &:hover {
            color: #fff;
        }
      }

      .closeBtn-categories {
          position: absolute;
          top:20px;
          right: 35px;
          font-size: 2rem;
      }

      .overlay__content-categories {
          position: relative;
          display: none;
          top: 10%;
          width: 0%;
          text-align: center;
          margin-top: 20px;
          transition: all 2s linear;
      }

  }
</code>```

Can you help me? Thanks.

答:
You can define css class for the opened/closed style rather than manipulate style attribute in the script runtime. It let you keep all the styles one place in the SCSS.

```<code>  /* defined nav-categories__closed class*/
  #nav-categories{
    width: 30%;
    .overlayContent-categories{
      display: block;
      width: 100%;
    }
  }

  #nav-categories.nav-categories__closed{
    width: 0%;
    transition: all 0.4s;

    .overlayContent-categories{
      display: none;
    }
  }
</code>```

Modify openNavCategories() and closeNavCategories() to only toggling the nav-categories__closed

```<code>function openNavCategories() {
  const navCategories = document.getElementById('nav-categories');
  navCategories.classList.toggle('nav-categories__closed', false);

}

function closeNavCategories() {
  const navCategories = document.getElementById('nav-categories');
  navCategories.classList.toggle('nav-categories__closed', true);
}
</code>```

You have a third function to close the sidebar when a click is performed outside the sidebar. You may need to modify the function to include in the checking: If the event target is also not the control to open the sidebar, then invoke closeNavCategories(). The purpose of closeNavCategories() and the core part of mouseup event more or less doing the same job: to close the sidebar. You can eliminate the repeating code by referring to the same function.

Example: https://jsfiddle.net/rgfbLyon/5/

Title: Close SideBar with Javascript

Body:
I need to close my sidebar with JavaScript. I try with the following code, but when I click on the icon that executes the opening of the sidebar, it simply does not open it anymore because the display:none is executed immediately.

This is my code with which I open and close the SideBar:

function openNavCategories() {
    const overlayContent = document.getElementById('overlayContent-categories');

    document.getElementById('nav-categories').style.width = '30%';
    overlayContent.style.display = 'block';
    overlayContent.style.width = '100%';
    document.getElementById('category-icon').style.display = 'none';
    document.getElementById('category-icon-open').style.display = 'block';
}

function closeNavCategories() {
    const navCategories = document.getElementById('nav-categories');
    navCategories.style.width = '0%';
    navCategories.style.transition = 'all 0.4s';
    document.getElementById('overlayContent-categories').style.display = 'none';
}

And this one with which I try to verify that the click is outside of my SideBar but it does not even show it anymore:

window.addEventListener('mouseup', function(event) {
    var SideBar = document.getElementById('nav-categories');
    if(event.target != SideBar && event.target.parentNode != SideBar ) {
        SideBar.style.display = 'none';
    }
})

And this is my HTML and SCSS:

    X

Categorías

        Categoría 1
        Categoría 2
        Categoría 3
        Categoría 4

SCSS:

    .overlay-categories {
      position: fixed;
      top:0;
      right:0; // de derecha
      width: 0%;
      height: 100%;
      background: rgba(0,0,0,.9);
      overflow-x: hidden;
      z-index: 10;
      transition: all 0.8s;

      h2 {
        color: #506a80;
        margin: .2rem 0 .5rem 0rem;
      }

      a {
        padding: 10px;
        color: #ccc;
        font-size: 1rem;
        text-decoration: none;
        display:block;

        &:hover {
            color: #fff;
        }
      }

      .closeBtn-categories {
          position: absolute;
          top:20px;
          right: 35px;
          font-size: 2rem;
      }

      .overlay__content-categories {
          position: relative;
          display: none;
          top: 10%;
          width: 0%;
          text-align: center;
          margin-top: 20px;
          transition: all 2s linear;
      }

  }

Can you help me? Thanks.

Body:
You can define css class for the opened/closed style rather than manipulate style attribute in the script runtime. It let you keep all the styles one place in the SCSS.

  /* defined nav-categories__closed class*/
  #nav-categories{
    width: 30%;
    .overlayContent-categories{
      display: block;
      width: 100%;
    }
  }

  #nav-categories.nav-categories__closed{
    width: 0%;
    transition: all 0.4s;

    .overlayContent-categories{
      display: none;
    }
  }

Modify openNavCategories() and closeNavCategories() to only toggling the nav-categories__closed

function openNavCategories() {
  const navCategories = document.getElementById('nav-categories');
  navCategories.classList.toggle('nav-categories__closed', false);

}

function closeNavCategories() {
  const navCategories = document.getElementById('nav-categories');
  navCategories.classList.toggle('nav-categories__closed', true);
}

You have a third function to close the sidebar when a click is performed outside the sidebar. You may need to modify the function to include in the checking: If the event target is also not the control to open the sidebar, then invoke closeNavCategories(). The purpose of closeNavCategories() and the core part of mouseup event more or less doing the same job: to close the sidebar. You can eliminate the repeating code by referring to the same function.

Example: https://jsfiddle.net/rgfbLyon/5/


来源: stackexchange

问:
Multiple Logic Apps in same Azure Resource Group Project
I have a requirement to create around 20 small logic apps. I want all of them to be part of single solution ideally single Azure Resource Group project.

Once it is created, I want to set up CI/CD on Azure Devops to deploy all these logic apps to multiple environments with different parameters in each environment.

Is it right to include all the logic apps in one single project? If so, what are the options to set up CI/CD pipeline?

Edit: Rather what is the best way to organise multiple logic apps?

答:
To deploy your solution, you can use either a single template or a main template with many related templates. The related template can be either a separate file that is linked to from the main template, or a template that is nested within the main template.

For small to medium solutions, a single template is easier to understand and maintain. You can see all the resources and values in a single file. For advanced scenarios, linked templates enable you to break down the solution into targeted components, and reuse templates.

When using linked templates, you create a main template that receives the parameter values during deployment. The main template contains all the linked templates and passes values to those templates as needed.

see Tutorial: create linked Azure Resource Manager templates.

Note: For linked or nested templates, you can only use Incremental deployment mode.

You can find example templates here.

ContentLicense: CC BY-SA 4.0


问:
How to create and use docker volumes on Asp core Web app (MVC)
I have web app and I'm using docker to deploy it to Linux server. I'm using ASP .NET CORE 2.1, MVC model for my app, and I publish it through Visual studio's integrated Container Registry to docker hub. from my server i pull image, and then run it. Problem is, every time I publish update to my app it resets all files in app, as it should, that's how containers work. But I need some files to stay in server and not to reset every time i update my app, so i need to use volumes. But I can't figure out how to use ASP CORE app and docker volumes, I think i can create them, but how to access them from app ?

I'v tried some methods I found on web,

So normaly I to run docker I pull it from hub.docker with: docker pull mydockerid/appname:tag

Then, run it with command: docker run -p 3000:80 mydockerid/appname:tag
and that's it.

I'v tried : docker run -p 3000:80 -v ~mnt/files/xml:/xml mydockerid/appname:tag

As I understood it it should make docker use server folder, "mnt/files/xml" as folder in my app named "xml", but doesn't work.

I'm also Using Digital ocean and directory "mnt/files/xml" is volume connected to droplet.

Perfect solution would be so I could create docker volume inside droplets volume,  but really any solution that works would be great !

Thanks, for Help !

答:
Okay so I was close,

to create volume in docker you need to chose directory from server and folder from app.
the problem for me was, I was showing wrong directory in app. Because in docker container lets say root folder is under /app/root, so was my xml folder, all I needed to fix is to use docker run -p 3000:80 -v ~mnt/files/xml:/app/xml mydockerid/appname:tag instead of docker run -p 3000:80 -v ~mnt/files/xml:/xml mydockerid/appname:tag first directory is always from server and second is always from app.

As for volumes in digital Ocean:

Go to Volumes under manage on left.
Press Create Volume button on top right.
Choose configuration of Volume, then attach it to your droplet.

to mount it:

```<code>$ mkdir -p /mnt/files

# Mount your volume at the newly-created mount point:
$ mount -o discard,defaults,noatime /dev/disk/by-id/scsi-0DO_volume_name /mnt/files

# Change fstab so the volume will be mounted after a reboot
$ echo '/dev/disk/by-id/scsi-0DO_volume_name /mnt/files ext4 defaults,nofail,discard 0 0' | sudo tee -a /etc/fstab
</code>```

Digital Ocean will actualy show all these comands with your volume names if you go into "Config instruction" under "More" on your Volume.

Then becouse my DO volume is mounted to /mnt/files I connect to server via filezila, put needed files there in folder called "xml" and run the docker container with docker run -p 3000:80 -v ~mnt/files/xml:/xml mydockerid/appname:tag, Now whatever is in folder xml in server. will be read at it is inside my app inside, folder called xml, and I can update app and the folder will never loose data. Also I can move this DO volume to another DO droplet without data loss.

Body:
Okay so I was close,

to create volume in docker you need to chose directory from server and folder from app.
the problem for me was, I was showing wrong directory in app. Because in docker container lets say root folder is under /app/root, so was my xml folder, all I needed to fix is to use docker run -p 3000:80 -v ~mnt/files/xml:/app/xml mydockerid/appname:tag instead of docker run -p 3000:80 -v ~mnt/files/xml:/xml mydockerid/appname:tag first directory is always from server and second is always from app.

As for volumes in digital Ocean:

Go to Volumes under manage on left.
Press Create Volume button on top right.
Choose configuration of Volume, then attach it to your droplet.

to mount it:

$ mkdir -p /mnt/files

# Mount your volume at the newly-created mount point:
$ mount -o discard,defaults,noatime /dev/disk/by-id/scsi-0DO_volume_name /mnt/files

# Change fstab so the volume will be mounted after a reboot
$ echo '/dev/disk/by-id/scsi-0DO_volume_name /mnt/files ext4 defaults,nofail,discard 0 0' | sudo tee -a /etc/fstab

Digital Ocean will actualy show all these comands with your volume names if you go into "Config instruction" under "More" on your Volume.

Then becouse my DO volume is mounted to /mnt/files I connect to server via filezila, put needed files there in folder called "xml" and run the docker container with docker run -p 3000:80 -v ~mnt/files/xml:/xml mydockerid/appname:tag, Now whatever is in folder xml in server. will be read at it is inside my app inside, folder called xml, and I can update app and the folder will never loose data. Also I can move this DO volume to another DO droplet without data loss.


问:
form.radio button in rails
How to select and create radio button in rails 3 when using like this

Database records like this

id name selected

1 abc false

2 efg true

3 hij false

4 klm false

The above will display on form as four radio buttons
I am using form_for and need to use f.radio_button for each group...

How to achieve which one is selected

thanks

答:
```<code>      Fetch all the records from database in @records then in your view file

      <% @records.each do |row| %>
        <br><%= radio_button_tag 'field_name', row.name, row.selected %>
        <%= row.name.humanize %>
      <% end %>
</code>```

ContentLicense: CC BY-SA 3.0

Title: form.radio button in rails


问:
Airflow: Get previous task id in the next task
I have 2 tasks. In the first, python operator computes something and in the second I want to use the output of the python operator in the Http operator. Here is my code:

```<code>source_list = ['account', 'sales']

for source_type in source_list:
    t2 = PythonOperator(
                task_id='compute_next_gather_time_for_' + source_type,
                python_callable=compute_next_gather_time,
                provide_context=True,
                trigger_rule=TriggerRule.ALL_SUCCESS,
                op_args=[source_type],
                retries=3
            )

    t3 = SimpleHttpOperator(
                task_id='request_' + source_type + '_report',
                method='POST',
                http_conn_id='abc',
                endpoint=endpoint,
                data=json.dumps({
                    "query": {
                        "start": "{{ task_instance.xcom_pull(task_ids='prev_task_id') }}",
                        "stop": str(yesterday),
                        "fields": [
                            1
                        ]
                    }
                }),
                headers={"Content-Type": "application/json", "Authorization": 'abc'},
                response_check=lambda response: True if len(response.json()) == 0 else False,
                log_response=True,
                retries=3
            )
</code>```

Query: I want to pass previous task id in t3 in its data variable. I am not sure how to do that since t2 task id is not constant. It changes with changing source_type. Evidently, when I tried it did not render it.

答:
I haven't used Jinja templating in any of my DAGs before, but I have been faced with similar problems where I was needing to retrieve XCOM values from a particular task that has a dynamically generated task_id.

You could define the task_ids in T3 in the same way you defined the task_id in T2. For example:

```<code>source_list = ['account', 'sales']

for source_type in source_list:

    task_id='compute_next_gather_time_for_' + source_type

    t2 = PythonOperator(
                task_id=task_id,
                python_callable=compute_next_gather_time,
                provide_context=True,
                trigger_rule=TriggerRule.ALL_SUCCESS,
                op_args=[source_type],
                retries=3
            )

    t3 = SimpleHttpOperator(
                task_id='request_' + source_type + '_report',
                method='POST',
                http_conn_id='abc',
                endpoint=endpoint,
                data=json.dumps({
                    "query": {
                        "start": "{{ task_instance.xcom_pull(task_ids=task_id) }}",
                        "stop": str(yesterday),
                        "fields": [
                            1
                        ]
                    }
                }),
                headers={"Content-Type": "application/json", "Authorization": 'abc'},
                response_check=lambda response: True if len(response.json()) == 0 else False,
                log_response=True,
                retries=3
            )
</code>```

Body:
I have 2 tasks. In the first, python operator computes something and in the second I want to use the output of the python operator in the Http operator. Here is my code:

source_list = ['account', 'sales']

for source_type in source_list:
    t2 = PythonOperator(
                task_id='compute_next_gather_time_for_' + source_type,
                python_callable=compute_next_gather_time,
                provide_context=True,
                trigger_rule=TriggerRule.ALL_SUCCESS,
                op_args=[source_type],
                retries=3
            )

    t3 = SimpleHttpOperator(
                task_id='request_' + source_type + '_report',
                method='POST',
                http_conn_id='abc',
                endpoint=endpoint,
                data=json.dumps({
                    "query": {
                        "start": "{{ task_instance.xcom_pull(task_ids='prev_task_id') }}",
                        "stop": str(yesterday),
                        "fields": [
                            1
                        ]
                    }
                }),
                headers={"Content-Type": "application/json", "Authorization": 'abc'},
                response_check=lambda response: True if len(response.json()) == 0 else False,
                log_response=True,
                retries=3
            )

Query: I want to pass previous task id in t3 in its data variable. I am not sure how to do that since t2 task id is not constant. It changes with changing source_type. Evidently, when I tried it did not render it.

Body:
I haven't used Jinja templating in any of my DAGs before, but I have been faced with similar problems where I was needing to retrieve XCOM values from a particular task that has a dynamically generated task_id.

You could define the task_ids in T3 in the same way you defined the task_id in T2. For example:

source_list = ['account', 'sales']

for source_type in source_list:

    task_id='compute_next_gather_time_for_' + source_type

    t2 = PythonOperator(
                task_id=task_id,
                python_callable=compute_next_gather_time,
                provide_context=True,
                trigger_rule=TriggerRule.ALL_SUCCESS,
                op_args=[source_type],
                retries=3
            )

    t3 = SimpleHttpOperator(
                task_id='request_' + source_type + '_report',
                method='POST',
                http_conn_id='abc',
                endpoint=endpoint,
                data=json.dumps({
                    "query": {
                        "start": "{{ task_instance.xcom_pull(task_ids=task_id) }}",
                        "stop": str(yesterday),
                        "fields": [
                            1
                        ]
                    }
                }),
                headers={"Content-Type": "application/json", "Authorization": 'abc'},
                response_check=lambda response: True if len(response.json()) == 0 else False,
                log_response=True,
                retries=3
            )


问:
Function that replaces .txt file \n (new line) with _ (underscore)?
I'm trying to write a function that takes a filename as its argument and returns a string with all \n characters replaced by the _ character.

This is what I did:

```<code>def replace_space(filename):
    wordfile = open(filename)
    text_str = wordfile.read()
    wordfile.close()
    text_str.replace("\n", "_")

replace_space("words.txt")
</code>```

I also tried using " " instead of "\n":

```<code>    text_str.replace(" ", "_")
</code>```

答:
```<code>def replace(filename):
    with open(filename, 'r') as file:
        text = file.read()
    text = text.replace('\n', '_')
    return text
</code>```

Body:
I'm trying to write a function that takes a filename as its argument and returns a string with all \n characters replaced by the _ character.

This is what I did:

def replace_space(filename):
    wordfile = open(filename)
    text_str = wordfile.read()
    wordfile.close()
    text_str.replace("\n", "_")

replace_space("words.txt")

I also tried using " " instead of "\n":

    text_str.replace(" ", "_")


答:
Python, unlike languages such as Haskell and Scala, will return None if it reaches the end of a function body without an explicit return statement. Therefore, you want this:

```<code>def replace_space(filename):
    with open(filename) as wordfile:
        text_str = wordfile.read()

    return text_str.replace("\n", "_")
</code>```

Note also the use of with in place of open and close; it ensures your file gets closed even if you get an exception somewhere along the way.

Title: Function that replaces .txt file \n (new line) with _ (underscore)?

Body:
Python, unlike languages such as Haskell and Scala, will return None if it reaches the end of a function body without an explicit return statement. Therefore, you want this:

def replace_space(filename):
    with open(filename) as wordfile:
        text_str = wordfile.read()

    return text_str.replace("\n", "_")

Note also the use of with in place of open and close; it ensures your file gets closed even if you get an exception somewhere along the way.


问:
Row counts of all pages in selenium
I have 5 pages(we are using pagination). Each page has 10 records on it.
If i use

```<code>int rcount =  selenium.getXpathCount("//table[@id='bank']/tbody/tr").intValue();
</code>```

I am getting rcount as 10, that means it is only getting the 1st page count only
I want to get all records of 5 pages(total 50 records)
Help me...

答:
Selenium works like a browser user!

So selenium test can only "see" what a use see (if he looks at the HTML code), and do want a user can do.

So if your application has a page size function, you need to set it first to lets say 100. For you selenium test: it means click/invoke the page size function for 100 items first.

Title: Row counts of all pages in selenium

Body:
I have 5 pages(we are using pagination). Each page has 10 records on it.
If i use

int rcount =  selenium.getXpathCount("//table[@id='bank']/tbody/tr").intValue();

I am getting rcount as 10, that means it is only getting the 1st page count only
I want to get all records of 5 pages(total 50 records)
Help me...


问:
Debug and Release package with productFlavors
I have created 2 productFlavors in build.gradle file

```<code>productFlavors {
        flavorA {
            dimension "default"
        }

        flavorB {
            dimension "default"
        }
    }
</code>```

And 2 buildTypes debug and release

So gradle created Build Variants as  flavorADebug, flavorARelease, flavorBDebug and flavorBRelease

I want to create a FlavorDI file in debug and release package such that debug/FlavorDI will be common for flavorADebug and flavorBDebug and release/FlavorDI will be common for flavorARelease and flavorBRelease.

But when I include the FlavorDI in AppComponent the package is not recognized.

```<code>@Singleton
@Component(modules = [
    AppModule::class,
    ActivityModule::class,
    FragmentModule::class,
    ViewModelModule::class,
    NetModule::class,
    FlavourDI::class,   // Could not import FlavourDI
    AndroidSupportInjectionModule::class,
    AndroidInjectionModule::class
])
</code>```

How exactly should I create the FlavorDI file such that debug/FlavorDI will be common to flavorADebug and flavorBDebug variant and release/FlavorDI will be common to flavorARelease and flavorBRelease variant?

答:
Make sure you are using the proper build variant. Also, you might need to use flavorDimension. This is what I have for a similar setup in my build.gradle:

```<code>flavorDimensions 'mobile'

productFlavors {
    internal {
        dimension = 'mobile'
        applicationId = 'com.labs.biletskiy.android.internal'
    }

    production {
        dimension = 'mobile'
        applicationId 'com.labs.biletskiy.android.production'
    }

}
</code>```

Body:
I have created 2 productFlavors in build.gradle file

productFlavors {
        flavorA {
            dimension "default"
        }

        flavorB {
            dimension "default"
        }
    }

And 2 buildTypes debug and release

So gradle created Build Variants as  flavorADebug, flavorARelease, flavorBDebug and flavorBRelease

I want to create a FlavorDI file in debug and release package such that debug/FlavorDI will be common for flavorADebug and flavorBDebug and release/FlavorDI will be common for flavorARelease and flavorBRelease.

But when I include the FlavorDI in AppComponent the package is not recognized.

@Singleton
@Component(modules = [
    AppModule::class,
    ActivityModule::class,
    FragmentModule::class,
    ViewModelModule::class,
    NetModule::class,
    FlavourDI::class,   // Could not import FlavourDI
    AndroidSupportInjectionModule::class,
    AndroidInjectionModule::class
])

How exactly should I create the FlavorDI file such that debug/FlavorDI will be common to flavorADebug and flavorBDebug variant and release/FlavorDI will be common to flavorARelease and flavorBRelease variant?

Body:
Make sure you are using the proper build variant. Also, you might need to use flavorDimension. This is what I have for a similar setup in my build.gradle:

flavorDimensions 'mobile'

productFlavors {
    internal {
        dimension = 'mobile'
        applicationId = 'com.labs.biletskiy.android.internal'
    }

    production {
        dimension = 'mobile'
        applicationId 'com.labs.biletskiy.android.production'
    }

}


问:
Making a quest system in a game. Is there a way to hide the next quest
I'm working on a quest system in my clicker game. I don't want each of the quests to be flat out on the page:

I'd like the user to be like "Oh cool this was hidden and it is only revealed once you have a certain amount of quests done". Then I want there to be rewards like a special sword or something. I mostly want to know how in HTML you can hide things from being on the screen until a condition is met.

Haven't tried anything new to HTML/ JavaScript

This is my HTML code: (don't have any JavaScript for this part yet but if I can get some examples on how to hide stuff id appreciate it)

```<code> Quests
 <br/>
 Click 1000 times <span id="Numberofclicks">0</span>
 <span id="Maxnumberofclicks">1000</span>
 <br/>
 Use skills 50 times <span id="Spelluses">0</span>
 <span id="Maxspelluses">50</span>
 <br/>
</code>```

I expect the quests: "Numberofclicks" and "Spelluses" to stay hidden until those quests are completed or a certain amount of quests are finished. My actual output is nothing yet because I don't know how to do this.

答:
Ok, this is pretty simplistic.

But we can click quests and the reveal rewards.

Note how the CSS hides .reward items by default.

const questClicks = {};

const questClick = ({dataset: {count: c, reward : r}}) => {
  questClicks[r] += 1;
  if(questClicks[r] >= c) document.querySelector(`#${r}`).style.display = 'block';
};

document.addEventListener('click', ({target}) => {
  if(target.matches('.quest')) {
    questClick(target);
  }
});

// Init all quests
document.addEventListener('DOMContentLoaded', () => {
  document.querySelectorAll('.quest').forEach(({dataset: { reward: r }}) => questClicks[r] = 0);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.clicker {
  border: 1px solid red;
  border-radius: 7px;
  margin: 10px;
  padding: 10px;
}

.reward {
  display: none;
  font-weight: bold;
}</code>```

Click Me Lots !!

Here is a sword

Click Me Lots !!

Here is a sword
```

Body:
I'm working on a quest system in my clicker game. I don't want each of the quests to be flat out on the page:

I'd like the user to be like "Oh cool this was hidden and it is only revealed once you have a certain amount of quests done". Then I want there to be rewards like a special sword or something. I mostly want to know how in HTML you can hide things from being on the screen until a condition is met.

Haven't tried anything new to HTML/ JavaScript

This is my HTML code: (don't have any JavaScript for this part yet but if I can get some examples on how to hide stuff id appreciate it)

 Quests

 Click 1000 times 0
 1000

 Use skills 50 times 0
 50

I expect the quests: "Numberofclicks" and "Spelluses" to stay hidden until those quests are completed or a certain amount of quests are finished. My actual output is nothing yet because I don't know how to do this.

Body:
Ok, this is pretty simplistic.

But we can click quests and the reveal rewards.

Note how the CSS hides .reward items by default.

const questClicks = {};

const questClick = ({dataset: {count: c, reward : r}}) => {
  questClicks[r] += 1;
  if(questClicks[r] >= c) document.querySelector(`#${r}`).style.display = 'block';
};

document.addEventListener('click', ({target}) => {
  if(target.matches('.quest')) {
    questClick(target);
  }
});

// Init all quests
document.addEventListener('DOMContentLoaded', () => {
  document.querySelectorAll('.quest').forEach(({dataset: { reward: r }}) => questClicks[r] = 0);
});

.clicker {
  border: 1px solid red;
  border-radius: 7px;
  margin: 10px;
  padding: 10px;
}

.reward {
  display: none;
  font-weight: bold;
}

<div id='sword-quest' class='quest' data-count='5' data-reward='sword'>Click Me Lots !!</div>
<div class='reward' id='sword'>Here is a sword</div>

<div id='shield-quest' class='quest' data-count='3' data-reward='shield'>Click Me Lots !!</div>
<div class='reward' id='shield'>Here is a sword</div>


问:
i can't delete image and i get unlink
I can not delete an article or image in case I delete anything that shows the page Whoops

if(!function_exists('image_delete')){
    function image_delete($dir){
        unlink(public_path().'/'.$dir);
    }
}```
</div>
</div>
</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>    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Article $article)
    {
        image_delete($article->image); // its helper function
        $article->delete();
        return back()->with('success','تم حذف المقال !!');
    }</code>```

this my problem

答:
For example, your article image store in public/article_images directory then code as per below.

In helper:

```<code>if(!function_exists('image_delete')){
    function image_delete($filename){
       $file = public_path().'/article_images/'.$filename;

       if(file_exists($file)){
          unlink($file);
       }
    }
}
</code>```

Title: i can't delete image and i get unlink

Body:
I can not delete an article or image in case I delete anything that shows the page Whoops

if(!function_exists('image_delete')){
    function image_delete($dir){
        unlink(public_path().'/'.$dir);
    }
}

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Article $article)
    {
        image_delete($article->image); // its helper function
        $article->delete();
        return back()->with('success','تم حذف المقال !!');
    }

this my problem

Body:
For example, your article image store in public/article_images directory then code as per below.

In helper:

if(!function_exists('image_delete')){
    function image_delete($filename){
       $file = public_path().'/article_images/'.$filename;

       if(file_exists($file)){
          unlink($file);
       }
    }
}


答:
Some suggestions for your code

You can use with context manager to open your file which will take care of closing the file for you

You need return back the updated string.

```<code>def replace_space(filename):
    text_str = ''
    #Open the file and read the contents
    with open(filename) as wordfile:
        text_str = wordfile.read()

    #Replace and return the updated string
    return text_str.replace("\n", "_")

replace_space("file.txt")
</code>```

If you don't want to use the context manager, you need to explicitly open and close the file like you were doing before

```<code>def replace_space(filename):
    text_str = ''

    #Open the file
    wordfile = open(filename)
    #Do the read and replace
    text_str = wordfile.read().replace("\n", "_")

    #Close file and return updated string
    wordfile.close()
    return text_str

replace_space("file.txt")
</code>```

Body:
Some suggestions for your code

You can use with context manager to open your file which will take care of closing the file for you

You need return back the updated string.

def replace_space(filename):
    text_str = ''
    #Open the file and read the contents
    with open(filename) as wordfile:
        text_str = wordfile.read()

    #Replace and return the updated string
    return text_str.replace("\n", "_")

replace_space("file.txt")

If you don't want to use the context manager, you need to explicitly open and close the file like you were doing before

def replace_space(filename):
    text_str = ''

    #Open the file
    wordfile = open(filename)
    #Do the read and replace
    text_str = wordfile.read().replace("\n", "_")

    #Close file and return updated string
    wordfile.close()
    return text_str

replace_space("file.txt")


问:
Elegant and maintainable way of populating Tree structures in c#
I have a Tree.

```<code>class TreeNode {
    public TreeNode(string name, string description) {
        Name = name;
        Description = description;
    }
    string Name { get; set; }
    string Description { get; set; }
    public List<TreeNode> Children = new List<TreeNode>();
}
</code>```

I would like to populate a large one for unit testing purposes. I would really like to keep stuff DRY.

Say for illustration purposes my tree has the following structure

```
Parent,desc
  Child 1, desc1
    Grandchild 1, desc1
  Child 2, desc2
```

How would you go about populating the tree in an elegant an maintainable way?

I find this code quite repetitious and error prone:

```<code>var parent = new TreeNode("Parent", "desc");
var child1 = new TreeNode("Child 1", "desc1");
var child2 = new TreeNode("Child 2", "desc2");
var grandchild1 = new TreeNode("Grandchild 1", "desc1");

parent.Children.Add(child1);
parent.Children.Add(child2);

child1.Children.Add(grandchild1);
</code>```

EDIT

I ended up doing the DSL approach:

A demo test lives here.

The implementation is here.

It uses a builder and a simple DSL.

答:
You could write up a simple XML representation of the tree contents with a simple parser that populates the tree. The following would give the structure you specified above.</p>

```<code><Node description="desc">
    Parent
    <Node description="desc1">
        Child 1
        <Node description="desc1">
            Grandchild 1
        </Node>
    </Node>
    <Node description="desc2">
        Child 2
    </Node>
</Node>
</code>```

Body:
I have a Tree.

class TreeNode {
    public TreeNode(string name, string description) {
        Name = name;
        Description = description;
    }
    string Name { get; set; }
    string Description { get; set; }
    public List<TreeNode> Children = new List<TreeNode>();
}

I would like to populate a large one for unit testing purposes. I would really like to keep stuff DRY.

Say for illustration purposes my tree has the following structure

Parent,desc
  Child 1, desc1
    Grandchild 1, desc1
  Child 2, desc2

How would you go about populating the tree in an elegant an maintainable way?

I find this code quite repetitious and error prone:

var parent = new TreeNode("Parent", "desc");
var child1 = new TreeNode("Child 1", "desc1");
var child2 = new TreeNode("Child 2", "desc2");
var grandchild1 = new TreeNode("Grandchild 1", "desc1");

parent.Children.Add(child1);
parent.Children.Add(child2);

child1.Children.Add(grandchild1);

EDIT

I ended up doing the DSL approach:

A demo test lives here.

The implementation is here.

It uses a builder and a simple DSL.

Body:
You could write up a simple XML representation of the tree contents with a simple parser that populates the tree. The following would give the structure you specified above.

<Node description="desc">
    Parent
    <Node description="desc1">
        Child 1
        <Node description="desc1">
            Grandchild 1
        </Node>
    </Node>
    <Node description="desc2">
        Child 2
    </Node>
</Node>

OwnerDisplayName: Snarfblam

ContentLicense: CC BY-SA 2.5


问:
Reflection: How to Invoke Method with parameters
I am trying to invoke a method via reflection with parameters and I get:

object does not match target type

If I invoke a method without parameters, it works fine. Based on the following code if I call the method Test("TestNoParameters"), it works fine. However if I call Test("Run"), I get an exception. Is something wrong with my code?

My initial purpose was to pass an array of objects e.g. public void Run(object[] options) but this did not work and I tried something simpler e.g. string without success.

```<code>// Assembly1.dll
namespace TestAssembly
{
    public class Main
    {
        public void Run(string parameters)
        {
            // Do something...
        }
        public void TestNoParameters()
        {
            // Do something...
        }
    }
}

// Executing Assembly.exe
public class TestReflection
{
    public void Test(string methodName)
    {
        Assembly assembly = Assembly.LoadFile("...Assembly1.dll");
        Type type = assembly.GetType("TestAssembly.Main");

        if (type != null)
        {
            MethodInfo methodInfo = type.GetMethod(methodName);

            if (methodInfo != null)
            {
                object result = null;
                ParameterInfo[] parameters = methodInfo.GetParameters();
                object classInstance = Activator.CreateInstance(type, null);

                if (parameters.Length == 0)
                {
                    // This works fine
                    result = methodInfo.Invoke(classInstance, null);
                }
                else
                {
                    object[] parametersArray = new object[] { "Hello" };

                    // The invoke does NOT work;
                    // it throws "Object does not match target type"
                    result = methodInfo.Invoke(methodInfo, parametersArray);
                }
            }
        }
    }
}
</code>```

答:
I m invoking the weighted average through reflection. And had used method with more than one parameter.</p>

```<code>Class cls = Class.forName(propFile.getProperty(formulaTyp));// reading class name from file

Object weightedobj = cls.newInstance(); // invoke empty constructor

Class<?>[] paramTypes = { String.class, BigDecimal[].class, BigDecimal[].class }; // 3 parameter having first is method name and other two are values and their weight
Method printDogMethod = weightedobj.getClass().getMethod("applyFormula", paramTypes); // created the object
return BigDecimal.valueOf((Double) printDogMethod.invoke(weightedobj, formulaTyp, decimalnumber, weight)); calling the method
</code>```

Body:
I am trying to invoke a method via reflection with parameters and I get:

object does not match target type

If I invoke a method without parameters, it works fine. Based on the following code if I call the method Test("TestNoParameters"), it works fine. However if I call Test("Run"), I get an exception. Is something wrong with my code?

My initial purpose was to pass an array of objects e.g. public void Run(object[] options) but this did not work and I tried something simpler e.g. string without success.

// Assembly1.dll
namespace TestAssembly
{
    public class Main
    {
        public void Run(string parameters)
        {
            // Do something...
        }
        public void TestNoParameters()
        {
            // Do something...
        }
    }
}

// Executing Assembly.exe
public class TestReflection
{
    public void Test(string methodName)
    {
        Assembly assembly = Assembly.LoadFile("...Assembly1.dll");
        Type type = assembly.GetType("TestAssembly.Main");

        if (type != null)
        {
            MethodInfo methodInfo = type.GetMethod(methodName);

            if (methodInfo != null)
            {
                object result = null;
                ParameterInfo[] parameters = methodInfo.GetParameters();
                object classInstance = Activator.CreateInstance(type, null);

                if (parameters.Length == 0)
                {
                    // This works fine
                    result = methodInfo.Invoke(classInstance, null);
                }
                else
                {
                    object[] parametersArray = new object[] { "Hello" };

                    // The invoke does NOT work;
                    // it throws "Object does not match target type"
                    result = methodInfo.Invoke(methodInfo, parametersArray);
                }
            }
        }
    }
}

Body:
I m invoking the weighted average through reflection. And had used method with more than one parameter.

Class cls = Class.forName(propFile.getProperty(formulaTyp));// reading class name from file

Object weightedobj = cls.newInstance(); // invoke empty constructor

Class<?>[] paramTypes = { String.class, BigDecimal[].class, BigDecimal[].class }; // 3 parameter having first is method name and other two are values and their weight
Method printDogMethod = weightedobj.getClass().getMethod("applyFormula", paramTypes); // created the object
return BigDecimal.valueOf((Double) printDogMethod.invoke(weightedobj, formulaTyp, decimalnumber, weight)); calling the method


问:
Hide and show on button click in angularjs
I want to hide the value by default and show the value when I click on button for 1st time. When you click on the same button for a 2nd time, it should hide the value instead of displaying. Vice versa it should happen.

Here is my html

```<code><!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <title>AngularJS</title>
  <script
  src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.js">
  </script>
  <script th:src="@{/main.js}"></script>
<head>
<body ng-app="EmployeeManagement" ng-controller="EmployeeController">
<input type="button" value="Show Angular" ng-click="ShowHide()"/>
 <div ng-show = "IsVisible"> yes </div>
</body>
</html>
</code>```

here is my JS File:

```<code>var app = angular.module("EmployeeManagement", []);
app.controller("EmployeeController", function($scope, $http) {
 $scope.ShowHide = function(){
     $scope.IsVisible =  true;
 }
</code>```

can anyone tell me how to achieve this scenario?

答:
@karthick, you can also do it on template end without any interaction of the controller.</p>

```<code>  <!DOCTYPE HTML>
  <html xmlns:th="http://www.thymeleaf.org">
  <head>
    <title>AngularJS</title>
    <script
    src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.js">
    </script>
    <script >
    var app = angular.module("EmployeeManagement", []);
      app.controller("EmployeeController", function($scope, $http) {
    })
  </script>
  <head>
  <body ng-app="EmployeeManagement" ng-controller="EmployeeController" ng-init="IsVisible=false">
  <input type="button" value="Show Angular" ng-click="IsVisible = !IsVisible"/>
  <div ng-show = "IsVisible"> yes </div>
  </body>
  </html>
</code>```

Body:
I want to hide the value by default and show the value when I click on button for 1st time. When you click on the same button for a 2nd time, it should hide the value instead of displaying. Vice versa it should happen.

Here is my html

<!DOCTYPE HTML>

  <title>AngularJS</title>

<input type="button" value="Show Angular" ng-click="ShowHide()"/>

 yes

here is my JS File:

var app = angular.module("EmployeeManagement", []);
app.controller("EmployeeController", function($scope, $http) {
 $scope.ShowHide = function(){
     $scope.IsVisible =  true;
 }

can anyone tell me how to achieve this scenario?

Body:
@karthick, you can also do it on template end without any interaction of the controller.

  <!DOCTYPE HTML>
  <html xmlns:th="http://www.thymeleaf.org">
  <head>
    <title>AngularJS</title>
    <script
    src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.js">
    </script>
    <script >
    var app = angular.module("EmployeeManagement", []);
      app.controller("EmployeeController", function($scope, $http) {
    })
  </script>
  <head>
  <body ng-app="EmployeeManagement" ng-controller="EmployeeController" ng-init="IsVisible=false">
  <input type="button" value="Show Angular" ng-click="IsVisible = !IsVisible"/>
  <div ng-show = "IsVisible"> yes </div>
  </body>
  </html>


问:
Lists Splitting Equal Split
I wrote a code that takes a certain input (int) and stores it to a list.

The next phase, which I can't manage to construct is to take the list and split it to 4 equal lists.

So far I take the sum of the prime_list and divide it to 4. the sum stored as var to further use.

prime_list = [1,2,3,4,5,6,7,8,9,10,11,12] split to equal 4 lists, divide by range (or other methods):

```<code>split_list_01 = [1,2,3]

split_list_02 = [4,5,6]

split_list_03 = [7,8,9]

split_list_04 = [10,11,12]
</code>```

答:
Try this:

```<code>prime_list = [1,2,3,4,5,6,7,8,9,10,11,12]
new_list = [prime_list[i:i+3] for i in range(0, len(prime_list), 3)]
print new_list
</code>```

Output:

```<code>[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
</code>```

A dictionary can be used to store each of the lists using different keys which can be accessed later:

```<code>prime_list = [1,2,3,4,5,6,7,8,9,10,11,12]

split_list = {}
count = 0
for i in range(0, len(prime_list), 3):
    split_list[count] = prime_list[i:i+3]
    count += 1
</code>```

print split_list

Output:

```<code>{0: [1, 2, 3], 1: [4, 5, 6], 2: [7, 8, 9], 3: [10, 11, 12]}
</code>```

Title: Lists Splitting Equal Split

Body:
I wrote a code that takes a certain input (int) and stores it to a list.

The next phase, which I can't manage to construct is to take the list and split it to 4 equal lists.

So far I take the sum of the prime_list and divide it to 4. the sum stored as var to further use.

prime_list = [1,2,3,4,5,6,7,8,9,10,11,12] split to equal 4 lists, divide by range (or other methods):

split_list_01 = [1,2,3]

split_list_02 = [4,5,6]

split_list_03 = [7,8,9]

split_list_04 = [10,11,12]

Body:
Try this:

prime_list = [1,2,3,4,5,6,7,8,9,10,11,12]
new_list = [prime_list[i:i+3] for i in range(0, len(prime_list), 3)]
print new_list

Output:

[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

A dictionary can be used to store each of the lists using different keys which can be accessed later:

prime_list = [1,2,3,4,5,6,7,8,9,10,11,12]

split_list = {}
count = 0
for i in range(0, len(prime_list), 3):
    split_list[count] = prime_list[i:i+3]
    count += 1

print split_list

Output:

{0: [1, 2, 3], 1: [4, 5, 6], 2: [7, 8, 9], 3: [10, 11, 12]}


问:
understanding crop hints by google vision ai
i am trying google vision api for crop hints and the output results are like below

i am having hard time understanding these crop hints to be able to use on my image. so first thing is the empty vertices. what are they? also i was hoping all the pairs will have a x and y value to draw on 2D space. but some has only x and some has only y.

finally how should i get my final image? i am using firebase cloud function which is a nodejs with typescript to operate on my original image to get final image?

ideally i want this to happen on device but it seems there are no cordova plugins yet to run autoML on device to capture and crop the image as soon as prominent object is detected.

is there any other cordova plugin that can help to capture the promiment image auto capture as soon as it is visible in camera?

```<code>{
  "cropHintsAnnotation": {
    "cropHints": [
      {
        "boundingPoly": {
          "vertices": [
            {},
            {
              "x": 2499
            },
            {
              "x": 2499,
              "y": 3132
            },
            {
              "y": 3132
            }
          ]
        },
        "confidence": 0.79999995,
        "importanceFraction": 0.98999995
      },
      {
        "boundingPoly": {
          "vertices": [
            {},
            {
              "x": 2499
            },
            {
              "x": 2499,
              "y": 2532
            },
            {
              "y": 2532
            }
          ]
        },
        "confidence": 0.79999995,
        "importanceFraction": 0.91999996
      },
      {
        "boundingPoly": {
          "vertices": [
            {},
            {
              "x": 2499
            },
            {
              "x": 2499,
              "y": 2098
            },
            {
              "y": 2098
            }
          ]
        },
        "confidence": 0.79999995,
        "importanceFraction": 0.81
      }
    ]
  }
}
```

```

答: A missing x or y means that its value is 0.</p>

Body:
i am trying google vision api for crop hints and the output results are like below

i am having hard time understanding these crop hints to be able to use on my image. so first thing is the empty vertices. what are they? also i was hoping all the pairs will have a x and y value to draw on 2D space. but some has only x and some has only y.

finally how should i get my final image? i am using firebase cloud function which is a nodejs with typescript to operate on my original image to get final image?

ideally i want this to happen on device but it seems there are no cordova plugins yet to run autoML on device to capture and crop the image as soon as prominent object is detected.

is there any other cordova plugin that can help to capture the promiment image auto capture as soon as it is visible in camera?

{
  "cropHintsAnnotation": {
    "cropHints": [
      {
        "boundingPoly": {
          "vertices": [
            {},
            {
              "x": 2499
            },
            {
              "x": 2499,
              "y": 3132
            },
            {
              "y": 3132
            }
          ]
        },
        "confidence": 0.79999995,
        "importanceFraction": 0.98999995
      },
      {
        "boundingPoly": {
          "vertices": [
            {},
            {
              "x": 2499
            },
            {
              "x": 2499,
              "y": 2532
            },
            {
              "y": 2532
            }
          ]
        },
        "confidence": 0.79999995,
        "importanceFraction": 0.91999996
      },
      {
        "boundingPoly": {
          "vertices": [
            {},
            {
              "x": 2499
            },
            {
              "x": 2499,
              "y": 2098
            },
            {
              "y": 2098
            }
          ]
        },
        "confidence": 0.79999995,
        "importanceFraction": 0.81
      }
    ]
  }
}
```


问:
Extract English letters and numbers using regex
I have the following code that extracts the English letters from mixed English and Arabic letters

```<code>Sub Test()
Dim a           As Variant
Dim i           As Long

With Cells(1).CurrentRegion.Resize(, 3)
    a = .Value
    With CreateObject("VBScript.RegExp")
        .Global = True
        For i = 1 To UBound(a, 1)
            .Pattern = "[^\w_ ]+"
            a(i, 3) = Trim$(.Replace(a(i, 1), ""))
        Next i
    End With
    .Value = a
End With
End Sub
</code>```

I need to change the pattern so as to be able to extract the numbers too .. so I need to extract the English letters and also the numbers.

答:
Add \d after \w . This allows for extraction of numbers if the numbers are between the Arabic letters.

From comment by @Tiw / OP.

Body:
I have the following code that extracts the English letters from mixed English and Arabic letters

Sub Test()
Dim a           As Variant
Dim i           As Long

With Cells(1).CurrentRegion.Resize(, 3)
    a = .Value
    With CreateObject("VBScript.RegExp")
        .Global = True
        For i = 1 To UBound(a, 1)
            .Pattern = "[^\w_ ]+"
            a(i, 3) = Trim$(.Replace(a(i, 1), ""))
        Next i
    End With
    .Value = a
End With
End Sub

I need to change the pattern so as to be able to extract the numbers too .. so I need to extract the English letters and also the numbers.


问:
p2p file sharing python
When I start the program to share files to client it received it but when i request for another file download it failed with this error.

```<code> Now i keep getting this error from the client
 socket1.send(bytes('0', 'UTF-8'))
 BrokenPipeError: [Errno 32] Broken pipe
 line 46 client.py
</code>```

I tried breaking out of the server's filedownload loop but still not working.
server

```<code>    #! /usr/bin/env python3

    import socket
    import sys
    import os
    import hashlib
    import time

    HOST = 127.0.0.1
    PORT = 5000
    c = 0 #used to count cycles
    bufsize = 4096

    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        print('Server Created')
    except OSError as e:
        print('Failed to create socket. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
        sys.exit()

    try:
        s.bind((HOST, PORT))
    except OSError as e:
        print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
        sys.exit()
    print('Socket bind complete')

    s.listen(1)
    print('Server now listening')

    while 1:
        conn, addr = s.accept()
        print('Connected with ' + addr[0] + ':' + str(addr[1]))
        reqCommand = conn.recv(1024).decode("utf-8", errors='ignore')
        print('Client> %s' % reqCommand)
        string = reqCommand.split(' ', 1)
        if reqCommand == 'quit':
            break
        elif reqCommand == 'lls':
            toSend = ""
            path = os.getcwd()
            dirs = os.listdir(path)
            for f in dirs:
                toSend = toSend + f + ' '
            conn.send(toSend.encode('utf-8'))
            # print path

        else:
            string = reqCommand.split(' ', 1)  # in case of 'put' and 'get' method
            if len(string) > 1:
                reqFile = string[1]

                if string[0] == 'FileDownload':
                    with open(reqFile, 'rb') as file_to_send1:
                        # get the entire filesize, which sets the read sector to EOF
                        file_size = len(file_to_send1.read())
                        # reset the read file sector to the start of the file
                        file_to_send1.seek(0)
                        # take filesize and write it to a temp file
                        with open('temp01',mode='w', encoding='UTF-8') as file_to_send2:
                            file_to_send2.write(str(file_size))
                        # pass the file size over to client in a small info chunk
                        with open('temp01', 'rb') as file_to_send3:
                            conn.send(file_to_send3.read(1024))
                        #send the total file size off the client
                        while (c*bufsize) < file_size:
                            send_data = file_to_send1.read(bufsize)
                            conn.send(send_data)
                            c += 1
                            # get bool (0 is bad | 1 is good) from client
                            chunk_write_flag = int(conn.recv(1024))
                            while chunk_write_flag != 1: #while whole data was not sent..retry until successful
                                conn.send(send_data)
                                #get status from client after a retry
                                chunk_write_flag = int(conn.recv(1024))
                            # used on the last chunk of the file xfer
                            # if the file.read() is less than buffer size do last tasks
                            if (file_size - (c*bufsize)) < bufsize:
                                send_data = file_to_send1.read(bufsize)
                                conn.send(send_data)
                                file_to_send1.close()
                            break
                        #for data in file_to_send:
                            #conn.sendall(data)
                    print('Send Successful')
        conn.close()
    s.close()
</code>```

client

```<code>   #! /usr/bin/env python3

    import socket
    import sys
    import os
    import hashlib
    import time

    HOST = 127.0.0.1
    PORT = 5000
    c = 0
    bufsize = 4096

    def get(commandName):
        socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        socket1.connect((HOST, PORT))
        socket1.send(commandName.encode("utf-8"))
        string = commandName.split(' ', 1)
        inputFile = string[1]
        c = 0
        # before starting to write new file, get file size
        file_size = int(socket1.recv(1024)) # from file_to_send3
        # print (file_size)
        # set byte buffer size
        bufsize = 4096
        # start writing at the beginning and use following variable to track
        write_sectors = 0
        # this only opens the file, the while loop controls when to close
        with open(inputFile, 'wb+') as file_to_write:
            # while written bytes to out is less than file_size
            while write_sectors < file_size:
                # write the BUFSIZE while the write_sector is less than file_size
                file_to_write.write(socket1.recv(bufsize))
                c += 1
                with open(inputFile, 'rb') as verify:
                    write_check = (len(verify.read()) / c)
                    verify.seek(0) # read cycle moves seek location, reset it
                    while write_check != bufsize:
                        # where the original write started, to send back to server
                        if c > 1: file_to_write.seek((c-1) * bufsize)
                        if c == 1: file_to_write.seek(0)
                        # send to server that the write was not successful
                        socket1.send(bytes('0', 'UTF-8'))
                        file_to_write.write(socket1.recv(bufsize))
                        write_check = int(len(verify.read()) /c )
                        # if last packet, smaller than bufsize
                    socket1.send(bytes('1', 'UTF-8')) #send SUCCESS back to server
                if (file_size - (write_check * c)) < bufsize:
                    #file_to_write.write(socket1.recv(bufsize))
                    verify.close()
                    #file_to_write.close()
                    file_size = 0
                write_sectors += bufsize # successful write, move 'while' check
                # add the written sectors by the bufsize.
                # example if filesize in bytes is 4096 you need to track how much
                # was written to figure out where the EOF  is
            file_to_write.write(socket1.recv(bufsize)) # write the last chunk missed by while loop
                #data = socket1.recv(4096).decode("utf-8", errors="ignore")
                #if not data: break
                    #break
                # print data
                #file_to_write.write(bytes(data.encode()))
            #file_to_write.close()
        print('Download Successful')
        socket1.close()
        return

                  def serverList(commandName):
        socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        socket1.connect((HOST, PORT))
        socket1.send(commandName.encode('utf-8'))
        fileStr = socket1.recv(1024)
        fileList = fileStr.decode('utf-8').split(' ')
        for f in fileList:
            print(f)

        socket1.close()
        return

    msg = input('Enter your name: ')
    while 1:
        print("\n")
        print('"FileDownload [filename]" to download the file from the server ')
        print('"lls" to list all files in the server')
        sys.stdout.write('%s> ' % msg)
        inputCommand = sys.stdin.readline().strip()

            if inputCommand == 'lls':
            serverList('lls')

        else:
            string = inputCommand.split(' ', 1)
            if string[0] == 'FileDownload':
</code>```

Please can anyone help me,i don't know to fix it. I'll appreciate any help.
Thanks

答:
Server.py

class BufferedReceiver():
    def __init__(self, sock):
        self.sock = sock
        self.buffer = ""
        self.bufferPos = 0

    def _fetch(self):
        while self.bufferPos >= len(self.buffer):
            self.buffer = self.sock.recv(1024)
            # print(self.buffer)
            self.bufferPos = 0

    def take(self, amount):
        result = bytearray()
        while(len(result) < amount):
            # Fetch new data if necessary
            self._fetch()

            result.append(self.buffer[self.bufferPos])
            self.bufferPos += 1
        return bytes(result)

    def take_until(self, ch):
        result = bytearray()
        while True:
            # Fetch new data if necessary
            self._fetch()

            nextByte = self.buffer[self.bufferPos]
            self.bufferPos += 1

            result.append(nextByte)
            if bytes([nextByte]) == ch:
                break

        return bytes(result)
```

<p>Then, I simplified your server send routine after the <code>else:</code>:</p>

<pre class="lang-py prettyprint-override"><code>        string = reqCommand.split(' ', 1)  # in case of 'put' and 'get' method
        if len(string) > 1:
            reqFile = string[1]

            if string[0] == 'FileDownload':
                with open(reqFile, 'rb') as file_to_send1:
                    # get the entire filesize, which sets the read sector to EOF
                    file_size = len(file_to_send1.read())
                    # reset the read file sector to the start of the file
                    file_to_send1.seek(0)
                    # pass the file size over to client in a small info chunk
                    print('Filesize:', file_size)
                    conn.send((str(file_size)+'\n').encode())
                    #send the total file size off the client
                    c = 0
                    while (c*bufsize) < file_size:
                        send_data = file_to_send1.read(bufsize)
                        conn.send(send_data)
                        c += 1
                print('Send Successful')
</code>```

Client.py

def get(commandName):
    socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket1.connect((HOST, PORT))
    socket1.send(commandName.encode("utf-8"))

    receiver = BufferedReceiver(socket1)

    string = commandName.split(' ', 1)
    inputFile = string[1]

    # before starting to write new file, get file size
    file_size = int(receiver.take_until(b'\n').decode().strip()) # from file_to_send3
    print ('Filesize:', file_size)
    # set byte buffer size
    bufsize = 4096
    # this only opens the file, the while loop controls when to close
    with open(inputFile, 'wb+') as file_to_write:
        # while written bytes to out is less than file_size

        c = 0
        while True:

            # Compute how much bytes we have left to receive
            bytes_left = file_size - bufsize * c

            # If we are almost done, do the final iteration
            if bytes_left <= bufsize:
                file_to_write.write(receiver.take(bytes_left))
                break

            # Otherwise, just continue receiving
            file_to_write.write(receiver.take(bufsize))
            c += 1

    #TODO open file again, verify.
    # Generate MD5 on server while sending. Then, send MD5 to client.
    # Open finished file in client again and compare MD5s

    print('Download Successful')
    socket1.close()
    return
```

Title: p2p file sharing python

Body:
When I start the program to share files to client it received it but when i request for another file download it failed with this error.

 Now i keep getting this error from the client
 socket1.send(bytes('0', 'UTF-8'))
 BrokenPipeError: [Errno 32] Broken pipe
 line 46 client.py

I tried breaking out of the server's filedownload loop but still not working.
server

    #! /usr/bin/env python3

    import socket
    import sys
    import os
    import hashlib
    import time

    HOST = 127.0.0.1
    PORT = 5000
    c = 0 #used to count cycles
    bufsize = 4096

    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        print('Server Created')
    except OSError as e:
        print('Failed to create socket. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
        sys.exit()

    try:
        s.bind((HOST, PORT))
    except OSError as e:
        print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
        sys.exit()
    print('Socket bind complete')

    s.listen(1)
    print('Server now listening')

    while 1:
        conn, addr = s.accept()
        print('Connected with ' + addr[0] + ':' + str(addr[1]))
        reqCommand = conn.recv(1024).decode("utf-8", errors='ignore')
        print('Client> %s' % reqCommand)
        string = reqCommand.split(' ', 1)
        if reqCommand == 'quit':
            break
        elif reqCommand == 'lls':
            toSend = ""
            path = os.getcwd()
            dirs = os.listdir(path)
            for f in dirs:
                toSend = toSend + f + ' '
            conn.send(toSend.encode('utf-8'))
            # print path

        else:
            string = reqCommand.split(' ', 1)  # in case of 'put' and 'get' method
            if len(string) > 1:
                reqFile = string[1]

                if string[0] == 'FileDownload':
                    with open(reqFile, 'rb') as file_to_send1:
                        # get the entire filesize, which sets the read sector to EOF
                        file_size = len(file_to_send1.read())
                        # reset the read file sector to the start of the file
                        file_to_send1.seek(0)
                        # take filesize and write it to a temp file
                        with open('temp01',mode='w', encoding='UTF-8') as file_to_send2:
                            file_to_send2.write(str(file_size))
                        # pass the file size over to client in a small info chunk
                        with open('temp01', 'rb') as file_to_send3:
                            conn.send(file_to_send3.read(1024))
                        #send the total file size off the client
                        while (c*bufsize) < file_size:
                            send_data = file_to_send1.read(bufsize)
                            conn.send(send_data)
                            c += 1
                            # get bool (0 is bad | 1 is good) from client
                            chunk_write_flag = int(conn.recv(1024))
                            while chunk_write_flag != 1: #while whole data was not sent..retry until successful
                                conn.send(send_data)
                                #get status from client after a retry
                                chunk_write_flag = int(conn.recv(1024))
                            # used on the last chunk of the file xfer
                            # if the file.read() is less than buffer size do last tasks
                            if (file_size - (c*bufsize)) < bufsize:
                                send_data = file_to_send1.read(bufsize)
                                conn.send(send_data)
                                file_to_send1.close()
                            break
                        #for data in file_to_send:
                            #conn.sendall(data)
                    print('Send Successful')
        conn.close()
    s.close()

client

   #! /usr/bin/env python3

    import socket
    import sys
    import os
    import hashlib
    import time

    HOST = 127.0.0.1
    PORT = 5000
    c = 0
    bufsize = 4096

    def get(commandName):
        socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        socket1.connect((HOST, PORT))
        socket1.send(commandName.encode("utf-8"))
        string = commandName.split(' ', 1)
        inputFile = string[1]
        c = 0
        # before starting to write new file, get file size
        file_size = int(socket1.recv(1024)) # from file_to_send3
        # print (file_size)
        # set byte buffer size
        bufsize = 4096
        # start writing at the beginning and use following variable to track
        write_sectors = 0
        # this only opens the file, the while loop controls when to close
        with open(inputFile, 'wb+') as file_to_write:
            # while written bytes to out is less than file_size
            while write_sectors < file_size:
                # write the BUFSIZE while the write_sector is less than file_size
                file_to_write.write(socket1.recv(bufsize))
                c += 1
                with open(inputFile, 'rb') as verify:
                    write_check = (len(verify.read()) / c)
                    verify.seek(0) # read cycle moves seek location, reset it
                    while write_check != bufsize:
                        # where the original write started, to send back to server
                        if c > 1: file_to_write.seek((c-1) * bufsize)
                        if c == 1: file_to_write.seek(0)
                        # send to server that the write was not successful
                        socket1.send(bytes('0', 'UTF-8'))
                        file_to_write.write(socket1.recv(bufsize))
                        write_check = int(len(verify.read()) /c )
                        # if last packet, smaller than bufsize
                    socket1.send(bytes('1', 'UTF-8')) #send SUCCESS back to server
                if (file_size - (write_check * c)) < bufsize:
                    #file_to_write.write(socket1.recv(bufsize))
                    verify.close()
                    #file_to_write.close()
                    file_size = 0
                write_sectors += bufsize # successful write, move 'while' check
                # add the written sectors by the bufsize.
                # example if filesize in bytes is 4096 you need to track how much
                # was written to figure out where the EOF  is
            file_to_write.write(socket1.recv(bufsize)) # write the last chunk missed by while loop
                #data = socket1.recv(4096).decode("utf-8", errors="ignore")
                #if not data: break
                    #break
                # print data
                #file_to_write.write(bytes(data.encode()))
            #file_to_write.close()
        print('Download Successful')
        socket1.close()
        return

                  def serverList(commandName):
        socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        socket1.connect((HOST, PORT))
        socket1.send(commandName.encode('utf-8'))
        fileStr = socket1.recv(1024)
        fileList = fileStr.decode('utf-8').split(' ')
        for f in fileList:
            print(f)

        socket1.close()
        return

    msg = input('Enter your name: ')
    while 1:
        print("\n")
        print('"FileDownload [filename]" to download the file from the server ')
        print('"lls" to list all files in the server')
        sys.stdout.write('%s> ' % msg)
        inputCommand = sys.stdin.readline().strip()

            if inputCommand == 'lls':
            serverList('lls')

        else:
            string = inputCommand.split(' ', 1)
            if string[0] == 'FileDownload':

Please can anyone help me,i don't know to fix it. I'll appreciate any help.
Thanks

Body:
Server.py

class BufferedReceiver():
    def __init__(self, sock):
        self.sock = sock
        self.buffer = ""
        self.bufferPos = 0

    def _fetch(self):
        while self.bufferPos >= len(self.buffer):
            self.buffer = self.sock.recv(1024)
            # print(self.buffer)
            self.bufferPos = 0

    def take(self, amount):
        result = bytearray()
        while(len(result) < amount):
            # Fetch new data if necessary
            self._fetch()

            result.append(self.buffer[self.bufferPos])
            self.bufferPos += 1
        return bytes(result)

    def take_until(self, ch):
        result = bytearray()
        while True:
            # Fetch new data if necessary
            self._fetch()

            nextByte = self.buffer[self.bufferPos]
            self.bufferPos += 1

            result.append(nextByte)
            if bytes([nextByte]) == ch:
                break

        return bytes(result)

Then, I simplified your server send routine after the else::

        string = reqCommand.split(' ', 1)  # in case of 'put' and 'get' method
        if len(string) > 1:
            reqFile = string[1]

            if string[0] == 'FileDownload':
                with open(reqFile, 'rb') as file_to_send1:
                    # get the entire filesize, which sets the read sector to EOF
                    file_size = len(file_to_send1.read())
                    # reset the read file sector to the start of the file
                    file_to_send1.seek(0)
                    # pass the file size over to client in a small info chunk
                    print('Filesize:', file_size)
                    conn.send((str(file_size)+'\n').encode())
                    #send the total file size off the client
                    c = 0
                    while (c*bufsize) < file_size:
                        send_data = file_to_send1.read(bufsize)
                        conn.send(send_data)
                        c += 1
                print('Send Successful')

Client.py

def get(commandName):
    socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket1.connect((HOST, PORT))
    socket1.send(commandName.encode("utf-8"))

    receiver = BufferedReceiver(socket1)

    string = commandName.split(' ', 1)
    inputFile = string[1]

    # before starting to write new file, get file size
    file_size = int(receiver.take_until(b'\n').decode().strip()) # from file_to_send3
    print ('Filesize:', file_size)
    # set byte buffer size
    bufsize = 4096
    # this only opens the file, the while loop controls when to close
    with open(inputFile, 'wb+') as file_to_write:
        # while written bytes to out is less than file_size

        c = 0
        while True:

            # Compute how much bytes we have left to receive
            bytes_left = file_size - bufsize * c

            # If we are almost done, do the final iteration
            if bytes_left <= bufsize:
                file_to_write.write(receiver.take(bytes_left))
                break

            # Otherwise, just continue receiving
            file_to_write.write(receiver.take(bufsize))
            c += 1

    #TODO open file again, verify.
    # Generate MD5 on server while sending. Then, send MD5 to client.
    # Open finished file in client again and compare MD5s

    print('Download Successful')
    socket1.close()
    return


问:
Why does an empty Perl hash have one key?
The standard googleable answer to "How do I find out the size of a hash in Perl?" is "take the size of keys(%hash)":

```<code>my %h = {};
print scalar (keys (%h));
</code>```

This prints '1'. I was expecting zero. On the other hand. Similarly,

```<code>my %h = {};
$h{"a"} = "b";
$h{"x"} = "y";
print scalar keys (%h);
print "\nKey: $_" for (keys %h);
</code>```

Prints:

3

Key: a

Key: x

Key: HASH(0x229e8)

Where has this extra value come from?

答:
```<code>use Data::Dumper;

my %h = {};
warn Dumper \%h;
</code>```

%h gets assigned with a hash reference as the key and undef as the value.

Output:

```<code>$VAR1 = {
          'HASH(0x8683830)' => undef
        };
</code>```

As rafl suggested, the warnings pragma would have caught this.
Look at Greg Hewgill's answer for the corrected code.

Body:
The standard googleable answer to "How do I find out the size of a hash in Perl?" is "take the size of keys(%hash)":

my %h = {};
print scalar (keys (%h));

This prints '1'. I was expecting zero. On the other hand. Similarly,

my %h = {};
$h{"a"} = "b";
$h{"x"} = "y";
print scalar keys (%h);
print "\nKey: $_" for (keys %h);

Prints:

3

Key: a

Key: x

Key: HASH(0x229e8)

Where has this extra value come from?

Body:
use Data::Dumper;

my %h = {};
warn Dumper \%h;

%h gets assigned with a hash reference as the key and undef as the value.

Output:

$VAR1 = {
          'HASH(0x8683830)' => undef
        };

As rafl suggested, the warnings pragma would have caught this.
Look at Greg Hewgill's answer for the corrected code.