问:
Problem with custom link cursor in Chrome
I want to use a custom cursor on hover for links. It works fine on Safari and Firefox, but on Chrome it jumps back to the default cursor for a millisecond, and then goes to my custom cursor.

Codepen: https://codepen.io/ford1234/pen/vwzRgJ

I've recreated the problem in Codepen but it also happens on the site I'm applying it to.

```<code><div>
  <a href="#"><p>Hello</p></a>
</div>

<style>
html {
    cursor: url('http://telephoneavenue.art/wp-content/uploads/2019/02/black-01.png'), auto;
}

a:hover {
    cursor: url('http://telephoneavenue.art/wp-content/uploads/2019/05/blacktriangle-small17px.png'), auto;
</code>```

}

Expected result: A transition from the circle to the triangle.
Actual result: A transition from the circle, to the default hand pointer, to the triangle.

答:
Have you tried out a transition-duration or a transition-delay? This is used to define the duration of a specified transition. This is the length of time it will take for the targeted element to transition between two defined states.

```<code>.example {
    transition-duration: 0s;
    // or
    transition-delay: -1s;
}
</code>```

Also keep in mind that some features are only supported by certain versions of the browser.

Body:
I want to use a custom cursor on hover for links. It works fine on Safari and Firefox, but on Chrome it jumps back to the default cursor for a millisecond, and then goes to my custom cursor.

Codepen: https://codepen.io/ford1234/pen/vwzRgJ

I've recreated the problem in Codepen but it also happens on the site I'm applying it to.

Hello

Body:
Have you tried out a transition-duration or a transition-delay? This is used to define the duration of a specified transition. This is the length of time it will take for the targeted element to transition between two defined states.

.example {
    transition-duration: 0s;
    // or
    transition-delay: -1s;
}

Also keep in mind that some features are only supported by certain versions of the browser.


来源: stackexchange

问:
Develop iPhone applications on Windows (with Virtualbox etc)
This has been asked before, I know, but the answers are a bit dated.

I think I've read somewhere that the Snow Leopard EULA has changed and that you now are allowed to install the OS on a Virtual Machine of some sort.

I know I should buy a Mac and I might do so, but I want to try Objective-C in practice before I do that.

I want to develop an application for iPhone, but if the IDE is as nasty as they say I might skip it altogether. I just want to have a look at it first.

So, is it possible do install what you need to develop iPhone apps on a Windows based machine as host?

答: Yes. You can run OSX in a VM. I use MonoTouch and Visual Studio to write my applications in C# with a shared directory between the two. Write code in VS, build and debug on OSX within the simulator. It would also work with Objective-C if that's the path you take. If you're not a Mac Guy I would recommend MonoTouch though, it makes development MUCH faster.</p>

ContentLicense: CC BY-SA 3.0


问:
How should I use the new static option for @ViewChild in Angular 8?
How should I configure the new Angular 8 view child?

```<code>@ViewChild('searchText', {read: ElementRef, static: false})
public searchTextInput: ElementRef;
</code>```

vs

```<code>@ViewChild('searchText', {read: ElementRef, static: true})
public searchTextInput: ElementRef;
</code>```

Which is better? When should I use static:true vs static:false?

答:
From the angular docs

static - whether or not to resolve query results before change detection runs (i.e. return static results only). If this option is not provided, the compiler will fall back to its default behavior, which is to use query results to determine the timing of query resolution. If any query results are inside a nested view (e.g. *ngIf), the query will be resolved after change detection runs. Otherwise, it will be resolved before change detection runs.

It may be a better idea to use static:true if the child does not depend on any conditions. If the visibility of element changes, then static:false may give better results.

PS: Since its a new feature, we may need to run benchmarks for performance.

Edit

As mentioned by @Massimiliano Sartoretto , github commit may give you more insights.

ContentLicense: CC BY-SA 4.0

Body:
How should I configure the new Angular 8 view child?

@ViewChild('searchText', {read: ElementRef, static: false})
public searchTextInput: ElementRef;

vs

@ViewChild('searchText', {read: ElementRef, static: true})
public searchTextInput: ElementRef;

Which is better? When should I use static:true vs static:false?


问:
Add library to Eclipse plugin
In my Eclipse Plugin I have a table that shows Integer and String values. To edit the String values I'm using a TextCellEditor which is in the package org.eclipse.jface.viewers.

I have found a NumberCellEditor which I want to try. It is in the package org.eclipse.ve.internal.propertysheet.NumberCellEditor.

I cannot see this package in eclipse it is not listed in the plugin.xml file under Dependencies. It's not in the list that shows up when clicking the "Add"-Button either.

How can I use this class?

答:
org.eclipse.ve appears to be the old Eclipse Visual Editor plugin which is no longer available.

Additionally classes in a package with internal in the name are off-limits (see Eclipse API Rules of Engagement). They may be changed or removed at any time.

Title: Add library to Eclipse plugin


问:
python mutable string class not working correctly
I created a mutable String class in Python, based on the builtin str class.

I can change the first character, but when I call capitalize(), it uses the old value instead

```<code>class String(str):

    def __init__(self, string):
        self.string = list(string)

    def __repr__(self):
        return "".join(self.string)

    def __str__(self):
        return "".join(self.string)

    def __setitem__(self, index, value):
        self.string[index] = value

    def __getitem__(self, index):
        if type(index) == slice:
            return "".join(self.string[index])
        return self.string[index]

    def __delitem__(self, index):
        del self.string[index]

    def __add__(self, other_string):
        return String("".join(self.string) + other_string)

    def __len__(self):
        return len(self.string)

text = String("cello world")
text[0] = "h"
print(text)
print(text.capitalize())
</code>```

Expected Output :

```<code>hello world

Hello world
</code>```

Actual Output :

```<code>hello world

Cello world
</code>```

答:
This approach is inferior to the already suggested answers. There is more overhead because you don't get to just track things as a list, and isinstance(s, str) won't work, for example.

Another way to accomplish this is to subclass collections.UserString. It's a wrapper around the built-in string type that stores it as a member named data. So you could do something like

```<code>from collections import UserString

class String(UserString):
    def __init__(self, string):
        super().__init__(string)
    def __setitem__(self, index, value):
        data_list = list(self.data)
        data_list[index] = value
        self.data = "".join(data_list)
    # etc.
</code>```

And then you will get capitalize and the other string methods for free.

Body:
I created a mutable String class in Python, based on the builtin str class.

I can change the first character, but when I call capitalize(), it uses the old value instead

class String(str):

    def __init__(self, string):
        self.string = list(string)

    def __repr__(self):
        return "".join(self.string)

    def __str__(self):
        return "".join(self.string)

    def __setitem__(self, index, value):
        self.string[index] = value

    def __getitem__(self, index):
        if type(index) == slice:
            return "".join(self.string[index])
        return self.string[index]

    def __delitem__(self, index):
        del self.string[index]

    def __add__(self, other_string):
        return String("".join(self.string) + other_string)

    def __len__(self):
        return len(self.string)

text = String("cello world")
text[0] = "h"
print(text)
print(text.capitalize())

Expected Output :

hello world

Hello world

Actual Output :

hello world

Cello world

Body:
This approach is inferior to the already suggested answers. There is more overhead because you don't get to just track things as a list, and isinstance(s, str) won't work, for example.

Another way to accomplish this is to subclass collections.UserString. It's a wrapper around the built-in string type that stores it as a member named data. So you could do something like

from collections import UserString

class String(UserString):
    def __init__(self, string):
        super().__init__(string)
    def __setitem__(self, index, value):
        data_list = list(self.data)
        data_list[index] = value
        self.data = "".join(data_list)
    # etc.

And then you will get capitalize and the other string methods for free.


问:
document.hasOwnProperty("hidden") returns false but document has the property hidden
I'm trying to check if document has 'hidden' property using document.hasOwnProperty but it always returns false in Chrome (74).

I've tried Object.prototype.hasOwnProperty but that too returns false. When I tried to stringify and parse back document I got back Location object as a property.

console.log(document.hasOwnProperty("hidden"));
console.log(Object.prototype.hasOwnProperty.call(document, "false"));
console.log(JSON.parse(JSON.stringify(document)));
console.log(typeof document.hidden !== "undefined");
console.log(document.hidden);
console.log(Document.prototype.hasOwnProperty.call(document, "hidden"));
console.log(Document.prototype.hasOwnProperty.call(document, "location"));```

Shouldn't hasOwnProperty check if an object has a property irrespective of the object type? I apologize if the question has already been answered.

答:
Copying and correcting @haim770’s deleted answer for now:

The purpose of hasOwnProperty() is to check whether a certain property is defined on the object itself and is not inherited through its prototype.

In the case of document, it rightfully returns false since the hidden property is actually defined on [Document] and not on [the document object] itself.

console.log('' + Object.getPrototypeOf(document));
console.log('' + Object.getPrototypeOf(Object.getPrototypeOf(document)));

console.log(document.__proto__.__proto__.hasOwnProperty('hidden'));

console.log(Object.getOwnPropertyDescriptor(Document.prototype, 'hidden'));```

Body:
I'm trying to check if document has 'hidden' property using document.hasOwnProperty but it always returns false in Chrome (74).

I've tried Object.prototype.hasOwnProperty but that too returns false. When I tried to stringify and parse back document I got back Location object as a property.

console.log(document.hasOwnProperty("hidden"));
console.log(Object.prototype.hasOwnProperty.call(document, "false"));
console.log(JSON.parse(JSON.stringify(document)));
console.log(typeof document.hidden !== "undefined");
console.log(document.hidden);
console.log(Document.prototype.hasOwnProperty.call(document, "hidden"));
console.log(Document.prototype.hasOwnProperty.call(document, "location"));

Shouldn't hasOwnProperty check if an object has a property irrespective of the object type? I apologize if the question has already been answered.


答:
pd.qcut is for when you want to specify the quantiles. For what you want, I suspect you need pd.cut, for example:

```<code>edges = [0, 30000, 50000, 70000, 90000, 110000, 150000, df['wage'].max()]

pd.cut(df['wage'], edges)
</code>```

Title: Python bin data in specified ranges

Body:
I have a 1 dimensional array that has salary information like so:

|wage    |
|75000   |
|125000  |
|130000  |

and so on. I used the qcut function to bin the data, but I want to use rounded out ranges so it looks more aesthetic.

Currently my code is as follows:

quant = pd.qcut(df['wage'], [0.1, 0.2,
0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]).value_counts()

and that produces

(42500.0, 50000.0]         3285
(27882.399, 32500.0]       3158
(32500.0, 37500.0]         3000
(69926.75, 82500.0]        2988
(58878.5, 69926.75]        2922
(82500.0, 110000.0]        2914
(110000.0, 145600000.0]    2866
(37500.0, 42500.0]         2677
(50000.0, 58878.5]         2554
Name: wage, dtype: int64

I would like the following ranges:

(0, 30000]
(30000, 50000]
(50000, 70000]
(70000, 90000]
(90000, 110000]
(110000, 150000]
(150000, max wage]

any suggestions on how to do this?

Body:
pd.qcut is for when you want to specify the quantiles. For what you want, I suspect you need pd.cut, for example:

edges = [0, 30000, 50000, 70000, 90000, 110000, 150000, df['wage'].max()]

pd.cut(df['wage'], edges)


问:
Array filter - get rid of O(n^2)
I need to perform 2 filters on array of objects which is very big (over 200k elements) so I want my code to be as fast as possible in javascript.

First filter is simple because I just need to delete elements which are empty (null):

```<code>let validArr = originalArr.filter(el => { return el != null });
</code>```

Second filter is to check if validArr[i].name is equal to one of elements from other array. Currently I do it like this:

```<code>for(let i = 0, l = validArr.length; i < l; i++) {
    if (findInArray(validArr[i].name, otherArr)) {
        finalArr.push({
            name: validNpc[i].nick,
            id: validNpc[i].id
        });
    }
}

const findInArray = (val, arr) => {
    for(let i = 0, l = arr.length; i < l; i++) {
        if(arr[i] === val) return true;
    }
    return false;
};
</code>```

In loop I have micro optimization but there is O(n^2) which I want to refactor but I don't know how.

答:
Turn otherArr into a Set, then lookup takes O(1) and the overall loop is O(n):</p>

```<code>  const names = new Set(otherArr);

  const result = validArr
    .filter(it => names.has(it.name))
    .map(({ nick, id }) => ({ name: nick, id }));
</code>```

Title: Array filter - get rid of O(n^2)

Body:
I need to perform 2 filters on array of objects which is very big (over 200k elements) so I want my code to be as fast as possible in javascript.

First filter is simple because I just need to delete elements which are empty (null):

let validArr = originalArr.filter(el => { return el != null });

Second filter is to check if validArr[i].name is equal to one of elements from other array. Currently I do it like this:

for(let i = 0, l = validArr.length; i < l; i++) {
    if (findInArray(validArr[i].name, otherArr)) {
        finalArr.push({
            name: validNpc[i].nick,
            id: validNpc[i].id
        });
    }
}

const findInArray = (val, arr) => {
    for(let i = 0, l = arr.length; i < l; i++) {
        if(arr[i] === val) return true;
    }
    return false;
};

In loop I have micro optimization but there is O(n^2) which I want to refactor but I don't know how.

Body:
Turn otherArr into a Set, then lookup takes O(1) and the overall loop is O(n):

  const names = new Set(otherArr);

  const result = validArr
    .filter(it => names.has(it.name))
    .map(({ nick, id }) => ({ name: nick, id }));


问:
MPMoviePlayerController delay when there should be virtually none
each time my app changes the displayed animation, which is a looping movie, he takes a pause till he finally start the movie.
The MoviePlayerConntroller is created this way

```<code>    self.moviePlayer = [MPMoviePlayerController alloc];
    [moviePlayer initWithContentURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"NewChar" ofType:@"m4v"]] ];
    // remove playerview from our view (no prob is he isnt attached to any)
    [moviePlayer.view removeFromSuperview];
    // tell our playerview the size he has to use
    moviePlayer.view.frame = CGRectMake(0, 0, 320, 430);
    // and add hin to the superview behind everything else
    [self.view insertSubview:moviePlayer.view atIndex:0];
    // no moviecontrolls
    moviePlayer.controlStyle = MPMovieControlStyleNone;
    // looping forever
    moviePlayer.repeatMode= MPMovieRepeatModeOne;
    // let him use his own Audio Session for old devices
    moviePlayer.useApplicationAudioSession= NO;
    // fix the silly black background on iOS 4.3
    moviePlayer.view.backgroundColor = [UIColor clearColor];
</code>```

the actual movie is played this way

```<code>[moviePlayer initWithContentURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Whatever" ofType:@"m4v"]]];
[moviePlayer play];
</code>```

Just as I said, each time the movie is changed, he takes a while to display it. On newer devices its ok, since they are faster, but on G2 it is somewhat disturbing.
Tried prepare playback, but that makes no difference.

Any idea what I missed?

Thanks for reading! :)

答: It takes time to load up the movie from disk, and obviously will be slower on older devices.  How big is the video?</p>

Body:
each time my app changes the displayed animation, which is a looping movie, he takes a pause till he finally start the movie.
The MoviePlayerConntroller is created this way

    self.moviePlayer = [MPMoviePlayerController alloc];
    [moviePlayer initWithContentURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"NewChar" ofType:@"m4v"]] ];
    // remove playerview from our view (no prob is he isnt attached to any)
    [moviePlayer.view removeFromSuperview];
    // tell our playerview the size he has to use
    moviePlayer.view.frame = CGRectMake(0, 0, 320, 430);
    // and add hin to the superview behind everything else
    [self.view insertSubview:moviePlayer.view atIndex:0];
    // no moviecontrolls
    moviePlayer.controlStyle = MPMovieControlStyleNone;
    // looping forever
    moviePlayer.repeatMode= MPMovieRepeatModeOne;
    // let him use his own Audio Session for old devices
    moviePlayer.useApplicationAudioSession= NO;
    // fix the silly black background on iOS 4.3
    moviePlayer.view.backgroundColor = [UIColor clearColor];

the actual movie is played this way

[moviePlayer initWithContentURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"Whatever" ofType:@"m4v"]]];
[moviePlayer play];

Just as I said, each time the movie is changed, he takes a while to display it. On newer devices its ok, since they are faster, but on G2 it is somewhat disturbing.
Tried prepare playback, but that makes no difference.

Any idea what I missed?

Thanks for reading! :)


问:
How to fix: KeyError: '__file__' in sitecustomize.py (anaconda3) when using run file (F5)
The script below works fine when running it with (F9). When running it with (F5) it still works (all operations are done fine), but produces the following error:

File "", line 1, in  runfile('S:/Fakultaet/MFZ/NWFZ/AGdeHoz/Philipp/Python/Analysis_script.py',wdir='S:/Fakultaet/MFZ/NWFZ/AGdeHoz/Philipp/Python')

File "c:\anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py",
  line 709, in runfile namespace.pop('file')

KeyError: 'file'

I would like to know what is happening and how to fix it.

I read something about a nesting problem, so I took out the part where I import my own function and also the part where I use it. The error still persists. So it has at least nothing to do with my own function.

```<code>from IPython import get_ipython
get_ipython().magic('%reset -f')
import time
tic = time.time()
import sys
import os
import pickle
import CSC_getdata_timestamps

General_folder = 'Data' #where processed data will be saved
filename_extension =  '_Sleep_auditory'; #file extension name
Database_name = 'mydata.obj' #name of database
ExpDates = 'ExpDates.obj' #name of object containing all experimental
dates
root = r"S:\Fakultaet\MFZ\NWFZ\AGdeHoz\Philipp" #root directory (data
location)
AnalyType = "LFP" #"SP" Local field potential or Spike analysis
spr = 30000 #sample rate
Cname = "CH"
file_md = open(r"S:\Fakultaet\MFZ\NWFZ\AGdeHoz\Philipp\Data\Database\\" +
           Database_name, "rb")
md = pickle.load(file_md)
file_ExpDates =
open(r"S:\Fakultaet\MFZ\NWFZ\AGdeHoz\Philipp\Data\Database\\" +
                 ExpDates, "rb")
ExpDates = pickle.load(file_ExpDates)

for mi, expdates in enumerate(ExpDates):

    day = expdates
    mouse = md[expdates]['mouse']
    files = md[expdates]['rectime']
    filesm = md[expdates]['FRAm'] + md[expdates]['REMm'] + md[expdates]
    ['SWSm'] + md[expdates]['awakem']
    rect = md[expdates]['rect']
    filest = [md[expdates]['FRAt'], md[expdates]['REMt'], md[expdates]
    ['SWSt'], md[expdates]['awaket']]
    channels = md[expdates]['channels']

    for f, files_m in enumerate(filesm):

        try:
            if len(files) == 1:
                recname = files
            else:
                tfiles = []
                tfilesm = []
                for i, file in enumerate(files):
                    tfiles.append(int(files[i][0:2]) * 60 + int(files[i]
                    [3:5]))

                tfilesm = int(files_m[f][0:2]) * 60 + int(files_m[f]
                [3:5])
                recidx = [i for i in range(len(tfiles)) if tfiles[i] <
                tfilesm]
                recname = files[recidx[-1]]

            TS0 = (int(rect[0:2]) * 3600 + int(rect[3:5]) * 60 +
            int(rect[6:8])) * spr
            TS1 = TS0 + (int(filest[f][0][0:2]) * 3600 + int(filest[f][0]
            [3:5]) * 60 + int(filest[f][0][6:8])) * spr
            TS2 = TS0 + TS1 + (int(filest[f][1][0:2]) * 3600 +
            int(filest[f][1][3:5]) * 60 + int(filest[f][1][6:8])) * spr
            TS = [TS1, TS2]

            savename = files_m[0:2] + "-" + files_m[3:5]

            if AnalyType == "LFP":
                if not os.path.exists(root + "\Data\Raw" +
                filename_extension + "\LFP\\" + day):
                    os.makedirs(root + "\Data\Raw" + filename_extension +
                    "\LFP\\" + day)
                else:
                    print("Directory already exists.")

            elif AnalyType == "SP":
                if not os.path.exists(root + "\Data\Raw" +
                filename_extension + "\SP\\" + day):
                    os.makedirs(root + "\Data\Raw" + filename_extension +
                    "\SP\\" + day)
                else:
                    print("Directory already exists.")
            else:
                sys.exit("Invalid type of analysis. Check variable
                AnalyType.")

            varlist, trseq, trlength, stlength, ntrials, datacscini,
            samplefreq, tscsc, tstrig =
            CSC_getdata_timestamps.CSC_getdata_timestamps(root, day,
            savename, recname, channels, AnalyType, TS)

            print(trseq)

        except Exception as e:
            print('Error: ' + str(e))
            print('mi = {}, f = {}'.format(mi, f))

toc = round(time.time() - tic, 2)
print("elapsed time:", toc, "seconds")
</code>```

The whole script is to combine data from a (1) written database, with a (2) dataframe which includes specifications of a sound played during a (3) recording.
forgive me if it is written very unpythonic, I just recently switched from Matlab.
The script is for a application in Neuroscience.

答:
(Spyder maintainer here) This error is fixed in our latest version (3.3.4). Please update by opening the Anaconda prompt and running there

```<code>conda install spyder=3.3.4
</code>```

Body:
The script below works fine when running it with (F9). When running it with (F5) it still works (all operations are done fine), but produces the following error:

File "", line 1, in  runfile('S:/Fakultaet/MFZ/NWFZ/AGdeHoz/Philipp/Python/Analysis_script.py',wdir='S:/Fakultaet/MFZ/NWFZ/AGdeHoz/Philipp/Python')

File "c:\anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py",
  line 709, in runfile namespace.pop('file')

KeyError: 'file'

I would like to know what is happening and how to fix it.

I read something about a nesting problem, so I took out the part where I import my own function and also the part where I use it. The error still persists. So it has at least nothing to do with my own function.

from IPython import get_ipython
get_ipython().magic('%reset -f')
import time
tic = time.time()
import sys
import os
import pickle
import CSC_getdata_timestamps

