问:
MVC - Domain Service takes charge of filtering or does Repository Layer?
Should I be filtering my IQueryable results from the Domain Service?

For example... My 3 portals (Websites) access the same Domain Service Layer, depending on the type of user it is, I call a specific repository method and return the result,

Current Repository Layer:

```<code>    IQueryable<Products> GetAllProductsForCrazyUserNow(CrazyUser id);
    Products GetAProductForCrazyUserNow(CrazyUser id,product id);

    IQueryable<Products> GetProductsForNiceUserNow(NiceUser id);
    Products GetProductsForNiceUserNow(NiceUser id,product id);
</code>```

Would it be best just to do this in the Repository Layer:

```<code>    IQueryable<Products> GetAllProducts();
    Products GetAProduct(product id);
</code>```

Then within the Domain Service, I simple do the filter i.e.

```<code>var Niceman = IQueryable<Products> GetAllProducts().Where(u=> u.Name == "Nice");
</code>```

NOTE: I have a read only session and session which includes CRUD within the Repository Layer, so please keep that in mind when answering.

Second question: Should I do any filtering at all in the domain service layer? This very layer is the only layer than can amend the Entity i.e. Product.Price == 25.00; This is not delegated to the repository layer.

答:
Haroon,

I use extension methods on IQueryable<Classes> OUTSIDE of the repo.  in fact, i have a set of classes that i call 'Filters' and they are usually something along these lines:

```<code>public static class ProductFilters
{
    public static IQueryable<Products> NiceMan(
        this IQueryable<Products> customQuery, string filterName)
    {
        if (!string.IsNullOrEmpty(filterName))
           customQuery = customQuery.Where(u => u.Name == filterName);
        return customQuery;
    }
   // create lots of other Products based filters here
   // and repeat with seperate IQueryable<Classes> per type
}
</code>```

usage:

```<code>var Niceman = IQueryable<Products> GetAllProducts().NiceMan("Nice");
</code>```

I find this a good separation of logic and keeps the repo clean. And in answer to the second question, yes, use this filter/extension logic inside the service layer, rather than the repo as well.

Body:
Should I be filtering my IQueryable results from the Domain Service?

For example... My 3 portals (Websites) access the same Domain Service Layer, depending on the type of user it is, I call a specific repository method and return the result,

Current Repository Layer:

    IQueryable<Products> GetAllProductsForCrazyUserNow(CrazyUser id);
    Products GetAProductForCrazyUserNow(CrazyUser id,product id);

    IQueryable<Products> GetProductsForNiceUserNow(NiceUser id);
    Products GetProductsForNiceUserNow(NiceUser id,product id);

Would it be best just to do this in the Repository Layer:

    IQueryable<Products> GetAllProducts();
    Products GetAProduct(product id);

Then within the Domain Service, I simple do the filter i.e.

var Niceman = IQueryable<Products> GetAllProducts().Where(u=> u.Name == "Nice");

NOTE: I have a read only session and session which includes CRUD within the Repository Layer, so please keep that in mind when answering.

Second question: Should I do any filtering at all in the domain service layer? This very layer is the only layer than can amend the Entity i.e. Product.Price == 25.00; This is not delegated to the repository layer.

Body:
Haroon,

I use extension methods on IQueryable<Classes> OUTSIDE of the repo.  in fact, i have a set of classes that i call 'Filters' and they are usually something along these lines:

public static class ProductFilters
{
    public static IQueryable<Products> NiceMan(
        this IQueryable<Products> customQuery, string filterName)
    {
        if (!string.IsNullOrEmpty(filterName))
           customQuery = customQuery.Where(u => u.Name == filterName);
        return customQuery;
    }
   // create lots of other Products based filters here
   // and repeat with seperate IQueryable<Classes> per type
}

usage:

var Niceman = IQueryable<Products> GetAllProducts().NiceMan("Nice");

I find this a good separation of logic and keeps the repo clean. And in answer to the second question, yes, use this filter/extension logic inside the service layer, rather than the repo as well.


来源: stackexchange

问:
Select current element from getElementsbyClassName
This code will hide the first div, even if it were activated from the second button. What keyword should I use to get it to hide the parent div (first button hides the first div, second button hides the second div)?

var x = document.getElementsbyClassName(myClass);

function myFunction() {
  x[0].display = "none";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="myClass">
  <button onclick="myFunction()">Click</button>
</div>
<div class="myClass">
  <button onclick="myFunction()">Click</button>
</div></code>```

答:
If you pass on the event to the click handler, you can access the parent element through event.target.parentElement:

function myFunction(event) {
    event.target.parentElement.style.display = "none";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="myClass">
    <button onclick="myFunction(event)">Click</button>
</div>
<div class="myClass">
    <button onclick="myFunction(event)">Click</button>
</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
This code will hide the first div, even if it were activated from the second button. What keyword should I use to get it to hide the parent div (first button hides the first div, second button hides the second div)?

var x = document.getElementsbyClassName(myClass);

function myFunction() {
  x[0].display = "none";
}

  <button onclick="myFunction()">Click</button>

  <button onclick="myFunction()">Click</button>

Body:
If you pass on the event to the click handler, you can access the parent element through event.target.parentElement:

function myFunction(event) {
    event.target.parentElement.style.display = "none";
}

<div class="myClass">
    <button onclick="myFunction(event)">Click</button>
</div>
<div class="myClass">
    <button onclick="myFunction(event)">Click</button>
</div>


答:
Rather than trying to anticipate which element will be clicked by the user, simply use an event-listener which can take the element that has been interacted with and respond appropriately:

function hide() {

  // EventTarget.addEventListener() passes the 'this'
  // Node to the function; here 'this' is whichever
  // element was clicked:
  let target = this;

  // here we set the display of the clicked element's
  // parentNode to 'none':
  target.parentNode.style.display = 'none';
}

// here we use document.querySelectorAll(), which takes
// a CSS selector as an argument and returns an Array-Like
// nodeList of the found elements, which is passed to
// nodeList.forEach():
document.querySelectorAll('.myClass > button').forEach(

  // nodeList.forEach() iterates over the supplied nodeList,
  // to perform the supplied actions. Here we use an Arrow
  // function to perform the required action;
  // myClassElement is the current Element of the nodeList over
  // which we're iterating.
  // In the Arrow function we bind an event-listener to listen
  // for a 'click' event, which executes the supplied function
  // in response (note the deliberate omission of the parentheses;
  // we don't pass 'hide()' (unless you want to bind the result of
  // a supplied function):
  myClassElement => myClassElement.addEventListener('click', hide)
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="myClass">
  <button>Click</button>
</div>
<div class="myClass">
  <button>Click</button>
</div></code>```

In the above approach I've used an unobtrusive JavaScript approach, moving the event-handlers out of the HTML and into the JavaScript, this is better for 'pretty' HTML, but it's also better from a code-maintenance standpoint: it prevents you having to find all mentions of a function in the HTML to either remove the event-listener, or update them to a new function.

Incidentally, though, the above code should either be in a

Title: Select current element from getElementsbyClassName

Body:
Rather than trying to anticipate which element will be clicked by the user, simply use an event-listener which can take the element that has been interacted with and respond appropriately:

function hide() {

  // EventTarget.addEventListener() passes the 'this'
  // Node to the function; here 'this' is whichever
  // element was clicked:
  let target = this;

  // here we set the display of the clicked element's
  // parentNode to 'none':
  target.parentNode.style.display = 'none';
}

// here we use document.querySelectorAll(), which takes
// a CSS selector as an argument and returns an Array-Like
// nodeList of the found elements, which is passed to
// nodeList.forEach():
document.querySelectorAll('.myClass > button').forEach(

  // nodeList.forEach() iterates over the supplied nodeList,
  // to perform the supplied actions. Here we use an Arrow
  // function to perform the required action;
  // myClassElement is the current Element of the nodeList over
  // which we're iterating.
  // In the Arrow function we bind an event-listener to listen
  // for a 'click' event, which executes the supplied function
  // in response (note the deliberate omission of the parentheses;
  // we don't pass 'hide()' (unless you want to bind the result of
  // a supplied function):
  myClassElement => myClassElement.addEventListener('click', hide)
);

<div class="myClass">
  <button>Click</button>
</div>
<div class="myClass">
  <button>Click</button>
</div>

In the above approach I've used an unobtrusive JavaScript approach, moving the event-handlers out of the HTML and into the JavaScript, this is better for 'pretty' HTML, but it's also better from a code-maintenance standpoint: it prevents you having to find all mentions of a function in the HTML to either remove the event-listener, or update them to a new function.

Incidentally, though, the above code should either be in a <script> tag at the end of the document, before the closing </body> tag, or in an on-ready event-handler in the <head> of the document; otherwise – as JavaScript runs as it's encountered – the elements you wish to bind events to won't yet be present in the DOM when the event-listeners are bound.


问:
"An unexpected error has occurred" after firebase deploy
When I am hosting my web page through firebase hosting then after writing command firebase deploy I got the following error:

```
Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.

C:\Users\amarg\Desktop\amar>firebase init

     ######## #### ########  ######## ########     ###     ######  ########
     ##        ##  ##     ## ##       ##     ##  ##   ##  ##       ##
     ######    ##  ########  ######   ########  #########  ######  ######
     ##        ##  ##    ##  ##       ##     ## ##     ##       ## ##
     ##       #### ##     ## ######## ########  ##     ##  ######  ########

You're about to initialize a Firebase project in this directory:

  C:\Users\amarg\Desktop\amar

Before we get started, keep in mind:

  * You are initializing in an existing Firebase project directory

? Are you ready to proceed? Yes
? What Firebase CLI features do you want to setup for this folder? Hosting: Configure and deploy Firebase Hosting sites

=== Project Setup

First, let's associate this project directory with a Firebase project.
You can create multiple project aliases by running firebase use --add,
but for now we'll just set up a default project.

i  .firebaserc already has a default project, skipping

=== Hosting Setup

Your public directory is the folder (relative to your project directory) that
will contain Hosting assets to be uploaded with firebase deploy. If you
have a build process for your assets, use your build's output directory.

? What do you want to use as your public directory? public
? Configure as a single-page app (rewrite all urls to /index.html)? No
? File public/404.html already exists. Overwrite? No
i  Skipping write of public/404.html
? File public/index.html already exists. Overwrite? No
i  Skipping write of public/index.html

i  Writing configuration info to firebase.json...
i  Writing project information to .firebaserc...

+  Firebase initialization complete!

C:\Users\amarg\Desktop\amar>firebase deploy

=== Deploying to 'learningweb-6b2a3'...

i  deploying hosting
+  database: rules ready to deploy.
i  hosting: preparing public directory for upload...

Error: An unexpected error has occurred.

C:\Users\amarg\Desktop\amar>
```

答:
Yes I've faced this issue..
This is because of my node version I was using Node v.8.0.0
I just downgrade it to Node v.16.0.3 and then my deployment done :)

