问:
Separating paging, sorting and filtering
In my ASP.NET MVC application I have a service that had a method for paging, sorting and filtering of Vehicle Makes:

```<code>     public class VehicleService : IVehicleService
 {
     private readonly DbContext _context;

     public VehicleService(DbContext context)
     {
         _context = context;
     }

       public async Task<IPagedList<VehicleMake>> GetVehicleMakesWithPaginationAsync(string search, int? page, string sort)
    {
        var makes = _context.VehicleMakes.AsQueryable();

        switch (sort)
        {
            case "Name desc":
                makes = makes.OrderByDescending(x => x.Name);
                break;
            default:
                makes = makes.OrderBy(x => x.Name);
                break;
        }

        return await makes.Where(x => x.Name.StartsWith(search) || search == null).ToPagedListAsync(page ?? 1, 5);
 }
}
</code>```

After the review of my code, I was told that sorting, filtering and paging should be in separate classes that have interfaces. I implemented that in following way:

Sorting:

```<code>internal class Sorting : ISorting
{
    private readonly DbContext _context;

    public Sorting(DbContext context)
    {
        _context = context;
    }

    public IEnumerable<VehicleMake> SortMakes(string sort)
    {
        var makes = _context.VehicleMakes.AsQueryable();

        makes = sort == "Name desc" ? makes.OrderByDescending(x => x.Name) : makes.OrderBy(x => x.Name);
        return makes;
    }
}
</code>```

Paging:

```<code>class Paging : IPaging
{
    private readonly ISorting _sorting;

    public Paging(DbContext context)
    {
        _sorting = new Sorting(context);
    }

    public async Task<IPagedList<VehicleMake>> GetPagedListOfSortedMakes(string search, int? page, string sort)
    {
        var sortedMakes = _sorting.SortMakes(sort).AsQueryable();
        return await sortedMakes.Where(x => x.Name.StartsWith(search) || search == null).ToPagedListAsync(page ?? 1, 5);
    }
}
</code>```

And then in my service:

```<code>    public class VehicleMakeService : IVehicleMakeService
{
    private readonly DbContext _context;
    private readonly IPaging _paging;

    public VehicleMakeService(DbContext context)
    {
        _context = context;
        _paging = new Paging(context);
    }

    public async Task<IPagedList<VehicleMake>> GetVehicleMakesWithPaginationAsync(string search, int? page, string sort)
    {
        return await _paging.GetPagedListOfSortedMakes(search, page, sort);
    }
}
</code>```

This works well, but I'm not sure if I implemented this correctly. Is there a better (cleaner) way to do this?

答:
Any reason why you don't use https://github.com/dncuug/X.PagedList

This seems like a pretty good component.

Body:
In my ASP.NET MVC application I have a service that had a method for paging, sorting and filtering of Vehicle Makes:

     public class VehicleService : IVehicleService
 {
     private readonly DbContext _context;

     public VehicleService(DbContext context)
     {
         _context = context;
     }

       public async Task<IPagedList<VehicleMake>> GetVehicleMakesWithPaginationAsync(string search, int? page, string sort)
    {
        var makes = _context.VehicleMakes.AsQueryable();

        switch (sort)
        {
            case "Name desc":
                makes = makes.OrderByDescending(x => x.Name);
                break;
            default:
                makes = makes.OrderBy(x => x.Name);
                break;
        }

        return await makes.Where(x => x.Name.StartsWith(search) || search == null).ToPagedListAsync(page ?? 1, 5);
 }
}

After the review of my code, I was told that sorting, filtering and paging should be in separate classes that have interfaces. I implemented that in following way:

Sorting:

internal class Sorting : ISorting
{
    private readonly DbContext _context;

    public Sorting(DbContext context)
    {
        _context = context;
    }

    public IEnumerable<VehicleMake> SortMakes(string sort)
    {
        var makes = _context.VehicleMakes.AsQueryable();

        makes = sort == "Name desc" ? makes.OrderByDescending(x => x.Name) : makes.OrderBy(x => x.Name);
        return makes;
    }
}

Paging:

class Paging : IPaging
{
    private readonly ISorting _sorting;

    public Paging(DbContext context)
    {
        _sorting = new Sorting(context);
    }

    public async Task<IPagedList<VehicleMake>> GetPagedListOfSortedMakes(string search, int? page, string sort)
    {
        var sortedMakes = _sorting.SortMakes(sort).AsQueryable();
        return await sortedMakes.Where(x => x.Name.StartsWith(search) || search == null).ToPagedListAsync(page ?? 1, 5);
    }
}

And then in my service:

    public class VehicleMakeService : IVehicleMakeService
{
    private readonly DbContext _context;
    private readonly IPaging _paging;

    public VehicleMakeService(DbContext context)
    {
        _context = context;
        _paging = new Paging(context);
    }

    public async Task<IPagedList<VehicleMake>> GetVehicleMakesWithPaginationAsync(string search, int? page, string sort)
    {
        return await _paging.GetPagedListOfSortedMakes(search, page, sort);
    }
}

This works well, but I'm not sure if I implemented this correctly. Is there a better (cleaner) way to do this?


来源: stackexchange

问:
GLSL performance differences between function call vs. inlining

Does it make a performance difference in GLSL if something simple like a + operator is wrapped into a function?

So for example these two scenarios:

Example 1:

in uniform float uValueA;
in uniform float uValueB;

void main()
{
    float value = uValueA + uValueB;
    // [...]
}
```

<h3>Example 2:</h3>

<pre class="lang-c prettyprint-override"><code>in uniform float uValueA;
in uniform float uValueB;

float addValues(float a, float b)
{
    return a + b;
}

void main()
{
    float value = addValues(uValueA, uValueB);
    // [...]
}
</code>```

is there any difference in the compiled end product? Or do they result in the same number of instructions and performance?

答:
You essentially can assume nothing about the optimization of your shader, because the compilation is vendor specific. It would make sense that a compiler would optimize this very simple case, and inline the function, making the two equivalent, but that is in no way guaranteed. They could in theory insert a million no-ops for every function call (although, the person who wrote their compiler might be fired :)).

That said, you can "pre-optimize" your GLSL code, such that these sorts of optimizations are performed before the code is sent to the compiler (generally done offline). The glsl-optimizer is frequently used for this purpose, and used built into the Unity engine.

ContentLicense: CC BY-SA 3.0

Body:
Does it make a performance difference in GLSL if something simple like a + operator is wrapped into a function?

So for example these two scenarios:

Example 1:

in uniform float uValueA;
in uniform float uValueB;

void main()
{
    float value = uValueA + uValueB;
    // [...]
}

Example 2:

in uniform float uValueA;
in uniform float uValueB;

float addValues(float a, float b)
{
    return a + b;
}

void main()
{
    float value = addValues(uValueA, uValueB);
    // [...]
}

is there any difference in the compiled end product? Or do they result in the same number of instructions and performance?


问:
Javascript file or module scope only variables
Correct me if am wrong the function require() imports the .js file somehow as copy past it in the current document so if the var name was both in two modules would the second override the first?

 and how can i define file scope only variables

 note that i want to define my variable outside any function in my .js file and not it be in the global scope

 what are the solutions, does using the keyword var affects the variable scope, what define the scope other than function in javascript, can module object be useful for defining private variables in one file

module1.js

```<code>var name = 'i am module 1'

foo = () => console.log(name)

module.exports = foo
</code>```

module2.js

```<code>var name = 'i am module 2'

foo = () => console.log(name)

module.exports = foo
</code>```

main.js

```<code>const module1 = require('./module1')
const module2 = require('./module2')

module1() // "i am module 1" or "i am module 2"?
module2() // "i am module 2"
</code>```

答:
In javascript when you load the .js file directly in the '.html' file then the variables declared outside of the function get registered on global scope. To prevent this kind of things people starts using IIFE functions and wrap the single file in the IIFE. But in modern Javascript you can use modules like we used in Nodejs and module loader to load those files. Now modern browser supports ECMAScript modules and you can directly use them.

Main benefits of using modules is that you don't have to use IIFE function to prevent the variable registered on global scope. Now Every variable declared in that file are private to that file only unless you export it.

For Example:
module1.js

```<code>var name = 'my name';

function getName(){
    return name;
}

module.exports  = {
    getName
}
</code>```

In the above example name is private to this file only you can't use it in another file unless you export it.

Body:
Correct me if am wrong the function require() imports the .js file somehow as copy past it in the current document so if the var name was both in two modules would the second override the first?

 and how can i define file scope only variables

 note that i want to define my variable outside any function in my .js file and not it be in the global scope

 what are the solutions, does using the keyword var affects the variable scope, what define the scope other than function in javascript, can module object be useful for defining private variables in one file

module1.js

var name = 'i am module 1'

foo = () => console.log(name)

module.exports = foo

module2.js

var name = 'i am module 2'

foo = () => console.log(name)

module.exports = foo

main.js

const module1 = require('./module1')
const module2 = require('./module2')

module1() // "i am module 1" or "i am module 2"?
module2() // "i am module 2"

Body:
In javascript when you load the .js file directly in the '.html' file then the variables declared outside of the function get registered on global scope. To prevent this kind of things people starts using IIFE functions and wrap the single file in the IIFE. But in modern Javascript you can use modules like we used in Nodejs and module loader to load those files. Now modern browser supports ECMAScript modules and you can directly use them.

Main benefits of using modules is that you don't have to use IIFE function to prevent the variable registered on global scope. Now Every variable declared in that file are private to that file only unless you export it.

For Example:
module1.js

var name = 'my name';

function getName(){
    return name;
}

module.exports  = {
    getName
}

In the above example name is private to this file only you can't use it in another file unless you export it.


问:
Regular Expressions not working with Pandas Dataframe
I've got a Pandas Dataframe that's made up of emails that I'm needing to clean using regex. However, my attempts to clean the column, aren't actually being applied to the text.

Example data is below:

```<code>|subeject         | description       |
---------------------------------------
|change email     | 'Hi, I'm trying...|
|how are you?     | 'Hi, how are...   |
</code>```

The actual dataset has about 2500 rows.

The example code that I'm using is:

```<code>data = pd.read_csv('file.csv', names=['subject', 'description'])
data['description'] = data['description'].str.lower().str.split()

# Text cleaning below:
data['description'] = data['description'].replace(r'<(.*?)\>', '')
data['description'] = data['description'].replace(r'www[a-z]+', '')
... # more regex
</code>```

Running this code in an iPython notebook using Python 2.7 I would expect the regex to identify statements and replace it with a space.

However, when running it, the text of the description does not change.

An alternative method I've tried with the same result is as follows:

```<code>for i in data['description']:
    re.sub(r'<(.*?)\>', '', i)
    re.sub(r'www[a-z]+', '', i)
</code>```

However, I got the same result with none of the text being removed.

Could you please advise or point me in the right direction?

答:
The syntax for text cleaning should be:</p>

```<code>data['description'] = data['description'].str.replace(r'www[a-z]+', '')
</code>```

Body:
I've got a Pandas Dataframe that's made up of emails that I'm needing to clean using regex. However, my attempts to clean the column, aren't actually being applied to the text.

Example data is below:

|subeject         | description       |
---------------------------------------
|change email     | 'Hi, I'm trying...|
|how are you?     | 'Hi, how are...   |

The actual dataset has about 2500 rows.

The example code that I'm using is:

data = pd.read_csv('file.csv', names=['subject', 'description'])
data['description'] = data['description'].str.lower().str.split()

# Text cleaning below:
data['description'] = data['description'].replace(r'<(.*?)\>', '')
data['description'] = data['description'].replace(r'www[a-z]+', '')
... # more regex

Running this code in an iPython notebook using Python 2.7 I would expect the regex to identify statements and replace it with a space.

However, when running it, the text of the description does not change.

An alternative method I've tried with the same result is as follows:

for i in data['description']:
    re.sub(r'<(.*?)\>', '', i)
    re.sub(r'www[a-z]+', '', i)

However, I got the same result with none of the text being removed.

Could you please advise or point me in the right direction?

Body:
The syntax for text cleaning should be:

data['description'] = data['description'].str.replace(r'www[a-z]+', '')


问:
When should I use a List vs a LinkedList
When is it better to use a List vs a LinkedList?</p>

答:
Essentially, a List<> in .NET is a wrapper over an array.  A LinkedList<> is a linked list.  So the question comes down to, what is the difference between an array and a linked list, and when should an array be used instead of a linked list.  Probably the two most important factors in your decision of which to use would come down to:

Linked lists have much better insertion/removal performance, so long as the insertions/removals are not on the last element in the collection.  This is because an array must shift all remaining elements that come after the insertion/removal point.  If the insertion/removal is at the tail end of the list however, this shift is not needed (although the array may need to be resized, if its capacity is exceeded).

Arrays have much better accessing capabilities.  Arrays can be indexed into directly (in constant time).  Linked lists must be traversed (linear time).

OwnerDisplayName: Grauenwolf

ContentLicense: CC BY-SA 4.0


问:
ListView always delete the last item
My list view item contains a remove button, and I set it up in my adapter to remove the item from the database. Now once that's done how can i refresh the fragment which contains the listView to remove that item? Relevant code as below:

Remove item function in adapter:

```<code>holder.actionIndicator.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            AlertDialog alertDialog = new AlertDialog.Builder(mContext).create();
            alertDialog.setTitle("Delete item");
            alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "yes",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {

                            FirebaseMethods firebaseMethods = new FirebaseMethods(mContext);
                            firebaseMethods.deleteHashtagFromDatabase(title);

                            dialog.dismiss();
                        }
                    });
            alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "no",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });

                    alertDialog.show();

        }
    });
</code>```

Listview is setup like this in my fragment:

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

    Log.d(TAG, "setupListView: setting up list");
    final ArrayList<HashTag> hashTags = new ArrayList<>();
    myRef = FirebaseDatabase.getInstance().getReference();
    Query query = myRef.child(getString(R.string.dbname_user_hashtags))
            .child(FirebaseAuth.getInstance().getCurrentUser().getUid());
    query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){

                if(singleSnapshot != null){
                    hashTags.add(0, singleSnapshot.getValue(HashTag.class));
                }

            }

            HashTagListViewAdapter adapter = new HashTagListViewAdapter(getActivity(), R.layout.layout_list_itemview, hashTags);
            hashtagListView.setAdapter(adapter);

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
</code>```

Thanks!

UPDATE:

Now I have passed the OnClickListener on the subItem from the adapter to the fragment ListView OnItemClickListener as below:

Updated Adapter

```<code>holder.actionIndicator.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            ((ListView) parent).performItemClick(v, position, 0);

        }
    });
</code>```

Updated Fragment

```<code>hashtagListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {

            long viewId = view.getId();
            Log.d(TAG, "onItemClick: viewId is " + viewId);
            Log.d(TAG, "onItemClick: position is " + position);

            final HashTagListViewAdapter adapter = new HashTagListViewAdapter(getActivity(), R.layout.layout_list_itemview, hashTags);
            final HashTag hashTag = hashTags.get(position);
            final String title = hashTag.getTitle();
            Log.d(TAG, "onItemClick: title is " + title);

            if(viewId == R.id.deleteFromListBtn){

                AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
                alertDialog.setTitle("delete item");
                alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "yes",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {

                                FirebaseMethods firebaseMethods = new FirebaseMethods(getActivity());
                                firebaseMethods.deleteHashtagFromDatabase(title);
                                Log.d(TAG, "onClick: title is " + title);

                                // NEW PROBLEM HERE!
                                adapter.remove(hashTag);
                                Log.d(TAG, "onClick: removed hashtag is " + hashTag);
                                adapter.notifyDataSetChanged();

                                Log.d(TAG, "onItemClick: item removed from list.");

                                dialog.dismiss();
                            }
                        });
                alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "no",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });

                alertDialog.show();

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

But now the problem is when I delete the item, the listView always delete the last item in the view. However, the correct item was deleted from database and according to the log, this code adapter.remove(hashTag) does grab the correct item i intent to delete.

答:
First thing, you should not refresh the whole Fragment. Bad habit

To refresh your ListView,

First remove the item from ArrayList (named 'hashTags').

And just call YOUR_ADAPTER.notifyDataSetChanged().

notifyDataSetChanged() will automatically remove item from the ListView.

Use of notifyDataSetChanged()

Title: ListView always delete the last item

Body:
My list view item contains a remove button, and I set it up in my adapter to remove the item from the database. Now once that's done how can i refresh the fragment which contains the listView to remove that item? Relevant code as below:

Remove item function in adapter:

holder.actionIndicator.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            AlertDialog alertDialog = new AlertDialog.Builder(mContext).create();
            alertDialog.setTitle("Delete item");
            alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "yes",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {

                            FirebaseMethods firebaseMethods = new FirebaseMethods(mContext);
                            firebaseMethods.deleteHashtagFromDatabase(title);

                            dialog.dismiss();
                        }
                    });
            alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "no",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });

                    alertDialog.show();

        }
    });

Listview is setup like this in my fragment:

private void setupListView(){

    Log.d(TAG, "setupListView: setting up list");
    final ArrayList<HashTag> hashTags = new ArrayList<>();
    myRef = FirebaseDatabase.getInstance().getReference();
    Query query = myRef.child(getString(R.string.dbname_user_hashtags))
            .child(FirebaseAuth.getInstance().getCurrentUser().getUid());
    query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){

                if(singleSnapshot != null){
                    hashTags.add(0, singleSnapshot.getValue(HashTag.class));
                }

            }

            HashTagListViewAdapter adapter = new HashTagListViewAdapter(getActivity(), R.layout.layout_list_itemview, hashTags);
            hashtagListView.setAdapter(adapter);

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

Thanks!

UPDATE:

Now I have passed the OnClickListener on the subItem from the adapter to the fragment ListView OnItemClickListener as below:

Updated Adapter

holder.actionIndicator.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            ((ListView) parent).performItemClick(v, position, 0);

        }
    });

Updated Fragment

hashtagListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {

            long viewId = view.getId();
            Log.d(TAG, "onItemClick: viewId is " + viewId);
            Log.d(TAG, "onItemClick: position is " + position);

            final HashTagListViewAdapter adapter = new HashTagListViewAdapter(getActivity(), R.layout.layout_list_itemview, hashTags);
            final HashTag hashTag = hashTags.get(position);
            final String title = hashTag.getTitle();
            Log.d(TAG, "onItemClick: title is " + title);

            if(viewId == R.id.deleteFromListBtn){

                AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
                alertDialog.setTitle("delete item");
                alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "yes",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {

                                FirebaseMethods firebaseMethods = new FirebaseMethods(getActivity());
                                firebaseMethods.deleteHashtagFromDatabase(title);
                                Log.d(TAG, "onClick: title is " + title);

                                // NEW PROBLEM HERE!
                                adapter.remove(hashTag);
                                Log.d(TAG, "onClick: removed hashtag is " + hashTag);
                                adapter.notifyDataSetChanged();

                                Log.d(TAG, "onItemClick: item removed from list.");

                                dialog.dismiss();
                            }
                        });
                alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "no",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });

                alertDialog.show();

            }
        }
    });

But now the problem is when I delete the item, the listView always delete the last item in the view. However, the correct item was deleted from database and according to the log, this code adapter.remove(hashTag) does grab the correct item i intent to delete.


问:
HTML5 formatting on MacOS X? (preferably with TextMate)
Are there any editors or bundles available for MacOS X that support formatting of HTML5 documents? Tidy errors out on newer tags like canvas.</p>

答:
I have to say that I am not familiar with TextMate bundles because I do not personally use that editor. None the less, I found out that they have a public subversion server where they keep different bundles. A quick search did not reveal any HTML5 bundle. You can find more information about bundles on their website.