General_folder = 'Data' #where processed data will be saved
filename_extension =  '_Sleep_auditory'; #file extension name
Database_name = 'mydata.obj' #name of database
ExpDates = 'ExpDates.obj' #name of object containing all experimental
dates
root = r"S:\Fakultaet\MFZ\NWFZ\AGdeHoz\Philipp" #root directory (data
location)
AnalyType = "LFP" #"SP" Local field potential or Spike analysis
spr = 30000 #sample rate
Cname = "CH"
file_md = open(r"S:\Fakultaet\MFZ\NWFZ\AGdeHoz\Philipp\Data\Database\\" +
           Database_name, "rb")
md = pickle.load(file_md)
file_ExpDates =
open(r"S:\Fakultaet\MFZ\NWFZ\AGdeHoz\Philipp\Data\Database\\" +
                 ExpDates, "rb")
ExpDates = pickle.load(file_ExpDates)

for mi, expdates in enumerate(ExpDates):

    day = expdates
    mouse = md[expdates]['mouse']
    files = md[expdates]['rectime']
    filesm = md[expdates]['FRAm'] + md[expdates]['REMm'] + md[expdates]
    ['SWSm'] + md[expdates]['awakem']
    rect = md[expdates]['rect']
    filest = [md[expdates]['FRAt'], md[expdates]['REMt'], md[expdates]
    ['SWSt'], md[expdates]['awaket']]
    channels = md[expdates]['channels']

    for f, files_m in enumerate(filesm):

        try:
            if len(files) == 1:
                recname = files
            else:
                tfiles = []
                tfilesm = []
                for i, file in enumerate(files):
                    tfiles.append(int(files[i][0:2]) * 60 + int(files[i]
                    [3:5]))

                tfilesm = int(files_m[f][0:2]) * 60 + int(files_m[f]
                [3:5])
                recidx = [i for i in range(len(tfiles)) if tfiles[i] <
                tfilesm]
                recname = files[recidx[-1]]

            TS0 = (int(rect[0:2]) * 3600 + int(rect[3:5]) * 60 +
            int(rect[6:8])) * spr
            TS1 = TS0 + (int(filest[f][0][0:2]) * 3600 + int(filest[f][0]
            [3:5]) * 60 + int(filest[f][0][6:8])) * spr
            TS2 = TS0 + TS1 + (int(filest[f][1][0:2]) * 3600 +
            int(filest[f][1][3:5]) * 60 + int(filest[f][1][6:8])) * spr
            TS = [TS1, TS2]

            savename = files_m[0:2] + "-" + files_m[3:5]

            if AnalyType == "LFP":
                if not os.path.exists(root + "\Data\Raw" +
                filename_extension + "\LFP\\" + day):
                    os.makedirs(root + "\Data\Raw" + filename_extension +
                    "\LFP\\" + day)
                else:
                    print("Directory already exists.")

            elif AnalyType == "SP":
                if not os.path.exists(root + "\Data\Raw" +
                filename_extension + "\SP\\" + day):
                    os.makedirs(root + "\Data\Raw" + filename_extension +
                    "\SP\\" + day)
                else:
                    print("Directory already exists.")
            else:
                sys.exit("Invalid type of analysis. Check variable
                AnalyType.")

            varlist, trseq, trlength, stlength, ntrials, datacscini,
            samplefreq, tscsc, tstrig =
            CSC_getdata_timestamps.CSC_getdata_timestamps(root, day,
            savename, recname, channels, AnalyType, TS)

            print(trseq)

        except Exception as e:
            print('Error: ' + str(e))
            print('mi = {}, f = {}'.format(mi, f))

toc = round(time.time() - tic, 2)
print("elapsed time:", toc, "seconds")

The whole script is to combine data from a (1) written database, with a (2) dataframe which includes specifications of a sound played during a (3) recording.
forgive me if it is written very unpythonic, I just recently switched from Matlab.
The script is for a application in Neuroscience.

Body:
(Spyder maintainer here) This error is fixed in our latest version (3.3.4). Please update by opening the Anaconda prompt and running there

conda install spyder=3.3.4


答:
You can use Set and has method which have O(1) time complexity

```<code>otherArr = new Set(otherArr);
for(let i = 0, l = validArr.length; i < l; i++) {
    if (findInArray(validArr[i].name, otherArr)) {
        finalArr.push({
            name: validNpc[i].nick,
            id: validNpc[i].id
        });
    }
}

const findInArray = (val, arr) => {
    return arr.has(val)
};
</code>```

You can clean up your code using forEach()

```<code>otherArr = new Set(otherArr)
const finalArr = [];
validArr.forEach(x => {
    if(otherArr.has(x.name)){
       finalArr.push({ name:x.nick, id:x.id })
    }
})
</code>```

Title: Array filter - get rid of O(n^2)

Body:
You can use Set and has method which have O(1) time complexity

otherArr = new Set(otherArr);
for(let i = 0, l = validArr.length; i < l; i++) {
    if (findInArray(validArr[i].name, otherArr)) {
        finalArr.push({
            name: validNpc[i].nick,
            id: validNpc[i].id
        });
    }
}

const findInArray = (val, arr) => {
    return arr.has(val)
};

You can clean up your code using forEach()

otherArr = new Set(otherArr)
const finalArr = [];
validArr.forEach(x => {
    if(otherArr.has(x.name)){
       finalArr.push({ name:x.nick, id:x.id })
    }
})


问:
Issue with SWIG for creating Python bindings for C library
I want to use SWIG to create Python bindings for C library, but I have some troubles with it. I used the following .c and .i files from tutorial.
example.c

```<code>/* Compute factorial of n */
int fact(int n) {
  if (n <= 1)
    return 1;
  else
    return n*fact(n-1);
}

/* Compute n mod m */
int my_mod(int n, int m) {
  return(n % m);
}

double My_variable;
</code>```

example.i

```<code>%module example
%{
extern double My_variable;
extern int    fact(int);
extern int    my_mod(int n, int m);
%}

extern double My_variable;
extern int    fact(int);
extern int    my_mod(int n, int m);
</code>```

Commands that I used:

```<code>$ swig -python -py3 example.i
$ gcc -c -fpic example.c example_wrap.c -I/usr/include/python3.6
$ gcc -shared example.o example_wrap.o -o example.so
</code>```

And when I try to import it in python3 I am getting this

```<code>>>> import example
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: dynamic module does not define module export function (PyInit_example)
</code>```

Any help appreciated

答:
SWIG generates a module with underscore prepended by default, so you'll get a module called _example which needs to be in _example.so.

This is explained in the SWIG documentation 34.2.3 Hand compiling a dynamic module:

While the preferred approach to building an extension module is to use the distutils, some people like to integrate building extensions with a larger build system, and thus may wish to compile their modules without the distutils. To do this, you need to compile your program using commands like this (shown for Linux):

```<code>$ swig -python example.i
$ gcc -O2 -fPIC -c example.c
$ gcc -O2 -fPIC -c example_wrap.c -I/usr/local/include/python2.5
$ gcc -shared example.o example_wrap.o -o _example.so
</code>```

The exact commands for doing this vary from platform to platform. However, SWIG tries to guess the right options when it is installed. Therefore, you may want to start with one of the examples in the SWIG/Examples/python directory. If that doesn't work, you will need to read the man-pages for your compiler and linker to get the right set of options. You might also check the SWIG Wiki for additional information.

When linking the module, the name of the output file has to match the name of the module prefixed by an underscore. If the name of your module is example, then the name of the corresponding object file should be _example.so or _examplemodule.so. The name of the module is specified using the %module directive or the -module command line option.

Compatibility Note: In SWIG-1.3.13 and earlier releases, module names did not include the leading underscore. This is because modules were normally created as C-only extensions without the extra Python support file (instead, creating Python code was supported as an optional feature). This has been changed in SWIG-1.3.14 and is consistent with other Python extension modules. For example, the socket module actually consists of two files; socket.py and _socket.so. Many other built-in Python modules follow a similar convention.

Body:
I want to use SWIG to create Python bindings for C library, but I have some troubles with it. I used the following .c and .i files from tutorial.
example.c

/* Compute factorial of n */
int fact(int n) {
  if (n <= 1)
    return 1;
  else
    return n*fact(n-1);
}

/* Compute n mod m */
int my_mod(int n, int m) {
  return(n % m);
}

double My_variable;

example.i

%module example
%{
extern double My_variable;
extern int    fact(int);
extern int    my_mod(int n, int m);
%}

extern double My_variable;
extern int    fact(int);
extern int    my_mod(int n, int m);

Commands that I used:

$ swig -python -py3 example.i
$ gcc -c -fpic example.c example_wrap.c -I/usr/include/python3.6
$ gcc -shared example.o example_wrap.o -o example.so

And when I try to import it in python3 I am getting this

>>> import example
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: dynamic module does not define module export function (PyInit_example)

Any help appreciated

Body:
SWIG generates a module with underscore prepended by default, so you'll get a module called _example which needs to be in _example.so.

This is explained in the SWIG documentation 34.2.3 Hand compiling a dynamic module:

While the preferred approach to building an extension module is to use the distutils, some people like to integrate building extensions with a larger build system, and thus may wish to compile their modules without the distutils. To do this, you need to compile your program using commands like this (shown for Linux):

$ swig -python example.i
$ gcc -O2 -fPIC -c example.c
$ gcc -O2 -fPIC -c example_wrap.c -I/usr/local/include/python2.5
$ gcc -shared example.o example_wrap.o -o _example.so

The exact commands for doing this vary from platform to platform. However, SWIG tries to guess the right options when it is installed. Therefore, you may want to start with one of the examples in the SWIG/Examples/python directory. If that doesn't work, you will need to read the man-pages for your compiler and linker to get the right set of options. You might also check the SWIG Wiki for additional information.

When linking the module, the name of the output file has to match the name of the module prefixed by an underscore. If the name of your module is example, then the name of the corresponding object file should be _example.so or _examplemodule.so. The name of the module is specified using the %module directive or the -module command line option.

Compatibility Note: In SWIG-1.3.13 and earlier releases, module names did not include the leading underscore. This is because modules were normally created as C-only extensions without the extra Python support file (instead, creating Python code was supported as an optional feature). This has been changed in SWIG-1.3.14 and is consistent with other Python extension modules. For example, the socket module actually consists of two files; socket.py and _socket.so. Many other built-in Python modules follow a similar convention.


问:
Enabling Microsoft's Code Analysis on .NET Core Projects
Our team uses the Code Analysis feature with a custom ruleset to cause our build to fail if we forget to do things like null checks on method arguments.

However, now as we create a new .NET Core project, it doesn't look like Code Analysis is a feature of these new projects. There is no UI for it in the Project Properties area, and adding a custom ruleset to the project as recommended here only appears to affect StyleCop Analyzers (the SAxxxx rules).

Is there any way to enable Code Analysis (CAxxxx) rules in a .NET Core project?

答:
Normally, the only thing you need to do is install the Microsoft.CodeAnalysis.FxCopAnalyzers nuget on your project.

But as mentioned correctly, this does not work, especially for .Net Core (currently in vs2017).

In order to work for aspnet core projects, as well, and resolve the error:

"Could not identify platform for ..."

Manually modify the project's csproj file and make sure to not insert the RunCodeAnalysis tag. Make the PropertyGroup like that:

```<code><PropertyGroup>
  <TargetFramework>netcoreapp2.2</TargetFramework>
  <CodeAnalysisRuleSet>..\MyStylecop.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
</code>```

Also, if you need to put a given ruleset file, make sure to place it to the correct path, as seen above ..\MyStylecop.ruleset. MyStylecop.ruleset is the file with the rules (actually the ones suppresed I think - so it is inverse logic).

For example my ruleset file is:

```<code><?xml version="1.0" encoding="utf-8"?>
<RuleSet Name="Default stylecop settings" Description="This rule set contains all rules (as warnings), with a few specific supressions." ToolsVersion="15.0">
  <IncludeAll Action="Warning" />
  <Rules AnalyzerId="Microsoft.Analyzers.ManagedCodeAnalysis" RuleNamespace="Microsoft.Rules.Managed">
    <Rule Id="CA1004" Action="None" />
    <Rule Id="CA1006" Action="None" />
    <Rule Id="CA1020" Action="None" />
    <Rule Id="CA1025" Action="None" />
    <Rule Id="CA1032" Action="None" />
    <Rule Id="CA1054" Action="None" />
    <Rule Id="CA1055" Action="None" />
    <Rule Id="CA1056" Action="None" />
    <Rule Id="CA1062" Action="None" />
    <Rule Id="CA1300" Action="None" />
    <Rule Id="CA1303" Action="None" />
    <Rule Id="CA1704" Action="Warning" />
    <Rule Id="CA1709" Action="None" />
    <Rule Id="CA2007" Action="None" />
    <Rule Id="CA2225" Action="None" />
    <Rule Id="CA2227" Action="None" />
    <Rule Id="CA2233" Action="None" />
    <Rule Id="CA2234" Action="None" />
    <Rule Id="CA2237" Action="None" />
    <Rule Id="CS1591" Action="None" />
    <Rule Id="CA1715" Action="None" />
  </Rules>
  <Rules AnalyzerId="StyleCop.Analyzers" RuleNamespace="StyleCop.Analyzers">
    <Rule Id="SA1101" Action="None" />
    <Rule Id="SA1116" Action="None" />
    <Rule Id="SA1117" Action="None" />
    <Rule Id="SA1118" Action="None" />
    <Rule Id="SA1208" Action="None" />
    <Rule Id="SA1600" Action="None" />
    <Rule Id="SA1601" Action="None" />
    <Rule Id="SA1602" Action="None" />
    <Rule Id="SA1623" Action="None" />
    <Rule Id="SA1633" Action="None" />
    <Rule Id="SA1634" Action="None" />
    <Rule Id="SA1637" Action="None" />
    <Rule Id="SA1640" Action="None" />
    <Rule Id="SA1652" Action="None" />
    <Rule Id="SA0001" Action="None" />
    <Rule Id="SA1314" Action="None" />
  </Rules>
</RuleSet>
</code>```

Body:
Normally, the only thing you need to do is install the Microsoft.CodeAnalysis.FxCopAnalyzers nuget on your project.

But as mentioned correctly, this does not work, especially for .Net Core (currently in vs2017).

In order to work for aspnet core projects, as well, and resolve the error:

"Could not identify platform for ..."

Manually modify the project's csproj file and make sure to not insert the RunCodeAnalysis tag. Make the PropertyGroup like that:

<PropertyGroup>
  <TargetFramework>netcoreapp2.2</TargetFramework>
  <CodeAnalysisRuleSet>..\MyStylecop.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>

Also, if you need to put a given ruleset file, make sure to place it to the correct path, as seen above ..\MyStylecop.ruleset. MyStylecop.ruleset is the file with the rules (actually the ones suppresed I think - so it is inverse logic).

For example my ruleset file is:

<?xml version="1.0" encoding="utf-8"?>
<RuleSet Name="Default stylecop settings" Description="This rule set contains all rules (as warnings), with a few specific supressions." ToolsVersion="15.0">
  <IncludeAll Action="Warning" />
  <Rules AnalyzerId="Microsoft.Analyzers.ManagedCodeAnalysis" RuleNamespace="Microsoft.Rules.Managed">
    <Rule Id="CA1004" Action="None" />
    <Rule Id="CA1006" Action="None" />
    <Rule Id="CA1020" Action="None" />
    <Rule Id="CA1025" Action="None" />
    <Rule Id="CA1032" Action="None" />
    <Rule Id="CA1054" Action="None" />
    <Rule Id="CA1055" Action="None" />
    <Rule Id="CA1056" Action="None" />
    <Rule Id="CA1062" Action="None" />
    <Rule Id="CA1300" Action="None" />
    <Rule Id="CA1303" Action="None" />
    <Rule Id="CA1704" Action="Warning" />
    <Rule Id="CA1709" Action="None" />
    <Rule Id="CA2007" Action="None" />
    <Rule Id="CA2225" Action="None" />
    <Rule Id="CA2227" Action="None" />
    <Rule Id="CA2233" Action="None" />
    <Rule Id="CA2234" Action="None" />
    <Rule Id="CA2237" Action="None" />
    <Rule Id="CS1591" Action="None" />
    <Rule Id="CA1715" Action="None" />
  </Rules>
  <Rules AnalyzerId="StyleCop.Analyzers" RuleNamespace="StyleCop.Analyzers">
    <Rule Id="SA1101" Action="None" />
    <Rule Id="SA1116" Action="None" />
    <Rule Id="SA1117" Action="None" />
    <Rule Id="SA1118" Action="None" />
    <Rule Id="SA1208" Action="None" />
    <Rule Id="SA1600" Action="None" />
    <Rule Id="SA1601" Action="None" />
    <Rule Id="SA1602" Action="None" />
    <Rule Id="SA1623" Action="None" />
    <Rule Id="SA1633" Action="None" />
    <Rule Id="SA1634" Action="None" />
    <Rule Id="SA1637" Action="None" />
    <Rule Id="SA1640" Action="None" />
    <Rule Id="SA1652" Action="None" />
    <Rule Id="SA0001" Action="None" />
    <Rule Id="SA1314" Action="None" />
  </Rules>
</RuleSet>


问:
AwsS3Adapter exception appearing locally but not in dev server
I'm working locally on a Laravel project, and suddenly started getting the following exception:

ErrorException in FilesystemManager.php line 193:
Class 'League\Flysystem\AwsS3v3\AwsS3Adapter' not found (View: /Users/mypetproject/resources/views/layouts/topheader.blade.php) (View: /Users/mypetproject/resources/views/layouts/topheader.blade.php) (View: /Users/mypetproject/resources/views/layouts/topheader.blade.php)

A version of this is running on a server without any issue. Just to verify, I checked out the same branch, compared composer.json and composer.lock files and they are the same locally and on the server, did a composer update just in case, and it still fails locally but not in the server. The .env file is also the same.

FilesystemManager is in vender/laravel/framework/src/Illuminate/Filesystem and indeed attempts to use League\Flysystem\AwsS3v3\AwsS3Adapter as S3Adapter; however this is also the case with the version running on the server.

As a note, I'm not using S3 at all, and I don't really want to install league/flysystem-aws-s3-v3 since I'm not using it.

Any idea what could be wrong?

This is my composer.json

```<code>{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.3.*",
        "laravelcollective/html": "5.3.*",
        "guzzlehttp/guzzle": "^6.2",
        "google/cloud-storage": "1.1.5"
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~4.0",
        "phpspec/phpspec": "~2.1"
    },
    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
    "autoload-dev": {
        "classmap": [
            "tests/TestCase.php"
        ]
    },
    "scripts": {
        "post-install-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "post-update-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "post-root-package-install": [
            "php -r \"copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ]
    },
    "config": {
        "preferred-install": "dist"
    },
    "minimum-stability": "dev",
    "prefer-stable": true
}

</code>```

答:
I finally tracked it down to the autoload_static.php and autoload_classmap.php files in vendor/composer/

For some reason it was referencing an incorrect file (one previously using S3):

'App\\IsoClasses\\IsoStorage' => __DIR__ . '/../..' . '/app/IsoClasses/IsoStorageS3.php',

updated to

'App\\IsoClasses\\IsoStorage' => __DIR__ . '/../..' . '/app/IsoClasses/IsoStorage.php',

and it now works.

What is weird is that the dev server's files also have this, but it works in the dev server with no problems.

Body:
I'm working locally on a Laravel project, and suddenly started getting the following exception:

ErrorException in FilesystemManager.php line 193:
Class 'League\Flysystem\AwsS3v3\AwsS3Adapter' not found (View: /Users/mypetproject/resources/views/layouts/topheader.blade.php) (View: /Users/mypetproject/resources/views/layouts/topheader.blade.php) (View: /Users/mypetproject/resources/views/layouts/topheader.blade.php)

A version of this is running on a server without any issue. Just to verify, I checked out the same branch, compared composer.json and composer.lock files and they are the same locally and on the server, did a composer update just in case, and it still fails locally but not in the server. The .env file is also the same.

FilesystemManager is in vender/laravel/framework/src/Illuminate/Filesystem and indeed attempts to use League\Flysystem\AwsS3v3\AwsS3Adapter as S3Adapter; however this is also the case with the version running on the server.

As a note, I'm not using S3 at all, and I don't really want to install league/flysystem-aws-s3-v3 since I'm not using it.

Any idea what could be wrong?

This is my composer.json

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.3.*",
        "laravelcollective/html": "5.3.*",
        "guzzlehttp/guzzle": "^6.2",
        "google/cloud-storage": "1.1.5"
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~4.0",
        "phpspec/phpspec": "~2.1"
    },
    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
    "autoload-dev": {
        "classmap": [
            "tests/TestCase.php"
        ]
    },
    "scripts": {
        "post-install-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "post-update-cmd": [
            "php artisan clear-compiled",
            "php artisan optimize"
        ],
        "post-root-package-install": [
            "php -r \"copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ]
    },
    "config": {
        "preferred-install": "dist"
    },
    "minimum-stability": "dev",
    "prefer-stable": true
}