Body:
When I am hosting my web page through firebase hosting then after writing command firebase deploy I got the following error:

Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.

C:\Users\amarg\Desktop\amar>firebase init

     ######## #### ########  ######## ########     ###     ######  ########
     ##        ##  ##     ## ##       ##     ##  ##   ##  ##       ##
     ######    ##  ########  ######   ########  #########  ######  ######
     ##        ##  ##    ##  ##       ##     ## ##     ##       ## ##
     ##       #### ##     ## ######## ########  ##     ##  ######  ########

You're about to initialize a Firebase project in this directory:

  C:\Users\amarg\Desktop\amar

Before we get started, keep in mind:

  * You are initializing in an existing Firebase project directory

? Are you ready to proceed? Yes
? What Firebase CLI features do you want to setup for this folder? Hosting: Configure and deploy Firebase Hosting sites

=== Project Setup

First, let's associate this project directory with a Firebase project.
You can create multiple project aliases by running firebase use --add,
but for now we'll just set up a default project.

i  .firebaserc already has a default project, skipping

=== Hosting Setup

Your public directory is the folder (relative to your project directory) that
will contain Hosting assets to be uploaded with firebase deploy. If you
have a build process for your assets, use your build's output directory.

? What do you want to use as your public directory? public
? Configure as a single-page app (rewrite all urls to /index.html)? No
? File public/404.html already exists. Overwrite? No
i  Skipping write of public/404.html
? File public/index.html already exists. Overwrite? No
i  Skipping write of public/index.html

i  Writing configuration info to firebase.json...
i  Writing project information to .firebaserc...

+  Firebase initialization complete!

C:\Users\amarg\Desktop\amar>firebase deploy

=== Deploying to 'learningweb-6b2a3'...

i  deploying hosting
+  database: rules ready to deploy.
i  hosting: preparing public directory for upload...

Error: An unexpected error has occurred.

C:\Users\amarg\Desktop\amar>


问:
Python, specific count of chars in string
I am trying to count the number of occurrences in a string in python. I would like to take a binary input, say '001101'. Then count the number of 1s, 0s, 11s, 00s etc.

I have tried to implement this by using count, but this will output that there are 3 1s, when i only want it to output 1 1, and 1 11s and for it to not count them individually, unless they are on their own.

I have also tried to implement this with find, but i am having the same problem.

Any help would be appreciated, thanks.

答:
You could tackle this with regular expressions:

```<code>>>> import re
>>> s='001101'
</code>```

Single ones:

```<code>>>> sum(1 for _ in re.finditer('(?<!1)1(?!1)', s))
1
</code>```

Pairs of ones:

```<code>>>> sum(1 for _ in re.finditer('(?<!1)11(?!1)', s))
1
</code>```

and the same approach applies for groups of zeros.

Body:
You could tackle this with regular expressions:

>>> import re
>>> s='001101'

Single ones:

>>> sum(1 for _ in re.finditer('(?<!1)1(?!1)', s))
1

Pairs of ones:

>>> sum(1 for _ in re.finditer('(?<!1)11(?!1)', s))
1

and the same approach applies for groups of zeros.


问:
Outlook cant send intent pdf file in 7 android
Sorry for my english. In everething email client it code work fine. I send some files to email client and then if need edit this message and send from email client. But in outlook i have error:

```<code>Failed to attach attachments
</code>```

Bellow my code:

```<code>String theme = "Test";
 ArrayList<Uri> uris = new ArrayList<>();
        for(int i = 0; i < pdfs.length; i++) {
            File fileIn = new File(pdfs[i].getAbsolutePath());
            fileIn.setReadable(true);
            Uri u = Uri.fromFile(fileIn);
            uris.add(u);
        }

      Intent emailIntent = new Intent(ACTION_SEND_MULTIPLE);
     emailIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    emailIntent.setType("message/rfc822");

    String to[] = {sendTo};
        emailIntent.putExtra(EXTRA_EMAIL, to);
        emailIntent.putParcelableArrayListExtra(EXTRA_STREAM, uris);
        emailIntent.putExtra(EXTRA_SUBJECT, theme);
        emailIntent.putExtra(EXTRA_TEXT, context.getResources().getString(R.string.text_email_message_body));

        ((Activity) context).startActivityForResult(Intent.createChooser(emailIntent, "Choose an Email client:"), 1);
</code>```

I tryed setType text/plain, application/octet-stream, message/rfc822 nothing work

UPD:

I go to  Settings -> Applications -> Application Manager -> Outlook -> Permissions and enable the "Storage" permission manually and everething is work. But how i can enable permission  automaticaly when i send file outlook?

答:
You better do not mess around with permissions of other apps.

Instead you should use a file provider to serve your files

Body:
Sorry for my english. In everething email client it code work fine. I send some files to email client and then if need edit this message and send from email client. But in outlook i have error:

Failed to attach attachments

Bellow my code:

String theme = "Test";
 ArrayList<Uri> uris = new ArrayList<>();
        for(int i = 0; i < pdfs.length; i++) {
            File fileIn = new File(pdfs[i].getAbsolutePath());
            fileIn.setReadable(true);
            Uri u = Uri.fromFile(fileIn);
            uris.add(u);
        }

      Intent emailIntent = new Intent(ACTION_SEND_MULTIPLE);
     emailIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    emailIntent.setType("message/rfc822");

    String to[] = {sendTo};
        emailIntent.putExtra(EXTRA_EMAIL, to);
        emailIntent.putParcelableArrayListExtra(EXTRA_STREAM, uris);
        emailIntent.putExtra(EXTRA_SUBJECT, theme);
        emailIntent.putExtra(EXTRA_TEXT, context.getResources().getString(R.string.text_email_message_body));

        ((Activity) context).startActivityForResult(Intent.createChooser(emailIntent, "Choose an Email client:"), 1);

I tryed setType text/plain, application/octet-stream, message/rfc822 nothing work

UPD:

I go to  Settings -> Applications -> Application Manager -> Outlook -> Permissions and enable the "Storage" permission manually and everething is work. But how i can enable permission  automaticaly when i send file outlook?


问:
Inherit Post-Build-Event in Visual Studio?
I have a solution in Visual Studio in which I have a shared property sheet which contains a Post-Build Event command (bar) which needs to execute for every project.

Foo.props > Common Properties > Build Events > Post-Build Event >
  Command Line = bar

How do I then specify additional project-specific Post-Build Events? The usual "Inherit from parent or project defaults" is missing, and I would rather not have to manually add bar to every single project as it makes it hard to maintain.

答:
As some Post-Build Events did non inherit from the property sheet they are defined in, I questioned the duck and landed here.

I have good news:
Since Visual Studio 2013, the Pre-Build and Post-Build event command lines have a "Inherit from parent or project defaults" option, which adds all events from the property sheets.

(Tested with Visual Studio 2013 and 2017 Professional)


问:
Git best practices when creating multiple test branches
I've recently started using the branching functionality in git for maintaining my github project, and I understand how to create branches, switch between them, and merge them. However, most of the examples I've seen involve creating one non-master branch, then merging the new branch with master if the changes are to be kept. I haven't found examples for having multiple test branches in parallel.

For example, I'm trying to improve my one of my scripts and I have three different mutually exclusive ideas for improvements, so I make three new branches. I test the performance of the different branches, and decide to keep one.

Should I then just delete the two branches that I don't want, and then merge the final branch with master? Will the commits from those branches be kept so that I can revisit them if necessary, or will deleting the branches also delete those commits?

I'm the only contributor, so there's no issue with conflicts with other contributors.

答:
If you delete the other branches, this does not immediately delete the commits; but if you leave the commits unreferenced, then they can eventually be deleted.  There is a "garbage collection" process (gc) which runs at certain times (or when you ask it to run), and one of its tasks is to clean up "unreachable" objects (such as commits that are neither pointed to be a ref, nor pointed to by parent pointers of other reachable commits).

So if you want to keep the commits for future reference, you may not want to delete the branches.  Or, if you do want to delete the branches - so that they don't show up on "unmerge branch" lists, or something like that - then you can tag the head of each branch and then delete the branch.

Another option would be to merge each "wrong" branch and then revert the merge

```<code>A -------------- M1 - W1 - M2 - W2 - M3 <--(master)
 \              /         /          /
  x1 -- x2 -- x3         /          /
   \                    /          /
    y1 -- y2 -- y3 -- y4          /
     \                           /
      z1 - x2 - x3 - x4 - x5 - x6
</code>```

In this example, if you had branch_x and branch_y with solutions you decided not to keep, and branch_z with a solution you decided to keep, you could say

```<code>git checkout master
git merge x
git revert HEAD
git branch -d x
git merge y
git revert HEAD
git branch -d y
git merge z
git branch -d z
</code>```

This would tell git that you've accounted for the changes in all three branches, but only want to keep the changes from z.  This ensures the commits remain reachable so they can't be garbage-collected, and it lets you delete the branches.

On the other hand, actually finding the old commits, unless you tag them, could be a hassle - and if you're going to tag them so that you can find them later, then it may not make sense to merge them into your master where they can clutter history.

Body:
If you delete the other branches, this does not immediately delete the commits; but if you leave the commits unreferenced, then they can eventually be deleted.  There is a "garbage collection" process (gc) which runs at certain times (or when you ask it to run), and one of its tasks is to clean up "unreachable" objects (such as commits that are neither pointed to be a ref, nor pointed to by parent pointers of other reachable commits).

So if you want to keep the commits for future reference, you may not want to delete the branches.  Or, if you do want to delete the branches - so that they don't show up on "unmerge branch" lists, or something like that - then you can tag the head of each branch and then delete the branch.

Another option would be to merge each "wrong" branch and then revert the merge

A -------------- M1 - W1 - M2 - W2 - M3 <--(master)
 \              /         /          /
  x1 -- x2 -- x3         /          /
   \                    /          /
    y1 -- y2 -- y3 -- y4          /
     \                           /
      z1 - x2 - x3 - x4 - x5 - x6

In this example, if you had branch_x and branch_y with solutions you decided not to keep, and branch_z with a solution you decided to keep, you could say

git checkout master
git merge x
git revert HEAD
git branch -d x
git merge y
git revert HEAD
git branch -d y
git merge z
git branch -d z