If you want an out of the box way of create web content in HTML5, have a look at Aloha Editor.

ContentLicense: CC BY-SA 2.5


问:
Django: Order objects based on likes for popular feed
I want to implement 'Popular' Feed. I want to show the series of posts which has the likes the most.

Here is abstract model schema.

```<code>(Model) Like
      user = User
      content_type = Post, User, Group
      object_id = 22

(Model) Post
      user = User
      content = ''
      created_at = '12082017'
</code>```

In views.py, I want to get sorted queryset like,

```<code> Post.objects.order_by('-like')[:30]
</code>```

Since my Post model doesn't have like field, I can't use order_by.

I'm thinking about adding score field to track of likes and current time since then. Do you think it will work? :)

Also any thought or advice on how to make popular feed will be highly appreciated. Thank you

答:
You have something called the reverse generic relation for this purpose:

Reverse Generic Relations

Add the reverse generic relation to your post model and you can get the count of the number of likes and then order it based on likes for popularity based ordering.

In your post model add:

```<code>likes = GenericRelation(Like)
</code>```

Maybe use annotate for ordering:

```<code>Post.objects.annotate(like_count=Count('likes')).order_by('-like_count')
</code>```

You would get an additional field 'like_count' for each post object plus it will be ordered based on the number of likes.

Body:
I want to implement 'Popular' Feed. I want to show the series of posts which has the likes the most.

Here is abstract model schema.

(Model) Like
      user = User
      content_type = Post, User, Group
      object_id = 22

(Model) Post
      user = User
      content = ''
      created_at = '12082017'

In views.py, I want to get sorted queryset like,

 Post.objects.order_by('-like')[:30]

Since my Post model doesn't have like field, I can't use order_by.

I'm thinking about adding score field to track of likes and current time since then. Do you think it will work? :)

Also any thought or advice on how to make popular feed will be highly appreciated. Thank you

Body:
You have something called the reverse generic relation for this purpose:

Reverse Generic Relations

Add the reverse generic relation to your post model and you can get the count of the number of likes and then order it based on likes for popularity based ordering.

In your post model add:

likes = GenericRelation(Like)

Maybe use annotate for ordering:

Post.objects.annotate(like_count=Count('likes')).order_by('-like_count')

You would get an additional field 'like_count' for each post object plus it will be ordered based on the number of likes.


问:
Auto download PDF in Firefox
I want Firefox to directly download the PDF files instead of showing them in browser. I used following settings

```<code>FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("browser.download.folderList", 2);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting", false);
firefoxProfile.setPreference("browser.download.dir", "c:\\tmp");
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf");
WebDriver driver = new FirefoxDriver(firefoxProfile);
// Its just a sample URL
driver.get("http://www.energy.umich.edu/sites/default/files/pdf-sample.pdf");
</code>```

On about:config page I can see that this setting are successfully reflected also the response type is application/pdf.

When Webdriver launches Firefox I can see following option.

It should be "Save File".

Still Firefox is showing PDF in browser. I am using Firefox 29.0.1, does the preference values have changed?

答:
For Firefox Quantum 57.0 64-bit, Selenium 3.8.1, the following solution works.</p>

```<code>FirefoxProfile ffprofile = new FirefoxProfile();

// Required if you want to download other than the default location
ffprofile.setPreference("browser.download.folderList", 2);
// Specify your own location
ffprofile.setPreference("browser.download.dir", "C:\\TestAutomationDataSheets\\Files_To_Download\\");
ffprofile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf");
ffprofile.setPreference("pdfjs.enabledCache.state", false);

DesiredCapabilities ffcapabilities = DesiredCapabilities.firefox();
ffcapabilities.setCapability(FirefoxDriver.PROFILE, ffprofile);

WebDriver driver = new FirefoxDriver(ffcapabilities);
</code>```

Title: Auto download PDF in Firefox

Body:
I want Firefox to directly download the PDF files instead of showing them in browser. I used following settings

FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("browser.download.folderList", 2);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting", false);
firefoxProfile.setPreference("browser.download.dir", "c:\\tmp");
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf");
WebDriver driver = new FirefoxDriver(firefoxProfile);
// Its just a sample URL
driver.get("http://www.energy.umich.edu/sites/default/files/pdf-sample.pdf");

On about:config page I can see that this setting are successfully reflected also the response type is application/pdf.

When Webdriver launches Firefox I can see following option.

It should be "Save File".

Still Firefox is showing PDF in browser. I am using Firefox 29.0.1, does the preference values have changed?

Body:
For Firefox Quantum 57.0 64-bit, Selenium 3.8.1, the following solution works.

FirefoxProfile ffprofile = new FirefoxProfile();

// Required if you want to download other than the default location
ffprofile.setPreference("browser.download.folderList", 2);
// Specify your own location
ffprofile.setPreference("browser.download.dir", "C:\\TestAutomationDataSheets\\Files_To_Download\\");
ffprofile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf");
ffprofile.setPreference("pdfjs.enabledCache.state", false);

DesiredCapabilities ffcapabilities = DesiredCapabilities.firefox();
ffcapabilities.setCapability(FirefoxDriver.PROFILE, ffprofile);

WebDriver driver = new FirefoxDriver(ffcapabilities);


问:
Obtain consecutive substrings in python
Given a n-gram word I want to get the consecutive substrings patterns from 'start to end' and 'end to start'.

For example, for the 4-gram computer supported machine translation I should get the following substrings.

from start to end: computer supported, computer supported machine

from end to start: machine translation, supported machine translation

for the 3-gram natural language processing, I should get natural language and language processing.

I have really large n-grams, so I am interested in knowing the quickest way of doing this!