问:
Execute promises concurrently with a buffer pool size in Javascript
I have a function with a promises which must be executed n times with different params each time. I want to chain the promises in a way that the script is always working on 3-4 promises at the time.

I made it with promise.all, this executes 3 concurrently and when all the promises resolves it goes on with the next 3.

How to make it work that when one of 3 resolves it starts immediatly with another but always working on max 3 at the time?

```<code>for( var i = 0; i < tasks.length; i++){

    if( i > 0 && i%3 == 0 ){

      await Promise.all([
       doTaskFunction(tasks[i]),
        doTaskFunction(tasks[i-1]),
        doTaskFunction(tasks[i-2]),
      ]);
    }

  }
</code>```

答:
No external libraries. Just plain JS.

It can be resolved using recursion.

The idea is that initially we immediately run the maximum allowed number of tasks and each of these tasks should recursively initiate a new task on its completion.

In this example I populate successful responses together with errors and I execute all requests but it's possible to slightly modify algorithm if you want to terminate batch execution on the first failure.

async function batchExecute(tasks, limit) {
  limit = Math.min(tasks.length, limit);

  return new Promise((resolve, reject) => {
    const responsesOrErrors = new Array(tasks.length);
    let startedCount = 0;
    let finishedCount = 0;
    let hasErrors = false;

    function recursiveExecute() {
      let index = startedCount++;

      doTaskFunction(tasks[index])
        .then(res => {
          responsesOrErrors[index] = res;
        })
        .catch(error => {
          responsesOrErrors[index] = error;
          hasErrors = true;
        })
        .finally(() => {
          finishedCount++;
          if (finishedCount === tasks.length) {
            hasErrors ? reject(responsesOrErrors) : resolve(responsesOrErrors);
          } else if (startedCount < tasks.length) {
            recursiveExecute();
          }
        });
    }

    for (let i = 0; i < limit; i++) {
      recursiveExecute();
    }
  });
}