This would tell git that you've accounted for the changes in all three branches, but only want to keep the changes from z.  This ensures the commits remain reachable so they can't be garbage-collected, and it lets you delete the branches.

On the other hand, actually finding the old commits, unless you tag them, could be a hassle - and if you're going to tag them so that you can find them later, then it may not make sense to merge them into your master where they can clutter history.


问:
Why the Retrofit response gives null value for fields, while the response can get the object?
I'm just making a simple application in Android Studio 2.3 to get a JSON response from the Web app. I chose Retrofit 2.0 for consuming the response.

It seems I could get the   objects inside onResponse

```<code>Object item =  response.body().get(1);
Log.e("success", String.valueOf(item));
</code>```

inside logcat it gives a success,

```<code>success:com.makemyapp.firstapplication.Item@67205ae
</code>```

But when tried to fetch the fields inside the object,

```<code>Object item =  response.body().get(1).getItemDescription();
Log.e("success", String.valueOf(item));
</code>```

It returns a null

```<code>success: null
</code>```

This is the Interface- GrocsApi,

```<code>package com.makemyapp.firstapplication;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;

public interface GrocsApi {

    @GET("api/getitemlist")
    Call<List<Item>> getItem();

}
</code>```

Class for returning service- GrocsService

```<code>package com.makemyapp.firstapplication;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class GrocsService {

    public  static GrocsApi service;
    public static String BASE_URL = "http://10.0.2.2:8000/";

    public static GrocsApi getGrocsService(){
        if (service==null){

            Retrofit retrofit= new Retrofit.Builder()
                              .baseUrl(BASE_URL)
                              .addConverterFactory(GsonConverterFactory.create())
                              .build();
            service = retrofit.create(GrocsApi.class);

            return service;
        }

return  service;
    }

}
</code>```

MainActivity.java ,where Request Call is initiated,

```<code>package com.makemyapp.firstapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {

    Button button;
    //TextView textView; for later use

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        onClickGetData();
    }

    public void onClickGetData(){

      //  textView=(TextView)findViewById(R.id.textView); for later use
        button=(Button)findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
  Call<List<Item>> call =   GrocsService.getGrocsService().getItem();

           call.enqueue(new Callback<List<Item>>  () {
                  @Override
                  public void onResponse(Call<List<Item>>  call, Response<List<Item>>   response) {

 if(response.isSuccessful()) {
     Object item =  response.body().get(1).getItemDescription();

     Log.e("success", String.valueOf(item));

 } else{
     Log.e("response is not good", "");
 }
                  }

                  @Override
                  public void onFailure(Call<List<Item>>   call, Throwable t) {

                      Log.e("failed", t.getMessage());

                  }
              });

            }

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

This is my POJO class- Item

```<code>package com.makemyapp.firstapplication;

public class Item {

    private Integer itemId;
    private Object itemName;
    private Object itemDescription;
    private Object itemPhotoUrl;
    private Object itemWikipediaLink;
    private Object itemTag;

    public Integer getItemId() {
        return itemId;
    }

    public void setItemId(Integer itemId) {
        this.itemId = itemId;
    }

    public Object getItemName() {
        return itemName;
    }

    public void setItemName(Object itemName) {
        this.itemName = itemName;
    }

    public Object getItemDescription() {
        return itemDescription;
    }

    public void setItemDescription(Object itemDescription) {
        this.itemDescription = itemDescription;
    }

    public Object getItemPhotoUrl() {
        return itemPhotoUrl;
    }

    public void setItemPhotoUrl(Object itemPhotoUrl) {
        this.itemPhotoUrl = itemPhotoUrl;
    }

    public Object getItemWikipediaLink() {
        return itemWikipediaLink;
    }

    public void setItemWikipediaLink(Object itemWikipediaLink) {
        this.itemWikipediaLink = itemWikipediaLink;
    }

    public Object getItemTag() {
        return itemTag;
    }

    public void setItemTag(Object itemTag) {
        this.itemTag = itemTag;
    }

}
</code>```

And the JSON response is ,

```<code>[{"ItemId":1,"ItemName":"Orange","ItemDescription":"Sweet and Juicy","ItemPhotoUrl":"https:\/\/en.wikipedia.org\/wiki\/Orange_(fruit)","ItemWikipediaLink":"'https:\/\/en.wikipedia.org\/wiki\/Orange_(fruit)#\/media\/File:Orange-Whole-%26-Split.jpg","ItemTag":"RS.70 per kg"},{"ItemId":3,"ItemName":"Apple","ItemDescription":"Reddish","ItemPhotoUrl":"https:\/\/en.wikipedia.org\/wiki\/Apple","ItemWikipediaLink":"https:\/\/en.wikipedia.org\/wiki\/Apple#\/media\/File:Red_Apple.jpg","ItemTag":"RS.10 per kg"},{"ItemId":4,"ItemName":"Mango","ItemDescription":"Fresh","ItemPhotoUrl":"https:\/\/en.wikipedia.org\/wiki\/Mango#\/media\/File:Mangoes_pic.jpg","ItemWikipediaLink":"https:\/\/en.wikipedia.org\/wiki\/Mango","ItemTag":"RS.100 per kg"},{"ItemId":5,"ItemName":"Pineapple","ItemDescription":"Large and Juicy","ItemPhotoUrl":"https:\/\/en.wikipedia.org\/wiki\/Pineapple#\/media\/File:Pineapple_and_cross_section.jpg","ItemWikipediaLink":"https:\/\/en.wikipedia.org\/wiki\/Pineapple","ItemTag":"RS.50 per kg"},{"ItemId":6,"ItemName":"Grapes","ItemDescription":"Dark and Juicy","ItemPhotoUrl":"https:\/\/en.wikipedia.org\/wiki\/Grape#\/media\/File:Abhar-iran.JPG","ItemWikipediaLink":"https:\/\/en.wikipedia.org\/wiki\/Grape","ItemTag":"110 per kg"},{"ItemId":7,"ItemName":"Guava","ItemDescription":"Green","ItemPhotoUrl":null,"ItemWikipediaLink":null,"ItemTag":"50 per kg"},{"ItemId":8,"ItemName":null,"ItemDescription":null,"ItemPhotoUrl":null,"ItemWikipediaLink":null,"ItemTag":null}]
</code>```

Could any one spot a light on my problem?

答:
Just add @SerializedName on each field of Item class with the JsonObject name that will fill this field.

for example:

```<code>@SerializedName("ItemId") // Case sensitive
private Integer itemId;
</code>```

In your MainActivity:

```<code>Call<List<Item>> call =   GrocsService.getGrocsService().getItem(); //It's here where you call getItem(). you will enque the request after that as you already did.
</code>```

than in your onResponse callback, you get your list:

```<code>List<item> myResponse =  (List<Item>) response.body();
</code>```

and than you fetch your list of items.

Body:
I'm just making a simple application in Android Studio 2.3 to get a JSON response from the Web app. I chose Retrofit 2.0 for consuming the response.

It seems I could get the   objects inside onResponse

Object item =  response.body().get(1);
Log.e("success", String.valueOf(item));

inside logcat it gives a success,

success:com.makemyapp.firstapplication.Item@67205ae

But when tried to fetch the fields inside the object,

Object item =  response.body().get(1).getItemDescription();
Log.e("success", String.valueOf(item));

It returns a null

success: null

This is the Interface- GrocsApi,

package com.makemyapp.firstapplication;
import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;

public interface GrocsApi {

    @GET("api/getitemlist")
    Call<List<Item>> getItem();

}

Class for returning service- GrocsService

package com.makemyapp.firstapplication;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class GrocsService {

    public  static GrocsApi service;
    public static String BASE_URL = "http://10.0.2.2:8000/";

    public static GrocsApi getGrocsService(){
        if (service==null){

            Retrofit retrofit= new Retrofit.Builder()
                              .baseUrl(BASE_URL)
                              .addConverterFactory(GsonConverterFactory.create())
                              .build();
            service = retrofit.create(GrocsApi.class);

            return service;
        }

return  service;
    }

}

MainActivity.java ,where Request Call is initiated,

package com.makemyapp.firstapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {

    Button button;
    //TextView textView; for later use

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        onClickGetData();
    }

    public void onClickGetData(){

      //  textView=(TextView)findViewById(R.id.textView); for later use
        button=(Button)findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
  Call<List<Item>> call =   GrocsService.getGrocsService().getItem();

           call.enqueue(new Callback<List<Item>>  () {
                  @Override
                  public void onResponse(Call<List<Item>>  call, Response<List<Item>>   response) {

 if(response.isSuccessful()) {
     Object item =  response.body().get(1).getItemDescription();

     Log.e("success", String.valueOf(item));

 } else{
     Log.e("response is not good", "");
 }
                  }

                  @Override
                  public void onFailure(Call<List<Item>>   call, Throwable t) {

                      Log.e("failed", t.getMessage());

                  }
              });

            }

        }
    );
}
}

This is my POJO class- Item

package com.makemyapp.firstapplication;

public class Item {

    private Integer itemId;
    private Object itemName;
    private Object itemDescription;
    private Object itemPhotoUrl;
    private Object itemWikipediaLink;
    private Object itemTag;

    public Integer getItemId() {
        return itemId;
    }

    public void setItemId(Integer itemId) {
        this.itemId = itemId;
    }

    public Object getItemName() {
        return itemName;
    }

    public void setItemName(Object itemName) {
        this.itemName = itemName;
    }

    public Object getItemDescription() {
        return itemDescription;
    }

    public void setItemDescription(Object itemDescription) {
        this.itemDescription = itemDescription;
    }

    public Object getItemPhotoUrl() {
        return itemPhotoUrl;
    }

    public void setItemPhotoUrl(Object itemPhotoUrl) {
        this.itemPhotoUrl = itemPhotoUrl;
    }

    public Object getItemWikipediaLink() {
        return itemWikipediaLink;
    }

    public void setItemWikipediaLink(Object itemWikipediaLink) {
        this.itemWikipediaLink = itemWikipediaLink;
    }

    public Object getItemTag() {
        return itemTag;
    }

    public void setItemTag(Object itemTag) {
        this.itemTag = itemTag;
    }

}

And the JSON response is ,

[{"ItemId":1,"ItemName":"Orange","ItemDescription":"Sweet and Juicy","ItemPhotoUrl":"https:\/\/en.wikipedia.org\/wiki\/Orange_(fruit)","ItemWikipediaLink":"'https:\/\/en.wikipedia.org\/wiki\/Orange_(fruit)#\/media\/File:Orange-Whole-%26-Split.jpg","ItemTag":"RS.70 per kg"},{"ItemId":3,"ItemName":"Apple","ItemDescription":"Reddish","ItemPhotoUrl":"https:\/\/en.wikipedia.org\/wiki\/Apple","ItemWikipediaLink":"https:\/\/en.wikipedia.org\/wiki\/Apple#\/media\/File:Red_Apple.jpg","ItemTag":"RS.10 per kg"},{"ItemId":4,"ItemName":"Mango","ItemDescription":"Fresh","ItemPhotoUrl":"https:\/\/en.wikipedia.org\/wiki\/Mango#\/media\/File:Mangoes_pic.jpg","ItemWikipediaLink":"https:\/\/en.wikipedia.org\/wiki\/Mango","ItemTag":"RS.100 per kg"},{"ItemId":5,"ItemName":"Pineapple","ItemDescription":"Large and Juicy","ItemPhotoUrl":"https:\/\/en.wikipedia.org\/wiki\/Pineapple#\/media\/File:Pineapple_and_cross_section.jpg","ItemWikipediaLink":"https:\/\/en.wikipedia.org\/wiki\/Pineapple","ItemTag":"RS.50 per kg"},{"ItemId":6,"ItemName":"Grapes","ItemDescription":"Dark and Juicy","ItemPhotoUrl":"https:\/\/en.wikipedia.org\/wiki\/Grape#\/media\/File:Abhar-iran.JPG","ItemWikipediaLink":"https:\/\/en.wikipedia.org\/wiki\/Grape","ItemTag":"110 per kg"},{"ItemId":7,"ItemName":"Guava","ItemDescription":"Green","ItemPhotoUrl":null,"ItemWikipediaLink":null,"ItemTag":"50 per kg"},{"ItemId":8,"ItemName":null,"ItemDescription":null,"ItemPhotoUrl":null,"ItemWikipediaLink":null,"ItemTag":null}]

Could any one spot a light on my problem?

Body:
Just add @SerializedName on each field of Item class with the JsonObject name that will fill this field.

for example:

@SerializedName("ItemId") // Case sensitive
private Integer itemId;

In your MainActivity:

Call<List<Item>> call =   GrocsService.getGrocsService().getItem(); //It's here where you call getItem(). you will enque the request after that as you already did.

than in your onResponse callback, you get your list:

List<item> myResponse =  (List<Item>) response.body();

and than you fetch your list of items.


问:
exclude a sub directory from .htaccess 301 redirects
Can you tell me how I can exclude a specific folder from the 301 redirects set up as below in htaccess</p>

```<code><IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteCond %{REQUEST_METHOD} ^TRAC[EK]
RewriteRule .* - [L,R=405]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule .* index.php [L]
</IfModule>
</code>```

答:
This should work:</p>

```<code><IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine on

RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} !^(/excluded_directory)
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteCond %{REQUEST_METHOD} ^TRAC[EK]
RewriteRule .* - [L,R=405]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule .* index.php [L]
</IfModule>
</code>```

Body:
Can you tell me how I can exclude a specific folder from the 301 redirects set up as below in htaccess

<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteCond %{REQUEST_METHOD} ^TRAC[EK]
RewriteRule .* - [L,R=405]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule .* index.php [L]
</IfModule>

Body:
This should work:

<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine on

RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} !^(/excluded_directory)
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteCond %{REQUEST_METHOD} ^TRAC[EK]
RewriteRule .* - [L,R=405]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule .* index.php [L]
</IfModule>


问:
Deffered deep link throught playstore
I'm trying to configure my deffered deep link, but it only works when my app is already installed, I've been DeeplinkMe tutorial, but I only achieve downloading my app from playstore, when I open, it goes to main activity, not the one defined on Manifest. Here goes my Manifest file:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.guisantogui.randomize">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".randomGeneration.RandomizeActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".randomHistory.RandomizeHistoryActivity"
            android:label="@string/title_activity_randomize_history"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter android:label="@string/app_name">
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <!-- Accepts URIs that begin with "http://www.example.com/gizmos” -->
                <data
                    android:scheme="randomizer.app" />
            </intent-filter>

        </activity>
    </application>

</manifest>
</code>```

Deeplinkme configuration:

答:
I recently wrote an exhaustive list of deeplinking methods available on Android.
It contains advantages/drawbacks for each methods and code snippets to help implement them.

What might work for you is a mix of Referrer Receiver and Deferred Deeplink

Source: https://simonmarquis.github.io/Android-App-Linking/

Title: Deffered deep link throught playstore

Body:
I'm trying to configure my deffered deep link, but it only works when my app is already installed, I've been DeeplinkMe tutorial, but I only achieve downloading my app from playstore, when I open, it goes to main activity, not the one defined on Manifest. Here goes my Manifest file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.guisantogui.randomize">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".randomGeneration.RandomizeActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".randomHistory.RandomizeHistoryActivity"
            android:label="@string/title_activity_randomize_history"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter android:label="@string/app_name">
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <data
                    android:scheme="randomizer.app" />
            </intent-filter>

        </activity>
    </application>

</manifest>

Deeplinkme configuration:


问:
tensor processing unit in google cloud
Google offers Machine Learning Units for it's cloud machine learning platform, are these the Tensor Processing Units which gained so much attention a while back?

I have requested this information from Google, but the sales department did not have technical information available.

This question was answered over a year ago here: TPU custom chip available with Google Cloud ML
but as cloud is moving at amazing speed I am requesting up to date information.

答:
ML units are used as a until of billing on Cloud Machine Learning Engine, similar to vCPU*hours on GCE. They simpy track your usage of the product per hour.

Cloud TPU is an IaaS offering for using the TPUs you mentioned on Google Cloud.

Title: tensor processing unit in google cloud


问:
Is there a library / api for reading the contents of a .hlp help file?
I have a help file for my program and was asked to add a description of the menus in a toolbar as the user browses them. So I thought I could just use the beginning of the menu's description of the help but just cant find how to access the contents of it.

I saw WinHelp has a macro language, so I figured maybe through this, but I couldnt find any references on this around.

Anybody now some pointers or examples of hot to do this?

答:
First, your help system should have an Index on each topic that permits you to open help and have that topic appear (if not, then check out Help & Manual - it'll help you build more complete help files). However, this doesn't directly solve your problem since, as I understand it, you want this to pop up in a toolhelp Window.

Thus, you'll need to go under the surface and figure out how the Help system uses the key to pull the appropriate information.  However, it is not a trivial undertaking (as far as I can tell) to directly access a specific, indexed chunk of text in a WinHelp file. You may find some information here that is of use. You might also want to browse the forums on the Help and Manual web site.

Here's a bigger question though: does it really make sense to pop up an entire help topic (even if short) when a user just hovers over a menu item or button?  It doesn't to me and I spent years in a UI design group at Bell Labs.  It is A) simply too much information and B) going to be visually distracting (and thus incredibly irritating) to experienced users.  The accepted practice here is to pop up a toolhelp window with a very short (1-4 words) descriptor of the button ("Open" or "Open File").

If you want the help to be available for each menu item or button, I would suggest one of two alternatives.

First, consider having a "Help Cursor mode" where the cursor uses the help icon (an arrow with a question mark).  The user accesses it via a Help button on the button bar.  When in Help Cursor mode, a user click on any item will take them to the help topic for that item.  I'm kind of lukewarm to this approach since it is modal but I've certainly seen it done.

Second, you might simply beef up your help system a bit.  That is, create a topic in your Help system that features a screen shot of your application. On this screenshot, create hot spots for each menu item and/or button and permit the user to go to the appropriate topic by clicking on it.  Done right, this gives the user a visual key to the topics they wish to learn about without interfering with the normal operation of your program.

Most importantly: before doing all of the work necessary to implement your current plan, be sure it is the right plan!

OwnerDisplayName: boccato

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Mark Brittingham


问:
Get some random and some specific records in a single query?
So I have a cover-flow style image carousel populated by a query like

```<code>SELECT foo FROM `imageTable` ORDER BY RAND() LIMIT 0, 12;
</code>```

My client would like to add to this a set of permanent images.  Due to the way the results are used it would be very handy if I could make those records part of my original query.

I tried

```<code>SELECT foo FROM `imageTable` WHERE `id` = 'x' OR `id` = 'y'
  OR `id` IS NOT NULL ORDER BY RAND() LIMIT 0, 12;
</code>```

I was hoping the records with the ids would necessarily be in the result set but nope the RAND() shuffles the whole set.

So my question is whether any single query could provide the x permanent records and then y random records?

// EDIT WITH REVISED QUERY USING Adrian Serafin's answer:

```<code>(SELECT * FROM `imageTable` ORDER BY RAND() LIMIT 0, 6)
UNION
(SELECT * FROM `imageTable`  WHERE `id` = 'foo' OR `id` = 'bar' OR `id` = 'baz')
</code>```

答:
Union them together, but prevent X and Y from showing more than once
You can also use IN instead of multiple OR statements to be more concise.</p>

```<code>SELECT foo FROM (
    SELECT foo FROM `imageTable`
    WHERE id NOT IN ('x','y','z')
    ORDER BY RAND() LIMIT 0, 9    # reduce by 3
) A
UNION ALL
SELECT foo FROM (
    SELECT foo FROM `imageTable`
    WHERE id IN ('x','y','z')
) B
ORDER BY RAND()    # order again so that x,y,z are anywhere in the set
</code>```

Body:
So I have a cover-flow style image carousel populated by a query like

SELECT foo FROM `imageTable` ORDER BY RAND() LIMIT 0, 12;

My client would like to add to this a set of permanent images.  Due to the way the results are used it would be very handy if I could make those records part of my original query.

I tried

SELECT foo FROM `imageTable` WHERE `id` = 'x' OR `id` = 'y'
  OR `id` IS NOT NULL ORDER BY RAND() LIMIT 0, 12;

I was hoping the records with the ids would necessarily be in the result set but nope the RAND() shuffles the whole set.

So my question is whether any single query could provide the x permanent records and then y random records?

// EDIT WITH REVISED QUERY USING Adrian Serafin's answer:

(SELECT * FROM `imageTable` ORDER BY RAND() LIMIT 0, 6)
UNION
(SELECT * FROM `imageTable`  WHERE `id` = 'foo' OR `id` = 'bar' OR `id` = 'baz')

Body:
Union them together, but prevent X and Y from showing more than once
You can also use IN instead of multiple OR statements to be more concise.