答:
You could split the n-gram into a list of grams and then join slices (see Understanding Python's slice notation):

```<code>ngram = "computer supported machine translation"
grams = ngram.split(" ")

# Start to end
for c in range(2, len(grams)):
    print(" ".join(grams[:c]))

# End to start
for c in range(2, len(grams)):
    print(" ".join(grams[-c:]))
</code>```

Title: Obtain consecutive substrings in python

Body:
You could split the n-gram into a list of grams and then join slices (see Understanding Python's slice notation):

ngram = "computer supported machine translation"
grams = ngram.split(" ")

# Start to end
for c in range(2, len(grams)):
    print(" ".join(grams[:c]))

# End to start
for c in range(2, len(grams)):
    print(" ".join(grams[-c:]))


问:
Dump file outside the lxc container
I am able to view syslog of my lxc container, from outside the container... by;

```<code>sudo lxc exec my-abc-container -- /root/tail  /usr/local/var/syslog
</code>```

or either by tailing it

```<code>sudo lxc exec my-abc-container -- /root/tail --follow=name /usr/local/var/syslog
</code>```

But I have no clue on how to dump this log in a file. Tired of finding similar question but nothing helped.

答:
By using file pull

```<code>lxc file pull my-abc-container/usr/local/var/syslog ./my-abc-container-syslog
</code>```

Or by exec

```<code>lxc exec my-abc-container -- /bin/sh -c "cat /usr/local/var/syslog" > ./my-abc-container-syslog
</code>```

Title: Dump file outside the lxc container

Body:
I am able to view syslog of my lxc container, from outside the container... by;

sudo lxc exec my-abc-container -- /root/tail  /usr/local/var/syslog

or either by tailing it

sudo lxc exec my-abc-container -- /root/tail --follow=name /usr/local/var/syslog

But I have no clue on how to dump this log in a file. Tired of finding similar question but nothing helped.

Body:
By using file pull

lxc file pull my-abc-container/usr/local/var/syslog ./my-abc-container-syslog

Or by exec

lxc exec my-abc-container -- /bin/sh -c "cat /usr/local/var/syslog" > ./my-abc-container-syslog


问:
Cypress custom command is not recognized when invoked
I've created the following custom command in my cypress/support/commands.js file.

```<code>Cypress.Commands.add("login", (username, password) => {
    cy.request({
        method: 'POST',
        form: true,
        url: '/test/login/',
        body: {'username': username, 'password': password}
    })
})
</code>```

I had tests passing and login working before moving the login functionality to this custom command. I'm invoking it in my spec with cy.login(testuser, testpwd), but I'm getting the following error message: TypeError: cy.login is not a function. The docs say that /cypress/support/commands.js is loaded before any test files are evaluated, so I assumed that simply placing a custom command in there would make the command available.  I'm running the tests through the local (GUI) test runner.

答:
All the code and referenced modules in index.js are loaded before your test file. So you need to refer(require) commands.js in your index.js file.
You can however import commands.js module directly in your test file but then you need to include it every test file.
Recommended approach is to include it in index.js file and you are not worried about explicitly refer in your test files.

Body:
I've created the following custom command in my cypress/support/commands.js file.

Cypress.Commands.add("login", (username, password) => {
    cy.request({
        method: 'POST',
        form: true,
        url: '/test/login/',
        body: {'username': username, 'password': password}
    })
})

I had tests passing and login working before moving the login functionality to this custom command. I'm invoking it in my spec with cy.login(testuser, testpwd), but I'm getting the following error message: TypeError: cy.login is not a function. The docs say that /cypress/support/commands.js is loaded before any test files are evaluated, so I assumed that simply placing a custom command in there would make the command available.  I'm running the tests through the local (GUI) test runner.


问:
Ext. news: get news id in controller
I want to place a new plugin (from own extension) on the news detail page, which shows me news from related categories.

My problem is: How to get the news id in my new plugin controller.

```<code>$arguments = $this->request->getArguments();
</code>```

does not work.

Has anybody an idea?

答:
You can use below TYPO3 GeneralUtility::_GP() function for get another extension arguments in your own extension Controller file. Like below

```<code>$newsArr = GeneralUtility::_GP('tx_news_pi1');
$this->newsUid = intval($newsArr['news']);
</code>```

Title: Ext. news: get news id in controller

Body:
I want to place a new plugin (from own extension) on the news detail page, which shows me news from related categories.

My problem is: How to get the news id in my new plugin controller.

$arguments = $this->request->getArguments();

does not work.

Has anybody an idea?

Body:
You can use below TYPO3 GeneralUtility::_GP() function for get another extension arguments in your own extension Controller file. Like below

$newsArr = GeneralUtility::_GP('tx_news_pi1');
$this->newsUid = intval($newsArr['news']);


问:
Java ? super T in Collections copy why correct work
```<code>    List<String> srcList = new ArrayList<>();
    srcList.add("a");
    srcList.add("b");
    srcList.add("c");

    List<String> descList = new ArrayList<>(3);
    descList.add("1");
    descList.add("2");
    descList.add("3");
    // public static <T> void copy(List<? super T> dest, List<? extends T> src)
    Collections.copy(descList, srcList);

    for (String item: descList) {
        System.out.println(item);
    }

    List<? super String> listC = new ArrayList<>();
    listC.add("A");
    listC.add("B");
    listC.add("C");

    Collections.copy(listC, srcList);

    for (String item : listC) { System.out.println(item); }// complie error.
</code>```

<? super T> means T or T's super class.
In method Collections.copy() param dest can correct work on foreach.
Why custom List Object listC can't work on get item of this list.

答:
By declaring List<? super String> listC, you're saying that listC could be a List<String>, or a List<Object> or a List<CharSequence>, or a List of any other supertype of String.

Now, the line for (String item: listC) makes no sense, because if listC is a List<Object>, or something else other than List<String>, then its contents may not necessarily be Strings.  This is what the compiler is telling you.

Body:
    List<String> srcList = new ArrayList<>();
    srcList.add("a");
    srcList.add("b");
    srcList.add("c");

    List<String> descList = new ArrayList<>(3);
    descList.add("1");
    descList.add("2");
    descList.add("3");
    // public static <T> void copy(List<? super T> dest, List<? extends T> src)
    Collections.copy(descList, srcList);

    for (String item: descList) {
        System.out.println(item);
    }

    List<? super String> listC = new ArrayList<>();
    listC.add("A");
    listC.add("B");
    listC.add("C");

    Collections.copy(listC, srcList);

    for (String item : listC) { System.out.println(item); }// complie error.

<? super T> means T or T's super class.
In method Collections.copy() param dest can correct work on foreach.
Why custom List Object listC can't work on get item of this list.


问:
Using a JQuery $.each Operator Within a ui.bootstrap Angular Modal To Apply CSS to Each Element

I have a modal pop up when a certain item is clicked which displays certain numbers and I would like these numbers to change color depending on what their number is (i.e. a low score will be red and a high score will be green).

HTML

```<code><html ng-app="root">
    <div class="movie-display-section" ng-controller="movieThumbnailController">
        <a href class="movie-thumbnail" ng-repeat="movie in movies" ng-click="show(movie)">
            <img class="movie-thumbnail-image" src="{{movie.img_src}}">
            <div class="movie-thumbnail-desc">
                <h1>{{movie.name}}</h1>
                <h2>({{movie.year}})</h2>
            </div>
        </a>
    </div>

    <script type="text/ng-template" id="movie_modal.html">
        <div class="movie-modal">
            <div class="modal-body">
                <img class="movie-thumbnail-image" src="{{movie.img_src}}">
                <div class="movie-review" ng-repeat="review in reviews">
                    <h2 class="movie-review-user">{{review.user}}</h2>
                    <h1 class="movie-review-rating" ng-class="movieRatingClass">{{review.rating}}</h1>
                </div>
            </div>
        </div>
    </script>
</html>
</code>```

JavaScript

```<code>var movies = []; //An array of movies with reviews in them
var root = angular.module('root', ['ui.bootstrap']);

root.controller("modalController", function($scope, $modalInstance, movie){
    $scope.movie = movie;
    $scope.reviews = [];
    for(var i = 0; i < 3; i++){
        $scope.reviews[i] = reviews[movie.reviews[i]];
    };
    $scope.close = function() {
        $modalInstance.close();
    };
});

root.controller("movieThumbnailController", function($scope, $timeout, $modal, $log){
    $scope.movies = movies;
    $scope.show = function(_movie){
        console.log(_movie.name);
        var modalInstance = $modal.open({
            controller: "modalController",
            templateUrl: "movie_modal.html",
            windowClass: "movie-modal",
            size: "lg",
            resolve: {
                movie: function() {
                    return _movie;
                }
            }
        });
    };
});
</code>```

What shows up is a modal with the user's name and their rating as I expected (with some added CSS to prettify it). My questions is, is there a way I can change the style of the rating color inside the JavaScript file, either using JQuery or the Angular library/framework? Let's assume I have the rateColor function that returns a string that is the 6 character color code preceded by "#" (e.g. "#1D3D45")

```<code>var rateColor = function(rating) {
    //return color string id;
}
</code>```

I know there is the $.each operator in JQuery which I could use to apply it to every "movie-review-rating" class but that doesn't work (I think because the modal is within a script and won't work that way but I may be wrong).

答:
What about

var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',function($scope, $timeout) {
$scope.rating=5;
$scope.rating1=4;
$scope.rateColor = function(rating) {
if(rating==5)
   return "background-color:"+"red";
else
  return "background-color:"+"green"
 }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<h2 style="{{rateColor(rating)}}">
{{rating}}
</h2>
 <h3 style="{{rateColor(rating1)}}">
{{rating1}}
</h3>
</div></code>```

Body:
I have a modal pop up when a certain item is clicked which displays certain numbers and I would like these numbers to change color depending on what their number is (i.e. a low score will be red and a high score will be green).

HTML

{{movie.name}}

({{movie.year}})

JavaScript

var movies = []; //An array of movies with reviews in them
var root = angular.module('root', ['ui.bootstrap']);

root.controller("modalController", function($scope, $modalInstance, movie){
    $scope.movie = movie;
    $scope.reviews = [];
    for(var i = 0; i < 3; i++){
        $scope.reviews[i] = reviews[movie.reviews[i]];
    };
    $scope.close = function() {
        $modalInstance.close();
    };
});

root.controller("movieThumbnailController", function($scope, $timeout, $modal, $log){
    $scope.movies = movies;
    $scope.show = function(_movie){
        console.log(_movie.name);
        var modalInstance = $modal.open({
            controller: "modalController",
            templateUrl: "movie_modal.html",
            windowClass: "movie-modal",
            size: "lg",
            resolve: {
                movie: function() {
                    return _movie;
                }
            }
        });
    };
});

What shows up is a modal with the user's name and their rating as I expected (with some added CSS to prettify it). My questions is, is there a way I can change the style of the rating color inside the JavaScript file, either using JQuery or the Angular library/framework? Let's assume I have the rateColor function that returns a string that is the 6 character color code preceded by "#" (e.g. "#1D3D45")

var rateColor = function(rating) {
    //return color string id;
}

I know there is the $.each operator in JQuery which I could use to apply it to every "movie-review-rating" class but that doesn't work (I think because the modal is within a script and won't work that way but I may be wrong).

Body:
What about

var myApp = angular.module('myApp',[]);
myApp.controller('MyCtrl',function($scope, $timeout) {
$scope.rating=5;
$scope.rating1=4;
$scope.rateColor = function(rating) {
if(rating==5)
   return "background-color:"+"red";
else
  return "background-color:"+"green"
 }
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<h2 style="{{rateColor(rating)}}">
{{rating}}
</h2>
 <h3 style="{{rateColor(rating1)}}">
{{rating1}}
</h3>
</div>


问:
Access js variable of one file in another file using JQuery
I have 2 js files: 1.js and 2.js.

In 1.js I have a variable

```<code>var test ='Hello';
</code>```

I'm trying to access the variable in 2.js

```<code>alert(test);
</code>```

Sample Code:

1.js :

```<code>$(document).ready(function () {
    var test = 'Hello';
});
</code>```

2.js :

```<code> $(function () {
       function getData(){
            alert(test);
       }
   });
</code>```

In my aspx page order of js files:

```<code><script type="text/javascript" src="js/1.js"></script>
<script type="text/javascript" src="js/2.js?"></script>
</code>```

I know the question is asked before many times but none of the answers seems to work for me.

答:
Make sure your var test is not inside a function and that your file is load in the correct order.
In your first file use something like

```<code><script type="text/javascript">
  var test = "myVar"
</script>
// Now here include your js file too JS file
// Or set in window scope like window.test="myVar";
</code>```

And in your JS file use like

```<code>$(function() {
  alert(test);
  // alert(window.test);
});
</code>```

A variable in global scope can be access from all javascript file.
Your first js file

Here is another way.

```<code>//first.js file don't put variable inside any function here.
var globalVariable={
   test: 'myVar'
};
</code>```

And your second js file

```<code>//second.js file
alert(globalVariable.test);
</code>```

And in html page add

```<code><script type="text/javascript" src="first.js"></script>
<script type="text/javascript" src="second.js"></script>
</code>```

More from here

Body:
I have 2 js files: 1.js and 2.js.

In 1.js I have a variable

var test ='Hello';

I'm trying to access the variable in 2.js

alert(test);

Sample Code:

1.js :

$(document).ready(function () {
    var test = 'Hello';
});

2.js :

 $(function () {
       function getData(){
            alert(test);
       }
   });

In my aspx page order of js files:

I know the question is asked before many times but none of the answers seems to work for me.

Body:
Make sure your var test is not inside a function and that your file is load in the correct order.
In your first file use something like

<script type="text/javascript">
  var test = "myVar"
</script>
// Now here include your js file too JS file
// Or set in window scope like window.test="myVar";

And in your JS file use like

$(function() {
  alert(test);
  // alert(window.test);
});

A variable in global scope can be access from all javascript file.
Your first js file

Here is another way.

//first.js file don't put variable inside any function here.
var globalVariable={
   test: 'myVar'
};

And your second js file

//second.js file
alert(globalVariable.test);

And in html page add

<script type="text/javascript" src="first.js"></script>
<script type="text/javascript" src="second.js"></script>

More from here


问:
Regex plus vs star difference?
What is the difference between:

```<code>(.+?)
</code>```

and

```<code>(.*?)
</code>```

when I use it in my php preg_match regex?

答:
In RegEx, {i,f} means "between i to f matches". Let's take a look at the following examples:

{3,7} means between 3 to 7 matches

{,10} means up to 10 matches with no lower limit (i.e. the low limit is 0)

{3,} means at least 3 matches with no upper limit (i.e. the high limit is infinity)

{,} means no upper limit or lower limit for the number of matches (i.e. the lower limit is 0 and the upper limit is infinity)

{5} means exactly 4

Most good languages contain abbreviations, so does RegEx:

+ is the shorthand for {1,}

* is the shorthand for {,}

? is the shorthand for {,1}

This means + requires at least 1 match while * accepts any number of matches or no matches at all and ? accepts no more than 1 match or zero matches.

Credit: Codecademy.com

Title: Regex plus vs star difference?

Body:
What is the difference between:

(.+?)

and

(.*?)

when I use it in my php preg_match regex?


问:
How to put out apk file uses gradle v4.1 in Android Studio 3.0+?
I want to set APK filePath in gradle that version is v4.1,but I can set its name and not set file path. What do I do?</p>

```<code>applicationVariants.all {
    variant->
        variant.outputs.all {
            output->
                def outputFile = output.outputFile
                if (outputFile != null && outputFile.name.endsWith('.apk')) {
                    outputFileName = "${defaultConfig.applicationId}_${variant.productFlavors[0].name}_${defaultConfig.versionName}_${releaseTime()}.apk"
                }
        }
}
</code>```

答:
I've figured out solution for this:

```<code>applicationVariants.all{
            variant->
                //Android Studio 3.0+
                variant.outputs.all{
                    outputFileName = "${defaultConfig.applicationId}_${variant.productFlavors[0].name}_${defaultConfig.versionName}_${releaseTime()}.apk"
                    variant.packageApplication.outputDirectory = new File("xx/yyy/ttt")

                }
        }
</code>```

But It may be deprecated in gradle 5.0+，because variant.packageApplication.outputDirectory will be deleted in gradle 5.0. And you see a warning that: access outputDirectory exceeds its access rights

Body:
I want to set APK filePath in gradle that version is v4.1,but I can set its name and not set file path. What do I do?

applicationVariants.all {
    variant->
        variant.outputs.all {
            output->
                def outputFile = output.outputFile
                if (outputFile != null && outputFile.name.endsWith('.apk')) {
                    outputFileName = "${defaultConfig.applicationId}_${variant.productFlavors[0].name}_${defaultConfig.versionName}_${releaseTime()}.apk"
                }
        }
}

Body:
I've figured out solution for this:

applicationVariants.all{
            variant->
                //Android Studio 3.0+
                variant.outputs.all{
                    outputFileName = "${defaultConfig.applicationId}_${variant.productFlavors[0].name}_${defaultConfig.versionName}_${releaseTime()}.apk"
                    variant.packageApplication.outputDirectory = new File("xx/yyy/ttt")

                }
        }

But It may be deprecated in gradle 5.0+，because variant.packageApplication.outputDirectory will be deleted in gradle 5.0. And you see a warning that: access outputDirectory exceeds its access rights


问:
Prevent extra whitespace when piping data in a Windows batch script
I have to run an executable (written in C#) 42 times separately for 42 US states on Windows command line. I wrote a batch file to automate the process. The 1st user input to the executable is 1, and the 2nd one is the state abbreviation (AL, AZ, CT etc.). I have written the following script to do it:

```<code>@echo off

for /f "tokens=1 delims=" %%x in (CropHailStates.txt) do (

    (echo 1 & echo %%x)|Z:\Models\LossCalc.exe
)
</code>```

Each row in CropHailStates.txt file contains the state abbreviation as follows:

AL

AZ

CT

Now in manual mode, when 1 is entered at the 1st prompt and AL is entered at the 2nd, the C# program reads a file named "AL.Even.CropLoss.csv". But when I run the batch script to do it automatically, I get the error message saying that the file "AL .Even.CropLoss.csv" is not found. The problem is related to the extra whitespace after AL. It’s somehow adding the whitespace after inserting the state abbreviation. It’s like pressing the spacebar after writing the state abbreviation, but before pressing enter.

How can I get rid of that extra whitespace in the file name?

答:
The problem is an artifact of the pipe parser when dealing with a parenthesized block of code.

The source of the problem is described by jeb at Why does delayed expansion fail when inside a piped block of code?.
Each side of the pipe is executed in a new CMD /C process.

When a multi-line parenthesized block gets piped, the parser must repackage the entire block into a single line so that it can be executed via CMD /C

```<code>(
  echo line 1
  echo line 2
) | findstr "^"
</code>```

The left side of the pipe is executed as:

```<code>C:\WINDOWS\system32\cmd.exe  /S /D /c" ( echo line 1 & echo line 2 )"
</code>```

You can see the extra spaces that are introduced.

Even though your code is already on a single line, it still goes through the same parser that introduces those pesky spaces.

I know of three relatively simple solutions that eliminate the unwanted spaces without the need for a temporary file.

1) Add an extra CMD /C where you explicitly get the exact behavior you are looking for

```<code>@echo off
for /f "tokens=1 delims=" %%x in (CropHailStates.txt) do (
  cmd /c "echo 1&echo %%x"|Z:\Models\LossCalc.exe
)
</code>```

2) Store part of the command in a variable and delay expansion until execution of CMD /C

```<code>@echo off
setlocal
for /f "tokens=1 delims=" %%x in (CropHailStates.txt) do (
  set "cmd=&echo %%x"
  (echo 1%%cmd%%)|Z:\Models\LossCalc.exe
)
</code>```

3) Introduce delayed expansion of a linefeed variable - a mind blowing technique developed by jeb that he describes in that same SO link that I provided

```<code>@echo off
setlocal
set ^"LF=^
%= This creates a linefeed character =%
"
for /f "tokens=1 delims=" %%x in (CropHailStates.txt) do (
  (echo 1%%LF%%echo %%x%%LF%%)|Z:\Models\LossCalc.exe
)
</code>```

Body:
I have to run an executable (written in C#) 42 times separately for 42 US states on Windows command line. I wrote a batch file to automate the process. The 1st user input to the executable is 1, and the 2nd one is the state abbreviation (AL, AZ, CT etc.). I have written the following script to do it:

@echo off

for /f "tokens=1 delims=" %%x in (CropHailStates.txt) do (

    (echo 1 & echo %%x)|Z:\Models\LossCalc.exe
)

Each row in CropHailStates.txt file contains the state abbreviation as follows:

AL

AZ

CT

Now in manual mode, when 1 is entered at the 1st prompt and AL is entered at the 2nd, the C# program reads a file named "AL.Even.CropLoss.csv". But when I run the batch script to do it automatically, I get the error message saying that the file "AL .Even.CropLoss.csv" is not found. The problem is related to the extra whitespace after AL. It’s somehow adding the whitespace after inserting the state abbreviation. It’s like pressing the spacebar after writing the state abbreviation, but before pressing enter.

How can I get rid of that extra whitespace in the file name?

Body:
The problem is an artifact of the pipe parser when dealing with a parenthesized block of code.

The source of the problem is described by jeb at Why does delayed expansion fail when inside a piped block of code?.
Each side of the pipe is executed in a new CMD /C process.

When a multi-line parenthesized block gets piped, the parser must repackage the entire block into a single line so that it can be executed via CMD /C

(
  echo line 1
  echo line 2
) | findstr "^"

The left side of the pipe is executed as:

C:\WINDOWS\system32\cmd.exe  /S /D /c" ( echo line 1 & echo line 2 )"

You can see the extra spaces that are introduced.

Even though your code is already on a single line, it still goes through the same parser that introduces those pesky spaces.

I know of three relatively simple solutions that eliminate the unwanted spaces without the need for a temporary file.

1) Add an extra CMD /C where you explicitly get the exact behavior you are looking for

@echo off
for /f "tokens=1 delims=" %%x in (CropHailStates.txt) do (
  cmd /c "echo 1&echo %%x"|Z:\Models\LossCalc.exe
)

2) Store part of the command in a variable and delay expansion until execution of CMD /C

@echo off
setlocal
for /f "tokens=1 delims=" %%x in (CropHailStates.txt) do (
  set "cmd=&echo %%x"
  (echo 1%%cmd%%)|Z:\Models\LossCalc.exe
)

3) Introduce delayed expansion of a linefeed variable - a mind blowing technique developed by jeb that he describes in that same SO link that I provided

@echo off
setlocal
set ^"LF=^
%= This creates a linefeed character =%
"
for /f "tokens=1 delims=" %%x in (CropHailStates.txt) do (
  (echo 1%%LF%%echo %%x%%LF%%)|Z:\Models\LossCalc.exe
)


问:
Music21 to get sample of time and frequencies in txt or csv
I'm getting familiar with python but I just discovered music21 and even if I'm currently reading as much as possible from the documentation, I'm having a hard time finding simple answer to my simple question:

How to sample a piece of music (say from a .wav or .aup file) for a specific rate to get both time and frequencies (or log2),  eventually using music21?

The idea here would be to specify the rate (say every 0.1 second) and get the lines.

```<code>Time, Frequency
.1,441.223
.2,441.266
.3,441.488
etc.
</code>```

I'm guessing the music21.audioSearch.autocorrelationFunction tool should be okay but not sure if I understand exactly what it does...

If it helps -- my goal is to put those pieces of music through computational analysis in order to understand the fluctuations of the frequencies relatively to several factors coming from the performance and the performer.

So I'd need to print this to a .csv or .txt at some point in order to save data.

Thanks beforehand for any clues you may have for me ;-)

答: As Michael said, music 21 only works with symbolic notation, not audio. Librosa is a python library that works with audio files, but it is very difficult to isolate exact pitch and offset information from an audio signal. To look at analysis of performance differences, check out the Magenta project by Google. They had pianists perform on a midi keyboard and did machine learning to model the expressiveness. </p>

Body:
I'm getting familiar with python but I just discovered music21 and even if I'm currently reading as much as possible from the documentation, I'm having a hard time finding simple answer to my simple question:

How to sample a piece of music (say from a .wav or .aup file) for a specific rate to get both time and frequencies (or log2),  eventually using music21?

The idea here would be to specify the rate (say every 0.1 second) and get the lines.

Time, Frequency
.1,441.223
.2,441.266
.3,441.488
etc.

I'm guessing the music21.audioSearch.autocorrelationFunction tool should be okay but not sure if I understand exactly what it does...

If it helps -- my goal is to put those pieces of music through computational analysis in order to understand the fluctuations of the frequencies relatively to several factors coming from the performance and the performer.

So I'd need to print this to a .csv or .txt at some point in order to save data.

Thanks beforehand for any clues you may have for me ;-)


问:
How to add design dependency in android studio 3.0. its not working in standard way
```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.rohit.ironman"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner"android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:26.0.0-beta1'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:0.5'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    compile 'com.android.support:design:26.1.1'
}
</code>```

I have also tried-

Implementation 'com.android.support:design:26.1.1'
instead of

compile 'com.android.support:design:26.1.1'
but still the gradle sync fails

my gradle version is 4.1

android plugin version is 3.0.1

答:
Use The method to add Android default librarys like support,design,core,.. library

Open your project in Android Studio

Right-click your app in project view and select "Open Module Settings"

Click the "Dependencies" tab and then the '+' button

Select "Libary Dependency"

Select Required Library fom the List

Body:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.rohit.ironman"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner"android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:26.0.0-beta1'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:0.5'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    compile 'com.android.support:design:26.1.1'
}

I have also tried-

Implementation 'com.android.support:design:26.1.1'
instead of

compile 'com.android.support:design:26.1.1'
but still the gradle sync fails

my gradle version is 4.1

android plugin version is 3.0.1


问:
How do I clear System.Net client DNS cache?
I'm using the .NET WebRequest while changing my HOSTS file. I'm observing that System.Net doesn't honor those changes - how can I make it do so?

I have a number of servers load-balanced behind a single hostname, let's say 'example.com'. I want to target several of them individually, so my program will hard-code the machine-specific IP address in my HOSTS file before sending a request to example.com:

```<code>163.56.0.34  example.com
</code>```

For the first server and first request, this works fine. Then my program changes the HOSTS file again:

```<code>163.56.0.48  example.com
</code>```

And I create a new HttpWebRequest. When I send this one off, I can observe in NETMON that it goes to the first IP address (163.56.0.34) instead of the expected second one.

Using breakpoints and debug traces, I've verified that the correct value does get written to the HOSTS file each time. When I attempt to access example.com from a browser or other program, it does honor the HOSTS file and go to the second IP address.

Using NETMON I've verified that requests are going directly to the IP address shown; there is no HTTP proxy.

Since everything else is honoring the changed HOSTS file, I strongly suspect that the System.Net infrastructure has cached the DNS host-IP association for example.com. However, I can find no reference to this caching, and know of no way to flush it or turn it off.

I would welcome instructions for dealing with the cache, suggestions for what else might be causing these symptoms, or other proposed diagnostic steps that might be useful.

答:
A late answer to be sure, but I found this solution worked better than the accepted answer.  In my scenario I am testing SQL connections, and I couldn't apply the existing answer since I have no request.KeepAlive to set.

This page by Brian Mancini ("derp turkey") details his adventure in clearing the DNS cache.  Full props to him, I'm just adding his solution here:

```<code>public class DnsUtils
{
    [DllImport("dnsapi.dll", EntryPoint="DnsFlushResolverCache")]
    static extern UInt32 DnsFlushResolverCache();

    [DllImport("dnsapi.dll", EntryPoint = "DnsFlushResolverCacheEntry_A")]
    public static extern int DnsFlushResolverCacheEntry(string hostName);

    public static void FlushCache()
    {
        DnsFlushResolverCache();
    }

    public static void FlushCache(string hostName)
    {
        DnsFlushResolverCacheEntry(hostName);
    }
}
</code>```

Body:
I'm using the .NET WebRequest while changing my HOSTS file. I'm observing that System.Net doesn't honor those changes - how can I make it do so?

I have a number of servers load-balanced behind a single hostname, let's say 'example.com'. I want to target several of them individually, so my program will hard-code the machine-specific IP address in my HOSTS file before sending a request to example.com:

163.56.0.34  example.com

For the first server and first request, this works fine. Then my program changes the HOSTS file again:

163.56.0.48  example.com

And I create a new HttpWebRequest. When I send this one off, I can observe in NETMON that it goes to the first IP address (163.56.0.34) instead of the expected second one.

Using breakpoints and debug traces, I've verified that the correct value does get written to the HOSTS file each time. When I attempt to access example.com from a browser or other program, it does honor the HOSTS file and go to the second IP address.

Using NETMON I've verified that requests are going directly to the IP address shown; there is no HTTP proxy.

Since everything else is honoring the changed HOSTS file, I strongly suspect that the System.Net infrastructure has cached the DNS host-IP association for example.com. However, I can find no reference to this caching, and know of no way to flush it or turn it off.

I would welcome instructions for dealing with the cache, suggestions for what else might be causing these symptoms, or other proposed diagnostic steps that might be useful.

Body:
A late answer to be sure, but I found this solution worked better than the accepted answer.  In my scenario I am testing SQL connections, and I couldn't apply the existing answer since I have no request.KeepAlive to set.

This page by Brian Mancini ("derp turkey") details his adventure in clearing the DNS cache.  Full props to him, I'm just adding his solution here:

public class DnsUtils
{
    [DllImport("dnsapi.dll", EntryPoint="DnsFlushResolverCache")]
    static extern UInt32 DnsFlushResolverCache();

    [DllImport("dnsapi.dll", EntryPoint = "DnsFlushResolverCacheEntry_A")]
    public static extern int DnsFlushResolverCacheEntry(string hostName);

    public static void FlushCache()
    {
        DnsFlushResolverCache();
    }

    public static void FlushCache(string hostName)
    {
        DnsFlushResolverCacheEntry(hostName);
    }
}


问:
Better way of processing multiple form fields
Is there  a better way to process a form where I need to save a link and link text against a language and company?

The example below works, but I think it is hard work.

I have added the language and company id to the key of the link and link text fields as a way of grouping them together and passing the other information through to PHP and into the DB.

```<code>$newlinks = array();
foreach($_POST as $post_key => $post_value) {
  if (substr($post_key, 0, 7) == 'newlink') {
    $posted_link = explode('_', $post_key);
    $newlinks[$posted_link[1]][$posted_link[2]][$posted_link[0]] = $post_value;
    $newlinks[$posted_link[1]][$posted_link[2]]['language_id'] = $posted_link[1];
    $newlinks[$posted_link[1]][$posted_link[2]]['company_id'] = $posted_link[2];

  }
}