async function doTaskFunction(task) {
  console.log(`${task} started`);
  const delay = Math.floor(Math.random() * 1500);
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (delay <= 1000) {
        console.log(`${task} finished successfully`);
        resolve(`${task} success`);
      } else {
        console.log(`${task} finished with error`);
        reject(`${task} error`);
      }
    }, delay);
  });
}

const tasks = new Array(10).fill('task').map((task, index) => `${task}_${index + 1}`);

batchExecute(tasks, 3)
  .then(responses => console.log('All successfull', responses))
  .catch(responsesWithErrors => console.log('All with several failed', responsesWithErrors));```

Body:
I have a function with a promises which must be executed n times with different params each time. I want to chain the promises in a way that the script is always working on 3-4 promises at the time.

I made it with promise.all, this executes 3 concurrently and when all the promises resolves it goes on with the next 3.

How to make it work that when one of 3 resolves it starts immediatly with another but always working on max 3 at the time?

for( var i = 0; i < tasks.length; i++){

    if( i > 0 && i%3 == 0 ){

      await Promise.all([
       doTaskFunction(tasks[i]),
        doTaskFunction(tasks[i-1]),
        doTaskFunction(tasks[i-2]),
      ]);
    }

  }


问:
objective c interface access
this my first interface in a.h file.

```<code>@interface EventRow : NSObject
{
NSString *title;
NSString *photo;
NSString *description;

NSMutableArray *photoArray;
}
@property (nonatomic , retain) NSString *title;
@property (nonatomic , retain) NSString *photo;
@property (nonatomic , retain) NSString *description;

@property (nonatomic , retain) NSMutableArray *photoArray;

@end
</code>```

in the same file second

```<code>@interface PhotoRow : NSObject
{
//NSString *image;

NSMutableArray *imageArray;
}
@property (nonatomic , retain) NSMutableArray *imageArray;

@end
</code>```

Now every object of "PhotoRow" with filled array(imageArray) stored into the "photoArray" array in EventRow's object.

Now I want to count the total elements of "imageArray" . But getting problem in access it through the EventRow's object.

any suggestions ?

Thanks..

答:
To access the individual objects in photoArray (eventRow is an instance of EventRow

```<code>[[eventRow photoArray] objectAtIndex: someIndex]; // I don't like dot notation!
</code>```

or

```<code>[eventRow.photoArray objectAtIndex: someIndex];
</code>```

To access the imageArray

```<code>[[[eventRow photoArray] objectAtIndex: someIndex] imageArray];
</code>```

or

```<code>[eventRow.photoArray objectAtIndex: someIndex].imageArray;
</code>```

To get the count of images for that imageArray

```<code>[[[[eventRow photoArray] objectAtIndex: someIndex] imageArray] count];
</code>```

or

```<code>[eventRow.photoArray objectAtIndex: someIndex].imageArray.count;
</code>```

If you want to count all of the images, you need loops but you can use fast enumeration to simplifiy things

```<code>size_t total = 0;
for (PhotoRow* photoRow in  [eventRow photoArray])
{
    total += [[photoRow imageArray] count];
}
</code>```

However, I'd like you to rethink your design a bit.  Your exposure of the NSMutableArray in each class breaks encapsulation.  Once a caller has got hold of the array, it can modify the internal state of a PhotoRow or an EventRow without the object knowing about it.  It would be better not to have the NSMutableArray properties but to add methods to add images and photoRows directly to PhotoRows and EventRows respectively.  So, for instance your photoRow class might have the following methods:

```<code>-(size_t) imageCount; // returns the result of sending -count to the internal array
-(NSImage*) imageAtIndex: (size_t) index; // returns the result of sending -objectAtIndex: to the underlying array
-(void) addImage: (NSImage*) newImage;
// etc
</code>```

Title: objective c interface access

Body:
this my first interface in a.h file.

@interface EventRow : NSObject
{
NSString *title;
NSString *photo;
NSString *description;

NSMutableArray *photoArray;
}
@property (nonatomic , retain) NSString *title;
@property (nonatomic , retain) NSString *photo;
@property (nonatomic , retain) NSString *description;

@property (nonatomic , retain) NSMutableArray *photoArray;

@end

in the same file second

@interface PhotoRow : NSObject
{
//NSString *image;

NSMutableArray *imageArray;
}
@property (nonatomic , retain) NSMutableArray *imageArray;

@end

Now every object of "PhotoRow" with filled array(imageArray) stored into the "photoArray" array in EventRow's object.

Now I want to count the total elements of "imageArray" . But getting problem in access it through the EventRow's object.

any suggestions ?

Thanks..

Body:
To access the individual objects in photoArray (eventRow is an instance of EventRow

[[eventRow photoArray] objectAtIndex: someIndex]; // I don't like dot notation!

or

[eventRow.photoArray objectAtIndex: someIndex];

To access the imageArray

[[[eventRow photoArray] objectAtIndex: someIndex] imageArray];

or

[eventRow.photoArray objectAtIndex: someIndex].imageArray;

To get the count of images for that imageArray

[[[[eventRow photoArray] objectAtIndex: someIndex] imageArray] count];

or

[eventRow.photoArray objectAtIndex: someIndex].imageArray.count;

If you want to count all of the images, you need loops but you can use fast enumeration to simplifiy things

size_t total = 0;
for (PhotoRow* photoRow in  [eventRow photoArray])
{
    total += [[photoRow imageArray] count];
}

However, I'd like you to rethink your design a bit.  Your exposure of the NSMutableArray in each class breaks encapsulation.  Once a caller has got hold of the array, it can modify the internal state of a PhotoRow or an EventRow without the object knowing about it.  It would be better not to have the NSMutableArray properties but to add methods to add images and photoRows directly to PhotoRows and EventRows respectively.  So, for instance your photoRow class might have the following methods:

-(size_t) imageCount; // returns the result of sending -count to the internal array
-(NSImage*) imageAtIndex: (size_t) index; // returns the result of sending -objectAtIndex: to the underlying array
-(void) addImage: (NSImage*) newImage;
// etc


问:
The located assembly's manifest definition does not match the assembly reference
I am trying to run some unit tests in a C# Windows Forms application (Visual Studio 2005), and I get the following error:

System.IO.FileLoadException: Could not load file or assembly 'Utility, Version=1.2.0.200, Culture=neutral, PublicKeyToken=764d581291d764f7' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)**

at x.Foo.FooGO()

at x.Foo.Foo2(String groupName_) in Foo.cs:line 123

at x.Foo.UnitTests.FooTests.TestFoo() in FooTests.cs:line 98**

System.IO.FileLoadException: Could not load file or assembly 'Utility, Version=1.2.0.203, Culture=neutral, PublicKeyToken=764d581291d764f7' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

I look in my references, and I only have a reference to Utility version 1.2.0.203 (the other one is old).

Any suggestions on how I figure out what is trying to reference this old version of this DLL file?

Besides, I don't think I even have this old assembly on my hard drive.
Is there any tool to search for this old versioned assembly?

答:
Happened to me for System.ValueTuple

Unexpected Error Could not load file or assembly 'System.ValueTuple,
  Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or
  one of its dependencies. The system cannot find the file specified.

Solved it by installing .NET Framework 4.7.2 Runtime on the machine the error occurred on. Simple and no need to add bindingRedirect, modifying GAC or downgrading NuGet packages etc.

https://dotnet.microsoft.com/download/dotnet-framework/net472

OwnerDisplayName: akantro

LastEditorDisplayName: Adam Bellaire


问:
CQL update query not working using Python
I am trying to update new password after reset to cassandra db. This is the query I have written where both username and password fields are dynamic. Is this right?

```<code>    def update_db(uname, pwd):
        query = session.prepare('update user.userdetails set "password"=%s where "username" = ? ALLOW FILTERING', pwd)
        session.execute(query, (uname,))

update_db(username, new_pwd)
</code>```

I am calling this through an API. But it doesn't seem to update.

答:
for updating record you need to provide primary key(s) completely. It will not work with ALLOW FILTERING - you need first to get all primary keys that you want to update, and then issue individual update commands. See the documentation for more detailed description of UPDATE command.

If you really want to specify the default value for some column - why not simply handle it with something like .get('column', 'default-value')?

Body:
I am trying to update new password after reset to cassandra db. This is the query I have written where both username and password fields are dynamic. Is this right?

    def update_db(uname, pwd):
        query = session.prepare('update user.userdetails set "password"=%s where "username" = ? ALLOW FILTERING', pwd)
        session.execute(query, (uname,))

update_db(username, new_pwd)

I am calling this through an API. But it doesn't seem to update.


问:
How do I concatenate Strings in Kotlin?
Obviously there are multiple ways to concatenate Strings in Kotlin:

processString(pojo.name + " " + pojo.value)

processString("${pojo.name} ${pojo.value}")

processString(pojo.name.plus(" ").plus(pojo.value))

Of course also with StringBuilder, concat()-Method etc.
Those will work.

But my question is, why is Android Studio proposing "convert concatenation to template" and converts 1. to 2. ? Are there any speed advantages with 2.? So wahts the advantage using 2.?

答:
TL;DR: String Templates are the most idiomatic way to concatenate strings

The documentation states

Note that in most cases using string templates or raw strings is preferable to string concatenation.

String templates are basically the same as regular concatenation (using +) but more compact, idiomatic and equally efficient. Both variants are implemented using StringBuilders in the byte code.

Title: How do I concatenate Strings in Kotlin?


问:
How to convert a cURL multipart/form-data POST request to ruby request using rest-client?
I have to implement the curl POST request listed below in Ruby using Rest-Client so that I can upload a file to my server.

```<code>curl -X POST --header 'Content-Type: multipart/form-data' --header 'Accept: application/json' --header 'Authorization: Basic jhdsjhdshjhdshdhh' --header 'tenant-code:djdjhhsdsjhjsd=' {"type":"formData"} 'https://myserver.com/blobs/upload?fileName=some.ipa&groupId=098'
</code>```

I have tried the following -

```<code>require 'rest-client'
require 'json'

payload = {
    :multipart => true,
    :file => File.new(path_to_file, 'rb')
}

response = RestClient.post("https://myserver.com/blobs/upload?fileName=some.ipa&groupId=098", payload, {accept: :json, 'tenant-code':"djdjhhsdsjhjsd=", 'Authorization': "Basic jhdsjhdshjhdshdhh"})
</code>```

This works okay as I get 200 response from the server. However, when I check for the uploaded file on my server it is corrupted.

Is this the right way to do multipart/form-data request using ruby?

I see there is the following in cURL request which is not accounted for in ruby request anywhere.

```<code>{"type":"formData"}
</code>```

Do I need to do something extra for that?

答:
I solved it for my specific case (where I needed to upload an IPA file to my enterprise app store) by changing the request to the following :-

```<code>require 'rest-client'
require 'json'