SELECT foo FROM (
    SELECT foo FROM `imageTable`
    WHERE id NOT IN ('x','y','z')
    ORDER BY RAND() LIMIT 0, 9    # reduce by 3
) A
UNION ALL
SELECT foo FROM (
    SELECT foo FROM `imageTable`
    WHERE id IN ('x','y','z')
) B
ORDER BY RAND()    # order again so that x,y,z are anywhere in the set


问:
Relation between `<*>` and `<$>`
According to the Haskell Wikibook, the following relation between <$> and <*> hold:

```<code>f <$> x = pure f <*> x
</code>```

They claim that one can prove this theorem as a consequence of the functor and applicative laws.

I do not see how to prove this. Any help is appreciated.

答:
The Functor and Applicative Laws

Let's start with what the functor and applicative laws are. Let's take a look at these laws presented in the Haskell Wikibook.

```<code>fmap id = id                   -- 1st functor law
fmap (g . f) = fmap g . fmap f -- 2nd functor law
</code>```

Now we should look at the applicative laws.

```<code>pure id <*> v = v                            -- Identity
pure f <*> pure x = pure (f x)               -- Homomorphism
u <*> pure y = pure ($ y) <*> u              -- Interchange
pure (.) <*> u <*> v <*> w = u <*> (v <*> w) -- Composition
</code>```

The identity law says that applying the pure id morphism does nothing, exactly like with the plain id function.

The homomorphism law says that applying a "pure" function to a "pure" value is the same as applying the function to the value in the normal way and then using pure on the result. In a sense, that means pure preserves function application.

The interchange law says that applying a morphism to a "pure" value pure y is the same as applying pure ($ y) to the morphism. No surprises there - as we have seen in the higher order functions chapter, ($ y) is the function that supplies y as argument to another function.

The composition law says that pure (.) composes morphisms similarly to how (.) composes functions: applying the composed morphism pure (.) <*> u <*> v to w gives the same result as applying u to the result of applying v to w.

What we need to prove in order to prove the relation

Per @benjamin-hodgson

it suffices to show that fmap f x = pure f <*> x obeys the fmap id = id law as a consequence of the Applicative laws.

The reason that we only need to show that fmap f x = pure f <*> x obeys the fmap id = id law is because the second functor law can be shown to follow from the first law. I've provided a brief walk through this proof, but Edward Kmett has a more verbose version here

Section 3.5 of Wadler's Theorems for Free provides some work on the function map. Based on the idea of free theorems anything that is shown for a function holds for any other function of the same type signature. Since we know that the list is a functor the type of map :: (a -> b) -> [a] -> [b] is analogous to the type of fmap :: Functor f => (a -> b) -> [a] -> [b] which means that all of Wadler's work with map applies to fmap as well.

Wadler's conclusion about map leads to this theorem about fmap:

Given functions f, g, k, and h such that g . h = k . f then $map g . fmap h = fmap k . $map' f with $map being the "natural" mapping function for a given functor. The full proof of this theorem is a bit verbose, but Bartosz Milewski provides a good overview of it.

We will need two lemmas to show that the second functor law is a consequence of the first.

Lemma 1

Given fmap id = id --the first functor law then fmap f = $map f

```<code>fmap f = $map id . fmap f   --Because $map id = id
= fmap id . $map f          --Because of the free theorem with g = k = id and h = f
= $map f                    --Because of the first functor law
</code>```

So fmap f = $map f and by extension fmap = $map

Lemma 2

f . g = id . (f . g) which is obvious given that id . v = v

Putting it all together

Given fmap id = id then fmap f . fmap g = fmap (f . g)

```<code>fmap f . fmap g = $map f . fmap g  --Because of lemma 1
= fmap id . $map (f . g)           --Because of the free theorem for fmap and lemma 2
= $map (f . g)                     --Because of the first functor law
= fmap (f . g)                     --Because $map = fmap
</code>```

Therefore, if we can show that the first functor law holds, then the second will also hold.

Proving the relation

To show that we'll need the Applicative Identity law. Looking at the law we have pure id <*> v = v and from the equivalence we are trying to prove f <$> x = pure f <*> x. If we let x = id then the Applicative Identity law tells us that the right hand side of that equivalence is id x and the first Functor law tells us that the left hand side is id x.

```<code>f <$> x = pure f <*> x
id <$> x = pure id <*> x  -- Substitute id into the general form
id <$> x = x              -- Apply the applicative identity law
id x = x                  -- Apply the first functor law
x = x                     -- simplify id x to x
</code>```

There we have shown that fmap f x = pure f <*> x obeys the first functor law by applying the applicative laws.

Title: Relation between `<*>` and `<$>`

Body:
According to the Haskell Wikibook, the following relation between <$> and <*> hold:

f <$> x = pure f <*> x

They claim that one can prove this theorem as a consequence of the functor and applicative laws.

I do not see how to prove this. Any help is appreciated.

Body:
The Functor and Applicative Laws

Let's start with what the functor and applicative laws are. Let's take a look at these laws presented in the Haskell Wikibook.

fmap id = id                   -- 1st functor law
fmap (g . f) = fmap g . fmap f -- 2nd functor law

Now we should look at the applicative laws.

pure id <*> v = v                            -- Identity
pure f <*> pure x = pure (f x)               -- Homomorphism
u <*> pure y = pure ($ y) <*> u              -- Interchange
pure (.) <*> u <*> v <*> w = u <*> (v <*> w) -- Composition

The identity law says that applying the pure id morphism does nothing, exactly like with the plain id function.

The homomorphism law says that applying a "pure" function to a "pure" value is the same as applying the function to the value in the normal way and then using pure on the result. In a sense, that means pure preserves function application.

The interchange law says that applying a morphism to a "pure" value pure y is the same as applying pure ($ y) to the morphism. No surprises there - as we have seen in the higher order functions chapter, ($ y) is the function that supplies y as argument to another function.

The composition law says that pure (.) composes morphisms similarly to how (.) composes functions: applying the composed morphism pure (.) <*> u <*> v to w gives the same result as applying u to the result of applying v to w.

What we need to prove in order to prove the relation

Per @benjamin-hodgson

it suffices to show that fmap f x = pure f <*> x obeys the fmap id = id law as a consequence of the Applicative laws.

The reason that we only need to show that fmap f x = pure f <*> x obeys the fmap id = id law is because the second functor law can be shown to follow from the first law. I've provided a brief walk through this proof, but Edward Kmett has a more verbose version here

Section 3.5 of Wadler's Theorems for Free provides some work on the function map. Based on the idea of free theorems anything that is shown for a function holds for any other function of the same type signature. Since we know that the list is a functor the type of map :: (a -> b) -> [a] -> [b] is analogous to the type of fmap :: Functor f => (a -> b) -> [a] -> [b] which means that all of Wadler's work with map applies to fmap as well.

Wadler's conclusion about map leads to this theorem about fmap:

Given functions f, g, k, and h such that g . h = k . f then $map g . fmap h = fmap k . $map' f with $map being the "natural" mapping function for a given functor. The full proof of this theorem is a bit verbose, but Bartosz Milewski provides a good overview of it.

We will need two lemmas to show that the second functor law is a consequence of the first.

Lemma 1

Given fmap id = id --the first functor law then fmap f = $map f

fmap f = $map id . fmap f   --Because $map id = id
= fmap id . $map f          --Because of the free theorem with g = k = id and h = f
= $map f                    --Because of the first functor law

So fmap f = $map f and by extension fmap = $map

Lemma 2

f . g = id . (f . g) which is obvious given that id . v = v

Putting it all together

Given fmap id = id then fmap f . fmap g = fmap (f . g)

fmap f . fmap g = $map f . fmap g  --Because of lemma 1
= fmap id . $map (f . g)           --Because of the free theorem for fmap and lemma 2
= $map (f . g)                     --Because of the first functor law
= fmap (f . g)                     --Because $map = fmap

Therefore, if we can show that the first functor law holds, then the second will also hold.

Proving the relation

To show that we'll need the Applicative Identity law. Looking at the law we have pure id <*> v = v and from the equivalence we are trying to prove f <$> x = pure f <*> x. If we let x = id then the Applicative Identity law tells us that the right hand side of that equivalence is id x and the first Functor law tells us that the left hand side is id x.

f <$> x = pure f <*> x
id <$> x = pure id <*> x  -- Substitute id into the general form
id <$> x = x              -- Apply the applicative identity law
id x = x                  -- Apply the first functor law
x = x                     -- simplify id x to x

There we have shown that fmap f x = pure f <*> x obeys the first functor law by applying the applicative laws.


问:
Creating an url within a div button using django url + div button value ie div id
I have created a clickable div to act as  a 'button'that links to another page within my site. Is it possible to append the div ID into the url I call such that different divs call the same django url (as the base) but through the appended div id ended up going to different pages .

for example:
this example works with the pack.id being appended but in the scenario I want to implement I do not used a django model

```<code><div id="ticket1">
<a  href="{% url 'student-packages-add' pack.id %}">
</div>
</code>```

trying to do:

```<code><div id="ticket1">
<a  href="{% url 'student-packages-add' div.id %}">
</div>
</code>```

what doesn't work and creates errors:

```<code><div id="ticket1">
<a  href="{% url 'student-packages-add' ticket1 %}">
</div>
</code>```

or

```<code><div id="ticket1">
<a  href="{% url 'student-packages-add' "ticket1" %}">
</div>
</code>```

答:
You can do this by creating a variable inside your template with the with template tag:

```<code>{% with div_id="ticket1" %}
    <div id={{div_id}}>
    <a  href="{% url 'student-packages-add' div_id %}">
    </div>
{% endwith %}
</code>```

Alternatively, if each div represents a ticket, then you can do something like the following:

```<code><div id="ticket{{ ticket.id }}">
<a  href="{% url 'student-packages-add' ticket.id %}">
</div>
</code>```

supposing that ticket in ticket.id is an object representing an instance of your model.

Body:
I have created a clickable div to act as  a 'button'that links to another page within my site. Is it possible to append the div ID into the url I call such that different divs call the same django url (as the base) but through the appended div id ended up going to different pages .

for example:
this example works with the pack.id being appended but in the scenario I want to implement I do not used a django model

trying to do:

what doesn't work and creates errors:

or

Body:
You can do this by creating a variable inside your template with the with template tag:

{% with div_id="ticket1" %}
    <div id={{div_id}}>
    <a  href="{% url 'student-packages-add' div_id %}">
    </div>
{% endwith %}

Alternatively, if each div represents a ticket, then you can do something like the following:

<div id="ticket{{ ticket.id }}">
<a  href="{% url 'student-packages-add' ticket.id %}">
</div>

supposing that ticket in ticket.id is an object representing an instance of your model.