foreach($newlinks as $newlinklang) {
  foreach($newlinklang as $newlink) {
    if ($newlink['newlink'] != '' && $newlink['newlinkname'] != '') {
      $sql = "
        INSERT
          INTO
        ".$db_prefix."catalogue_links (
          link,
          link_name,
          language_id,
          company_id
        ) VALUES (
          '".$newlink['newlink']."',
          '".$newlink['newlinkname']."',
          '".$newlink['language_id']."',
          '".$newlink['company_id']."'
        ";
    }
  }
}
</code>```

And the HTML

```<code><input type="text" name="newlink_1_1" value="" />
<input type="text" name="newlinkname_1_1" value="" />
</code>```

There can be multiple languages and companies displayed on one page.

答:
Use something[] as the field name. Then PHP will create an array in $_POST['something'] (or $_GET, and $_REQUEST - obviously) which you can use without ugly substring comparisons.

You could also specify array indexes in the field name (name="something[42]"). This might be a good idea if you have multiple fields which belong together. While the order is supposed to be correct anyway (so you can foreach($_POST['field1'] as $idx => $val) and use _POST['field2'][$idx]) it might be safer or at least more intuitive for someone reading the code if the indexes are also in the HTML code.

Body:
Is there  a better way to process a form where I need to save a link and link text against a language and company?

The example below works, but I think it is hard work.

I have added the language and company id to the key of the link and link text fields as a way of grouping them together and passing the other information through to PHP and into the DB.

$newlinks = array();
foreach($_POST as $post_key => $post_value) {
  if (substr($post_key, 0, 7) == 'newlink') {
    $posted_link = explode('_', $post_key);
    $newlinks[$posted_link[1]][$posted_link[2]][$posted_link[0]] = $post_value;
    $newlinks[$posted_link[1]][$posted_link[2]]['language_id'] = $posted_link[1];
    $newlinks[$posted_link[1]][$posted_link[2]]['company_id'] = $posted_link[2];

  }
}

foreach($newlinks as $newlinklang) {
  foreach($newlinklang as $newlink) {
    if ($newlink['newlink'] != '' && $newlink['newlinkname'] != '') {
      $sql = "
        INSERT
          INTO
        ".$db_prefix."catalogue_links (
          link,
          link_name,
          language_id,
          company_id
        ) VALUES (
          '".$newlink['newlink']."',
          '".$newlink['newlinkname']."',
          '".$newlink['language_id']."',
          '".$newlink['company_id']."'
        ";
    }
  }
}

And the HTML

<input type="text" name="newlink_1_1" value="" />
<input type="text" name="newlinkname_1_1" value="" />

There can be multiple languages and companies displayed on one page.


问:
how to prevent cpu usage from changing timing in labview?
I'm trying to write a code in which every 1 ms a number plused one , should be replaced the old number . (something  like a chronometer !  )  .

the problem is whenever the cpu usage increases because of some other programs running on the pc,  this 1 milliseconds  is also increased and timing in my program changes !

is there any way to prevent cpu load changes affecting timing in my program ?

答: The answer to your question is "not on a desktop computer." This is why products like LabVIEW Real-Time and dedicated deterministic hardware exist: you need a computer built around dedication to a particular process in order to consistently serve that process. Every application in a regular Windows/Mac/Linux desktop system has the problem you are seeing of potentially being interrupted by other system processes, particularly in its UI layer. </p>


问:
Toggling Font Awesome 5 icon with React
I am trying to toggle a Font Awesome icon by clicking on a to-do list item. Here is the entire component...

```<code>import React from 'react';

import './TodoItem.scss';

class TodoItem extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      complete: false
    }
    this.toggleComplete = this.toggleComplete.bind(this);
  }

  toggleComplete() {
    this.setState(prevState => ({
      complete: !prevState.complete
    }));
  }

  render() {
    const incompleteIcon = <span className="far fa-circle todo-item-icon"></span>;
    const completeIcon = <span className="far fa-check-circle todo-item-icon"></span>;

    return (
      <div className="todo-item" onClick={this.toggleComplete}>
        {this.state.complete ? completeIcon : incompleteIcon}
        <span className="todo-item-text">{this.props.item}</span>
      </div>
    );
  }
}