response = RestClient::Request.execute(
  :url => "https://myserver.com/blobs/upload?fileName=some.ipa&groupId=098",
  :method => :post,
  :headers => {
    'Authorization' => "Basic jhdsjhdshjhdshdhh",
    'tenant-code' => "djdjhhsdsjhjsd=",
    'Accept' => 'application/json',
    'Content-Type' => 'application/octet-stream',
    'Expect' => '100-continue'
  },
  :payload => File.open(path_to_file, "rb")
)
</code>```

Basically, the content type needed to be octet-stream and Expect header needs to be set too.

Hopefully, it helps someone who comes looking for something like this.

Body:
I have to implement the curl POST request listed below in Ruby using Rest-Client so that I can upload a file to my server.

curl -X POST --header 'Content-Type: multipart/form-data' --header 'Accept: application/json' --header 'Authorization: Basic jhdsjhdshjhdshdhh' --header 'tenant-code:djdjhhsdsjhjsd=' {"type":"formData"} 'https://myserver.com/blobs/upload?fileName=some.ipa&groupId=098'

I have tried the following -

require 'rest-client'
require 'json'

payload = {
    :multipart => true,
    :file => File.new(path_to_file, 'rb')
}

response = RestClient.post("https://myserver.com/blobs/upload?fileName=some.ipa&groupId=098", payload, {accept: :json, 'tenant-code':"djdjhhsdsjhjsd=", 'Authorization': "Basic jhdsjhdshjhdshdhh"})

This works okay as I get 200 response from the server. However, when I check for the uploaded file on my server it is corrupted.

Is this the right way to do multipart/form-data request using ruby?

I see there is the following in cURL request which is not accounted for in ruby request anywhere.

{"type":"formData"}

Do I need to do something extra for that?

Body:
I solved it for my specific case (where I needed to upload an IPA file to my enterprise app store) by changing the request to the following :-

require 'rest-client'
require 'json'

response = RestClient::Request.execute(
  :url => "https://myserver.com/blobs/upload?fileName=some.ipa&groupId=098",
  :method => :post,
  :headers => {
    'Authorization' => "Basic jhdsjhdshjhdshdhh",
    'tenant-code' => "djdjhhsdsjhjsd=",
    'Accept' => 'application/json',
    'Content-Type' => 'application/octet-stream',
    'Expect' => '100-continue'
  },
  :payload => File.open(path_to_file, "rb")
)

Basically, the content type needed to be octet-stream and Expect header needs to be set too.

Hopefully, it helps someone who comes looking for something like this.


问:
Kentico - Display content of localization resource strings through repeater transformation
I have a custom pagetype with 1 text field where I keep re-usable html content to be included on other pages through a repeater. The transformation for the repeater has just 1 line of code <%# Eval("Content") %>.

I'm running into a situation where I want to use a resource string inside the content box together with other html content, something like {$ site.languages $}. However, when viewing, the pages displays this string {$ site.languages $} instead of the value of the resource string. Is it possible to display the resource string content in this case and how?

答:
Try this:

ASCX transformations – call the Localize transformation method:

<%# Localize("Text containing localization expressions: {$stringKey$}") %>

Text / XML transformations – use localization string macro expressions or the
GetResourceString macro method:

{$stringKey$} - OR - {% GetResourceString("stringKey") %}


问:
How to fix 'Cannot read property of undefined' error in Angular post request
I'm getting these errors and I'm not sure how to fix it. I am making a form that will make a post request to an API.

ERROR TypeError: Cannot read property 'email' of undefined

ERROR TypeError: Cannot read property 'paymentMethod' of undefined

I am expecting:

```<code>createdBy: string from email input,
paymentMethod: string from paymentMethod select input,
</code>```

But what I get is:

```<code>createdBy: null,
paymentMethod: null
</code>```

Interfaces

```<code>export interface BillingForm {
    fullName: string;
    email: string;
    address: string;
    city: string;
    paymentMethod: string;

  }