问:
Azure function cosmos db output using local.settings.json
Having a look through the documentation on azure functions, specifically this one. It's very clear how to setup integrations via the portal, but developing locally is very vague.

My code is structured below as follows:

```<code>[FunctionName("foobar")]
public static void Run([QueueTrigger("foo")]Foo myQueueItem, out object dbFoo)
{
  //do cool stuff here
}
</code>```

The queue trigger works very well with the Azure storage emulator but there are no instructions on how to setup the local.settings.json. The file that was auto-generated via visual studio and looks like:

```<code>{
   "IsEncrypted": false,
   "Values": {
      "AzureWebJobsStorage": "UseDevelopmentStorage=true",
      "AzureWebJobsDashboard": ""
   }
}
</code>```

Where would the connection information for cosmos db sit within this structure to enable the function to operate correctly?

答:
It should look like this:

public static void Run(
    [QueueTrigger("foo")] Foo myQueueItem,
    [DocumentDB("MyDB", "MyCollection", ConnectionStringSetting = "MyConnectionString")]
    out object dbFoo)
```

<p>and the config would be:</p>

<pre class="lang-cs prettyprint-override"><code>{
    "IsEncrypted": false,
    "Values": {
        "MyConnectionString": "...your cosmos db string..."
    }
}
</code>```

In Azure, you would have to put MyConnectionString parameter to App Settings.

Update: In V2 version of Functions DocumentDB binding attribute was replaced by CosmosDB attribute, see docs.

Body:
Having a look through the documentation on azure functions, specifically this one. It's very clear how to setup integrations via the portal, but developing locally is very vague.

My code is structured below as follows:

[FunctionName("foobar")]
public static void Run([QueueTrigger("foo")]Foo myQueueItem, out object dbFoo)
{
  //do cool stuff here
}

The queue trigger works very well with the Azure storage emulator but there are no instructions on how to setup the local.settings.json. The file that was auto-generated via visual studio and looks like:

{
   "IsEncrypted": false,
   "Values": {
      "AzureWebJobsStorage": "UseDevelopmentStorage=true",
      "AzureWebJobsDashboard": ""
   }
}

Where would the connection information for cosmos db sit within this structure to enable the function to operate correctly?

Body:
It should look like this:

public static void Run(
    [QueueTrigger("foo")] Foo myQueueItem,
    [DocumentDB("MyDB", "MyCollection", ConnectionStringSetting = "MyConnectionString")]
    out object dbFoo)

and the config would be:

{
    "IsEncrypted": false,
    "Values": {
        "MyConnectionString": "...your cosmos db string..."
    }
}

In Azure, you would have to put MyConnectionString parameter to App Settings.

Update: In V2 version of Functions DocumentDB binding attribute was replaced by CosmosDB attribute, see docs.

ContentLicense: CC BY-SA 4.0


问:
How can I correctly create a WSO2 ESB API that uses HTTPS instead HTTP as protocol?
I am not so into WSO2 ESB and I have the following doubt.

I have deployed on my Carbon server some APIs, that works fine.

These APIs are using HTTP as protocol. For some reason I have to change it into HTTPS.

My doubs is: have I only to change the protocol attribute (of the resource tag) value form http to https?

```<code><?xml version="1.0" encoding="UTF-8"?>
<api context="/meteo_forecast_weekly_v2/location" name="meteo_forecast_weekly_v2" xmlns="http://ws.apache.org/ns/synapse">
    <resource methods="GET" protocol="http" uri-template="/{localizationId}">
        ...............................................................
        ...............................................................
        ...............................................................
</code>```

Or have I also to configure a certificate in my Carbon server?

EDIT-1: I tryied to do as suggested by BHA but when I do the call in this way I obtain this unknown protocol error:

```<code>$ curl -k https://XXX.YYY.ZZZ.WWW:8280/meteo_forecast_weekly_v2/location/1
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
curl: (35) error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
</code>```

Into the WSO2 stacktrace I obtain this error log:

```<code>TID: [-1] [] [2017-11-14 14:46:00,107] ERROR {org.apache.synapse.transport.passthru.SourceHandler} -  HttpException occurred  {org.apache.synapse.transport.passthru.SourceHandler}
org.apache.http.ProtocolException: Invalid request line: ü8Ò�;Cá©h0ß©�ø_¹i°eõ»Ê.,q5© À0À,À(À$ÀÀ
        at org.apache.http.impl.nio.codecs.AbstractMessageParser.parse(AbstractMessageParser.java:208)
        at org.apache.synapse.transport.http.conn.LoggingNHttpServerConnection$LoggingNHttpMessageParser.parse(LoggingNHttpServerConnection.java:407)
        at org.apache.synapse.transport.http.conn.LoggingNHttpServerConnection$LoggingNHttpMessageParser.parse(LoggingNHttpServerConnection.java:381)
        at org.apache.http.impl.nio.DefaultNHttpServerConnection.consumeInput(DefaultNHttpServerConnection.java:265)
        at org.apache.synapse.transport.http.conn.LoggingNHttpServerConnection.consumeInput(LoggingNHttpServerConnection.java:114)
        at org.apache.synapse.transport.passthru.ServerIODispatch.onInputReady(ServerIODispatch.java:82)
        at org.apache.synapse.transport.passthru.ServerIODispatch.onInputReady(ServerIODispatch.java:39)
        at org.apache.http.impl.nio.reactor.AbstractIODispatch.inputReady(AbstractIODispatch.java:113)
        at org.apache.http.impl.nio.reactor.BaseIOReactor.readable(BaseIOReactor.java:159)
        at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvent(AbstractIOReactor.java:338)
        at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvents(AbstractIOReactor.java:316)
        at org.apache.http.impl.nio.reactor.AbstractIOReactor.execute(AbstractIOReactor.java:277)
        at org.apache.http.impl.nio.reactor.BaseIOReactor.execute(BaseIOReactor.java:105)
        at org.apache.http.impl.nio.reactor.AbstractMultiworkerIOReactor$Worker.run(AbstractMultiworkerIOReactor.java:586)
        at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.http.ParseException: Invalid request line: ü8Ò�;Cá©h0ß©�ø_¹i°eõ»Ê.,q5© À0À,À(À$ÀÀ
        at org.apache.http.message.BasicLineParser.parseRequestLine(BasicLineParser.java:287)
        at org.apache.http.impl.nio.codecs.DefaultHttpRequestParser.createMessage(DefaultHttpRequestParser.java:119)
        at org.apache.http.impl.nio.codecs.DefaultHttpRequestParser.createMessage(DefaultHttpRequestParser.java:51)
        at org.apache.http.impl.nio.codecs.AbstractMessageParser.parseHeadLine(AbstractMessageParser.java:156)
        at org.apache.http.impl.nio.codecs.AbstractMessageParser.parse(AbstractMessageParser.java:206)
        ... 14 more
TID: [-1] [] [2017-11-14 14:46:00,113]  INFO {org.apache.synapse.transport.passthru.SourceHandler} -  Writer null when calling informWriterError {org.apache.synapse.transport.passthru.SourceHandler}
</code>```

Why? What is the problem?

答: Yes, you only have to change protocol value. By default ESB uses it's default keystore which is in <ESB_HOME>/repository/reources/security/wso2carbon.jks. When you're in production it's recommended to change the default keystore.

Body:
I am not so into WSO2 ESB and I have the following doubt.

I have deployed on my Carbon server some APIs, that works fine.

These APIs are using HTTP as protocol. For some reason I have to change it into HTTPS.

My doubs is: have I only to change the protocol attribute (of the resource tag) value form http to https?

<?xml version="1.0" encoding="UTF-8"?>
<api context="/meteo_forecast_weekly_v2/location" name="meteo_forecast_weekly_v2" xmlns="http://ws.apache.org/ns/synapse">
    <resource methods="GET" protocol="http" uri-template="/{localizationId}">
        ...............................................................
        ...............................................................
        ...............................................................

Or have I also to configure a certificate in my Carbon server?

EDIT-1: I tryied to do as suggested by BHA but when I do the call in this way I obtain this unknown protocol error:

$ curl -k https://XXX.YYY.ZZZ.WWW:8280/meteo_forecast_weekly_v2/location/1
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
curl: (35) error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol

Into the WSO2 stacktrace I obtain this error log:

TID: [-1] [] [2017-11-14 14:46:00,107] ERROR {org.apache.synapse.transport.passthru.SourceHandler} -  HttpException occurred  {org.apache.synapse.transport.passthru.SourceHandler}
org.apache.http.ProtocolException: Invalid request line: ü8Ò�;Cá©h0ß©�ø_¹i°eõ»Ê.,q5© À0À,À(À$ÀÀ
        at org.apache.http.impl.nio.codecs.AbstractMessageParser.parse(AbstractMessageParser.java:208)
        at org.apache.synapse.transport.http.conn.LoggingNHttpServerConnection$LoggingNHttpMessageParser.parse(LoggingNHttpServerConnection.java:407)
        at org.apache.synapse.transport.http.conn.LoggingNHttpServerConnection$LoggingNHttpMessageParser.parse(LoggingNHttpServerConnection.java:381)
        at org.apache.http.impl.nio.DefaultNHttpServerConnection.consumeInput(DefaultNHttpServerConnection.java:265)
        at org.apache.synapse.transport.http.conn.LoggingNHttpServerConnection.consumeInput(LoggingNHttpServerConnection.java:114)
        at org.apache.synapse.transport.passthru.ServerIODispatch.onInputReady(ServerIODispatch.java:82)
        at org.apache.synapse.transport.passthru.ServerIODispatch.onInputReady(ServerIODispatch.java:39)
        at org.apache.http.impl.nio.reactor.AbstractIODispatch.inputReady(AbstractIODispatch.java:113)
        at org.apache.http.impl.nio.reactor.BaseIOReactor.readable(BaseIOReactor.java:159)
        at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvent(AbstractIOReactor.java:338)
        at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvents(AbstractIOReactor.java:316)
        at org.apache.http.impl.nio.reactor.AbstractIOReactor.execute(AbstractIOReactor.java:277)
        at org.apache.http.impl.nio.reactor.BaseIOReactor.execute(BaseIOReactor.java:105)
        at org.apache.http.impl.nio.reactor.AbstractMultiworkerIOReactor$Worker.run(AbstractMultiworkerIOReactor.java:586)
        at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.http.ParseException: Invalid request line: ü8Ò�;Cá©h0ß©�ø_¹i°eõ»Ê.,q5© À0À,À(À$ÀÀ
        at org.apache.http.message.BasicLineParser.parseRequestLine(BasicLineParser.java:287)
        at org.apache.http.impl.nio.codecs.DefaultHttpRequestParser.createMessage(DefaultHttpRequestParser.java:119)
        at org.apache.http.impl.nio.codecs.DefaultHttpRequestParser.createMessage(DefaultHttpRequestParser.java:51)
        at org.apache.http.impl.nio.codecs.AbstractMessageParser.parseHeadLine(AbstractMessageParser.java:156)
        at org.apache.http.impl.nio.codecs.AbstractMessageParser.parse(AbstractMessageParser.java:206)
        ... 14 more
TID: [-1] [] [2017-11-14 14:46:00,113]  INFO {org.apache.synapse.transport.passthru.SourceHandler} -  Writer null when calling informWriterError {org.apache.synapse.transport.passthru.SourceHandler}

Why? What is the problem?


问:
Unable to open Tensorboard in browser
I am following google cloud machine learning tutorial and I am unable to Launch TensorBoard

I've followed the steps in the above tutorial (also set up my environment using docker container) until typing the below command in the terminal

```<code>tensorboard --logdir=data/ --port=8080
</code>```

Where the terminal outputs the below prompt

```<code>Starting TensorBoard 29 on port 8080
(You can navigate to http://172.17.0.2:8080)
</code>```

When I visit http://172.17.0.2:8080 in my browser I see nothing (the server where this page is located is not responding).

Can someone please advice how I can launch Tensor Board ?

答:
Had the same problem this morning. Solved it with

```<code>tensorboard --logdir=data/ --host localhost --port 8088
</code>```

Navigated the browser to http://localhost:8088

Title: Unable to open Tensorboard in browser

Body:
I am following google cloud machine learning tutorial and I am unable to Launch TensorBoard

I've followed the steps in the above tutorial (also set up my environment using docker container) until typing the below command in the terminal

tensorboard --logdir=data/ --port=8080

Where the terminal outputs the below prompt

Starting TensorBoard 29 on port 8080
(You can navigate to http://172.17.0.2:8080)

When I visit http://172.17.0.2:8080 in my browser I see nothing (the server where this page is located is not responding).

Can someone please advice how I can launch Tensor Board ?

Body:
Had the same problem this morning. Solved it with

tensorboard --logdir=data/ --host localhost --port 8088

Navigated the browser to http://localhost:8088


问:
HSL Image Adjustements on GPU
I have an application where the user should be able to modify an image with sliders for hue, saturation and lightness. All image processing is done on the GPU using GLSL fragment shaders.

My problem is that RGB -> HSL -> RGB conversions are rather expensive on the gpu due to the extensive branching.

My question is whether I can convert the users "color adjustments" to some other color space which can more efficiently compute the adjusted image on the GPU.

答:
For lightness and saturation you can use YUV (actually YCbCr). It's easy to convert from RGB and back. No branching needed. Saturation is controlled by increasing or decreasing both Cr and Cb. Lightness is Y.

You get something similar to HSL hue modification by rotating Cb and Cr components (it's practically a 3D vector), but of course it depends on your application if that's enough.

Edit: A color component (Cb,Cr) is a point in a color plane like above. If you take any random point and rotate it around the center, result is hue changing. But as mechanism is a bit different than in HSL, results are not precisely same.

Image is public domain from Wikipedia.

Title: HSL Image Adjustements on GPU


问:
Identify how the function has been called in closure javascript
Recently i faced one problem in hackerrank which has to calculate multiplication operation and has to return the answer. For example

```<code>function multiply(a,b) {
     return a*b;
}
</code>```

Now here is the problem the function might call in different ways such as

```<code>multiply(4,5);
multiply(4)(5);
multiply(4)(5)(6);
</code>```

I know we have to closure apporach for the second one which is multiply(4)(5). I had written code for that

```<code>function multiply(a,b) {
  return function(b) {
    return a*b;
  }
}
</code>```

Now what if its been multiply function has been called with 3 arguments multiply(4)(5)(6). How can i identify how the function has been called and how can i write a common solution for all the inputs.

Any help is appreciated. Thanks

答:
You're close, what you are trying to do is called currying, a technique that takes advantage of closures.

In this case, your function should only take one argument at a time:

```<code>function multiply(a) {
    return function(b) {
        return a * b;
    }
}
</code>```

Now you could say

```<code>function multiplyBy5 = multiply(5);
console.log(multiplyBy5(4)); //would log 20
</code>```

If you're only expecting at max 3 arguments you could do:

```<code>function multiply(a) {
    return function(b) {
        return function(c) {
            c = c || 1;
            return a * b * c;
        }
    }
}
</code>```

Which makes c an optional argument. You can call that function by

```<code>multiply(4)(5)()

//or

multiply(4)(5)(6)
</code>```

Body:
Recently i faced one problem in hackerrank which has to calculate multiplication operation and has to return the answer. For example

function multiply(a,b) {
     return a*b;
}

Now here is the problem the function might call in different ways such as

multiply(4,5);
multiply(4)(5);
multiply(4)(5)(6);

I know we have to closure apporach for the second one which is multiply(4)(5). I had written code for that

function multiply(a,b) {
  return function(b) {
    return a*b;
  }
}

Now what if its been multiply function has been called with 3 arguments multiply(4)(5)(6). How can i identify how the function has been called and how can i write a common solution for all the inputs.

Any help is appreciated. Thanks

Body:
You're close, what you are trying to do is called currying, a technique that takes advantage of closures.

In this case, your function should only take one argument at a time:

function multiply(a) {
    return function(b) {
        return a * b;
    }
}

Now you could say

function multiplyBy5 = multiply(5);
console.log(multiplyBy5(4)); //would log 20

If you're only expecting at max 3 arguments you could do:

function multiply(a) {
    return function(b) {
        return function(c) {
            c = c || 1;
            return a * b * c;
        }
    }
}

Which makes c an optional argument. You can call that function by

multiply(4)(5)()

//or

multiply(4)(5)(6)


问:
ionic app ,on click of a button not work
I am developing an app and this is second screen where i am getting problem.
There is a skip button and when i press it the "div containing text in it " should hide .

I have written codes in typescript file "home.ts" and have written html of it it in home.html and css in home.css

there are only 2 screens i have done with these codes,one is splash screen and other one is disclaimer or home screen where i am trying to hide the div with text on click of skip button

Here is home.ts code:

```<code>import { Component,ViewChild} from '@angular/core';
import { NavController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl:'home.html'
})
export class HomePage {
@ViewChild('username')username;
@ViewChild('password')password;

  splash = true;

  constructor(public navCtrl: NavController ) {
    }
    showhide(){

      var toggle = function() {
      var mydiv = document.getElementById('div');
      if (mydiv.style.display === 'block' || mydiv.style.display === ''){
        mydiv.style.display = 'none';
      }
      else{
        mydiv.style.display = 'block';
      }
      }
    }

  ionViewDidLoad() {
    setTimeout(() => this.splash = false, 4000);

  }

    }

and here is home.html file

<html>
        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="initial-scale=1,maximum-scale=1, user-scalable=no">
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
            <script src="lib/jquery-1.11.1.js"></script>
            <script src="lib/ionic/js/ionic.bundle.js"></script>
            <script src="js/app.js"></script>
            <script src="js/controller.js"></script>
            <script src="js/show.js"></script>
            <script src="build/animation.css"></script>
        </head>
             <body ng-controller="imageshow_hide">
                    <ion-content>
                            <div id="custom-overlay"[style.display]="splash ? 'flex': 'none'">
                                    <div class="flb">
                                            <div class="Aligner-item Aligner-item--top">
                                            </div>
                                            <img src="assets/logo.png">
                                            <div class="Aligner-item Aligner-item--bottom">
                                            </div>
                                    </div>
                            </div>
                                <div class="scroll-content">
                                                <img class="image1" src="assets/bg2.jpg"/>

                                                <div id="hides" class="image2"><img src="assets/whitetop.png"/>
                                                        <h2 style="text-align:center">WHY SHOULD I USE THIS APP

                                                        </h2>
                                                                <p>Our thoughts and everything we see feel hear taste and smell
                                                                shapes the unconscious mind.
                                                                By listening to affirmations daily.guided meditation and performing simple NLP techniques
                                                                you can re-program your mind to focus on the results you desire in life and develop
                                                                positive patterns for motivation and action
                                                                </p>

                                                </div>
                                                <div id="hides" class="image3"><img src="assets/whitebottom.png"/>
                                                    <h2 style="text-align:center">HOW TO USE THIS APP</h2>
                                                    <p>Don't listen to any of these recordings
                                                        while operating machinery or driving.only listen to these materials if you
                                                        are in safe place where you can relax.
                                                        All contents provided within their applications are NOT meant to replace
                                                        any qualified medical treatment or health related advice.
                                                        If you suffer from any mental disorder,NOT Listen to this material.
                                                        MindVolution accepts No responsibility or liability for any injury,loss or damage
                                                        as direct or indirect result of the usage of the information here presented.
                                                    </p>

                                                </div>
                                                    <button (click)="showhide()" id="hides">
                                                    <img class="image4" ng-hide="checked" src="assets/skip.png"/>
                                                    </button>
                                                <img class="image5"src="assets/sound icon.png"/>
                                                <img class="image6"src="assets/sound icon.png"/>
                                </div>
                    </ion-content>
                </body>
    </html>
</code>```

答:
you are looking for a div with id "div" and there isn't any in your html, did you intend to use id "hidden"? Then your code should be var mydiv = document.getElementById('hidden').

A simpler way to achieve this is to create a boolean variable in your home.ts, e.g. isVisible, use *ngIf on the tags you want to depend on it's value to show or not, and then update it's value once the user clicks on the button.
e.g.

```<code><div *ngIf="isVisible">Content to hide when user clicks the button</div>
<button (click)="isVisible = !isVisible;"></button>
</code>```

To hide the splash screen is a good practice to use this.platform.ready().then(()={this.splashScreen.hide();});, by the way, you don't seem to be importing and using the splash screen native plugin, you are just giving a value to the variable splash.

Body:
I am developing an app and this is second screen where i am getting problem.
There is a skip button and when i press it the "div containing text in it " should hide .

I have written codes in typescript file "home.ts" and have written html of it it in home.html and css in home.css

there are only 2 screens i have done with these codes,one is splash screen and other one is disclaimer or home screen where i am trying to hide the div with text on click of skip button

Here is home.ts code:

import { Component,ViewChild} from '@angular/core';
import { NavController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl:'home.html'
})
export class HomePage {
@ViewChild('username')username;
@ViewChild('password')password;

  splash = true;

  constructor(public navCtrl: NavController ) {
    }
    showhide(){

      var toggle = function() {
      var mydiv = document.getElementById('div');
      if (mydiv.style.display === 'block' || mydiv.style.display === ''){
        mydiv.style.display = 'none';
      }
      else{
        mydiv.style.display = 'block';
      }
      }
    }

  ionViewDidLoad() {
    setTimeout(() => this.splash = false, 4000);

  }

    }

and here is home.html file

            <meta charset="utf-8">
            <meta name="viewport" content="initial-scale=1,maximum-scale=1, user-scalable=no">

                    <ion-content>

WHY SHOULD I USE THIS APP

Our thoughts and everything we see feel hear taste and smell
                                                                shapes the unconscious mind.
                                                                By listening to affirmations daily.guided meditation and performing simple NLP techniques
                                                                you can re-program your mind to focus on the results you desire in life and develop
                                                                positive patterns for motivation and action

HOW TO USE THIS APP

Don't listen to any of these recordings
                                                        while operating machinery or driving.only listen to these materials if you
                                                        are in safe place where you can relax.
                                                        All contents provided within their applications are NOT meant to replace
                                                        any qualified medical treatment or health related advice.
                                                        If you suffer from any mental disorder,NOT Listen to this material.
                                                        MindVolution accepts No responsibility or liability for any injury,loss or damage
                                                        as direct or indirect result of the usage of the information here presented.

                                                    <button (click)="showhide()" id="hides">

                                                    </button>

                    </ion-content>

Body:
you are looking for a div with id "div" and there isn't any in your html, did you intend to use id "hidden"? Then your code should be var mydiv = document.getElementById('hidden').

A simpler way to achieve this is to create a boolean variable in your home.ts, e.g. isVisible, use *ngIf on the tags you want to depend on it's value to show or not, and then update it's value once the user clicks on the button.
e.g.

<div *ngIf="isVisible">Content to hide when user clicks the button</div>
<button (click)="isVisible = !isVisible;"></button>

To hide the splash screen is a good practice to use this.platform.ready().then(()={this.splashScreen.hide();});, by the way, you don't seem to be importing and using the splash screen native plugin, you are just giving a value to the variable splash.


问:
Convert org.apache.avro.generic.GenericRecord to org.apache.spark.sql.Row
I have list of org.apache.avro.generic.GenericRecord, avro schemausing this we need to create dataframe with the help of SQLContext API, to create dataframe it needs RDD of org.apache.spark.sql.Row and avro schema. Pre-requisite to create DF is we should have RDD of org.apache.spark.sql.Row and it can be achieved using below code but some how it is not working and giving error, sample code.

```<code> 1. Convert GenericRecord to Row
    import org.apache.spark.sql.Row
    import org.apache.spark.sql.catalyst.expressions.GenericRowWithSchema
    import org.apache.avro.Schema
    import org.apache.spark.sql.types.StructType
    def convertGenericRecordToRow(genericRecords: Seq[GenericRecord], avroSchema: Schema, schemaType: StructType): Seq[Row] =
    {
      val fields = avroSchema.getFields
      var rows = new Seq[Row]
      for (avroRecord <- genericRecords) {
        var avroFieldsSeq = Seq[Any]();
        for (i <- 0 to fields.size - 1) {
          avroFieldsSeq = avroFieldsSeq :+avroRecord.get(fields.get(i).name)
        }
        val avroFieldArr = avroFieldsSeq.toArray
        val genericRow = new GenericRowWithSchema(avroFieldArr, schemaType)
        rows = rows :+ genericRow
      }
      return rows;
    }

2. Convert `Avro schema` to `Structtype`
   Use `com.databricks.spark.avro.SchemaConverters -> toSqlType` function , it will convert avro schema to StructType

3. Create `Dataframe` using `SQLContext`
   val rowSeq= convertGenericRecordToRow(genericRecords, avroSchema, schemaType)
   val rowRdd = sc.parallelize(rowSeq, 1)
   val finalDF =sqlContext.createDataFrame(rowRDD,structType)
</code>```

But it is throwing an error at creation of DataFrame. Can someone please help me what is wrong in above code. Apart from this if someone has different logic for converting and creation of dataframe.

Whenever I will invoke any action on Dataframe, it will execute DAG and try to create DF object but in this it is failing with below exception as

```<code> ERROR TaskSetManager: Task 0 in stage 0.0 failed 4 times; aborting job
 Error :Job aborted due to stage failure: Task 0 in stage 0.0 failed 4 times, most recent failure: Lost task 0.3 in stage 0.0 (TID 3, hdpoc-c01-r06-01, executor 1): java.io.InvalidClassException: org.apache.commons.lang3.time.FastDateFormat; local class incompatible: stream classdesc serialVersionUID = 2, local class serialVersionUID = 1
                        at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:617)
                        at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1622)
</code>```

After this I am trying to give correct version jar in jar parameter of spark submit and with other parameter as  --conf spark.driver.userClassPathFirst=true
but now it is failing with MapR as

```<code>ERROR CLDBRpcCommonUtils: Exception during init
java.lang.UnsatisfiedLinkError: com.mapr.security.JNISecurity.SetClusterOption(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)
                    at com.mapr.security.JNISecurity.SetClusterOption(Native Method)
                    at com.mapr.baseutils.cldbutils.CLDBRpcCommonUtils.init(CLDBRpcCommonUtils.java:163)
                    at com.mapr.baseutils.cldbutils.CLDBRpcCommonUtils.<init>(CLDBRpcCommonUtils.java:73)
                    at com.mapr.baseutils.cldbutils.CLDBRpcCommonUtils.<clinit>(CLDBRpcCommonUtils.java:63)
                    at org.apache.hadoop.conf.CoreDefaultProperties.<clinit>(CoreDefaultProperties.java:69)
                    at java.lang.Class.forName0(Native Method)
</code>```

We are using MapR distribution and after class path change in spark-submit, it is failing with above exception.

Can someone please help here or my basic need it to convert Avro GenericRecord into Spark Row so i can create Dataframe with it, please help

Thanks.

答:
Hopefully this will help. In the first part you can find how convert from GenericRecord to Row

How to convert RDD[GenericRecord] to dataframe in scala?

Body:
I have list of org.apache.avro.generic.GenericRecord, avro schemausing this we need to create dataframe with the help of SQLContext API, to create dataframe it needs RDD of org.apache.spark.sql.Row and avro schema. Pre-requisite to create DF is we should have RDD of org.apache.spark.sql.Row and it can be achieved using below code but some how it is not working and giving error, sample code.

 1. Convert GenericRecord to Row
    import org.apache.spark.sql.Row
    import org.apache.spark.sql.catalyst.expressions.GenericRowWithSchema
    import org.apache.avro.Schema
    import org.apache.spark.sql.types.StructType
    def convertGenericRecordToRow(genericRecords: Seq[GenericRecord], avroSchema: Schema, schemaType: StructType): Seq[Row] =
    {
      val fields = avroSchema.getFields
      var rows = new Seq[Row]
      for (avroRecord <- genericRecords) {
        var avroFieldsSeq = Seq[Any]();
        for (i <- 0 to fields.size - 1) {
          avroFieldsSeq = avroFieldsSeq :+avroRecord.get(fields.get(i).name)
        }
        val avroFieldArr = avroFieldsSeq.toArray
        val genericRow = new GenericRowWithSchema(avroFieldArr, schemaType)
        rows = rows :+ genericRow
      }
      return rows;
    }

2. Convert `Avro schema` to `Structtype`
   Use `com.databricks.spark.avro.SchemaConverters -> toSqlType` function , it will convert avro schema to StructType

3. Create `Dataframe` using `SQLContext`
   val rowSeq= convertGenericRecordToRow(genericRecords, avroSchema, schemaType)
   val rowRdd = sc.parallelize(rowSeq, 1)
   val finalDF =sqlContext.createDataFrame(rowRDD,structType)

But it is throwing an error at creation of DataFrame. Can someone please help me what is wrong in above code. Apart from this if someone has different logic for converting and creation of dataframe.

Whenever I will invoke any action on Dataframe, it will execute DAG and try to create DF object but in this it is failing with below exception as

 ERROR TaskSetManager: Task 0 in stage 0.0 failed 4 times; aborting job
 Error :Job aborted due to stage failure: Task 0 in stage 0.0 failed 4 times, most recent failure: Lost task 0.3 in stage 0.0 (TID 3, hdpoc-c01-r06-01, executor 1): java.io.InvalidClassException: org.apache.commons.lang3.time.FastDateFormat; local class incompatible: stream classdesc serialVersionUID = 2, local class serialVersionUID = 1
                        at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:617)
                        at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1622)

After this I am trying to give correct version jar in jar parameter of spark submit and with other parameter as  --conf spark.driver.userClassPathFirst=true
but now it is failing with MapR as

ERROR CLDBRpcCommonUtils: Exception during init
java.lang.UnsatisfiedLinkError: com.mapr.security.JNISecurity.SetClusterOption(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)
                    at com.mapr.security.JNISecurity.SetClusterOption(Native Method)
                    at com.mapr.baseutils.cldbutils.CLDBRpcCommonUtils.init(CLDBRpcCommonUtils.java:163)
                    at com.mapr.baseutils.cldbutils.CLDBRpcCommonUtils.<init>(CLDBRpcCommonUtils.java:73)
                    at com.mapr.baseutils.cldbutils.CLDBRpcCommonUtils.<clinit>(CLDBRpcCommonUtils.java:63)
                    at org.apache.hadoop.conf.CoreDefaultProperties.<clinit>(CoreDefaultProperties.java:69)
                    at java.lang.Class.forName0(Native Method)

We are using MapR distribution and after class path change in spark-submit, it is failing with above exception.

Can someone please help here or my basic need it to convert Avro GenericRecord into Spark Row so i can create Dataframe with it, please help

Thanks.


问:
CherryPy + Apache2 - Response cached
I'm trying to develop a CherryPy based system.
I'm actually using Apache2 web server + mod_python.
I have the next problem:

When I update the code of my cherrypy app, refresh several times the browser, and the result is the same as before editing.
It seems to be caching the response somewhere.
When I restart the Apache server, the problem is solved, but refreshing the browser without restarting apache allways return the same response despite updating the source code of my app.

How can I get the last version of my CherryPy app without having to restart the web server each time I make an edition on it?

Thanks a lot!

答:
It's not from the cherrypy docs (but from Django's Running a development server with mod_python), but maybe it helps:

Just set MaxRequestsPerChild 1 in your httpd.conf file to force Apache to reload everything for each request.

Title: CherryPy + Apache2 - Response cached