export default TodoItem;
</code>```

Here's my FA 5 CDN (straight from the website)...

```<code><script defer src="https://use.fontawesome.com/releases/v5.0.1/js/all.js"></script>
</code>```

I've taken a few screenshots of the React dev tool and inspector...

Here is the React component while incomplete (the default)

And while complete...

And the two icon elements in the inspector, I noticed the one not being used by default is commented out.

As you can see, I'm able to manually toggle the complete state and the component changes in the React tool but the change is not rendered. I changed the default state to make sure both icons are loaded correctly and they are. I made a Codepen to try it in a different environment and this one works, but I am using the FA 4.7.0 CDN. With the Codepen and FA 4.7.0, when I inspect the icon, it is just an HTML element not SVG.

I'd like to get this component working with FA 5 so any help would be appreciated!

答: as per discussion above this is likely a fontawesome bug, not a react bug</p>

Title: Toggling Font Awesome 5 icon with React

Body:
I am trying to toggle a Font Awesome icon by clicking on a to-do list item. Here is the entire component...

import React from 'react';

import './TodoItem.scss';

class TodoItem extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      complete: false
    }
    this.toggleComplete = this.toggleComplete.bind(this);
  }

  toggleComplete() {
    this.setState(prevState => ({
      complete: !prevState.complete
    }));
  }

  render() {
    const incompleteIcon = ;
    const completeIcon = ;

    return (

        {this.state.complete ? completeIcon : incompleteIcon}
        {this.props.item}

    );
  }
}

export default TodoItem;

Here's my FA 5 CDN (straight from the website)...

I've taken a few screenshots of the React dev tool and inspector...

Here is the React component while incomplete (the default)

And while complete...

And the two icon elements in the inspector, I noticed the one not being used by default is commented out.

As you can see, I'm able to manually toggle the complete state and the component changes in the React tool but the change is not rendered. I changed the default state to make sure both icons are loaded correctly and they are. I made a Codepen to try it in a different environment and this one works, but I am using the FA 4.7.0 CDN. With the Codepen and FA 4.7.0, when I inspect the icon, it is just an HTML element not SVG.

I'd like to get this component working with FA 5 so any help would be appreciated!


答:
This seems obvious that you have copied all elements from srcList to listC, so now the resultant list is of type List<? super String>.

when you're saying for (String item : listC) compiler will try to convert the type ? super String to String type. This is not allowed. Hence the compiler error. You should use the same type for both lists. As mentioned by @DawoodibnKareem, List<? super String> could be List<Object>, List<CharSequence> or a List of any other supertype of String. List of different types is not compatible.

Title: Java ? super T in Collections copy why correct work


问:
Can't upload app to iTunes connect Xcode 9
I had checked my provision profile and certificate. It was no problem to upload app in Xcode 7, but after update to Xcode 9, I receive error in Xcode

Apps must contain a provisioning profile in a file named embedded.mobileprovision

From application uploader I have error, too. Spent a lot of time to fix this problem, but has no idea for this time.

答:
The IPA structure for any IPA is as follows. Make sure to rename the IPA to .zip and extract, then you will have to Ctrl+Click and say show package contents to see the inside App.

Structure :

```<code>Payload
    MyApp.app
      -- _CodeSignature
      -- Plugins (optional if you have extension like Siri, widget)
      -- Watch (optional if you have extensions for watch)
      -- archived-content....xccent
      **-- embedded-provisionign.profile**
      -- Info.plist