export interface Order {
  id?: number;
  companyId: number;
  created: string;
  createdBy: string;
  paymentMethod: string;
  totalPrice: number;
  status: number;
  orderRows: OrderRows[];
}
</code>```

service.ts

```<code>public postOrder(order: Order): Observable<Order> {
      console.log(order);
      return this.http.post<Order>(this.ordersURL, order, httpOptions).pipe(
        catchError(this.handleError('postOrder', order))
      );
</code>```

component.ts

```<code>ngOnInit() {

    this.shippingForm = this.formBuilder.group({
      name: ['', Validators.required],
      email: ['', Validators.required],
      address: ['', Validators.required],
      paymentMethod: ['', Validators.required],
      city: ['', Validators.required],
    })
  }

  onSubmit(billingForm: BillingForm) {
    const order = this.newOrder(billingForm);

    this.productService.postOrder(order).subscribe (
      response => console.log('success', response),
      error => console.log('error', error)
    )

    this.submitted = true;

    if(this.shippingForm.invalid) {
      return;
    }
    this.success = true;

  }

  newOrder(billingForm: BillingForm ): Order {
    return {
      companyId: 6,
      created: moment().locale("sv").format("YYYY-MM-DDTLTS"),
      createdBy: billingForm.email,
      paymentMethod: billingForm.paymentMethod,
      totalPrice: this.totalPrice,
      status: 0,
      orderRows: this.orderRows

    }
  }

  get email() {
    return this.shippingForm.get("email") as FormControl;
  }

  get paymentMethod() {
    return this.shippingForm.get("paymentMethod") as FormControl;
  }

</code>```

component.html

```<code><form [formGroup]="shippingForm" (ngSubmit)="onSubmit(billingForm)">
        <h5 *ngIf="success">Your form is valid!</h5>
          <div class="form-group col-md-6">
            <label for="inputEmail">Email</label>
            <input type="email" formControlName="email" class="form-control" id="inputEmail" placeholder="Email">
            <div *ngIf="submitted && shippingForm.controls.email.errors" class="error">
              <div *ngIf="shippingForm.controls.email.errors.required">Your email is required!</div>
            </div>
          </div>
        </div>
        <div class="form-group col-md-6">
            <label for="payment">Payment Method: </label>
            <select type="select" formControlName="paymentMethod" class="form-control" id="payment"
              aria-placeholder="Mastercard">
              <option selected> Choose...</option>
              <option *ngFor="let paymentMethod of paymentMethods">
                {{ paymentMethod }}
              </option>
            </select>
            <div *ngIf="submitted && shippingForm.controls.paymentMethod.errors" class="error">
              <div *ngIf="shippingForm.controls.paymentMethod.errors.required">Your preferred payment method is required!</div>
            </div>
          </div>
</form>
</code>```

答:
```<code><form [formGroup]="shippingForm" (ngSubmit)="onSubmit(billingForm)">
</code>```

Correct me if I'm wrong, but this billingForm is nowhere defined. So onSubmit method gets called with undefined as argument.

shippingForm is defined (and it's the one connected to the template), I'm guessing you meant onSubmit(shippingForm).

Body:
I'm getting these errors and I'm not sure how to fix it. I am making a form that will make a post request to an API.

ERROR TypeError: Cannot read property 'email' of undefined

ERROR TypeError: Cannot read property 'paymentMethod' of undefined

I am expecting:

createdBy: string from email input,
paymentMethod: string from paymentMethod select input,

But what I get is:

createdBy: null,
paymentMethod: null

Interfaces

export interface BillingForm {
    fullName: string;
    email: string;
    address: string;
    city: string;
    paymentMethod: string;

  }

export interface Order {
  id?: number;
  companyId: number;
  created: string;
  createdBy: string;
  paymentMethod: string;
  totalPrice: number;
  status: number;
  orderRows: OrderRows[];
}

service.ts

public postOrder(order: Order): Observable<Order> {
      console.log(order);
      return this.http.post<Order>(this.ordersURL, order, httpOptions).pipe(
        catchError(this.handleError('postOrder', order))
      );

component.ts

ngOnInit() {

    this.shippingForm = this.formBuilder.group({
      name: ['', Validators.required],
      email: ['', Validators.required],
      address: ['', Validators.required],
      paymentMethod: ['', Validators.required],
      city: ['', Validators.required],
    })
  }

  onSubmit(billingForm: BillingForm) {
    const order = this.newOrder(billingForm);

    this.productService.postOrder(order).subscribe (
      response => console.log('success', response),
      error => console.log('error', error)
    )

    this.submitted = true;

    if(this.shippingForm.invalid) {
      return;
    }
    this.success = true;

  }

  newOrder(billingForm: BillingForm ): Order {
    return {
      companyId: 6,
      created: moment().locale("sv").format("YYYY-MM-DDTLTS"),
      createdBy: billingForm.email,
      paymentMethod: billingForm.paymentMethod,
      totalPrice: this.totalPrice,
      status: 0,
      orderRows: this.orderRows

    }
  }

  get email() {
    return this.shippingForm.get("email") as FormControl;
  }

  get paymentMethod() {
    return this.shippingForm.get("paymentMethod") as FormControl;
  }

component.html

<form [formGroup]="shippingForm" (ngSubmit)="onSubmit(billingForm)">

Your form is valid!

            Email
            <input type="email" formControlName="email" class="form-control" id="inputEmail" placeholder="Email">

Your email is required!

            Payment Method:
            <select type="select" formControlName="paymentMethod" class="form-control" id="payment"
              aria-placeholder="Mastercard">
              <option selected> Choose...</option>
              <option *ngFor="let paymentMethod of paymentMethods">
                {{ paymentMethod }}
              </option>
            </select>

Your preferred payment method is required!

</form>

Body:
<form [formGroup]="shippingForm" (ngSubmit)="onSubmit(billingForm)">

Correct me if I'm wrong, but this billingForm is nowhere defined. So onSubmit method gets called with undefined as argument.

shippingForm is defined (and it's the one connected to the template), I'm guessing you meant onSubmit(shippingForm).


问:
How to get 'isalpha' to iterate through each character of string?
I am having trouble figuring out how to check each character in the keyword (argv[1]). I know I am probably missing something super obvious. :(

I have tried saving the string to an array, declaring a new int, but still same problem.

```<code>//check to make sure 2nd argument is fully alphabetic
string keyword = argv[1];

for(int i = 0, n = strlen(keyword); i < n; i++)
{
    if(isalpha(keyword[i]))
    {
        printf("Success! \n");
        return 0;
    }
    else
    {
        printf("Invalid key, must be fully alphabetic. \n");
        return 1;
    }
}
</code>```

Expected output should be "Invalid key, must be fully alphabetic." for anything not fully alphabetic. Instead, it only works for the beginning character, not the whole keyword.

答:
Two problems

Do not always exit the loop

@ShadowRanger

Use unsigned character values

isalpha(int x) is defined for x in the unsigned char range and EOF.  Other negative char values re undefined behavior.

```<code>// if(!isalpha(keyword[i]))
if(!isalpha((unsigned char) keyword[i]))
</code>```

With simplified loop - strlen() not needed.

```<code>int alexa_alpha_test(const char *keyword) {
  while (*keyword) {
    if(!isalpha((unsigned char) *keyword)) {
      printf("Invalid key, must be fully alphabetic. \n");
      return 1;
    }
    keyword++;
  }
  printf("Success! \n");
  return 0;
}
</code>```

Body:
I am having trouble figuring out how to check each character in the keyword (argv[1]). I know I am probably missing something super obvious. :(

I have tried saving the string to an array, declaring a new int, but still same problem.

//check to make sure 2nd argument is fully alphabetic
string keyword = argv[1];

for(int i = 0, n = strlen(keyword); i < n; i++)
{
    if(isalpha(keyword[i]))
    {
        printf("Success! \n");
        return 0;
    }
    else
    {
        printf("Invalid key, must be fully alphabetic. \n");
        return 1;
    }
}

Expected output should be "Invalid key, must be fully alphabetic." for anything not fully alphabetic. Instead, it only works for the beginning character, not the whole keyword.

Body:
Two problems

Do not always exit the loop

@ShadowRanger

Use unsigned character values

isalpha(int x) is defined for x in the unsigned char range and EOF.  Other negative char values re undefined behavior.

// if(!isalpha(keyword[i]))
if(!isalpha((unsigned char) keyword[i]))

With simplified loop - strlen() not needed.

int alexa_alpha_test(const char *keyword) {
  while (*keyword) {
    if(!isalpha((unsigned char) *keyword)) {
      printf("Invalid key, must be fully alphabetic. \n");
      return 1;
    }
    keyword++;
  }
  printf("Success! \n");
  return 0;
}


问:
How to combine CSVs in Python?
So I have two CSV files, and wish to merge them to create one file. My first CSV file has names and balances from 2018, while the second one has names and balances from 2019.
For Eg

2018

ABC 123

XYZ 456

2019

ABC 123

PQR 234

Final Output Should Look Like

ABC 123 123

XYZ 456 0

PQR 0 234

I just don't understand how to do this with Pandas. I am new to python and this assignment was given this morning. This is something which will work as FULL OUTER JOIN if I was working in SQL, but I have no clue how to implement this in Python

答:
```<code>   table :test2018.csv
Name   T1
 ABC  123
 XYZ  456

table test2019.csv
Name   T1
ABC  123
PQR  234

import pandas as pd
    train =pd.read_csv('test2018.csv')
    train2 =pd.read_csv('test2019.csv')
    train.head()
    train2.head()
    t1=pd.merge(train,train2,on='Name',how='outer')
    print(t1)
</code>```

Title: How to combine CSVs in Python?


问:
How can I get the browser's scrollbar sizes?
How can I determine the height of a horizontal scrollbar, or the width of a vertical one, in JavaScript?</p>

答:
Here's the more concise and easy to read solution based on offset width difference:

function getScrollbarWidth(): number {

  // Creating invisible container
  const outer = document.createElement('div');
  outer.style.visibility = 'hidden';
  outer.style.overflow = 'scroll'; // forcing scrollbar to appear
  outer.style.msOverflowStyle = 'scrollbar'; // needed for WinJS apps
  document.body.appendChild(outer);

  // Creating inner element and placing it in the container
  const inner = document.createElement('div');
  outer.appendChild(inner);

  // Calculating difference between container's full width and the child width
  const scrollbarWidth = (outer.offsetWidth - inner.offsetWidth);

  // Removing temporary elements from the DOM
  outer.parentNode.removeChild(outer);

  return scrollbarWidth;

}
```

See the JSFiddle.

Body:
Here's the more concise and easy to read solution based on offset width difference:

function getScrollbarWidth(): number {

  // Creating invisible container
  const outer = document.createElement('div');
  outer.style.visibility = 'hidden';
  outer.style.overflow = 'scroll'; // forcing scrollbar to appear
  outer.style.msOverflowStyle = 'scrollbar'; // needed for WinJS apps
  document.body.appendChild(outer);

  // Creating inner element and placing it in the container
  const inner = document.createElement('div');
  outer.appendChild(inner);

  // Calculating difference between container's full width and the child width
  const scrollbarWidth = (outer.offsetWidth - inner.offsetWidth);

  // Removing temporary elements from the DOM
  outer.parentNode.removeChild(outer);

  return scrollbarWidth;

}

See the JSFiddle.


问:
i want to delete item from listview without restarting actitvity
i want to delete a listview item on long press on that item . after deleting item i need to restart activity to see changes  but i want to  see changes instantly

i already tried notifyDataSetChanged(); but it didn't work i am taking data from sqlite database and put it in hashmaps and sending it to custom adapter
on long press one row is deleted from database but no changes take place in listview.

```<code>@Override
public View getView( final  int position, View convertView, ViewGroup parent) {
    View view = super.getView(position, convertView, parent);
    ImageView imageView = view.findViewById(R.id.detailsimage);
    CardView cardView = view.findViewById(R.id.detailcardView);
    TextView textmo =view.findViewById(R.id.detailsmo);
    TextView texttu =view.findViewById(R.id.detailstu);
    TextView textwe =view.findViewById(R.id.detailswe);
    TextView textth =view.findViewById(R.id.detailsthu);
    TextView  textfr =view.findViewById(R.id.detailsfri);
    TextView textsa =view.findViewById(R.id.detailssat);
    TextView textsu =view.findViewById(R.id.detailssun);

    final databasehandler db = new databasehandler(context);
    cardView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {

            db.deleteTitle(position+1);
            Toast.makeText(context,Integer.toString(position),Toast.LENGTH_SHORT).show();
            notifyDataSetChanged();

            return true;
        }
    });

    imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            HashMap<String, String> hashmap= arrayList.get(position);
            String string= hashmap.get("repeat");
            string = Objects.requireNonNull(string).trim();

            Toast.makeText(context,string,Toast.LENGTH_SHORT).show();
        }
    });

    HashMap<String, String> hashmap= arrayList.get(position);
    String string= Objects.requireNonNull(hashmap.get("repeat")).trim();
   String[] separated = Objects.requireNonNull(string).split("");

                        }
            }}
 return view;
 }
}
</code>```

答:
Pass the list into the Adapter and change this block</p>

```<code>cardView.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View v) {

        db.deleteTitle(position+1);
        yourList.remove(position);
     Toast.makeText(context,Integer.toString(position),Toast.LENGTH_SHORT).show();
        notifyDataSetChanged();

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

Body:
i want to delete a listview item on long press on that item . after deleting item i need to restart activity to see changes  but i want to  see changes instantly

i already tried notifyDataSetChanged(); but it didn't work i am taking data from sqlite database and put it in hashmaps and sending it to custom adapter
on long press one row is deleted from database but no changes take place in listview.

@Override
public View getView( final  int position, View convertView, ViewGroup parent) {
    View view = super.getView(position, convertView, parent);
    ImageView imageView = view.findViewById(R.id.detailsimage);
    CardView cardView = view.findViewById(R.id.detailcardView);
    TextView textmo =view.findViewById(R.id.detailsmo);
    TextView texttu =view.findViewById(R.id.detailstu);
    TextView textwe =view.findViewById(R.id.detailswe);
    TextView textth =view.findViewById(R.id.detailsthu);
    TextView  textfr =view.findViewById(R.id.detailsfri);
    TextView textsa =view.findViewById(R.id.detailssat);
    TextView textsu =view.findViewById(R.id.detailssun);

    final databasehandler db = new databasehandler(context);
    cardView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {

            db.deleteTitle(position+1);
            Toast.makeText(context,Integer.toString(position),Toast.LENGTH_SHORT).show();
            notifyDataSetChanged();

            return true;
        }
    });

    imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            HashMap<String, String> hashmap= arrayList.get(position);
            String string= hashmap.get("repeat");
            string = Objects.requireNonNull(string).trim();

            Toast.makeText(context,string,Toast.LENGTH_SHORT).show();
        }
    });

    HashMap<String, String> hashmap= arrayList.get(position);
    String string= Objects.requireNonNull(hashmap.get("repeat")).trim();
   String[] separated = Objects.requireNonNull(string).split("");

                        }
            }}
 return view;
 }
}

Body:
Pass the list into the Adapter and change this block

cardView.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View v) {

        db.deleteTitle(position+1);
        yourList.remove(position);
     Toast.makeText(context,Integer.toString(position),Toast.LENGTH_SHORT).show();
        notifyDataSetChanged();

        return true;
    }
});


问:
jQuery DataTables: Delay search until 3 characters been typed OR a button clicked
Is there please an option to start the search only after 3 characters have been typed in?

I have written a PHP-script for colleagues displaying 20,000 entries and they complain, that when typing a word, the first few letters cause everything to freeze.

An alternative would be to have the search to be started by a button clicked and not by character typing.

Below is my current code:

```<code>$("#my_table").dataTable( {
        "bJQueryUI": true,
        "sPaginationType": "full_numbers",
        "bAutoWidth": false,
        "aoColumns": [
                /* qdatetime */   { "bSearchable": false },
                /* id */          null,
                /* name */        null,
                /* category */    null,
                /* appsversion */ null,
                /* osversion */   null,
                /* details */     { "bVisible": false },
                /* devinfo */     { "bVisible": false, "bSortable": false }
        ],
        "oLanguage": {
                "sProcessing":   "Wait please...",
                "sZeroRecords":  "No ids found.",
                "sInfo":         "Ids from _START_ to _END_ of _TOTAL_ total",
                "sInfoEmpty":    "Ids from 0 to 0 of 0 total",
                "sInfoFiltered": "(filtered from _MAX_ total)",
                "sInfoPostFix":  "",
                "sSearch":       "Search:",
                "sUrl":          "",
                "oPaginate": {
                        "sFirst":    "<<",
                        "sLast":     ">>",
                        "sNext":     ">",
                        "sPrevious": "<"
                },
                "sLengthMenu": 'Display <select>' +
                        '<option value="10">10</option>' +
                        '<option value="20">20</option>' +
                        '<option value="50">50</option>' +
                        '<option value="100">100</option>' +
                        '<option value="-1">all</option>' +
                        '</select> ids'
        }
} );
</code>```

答:
Can you write your own function to test for the length of the inputed string attached to an onKeyUp event handler and trigger the search function once the min length has been reached?

Something along the lines of:

```
input.onKeyUp(function() {
    if(input.length > 3) {
        mySearchfunction();
    }
});
```

...that is, in a pseudo code kind of way but you get the jist.

Body:
Is there please an option to start the search only after 3 characters have been typed in?

I have written a PHP-script for colleagues displaying 20,000 entries and they complain, that when typing a word, the first few letters cause everything to freeze.

An alternative would be to have the search to be started by a button clicked and not by character typing.

Below is my current code:

$("#my_table").dataTable( {
        "bJQueryUI": true,
        "sPaginationType": "full_numbers",
        "bAutoWidth": false,
        "aoColumns": [
                /* qdatetime */   { "bSearchable": false },
                /* id */          null,
                /* name */        null,
                /* category */    null,
                /* appsversion */ null,
                /* osversion */   null,
                /* details */     { "bVisible": false },
                /* devinfo */     { "bVisible": false, "bSortable": false }
        ],
        "oLanguage": {
                "sProcessing":   "Wait please...",
                "sZeroRecords":  "No ids found.",
                "sInfo":         "Ids from _START_ to _END_ of _TOTAL_ total",
                "sInfoEmpty":    "Ids from 0 to 0 of 0 total",
                "sInfoFiltered": "(filtered from _MAX_ total)",
                "sInfoPostFix":  "",
                "sSearch":       "Search:",
                "sUrl":          "",
                "oPaginate": {
                        "sFirst":    "<<",
                        "sLast":     ">>",
                        "sNext":     ">",
                        "sPrevious": "<"
                },
                "sLengthMenu": 'Display <select>' +
                        '<option value="10">10</option>' +
                        '<option value="20">20</option>' +
                        '<option value="50">50</option>' +
                        '<option value="100">100</option>' +
                        '<option value="-1">all</option>' +
                        '</select> ids'
        }
} );

Body:
Can you write your own function to test for the length of the inputed string attached to an onKeyUp event handler and trigger the search function once the min length has been reached?

Something along the lines of:

input.onKeyUp(function() {
    if(input.length > 3) {
        mySearchfunction();
    }
});

...that is, in a pseudo code kind of way but you get the jist.


问:
what can be used in place of window.location.replace to avoid page reloading?
I am using product filtering in a site like Flipkart. And I do not want to reload the page after filtering data. This is my jquery code for filtering data. Filter class is used in all the filters. Give some suggestions plz. </p>

```<code>$('.filter').click(function() {

    var typef = '';
    var currentURL = location.protocol + '//' + location.host + location.pathname;
    if (window.location.href.indexOf("search") > -1) {
        var searchParams = new URLSearchParams(window.location.search);
        var aquery = searchParams.get('query');
        typef = 'search';
    }
    var brands = [];
    var colors = [];
    var price = [];
    if ($(this).is(":checked")) {
        $("input:checkbox[name=brand_check]:checked").each(function() {
            brands.push($(this).val());
        });
        $("input:checkbox[name=color_check]:checked").each(function() {
            colors.push($(this).val());
        });
        $("input:radio[name=price_check]:checked").each(function() {
            price.push($(this).val());
        });
        var filterdata = {
            brands: jQuery.unique(brands),
            color: jQuery.unique(colors),
            price: jQuery.unique(price)
        };
        var filteruri = jQuery.param(filterdata);
        if (typef == 'search' && typeof aquery !== "undefined" && aquery !== '') {
            window.location.replace(currentURL + '?query=' + encodeURIComponent(aquery) + '&f=' + encodeURIComponent(filteruri));
        } else {
            window.location.replace(currentURL + '?f=' + encodeURIComponent(filteruri));
        }
    } else {
        $('input:checkbox[value="' + $(this).val() + '"]').attr('checked', false);
        $("input:checkbox[name=brand_check]:checked").each(function() {
            brands.push($(this).val());
        });
        $("input:checkbox[name=color_check]:checked").each(function() {
            colors.push($(this).val());
        });
        $("input:radio[name=price_check]:checked").each(function() {
            price.push($(this).val());
        });
        var filterdata = {
            brands: jQuery.unique(brands),
            color: jQuery.unique(colors),
            price: jQuery.unique(price)
        };
        var filteruri = jQuery.param(filterdata);
        if (typef == 'search' && typeof aquery !== "undefined" && aquery !== '') {
            if (filteruri.length > 0) {
                window.location.replace(currentURL + '?query=' + encodeURIComponent(aquery) + '&f=' + encodeURIComponent(filteruri));
            } else {
                window.location.replace(currentURL + '?query=' + encodeURIComponent(aquery));
            }
        } else {
            if (filteruri.length > 0) {
                window.location.replace(currentURL + '?f=' + encodeURIComponent(filteruri));
            } else {
                window.location.replace(currentURL);
            }
        }
    }

});
</code>```

答:
If I understood correctly, you want to change url without page reloading.
Read some about manipulating browser history (https://developer.mozilla.org/en-US/docs/Web/API/History_API), in particular: pushState.

In your case you can use window.history.pushState (https://developer.mozilla.org/en-US/docs/Web/API/History_API#The_pushState()_method).

Instead window.location.replace you can write something like this one:

```<code>window.history.pushState({ page: filteruri }, 'Page title', currentURL + '?somethingnew');
</code>```

Body:
I am using product filtering in a site like Flipkart. And I do not want to reload the page after filtering data. This is my jquery code for filtering data. Filter class is used in all the filters. Give some suggestions plz.

$('.filter').click(function() {

    var typef = '';
    var currentURL = location.protocol + '//' + location.host + location.pathname;
    if (window.location.href.indexOf("search") > -1) {
        var searchParams = new URLSearchParams(window.location.search);
        var aquery = searchParams.get('query');
        typef = 'search';
    }
    var brands = [];
    var colors = [];
    var price = [];
    if ($(this).is(":checked")) {
        $("input:checkbox[name=brand_check]:checked").each(function() {
            brands.push($(this).val());
        });
        $("input:checkbox[name=color_check]:checked").each(function() {
            colors.push($(this).val());
        });
        $("input:radio[name=price_check]:checked").each(function() {
            price.push($(this).val());
        });
        var filterdata = {
            brands: jQuery.unique(brands),
            color: jQuery.unique(colors),
            price: jQuery.unique(price)
        };
        var filteruri = jQuery.param(filterdata);
        if (typef == 'search' && typeof aquery !== "undefined" && aquery !== '') {
            window.location.replace(currentURL + '?query=' + encodeURIComponent(aquery) + '&f=' + encodeURIComponent(filteruri));
        } else {
            window.location.replace(currentURL + '?f=' + encodeURIComponent(filteruri));
        }
    } else {
        $('input:checkbox[value="' + $(this).val() + '"]').attr('checked', false);
        $("input:checkbox[name=brand_check]:checked").each(function() {
            brands.push($(this).val());
        });
        $("input:checkbox[name=color_check]:checked").each(function() {
            colors.push($(this).val());
        });
        $("input:radio[name=price_check]:checked").each(function() {
            price.push($(this).val());
        });
        var filterdata = {
            brands: jQuery.unique(brands),
            color: jQuery.unique(colors),
            price: jQuery.unique(price)
        };
        var filteruri = jQuery.param(filterdata);
        if (typef == 'search' && typeof aquery !== "undefined" && aquery !== '') {
            if (filteruri.length > 0) {
                window.location.replace(currentURL + '?query=' + encodeURIComponent(aquery) + '&f=' + encodeURIComponent(filteruri));
            } else {
                window.location.replace(currentURL + '?query=' + encodeURIComponent(aquery));
            }
        } else {
            if (filteruri.length > 0) {
                window.location.replace(currentURL + '?f=' + encodeURIComponent(filteruri));
            } else {
                window.location.replace(currentURL);
            }
        }
    }

});

Body:
If I understood correctly, you want to change url without page reloading.
Read some about manipulating browser history (https://developer.mozilla.org/en-US/docs/Web/API/History_API), in particular: pushState.

In your case you can use window.history.pushState (https://developer.mozilla.org/en-US/docs/Web/API/History_API#The_pushState()_method).

Instead window.location.replace you can write something like this one:

window.history.pushState({ page: filteruri }, 'Page title', currentURL + '?somethingnew');


问:
How to set Retrofit URL string from Resources
I've refactored some parts of my code which is written in Kotlin and tend to put url's in strings.xml, but when I want to point to the string in strings.xml file in annotation part of the Retrofit, I get the following error.

An annotation argument must be a compile-time constant

Here is my code:

```<code>interface SampleApiService {
    @GET(Resources.getSystem().getString(R.string.sample_url))
    fun getSamples(){
    }
}
</code>```

Could anyone please tell me what is wrong?

Found the answer in the following post.

答:
Based upon the example provided - one could as well just use a static URL. It would need to be annotated alike this, in order not to use any run-time values and be able to change it at run-time:

```<code>@GET("{path}")
fun getSamples(@Path("path") path: String) {}
</code>```

Then one can load whatever String path from string resources, at run-time. When the base URL shall be changed, one may need to reconfigure the client. That is because this interface definition is being used by the annotation processor to generate the abstraction layer from it - at compile time already, not at run-time... when taking the complaint literal, it would have to look alike this:

```<code>@GET(Constants.SOME_PATH)
fun getSamples() {}
</code>```

but there is little advance over just hard-coding that String, because it cannot be changed later.

Body:
I've refactored some parts of my code which is written in Kotlin and tend to put url's in strings.xml, but when I want to point to the string in strings.xml file in annotation part of the Retrofit, I get the following error.

An annotation argument must be a compile-time constant

Here is my code:

interface SampleApiService {
    @GET(Resources.getSystem().getString(R.string.sample_url))
    fun getSamples(){
    }
}

Could anyone please tell me what is wrong?

Found the answer in the following post.

Body:
Based upon the example provided - one could as well just use a static URL. It would need to be annotated alike this, in order not to use any run-time values and be able to change it at run-time:

@GET("{path}")
fun getSamples(@Path("path") path: String) {}

Then one can load whatever String path from string resources, at run-time. When the base URL shall be changed, one may need to reconfigure the client. That is because this interface definition is being used by the annotation processor to generate the abstraction layer from it - at compile time already, not at run-time... when taking the complaint literal, it would have to look alike this:

@GET(Constants.SOME_PATH)
fun getSamples() {}

but there is little advance over just hard-coding that String, because it cannot be changed later.


问:
Reverse a ResourceManager
If you do ResourceManager.GetString(Key), you can get the value of an item in a resource. Is there a way to do a reverse lookup to get the key from the resource given the value (essentially de-translate)?</p>

答:
You should be able to get the ResourceSet and iterate over it's values and return the key if they are equal.  Just remember, you need to compare values, not references.  Something along these lines (Not compiled and tested, but something similar)</p>

```<code>  System.Resources.ResourceManager rm =
     new System.Resources.ResourceManager("MyAssembly.MyResources",
         System.Reflection.Assembly.GetExecutingAssembly());
  System.Resources.ResourceSet rs =
     rm.GetResourceSet(System.Globalization.CultureInfo.CurrentCulture,
         false, false);
  System.Collections.IDictionaryEnumerator ide = rs.GetEnumerator();
  while(ide.MoveNext())
  {
      if (ide.Value == val)
          return ide.Key;
  }
</code>```

OwnerDisplayName: brian

ContentLicense: CC BY-SA 2.5

Title: Reverse a ResourceManager

Body:
You should be able to get the ResourceSet and iterate over it's values and return the key if they are equal.  Just remember, you need to compare values, not references.  Something along these lines (Not compiled and tested, but something similar)

  System.Resources.ResourceManager rm =
     new System.Resources.ResourceManager("MyAssembly.MyResources",
         System.Reflection.Assembly.GetExecutingAssembly());
  System.Resources.ResourceSet rs =
     rm.GetResourceSet(System.Globalization.CultureInfo.CurrentCulture,
         false, false);
  System.Collections.IDictionaryEnumerator ide = rs.GetEnumerator();
  while(ide.MoveNext())
  {
      if (ide.Value == val)
          return ide.Key;
  }

OwnerDisplayName: Mystere Man