</code>```

Now check this profile if its double clicked and installed properly in your Xcode and found, if not the profile cert and p12, and profile file have issued from the generation time. Solve this and try to compile new IPA.

It should solve your purpose. Note If you are using a developer account, go to its dev portal member centre and see if the profile and AppId are valid as per one in the code. You can check the extracted above Plist for the CFBundleIdentifier value and check if its relevant dev account portal profile is Active and not Invalid due to any cause for that APP ID associated with the profile.

Body:
The IPA structure for any IPA is as follows. Make sure to rename the IPA to .zip and extract, then you will have to Ctrl+Click and say show package contents to see the inside App.

Structure :

Payload
    MyApp.app
      -- _CodeSignature
      -- Plugins (optional if you have extension like Siri, widget)
      -- Watch (optional if you have extensions for watch)
      -- archived-content....xccent
      **-- embedded-provisionign.profile**
      -- Info.plist

Now check this profile if its double clicked and installed properly in your Xcode and found, if not the profile cert and p12, and profile file have issued from the generation time. Solve this and try to compile new IPA.

It should solve your purpose. Note If you are using a developer account, go to its dev portal member centre and see if the profile and AppId are valid as per one in the code. You can check the extracted above Plist for the CFBundleIdentifier value and check if its relevant dev account portal profile is Active and not Invalid due to any cause for that APP ID associated with the profile.


问:
Is it possible to run each layer in a cnn parallely in either caffe or tensorflow?
I want to run each layer of a trained CNN in parallel to reduce the computation time during forward propagation ( Basically I want to run the CNN for a real time application involving a camera without affecting the FPS too much ). I will keep an input queue and an output queue for each layer. Each layer can process a blob from input layer and dump it in the output layer ( This can logically be done in parallel ). Output queue for each layer will work as the Input Queue for the following layer. And then I will collect all the outputs from the output queue ( its going to be a binary label ) of the final layer and process them. So my question is that is it possible to run each layer of a CNN in parallel in either Caffe or Tensorflow to implement this.</p>

答: With Tensorflow you can specify "device placement", so for each operation or group of operations in the graph you can say on which GPU to run it, for example, if you have several GPUs. See this tutorial for sample code on how to place operations on GPUs.</p>


问:
How to avoid wasting memory on 64-bit pointers
I'm hoping for some high-level advice on how to approach a design I'm about to undertake.

The straightforward approach to my problem will result in millions and millions of pointers. On a 64-bit system these will presumably be 64-bit pointers. But as far as my application is concerned, I don't think I need more than a 32-bit address space. I would still like for the system to take advantage of 64-bit processor arithmetic, however (assuming that is what I get by running on a 64-bit system).

Further background

I'm implementing a tree-like data structure where each "node" contains an 8-byte payload, but also needs pointers to four neighboring nodes (parent, left-child, middle-child, right-child). On a 64-bit system using 64-bit pointers, this amounts to 32 bytes just for linking an 8-byte payload into the tree -- a "linking overhead" of 400%.

The data structure will contain millions of these nodes, but my application will not need much memory beyond that, so all these 64-bit pointers seem wasteful. What to do? Is there a way to use 32-bit pointers on a 64-bit system?

I've considered

Storing the payloads in an array in a way such that an index implies (and is implied by) a "tree address" and neighbors of a given index can be calculated with simple arithmetic on that index. Unfortunately this requires me to size the array according to the maximum depth of the tree, which I don't know beforehand, and it would probably incur even greater memory overhead due to empty node elements in the lower levels because not all branches of the tree go to the same depth.

Storing nodes in an array large enough to hold them all, and then using indices instead of pointers to link neighbors. AFAIK the main disadvantage here would be that each node would need the array's base address in order to find its neighbors. So they either need to store it (a million times over) or it needs to be passed around with every function call. I don't like this.

Assuming that the most-significant 32 bits of all these pointers are zero, throwing an exception if they aren't, and storing only the least-significant 32 bits. So the required pointer can be reconstructed on demand. The system is likely to use more than 4GB, but the process will never. I'm just assuming that pointers are offset from a process base-address and have no idea how safe (if at all) this would be across the common platforms (Windows, Linux, OSX).

Storing the difference between 64-bit this and the 64-bit pointer to the neighbor, assuming that this difference will be within the range of int32_t (and throwing if it isn't). Then any node can find it's neighbors by adding that offset to this.

Any advice? Regarding that last idea (which I currently feel is my best candidate) can I assume that in a process that uses less than 2GB, dynamically allocated objects will be within 2 GB of each other? Or not at all necessarily?

答:
You can remove the disadvantage of (2) by exploiting the alignment of memory regions to find the base address of the the array "automatically". For example, if you want to support up to 4 GB of nodes, ensure your node array starts at a 4GB boundary.

Then within a node with address addr, you can determine the address of another at index as addr & -(1UL << 32) + index.

This is kind of the "absolute" variant of the accepted solution which is "relative". One advantage of this solution is that an index always has the same meaning within a tree, whereas in the relative solution you really need the (node_address, index) pair to interpret an index (of course, you can also use the absolute indexes in the relative scenarios where it is useful). It means that when you duplicate a node, you don't need to adjust any index values it contains.

The "relative" solution also loses 1 effective index bit relative to this solution in its index since it needs to store a signed offset, so with a 32-bit index, you could only support 2^31 nodes (assuming full compression of trailing zero bits, otherwise it is only 2^31 bytes of nodes).

You can also store the base tree structure (e.g,. the pointer to the root and whatever bookkeeping your have outside of the nodes themselves) right at the 4GB address which means that any node can jump to the associated base structure without traversing all the parent pointers or whatever.

Finally, you can also exploit this alignment idea within the tree itself to "implicitly" store other pointers. For example, perhaps the parent node is stored at an N-byte aligned boundary, and then all children are stored in the same N-byte block so they know their parent "implicitly". How feasible that is depends on how dynamic your tree is, how much the fan-out varies, etc.

You can accomplish this kind of thing by writing your own allocator that uses mmap to allocate suitably aligned blocks (usually just reserve a huge amount of virtual address space and then allocate blocks of it as needed) - ether via the hint parameter or just by reserving a big enough region that you are guaranteed to get the alignment you want somewhere in the region. The need to mess around with allocators is the primary disadvantage compared to the accepted solution, but if this is the main data structure in your program it might be worth it. When you control the allocator you have other advantages too: if you know all your nodes are allocated on an 2^N-byte boundary you can "compress" your indexes further since you know the low N bits will always be zero, so with a 32-bit index you could actually store 2^(32+5) = 2^37 nodes if you knew they were 32-byte aligned.

These kind of tricks are really only feasible in 64-bit programs, with the huge amount of virtual address space available, so in a way 64-bit giveth and also taketh away.


问:
Why my onclick can't trigger Animation Imageview
I want to make my Image View rotate to random angle by using Onclick(). But why the Onlick() works but the Imageview can't rotate?Here is my code.</p>

```<code>ImageView rotate_plate;
Button debug_button;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    debug_button=(Button) findViewById(R.id.test_button);
    debug_button.setOnClickListener(btngoOnClick);

}
private OnClickListener btngoOnClick = new OnClickListener() {
    public void onClick(View v) {

        debug_button.setText("Click");
        rotate_plate=(ImageView) findViewById(R.id.wheel);
        int stopturnnum = (int)(Math.random() *360);
        Animation am = new RotateAnimation(0, stopturnnum, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);

        am.setDuration( 3000 );
        am.setRepeatCount(1);
        am.setFillAfter(true);
        rotate_plate.setAnimation(am);
        am.startNow();
    }
};
</code>```

答:
Try with ViewPropertyAnimator API, it's way more convenient:

```<code>rotate_plate.animate()
    .rotation(angle)
    .setDuration(3000L)
</code>```

Body:
I want to make my Image View rotate to random angle by using Onclick(). But why the Onlick() works but the Imageview can't rotate?Here is my code.

ImageView rotate_plate;
Button debug_button;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    debug_button=(Button) findViewById(R.id.test_button);
    debug_button.setOnClickListener(btngoOnClick);

}
private OnClickListener btngoOnClick = new OnClickListener() {
    public void onClick(View v) {

        debug_button.setText("Click");
        rotate_plate=(ImageView) findViewById(R.id.wheel);
        int stopturnnum = (int)(Math.random() *360);
        Animation am = new RotateAnimation(0, stopturnnum, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);

        am.setDuration( 3000 );
        am.setRepeatCount(1);
        am.setFillAfter(true);
        rotate_plate.setAnimation(am);
        am.startNow();
    }
};

Body:
Try with ViewPropertyAnimator API, it's way more convenient:

rotate_plate.animate()
    .rotation(angle)
    .setDuration(3000L)


问:
What will it take to add Objective-C support to the .NET common language runtime?
Is it possible for the .NET CLR to support Objective-C? Are there any reasons (either from a legal or implementational) standpoint why this wouldn't be possible?

In the spirit of cross-platform application development, it would be nice to be able to write and run Objective-C applications on Windows machines. At least I think it would.

答:
What about Objective-J and Cappuccino for .Net, rather than Objective-C and Cocoa? Objective-J is just as appealing as Objective-C, however, Objective-J is closer to C# than Objective-C (no pointers, garbage collection, etc.)

I recently asked about this on the Cappuccino developers forum, and they pointed me towards Jurassic (a JavaScript compiler for .NET). They also said that Cappuccino works fine on IronJS. So, it looks like the components are there (Objective-J → JavaScript → .NET), but the bridge linking them together has to be built.

LastEditorDisplayName: Ned Batchelder


问:
UITextView left image icon swift
How to set left image icon in UITextView?

with padding because of which cannot overlap image and text on each other.

This is not UItextField,use "UITextView" instead of "UItextField" UItextField it gives inbuilt leftview and rightview which are absent in "UITextView"

```<code>class CustomTextView:UITextView{

    /// A UIImage value that set LeftImage to the UITextView
    @IBInspectable open var leftImage:UIImage? {
         didSet {
            if (leftImage != nil) {
               self.leftImage(leftImage!)
            }
        }
    }

fileprivate func leftImage(_ image: UIImage) {
    let icn : UIImage = image
    let imageView = UIImageView(image: icn)
    imageView.frame = CGRect(x: 0, y: 2.0, width: icn.size.width + 20, height: icn.size.height)
    imageView.contentMode = UIViewContentMode.center

}
</code>```

I hope you understand what I should need.

答:
This is the code snippet to make custom UITextView:

```<code>//MARK:- CustomTextView
class CustomTextView:UITextView{

    /// A UIImage value that set LeftImage to the UITextView
    @IBInspectable open var leftImage:UIImage? {
        didSet {
            if (leftImage != nil) {
                self.applyLeftImage(leftImage!)
            }
        }
    }

fileprivate func applyLeftImage(_ image: UIImage) {
        let icn : UIImage = image
        let imageView = UIImageView(image: icn)
        imageView.frame = CGRect(x: 0, y: 2.0, width: icn.size.width + 20, height: icn.size.height)
        imageView.contentMode = UIViewContentMode.center
        //Where self = UItextView
        self.addSubview(imageView)
        self.textContainerInset = UIEdgeInsets(top: 2.0, left: icn.size.width + 10.0 , bottom: 2.0, right: 2.0)
    }
}
</code>```

After write this code select UITextView in Storyboard and give the name of class "CustomTextView" Now go to attribute inspector set your image as left image.

Thank you,

Title: UITextView left image icon swift

Body:
How to set left image icon in UITextView?

with padding because of which cannot overlap image and text on each other.

This is not UItextField,use "UITextView" instead of "UItextField" UItextField it gives inbuilt leftview and rightview which are absent in "UITextView"

class CustomTextView:UITextView{

    /// A UIImage value that set LeftImage to the UITextView
    @IBInspectable open var leftImage:UIImage? {
         didSet {
            if (leftImage != nil) {
               self.leftImage(leftImage!)
            }
        }
    }

fileprivate func leftImage(_ image: UIImage) {
    let icn : UIImage = image
    let imageView = UIImageView(image: icn)
    imageView.frame = CGRect(x: 0, y: 2.0, width: icn.size.width + 20, height: icn.size.height)
    imageView.contentMode = UIViewContentMode.center

}

I hope you understand what I should need.

Body:
This is the code snippet to make custom UITextView:

//MARK:- CustomTextView
class CustomTextView:UITextView{

    /// A UIImage value that set LeftImage to the UITextView
    @IBInspectable open var leftImage:UIImage? {
        didSet {
            if (leftImage != nil) {
                self.applyLeftImage(leftImage!)
            }
        }
    }

fileprivate func applyLeftImage(_ image: UIImage) {
        let icn : UIImage = image
        let imageView = UIImageView(image: icn)
        imageView.frame = CGRect(x: 0, y: 2.0, width: icn.size.width + 20, height: icn.size.height)
        imageView.contentMode = UIViewContentMode.center
        //Where self = UItextView
        self.addSubview(imageView)
        self.textContainerInset = UIEdgeInsets(top: 2.0, left: icn.size.width + 10.0 , bottom: 2.0, right: 2.0)
    }
}

After write this code select UITextView in Storyboard and give the name of class "CustomTextView" Now go to attribute inspector set your image as left image.

Thank you,


问:
Querying varchars as decimals in SQL Server
I have a problem in SQL Server, I am trying to query

```<code>where x.numbers >= '9'
</code>```

where x.numbers was stored as varchar and some of the values I have in that field are

```<code>8.9
9.3
6.7
>10
8.3
>= 9
</code>```

If I try isnumeric(x.numbers), then it is excluding those values that start with > or >=. and I tried cast(x.numbers as decimal) but it is not working as well. Please advise

答:
try cast(n as float) as shown below:</p>

```<code>        create table #tmp(numbers varchar(10))

        insert into #tmp values('8.9')
        insert into #tmp values('9.3')
        insert into #tmp values('6.7')
        insert into #tmp values('11')
        insert into #tmp values('8.3')
        insert into #tmp values('9')
        insert into #tmp values('10')

        Select *  from #tmp where cast(numbers as float)> = cast('9' as float)

        Drop table #tmp
</code>```

Body:
I have a problem in SQL Server, I am trying to query

where x.numbers >= '9'

where x.numbers was stored as varchar and some of the values I have in that field are

8.9
9.3
6.7
>10
8.3
>= 9

If I try isnumeric(x.numbers), then it is excluding those values that start with > or >=. and I tried cast(x.numbers as decimal) but it is not working as well. Please advise

Body:
try cast(n as float) as shown below:

        create table #tmp(numbers varchar(10))

        insert into #tmp values('8.9')
        insert into #tmp values('9.3')
        insert into #tmp values('6.7')
        insert into #tmp values('11')
        insert into #tmp values('8.3')
        insert into #tmp values('9')
        insert into #tmp values('10')

        Select *  from #tmp where cast(numbers as float)> = cast('9' as float)

        Drop table #tmp