问:
Convert consecutive Trues, to False python
Essentially, I want to convert consecutive duplicates of Trues, to False as the title suggests.

For example, say, i have an array of 0s and 1s

```<code>x = pd.Series([1,0,0,1,1])
</code>```

should become:

```<code>y = pd.Series([0,0,0,0,1])
# where the 1st element of x becomes 0 since its not a consecutive
# and the 4th element becomes 0 because its the first instance of the consecutive duplicate
# And everything else should remain the same.
</code>```

This can also apply to consecutives of more than two, Say i have a much longer array:
eg.

```<code>x = pd.Series([1,0,0,1,1,1,0,1,1,0,1,1,1,1,0,0,1,1,1,1,1])
</code>```

becomes;

```<code>y = pd.Series([0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0,1])
</code>```

Posts that i have searched are mostly either deleting consecutive duplicates, and does not retain the original length. In this case, it should retain the original length.

It is something like the following code:

```<code>for i in range(len(x)):
    if x[i] == x[i+1]:
        x[i] = True
    else:
       x[i] = False
</code>```

but this gives me a never ending run. And does not accommodate consecutives of more than two.

Body:
Essentially, I want to convert consecutive duplicates of Trues, to False as the title suggests.

For example, say, i have an array of 0s and 1s

x = pd.Series([1,0,0,1,1])

should become:

y = pd.Series([0,0,0,0,1])
# where the 1st element of x becomes 0 since its not a consecutive
# and the 4th element becomes 0 because its the first instance of the consecutive duplicate
# And everything else should remain the same.

This can also apply to consecutives of more than two, Say i have a much longer array:
eg.

x = pd.Series([1,0,0,1,1,1,0,1,1,0,1,1,1,1,0,0,1,1,1,1,1])

becomes;

y = pd.Series([0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,0,0,0,1])

Posts that i have searched are mostly either deleting consecutive duplicates, and does not retain the original length. In this case, it should retain the original length.

It is something like the following code:

for i in range(len(x)):
    if x[i] == x[i+1]:
        x[i] = True
    else:
       x[i] = False

but this gives me a never ending run. And does not accommodate consecutives of more than two.

Body:
Vanilla Python :

x = [1,0,0,1,1,1,0,1,1,0,1,1,1,1,0,0,1,1,1,1,1]
counter = 0
for i, e in enumerate(x):
    if not e:
        counter = 0
        continue
    if not counter or (i < len(x) - 1 and x[i+1]):
        counter += 1
        x[i] = 0
print(x)

Prints :

[0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1]


来源: stackexchange

问:
Hash json and compare in Java
I am doing some migration & I would like to compare JSON Requests being sent on new vs old service. I have some sensitive data in my JSON, so I don't want to log it directly, I want to hash and then log it. Once hashed I want to compare the hashes.

PS: I have complex JSON Strings

```<code>{'method': 'do.stuff', 'params': ['asdf', 3, {'foo': 'bar'}]}
</code>```

and

```<code>{'params': ['asdf', 3, {'foo': 'bar'}], 'method': 'do.stuff'}
</code>```

Should return the same hash irrespective of the order

答:
One way of doing this would be to sort the keys of each object so the JSON would be in the same order and then create a hash. You need to take care of nested objects and arrays also.

For example...

```<code>import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.DigestUtils;

import javax.xml.bind.DatatypeConverter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class JsonHash {

    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();

        String jsonStringA = "{\"a\": \"100\", \"b\": \"200\", \"c\": [{\"d\": 200, \"e\": 100}], \"p\": null}";
        String jsonStringB = "{\"p\": null, \"b\": \"200\", \"a\": \"100\", \"c\": [{\"e\": 100, \"d\": 200}]}";
        String jsonStringC = "{\"p\": 1, \"b\": \"200\", \"a\": \"100\", \"c\": [{\"e\": 100, \"d\": 200}]}";

        String hashA = getHash(mapper, jsonStringA);
        String hashB = getHash(mapper, jsonStringB);
        String hashC = getHash(mapper, jsonStringC);

        System.out.println(hashA);
        System.out.println(hashB);
        System.out.println(hashC);
    }

    private static String getHash(ObjectMapper mapper, String jsonStringA) throws IOException {
        JsonNode jsonNode = mapper.readTree(jsonStringA);
        Map map = mapper.convertValue(jsonNode, Map.class);
        TreeMap sorted = sort(map);
        String s = mapper.writeValueAsString(sorted);
        byte[] md5Digest = DigestUtils.md5Digest(s.getBytes());
        return DatatypeConverter.printHexBinary(md5Digest).toUpperCase();
    }

    private static TreeMap sort(Map map) {
        TreeMap result = new TreeMap();
        map.forEach((k, v) -> {
            if(v != null) {
                if (v instanceof Map) {
                    result.put(k, sort((Map) v));
                } else if (v instanceof List) {
                    result.put(k, copyArray((List) v));
                } else {
                    result.put(k, v);
                }
            } else {
               result.put(k, null);
            }
        });
        return result;
    }

    private static List copyArray(List v) {
        List result = new ArrayList(v.size());

        for (int i = 0; i < v.size(); i++) {
            Object element = v.get(i);

            if(element != null) {
                if (element instanceof Map) {
                    result.add(sort((Map) element));
                } else if (element instanceof List) {
                    result.add(copyArray((List) element));
                } else {
                    result.add(element);
                }
            } else {
                result.add(null);
            }
        }

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

Output:

```<code>FADE525B0423415184D913299E90D959
FADE525B0423415184D913299E90D959
B49993CB657F1C9A62A339E5482F93D1
</code>```

The hash of your examples both come out as 3EBAD6BDF5064304B3DD499BDAF0E635

ContentLicense: CC BY-SA 4.0

Title: Hash json and compare in Java

Body:
I am doing some migration & I would like to compare JSON Requests being sent on new vs old service. I have some sensitive data in my JSON, so I don't want to log it directly, I want to hash and then log it. Once hashed I want to compare the hashes.

PS: I have complex JSON Strings

{'method': 'do.stuff', 'params': ['asdf', 3, {'foo': 'bar'}]}

and

{'params': ['asdf', 3, {'foo': 'bar'}], 'method': 'do.stuff'}

Should return the same hash irrespective of the order

Body:
One way of doing this would be to sort the keys of each object so the JSON would be in the same order and then create a hash. You need to take care of nested objects and arrays also.

For example...

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.DigestUtils;

import javax.xml.bind.DatatypeConverter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class JsonHash {

    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();

        String jsonStringA = "{\"a\": \"100\", \"b\": \"200\", \"c\": [{\"d\": 200, \"e\": 100}], \"p\": null}";
        String jsonStringB = "{\"p\": null, \"b\": \"200\", \"a\": \"100\", \"c\": [{\"e\": 100, \"d\": 200}]}";
        String jsonStringC = "{\"p\": 1, \"b\": \"200\", \"a\": \"100\", \"c\": [{\"e\": 100, \"d\": 200}]}";

        String hashA = getHash(mapper, jsonStringA);
        String hashB = getHash(mapper, jsonStringB);
        String hashC = getHash(mapper, jsonStringC);

        System.out.println(hashA);
        System.out.println(hashB);
        System.out.println(hashC);
    }

    private static String getHash(ObjectMapper mapper, String jsonStringA) throws IOException {
        JsonNode jsonNode = mapper.readTree(jsonStringA);
        Map map = mapper.convertValue(jsonNode, Map.class);
        TreeMap sorted = sort(map);
        String s = mapper.writeValueAsString(sorted);
        byte[] md5Digest = DigestUtils.md5Digest(s.getBytes());
        return DatatypeConverter.printHexBinary(md5Digest).toUpperCase();
    }

    private static TreeMap sort(Map map) {
        TreeMap result = new TreeMap();
        map.forEach((k, v) -> {
            if(v != null) {
                if (v instanceof Map) {
                    result.put(k, sort((Map) v));
                } else if (v instanceof List) {
                    result.put(k, copyArray((List) v));
                } else {
                    result.put(k, v);
                }
            } else {
               result.put(k, null);
            }
        });
        return result;
    }

    private static List copyArray(List v) {
        List result = new ArrayList(v.size());

        for (int i = 0; i < v.size(); i++) {
            Object element = v.get(i);

            if(element != null) {
                if (element instanceof Map) {
                    result.add(sort((Map) element));
                } else if (element instanceof List) {
                    result.add(copyArray((List) element));
                } else {
                    result.add(element);
                }
            } else {
                result.add(null);
            }
        }

        return result;
    }
}

Output:

FADE525B0423415184D913299E90D959
FADE525B0423415184D913299E90D959
B49993CB657F1C9A62A339E5482F93D1

The hash of your examples both come out as 3EBAD6BDF5064304B3DD499BDAF0E635


问:
iOS Swift Value from [String : AnyObject]
I am trying to get the value out of an [String : AnyObject] and have not yet found the answer on a web-reference

One of the parameters in a method call is:

advertisementData: [String : AnyObject]

And, when I run the code, a debug line print("\(advertisementData)") shows one of its values as:

["kCBAdvDataIsConnectable": 1, "kCBAdvDataServiceUUIDs": <__NSArrayM 0x13cd812e0>(
  C9CAB9B8-3ABF-4043-A5AF-9AD00C6074D5]

On each pass, I am trying to identify the value of the key:

 kCBAdvDataServiceUUIDs  --  it often changes on each pass through the code

I am looking to see if the value contains:  C9CAB9B8-3ABF-4043-A5AF-9AD00C6074D5  (as this example does) - many times it does not.

If so I will do something. If not do nothing.

I have tried:

```<code>let value = advertisementData["kCBAdvDataServiceUUIDs"]
</code>```

but it did not work and the error message was not clear (at least for this newbie it wasn't clear)

How can I get this value into a variable so that I can compare it to another String value?

答:
Updated for swift :

use below simple code;

```<code>    let yourServiceUUIDString = "FFF0"
    if let
        mAdvData = advertisementData["kCBAdvDataServiceUUIDs"] as? [AnyObject], (mAdvData.contains { ($0 as? CBUUID)?.uuidString == yourServiceUUIDString}) {
        print("BLE device found..!")
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to get the value out of an [String : AnyObject] and have not yet found the answer on a web-reference

One of the parameters in a method call is:

advertisementData: [String : AnyObject]

And, when I run the code, a debug line print("\(advertisementData)") shows one of its values as:

["kCBAdvDataIsConnectable": 1, "kCBAdvDataServiceUUIDs": <__NSArrayM 0x13cd812e0>(
  C9CAB9B8-3ABF-4043-A5AF-9AD00C6074D5]

On each pass, I am trying to identify the value of the key:

 kCBAdvDataServiceUUIDs  --  it often changes on each pass through the code

I am looking to see if the value contains:  C9CAB9B8-3ABF-4043-A5AF-9AD00C6074D5  (as this example does) - many times it does not.

If so I will do something. If not do nothing.

I have tried:

let value = advertisementData["kCBAdvDataServiceUUIDs"]

but it did not work and the error message was not clear (at least for this newbie it wasn't clear)

How can I get this value into a variable so that I can compare it to another String value?

Body:
Updated for swift :

use below simple code;

    let yourServiceUUIDString = "FFF0"
    if let
        mAdvData = advertisementData["kCBAdvDataServiceUUIDs"] as? [AnyObject], (mAdvData.contains { ($0 as? CBUUID)?.uuidString == yourServiceUUIDString}) {
        print("BLE device found..!")
    }


问:
Do you have any tips to improve ReSharper and/or Visual Studio performance?
I'm using visual studio 2008 and ReSharper 4 and it's kind of slow. My machine has 2 GB of RAM, dual core processor and a 7200 rpm hard disk. I know more RAM and a faster hard disk could improve performance, but do you have any tips to improve ReSharper/Visual Studio performance?</p>

答:
Having too many projects within your solution also appears to be a factor when it comes to performance. I have no real evidence of this but from my experience, less projects equates to better performance.

If consolidating projects is not an option then create an alternate solution file so you can add only the existing projects that are relevant to the work you are doing.

OwnerDisplayName: Rismo

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Rismo

OwnerDisplayName: berko


问:
Why am I getting these jagged edges in my shader?
I wrote a simple shadertoy example of ray-plane intersection. I am using a checker pattern on the plane and I noticed odd artifacts. I know that this lacks anti-aliasing, so I was fully expecting jagged lines. However, there are random pixels along the edges that seem to stand out as being incorrect. I tried my best to recreate the same thing in Blender using the Cycles renderer with 1 sample per pixel, and it produced a result closer to what I was expecting. Can anyone explain this?

```<code>float intersect(in vec3 ro, in vec3 rd)
{
    return -ro.y / rd.y;
}

void mainImage(out vec4 fragColor, in vec2 fragCoord)
{
    vec2 uv = ((fragCoord + vec2(0.5)) / iResolution.xy * 2.0 - 1.0) * vec2(16.0 / 9.0, 1.0);
    vec3 ro = vec3(0.0, 1.0, 0.0);
    vec3 rd = normalize(vec3(uv, 2.0));

    float t = intersect(ro, rd);

    vec3 col = vec3(0.0, 0.0, 0.0);

    if (t >= 0.0)
    {
        vec3 pos = ro + t * rd;
        vec2 tex = floor(pos.xz);
        col = vec3(mod(tex.x + tex.y, 2.0));
    }

    fragColor = vec4(col, 1.0);
}
</code>```

答: If the grid lines fall directly on a sampling point then floating point error will determine which grid square is chosen for that pixel. Cycles uses random sampling points, while you are using integers (fragCoord + vec2(0.5)). Changing your sampling points to fragCoord + vec2(0.001234, 0.004321) removes the artifacts.

Body:
I wrote a simple shadertoy example of ray-plane intersection. I am using a checker pattern on the plane and I noticed odd artifacts. I know that this lacks anti-aliasing, so I was fully expecting jagged lines. However, there are random pixels along the edges that seem to stand out as being incorrect. I tried my best to recreate the same thing in Blender using the Cycles renderer with 1 sample per pixel, and it produced a result closer to what I was expecting. Can anyone explain this?

float intersect(in vec3 ro, in vec3 rd)
{
    return -ro.y / rd.y;
}

void mainImage(out vec4 fragColor, in vec2 fragCoord)
{
    vec2 uv = ((fragCoord + vec2(0.5)) / iResolution.xy * 2.0 - 1.0) * vec2(16.0 / 9.0, 1.0);
    vec3 ro = vec3(0.0, 1.0, 0.0);
    vec3 rd = normalize(vec3(uv, 2.0));

    float t = intersect(ro, rd);

    vec3 col = vec3(0.0, 0.0, 0.0);

    if (t >= 0.0)
    {
        vec3 pos = ro + t * rd;
        vec2 tex = floor(pos.xz);
        col = vec3(mod(tex.x + tex.y, 2.0));
    }

    fragColor = vec4(col, 1.0);
}


问:
oracle forms not showing all fields
I have 2 tables: product which has primary key product_id and Review which has product_id which references the product_id of product table;
I created form master-detail for them but when executing I get at the bottom of page:

FRM-40505: ORACLE error: unable to perform query

and when pressing ctrl+shift+e I get:

```<code>SELECT ROWID, REVIEW_ID, LIKE, DISLIKE, FIRST_NAME, LAST_NAME, PRODUCT_ID
  FROM U1.REVIEW WHERE (PRODUCT_ID=:1)

ORA-00936: missing expression
</code>```

how to solve this? what is wrong? thank you in advance

答: Seems you have a field named like in your block with base table named review has Database Item set to Yes in the property palette, and for this reason Oracle treats that field as if a column of the table, but there's no such column, and not possible to have a column named like within a db table, since it's a reserved keyword.

Title: oracle forms not showing all fields

Body:
I have 2 tables: product which has primary key product_id and Review which has product_id which references the product_id of product table;
I created form master-detail for them but when executing I get at the bottom of page:

FRM-40505: ORACLE error: unable to perform query

and when pressing ctrl+shift+e I get:

SELECT ROWID, REVIEW_ID, LIKE, DISLIKE, FIRST_NAME, LAST_NAME, PRODUCT_ID
  FROM U1.REVIEW WHERE (PRODUCT_ID=:1)

ORA-00936: missing expression

how to solve this? what is wrong? thank you in advance


问:
async methods in a foreach and add results in a list
I would like to run several methods asyncron in a foreach. The return value should be written to a list.

The method is executed in a WPF application. The method GetItemPricesFromJsonAsync fetches from the web data.

public async Task LoadBlackMarketListView(List<MarketAnalysisManager.ItemTier> tiers, List<MarketAnalysisManager.ItemLevel> levels,
            List<MarketAnalysisManager.ItemQuality> quialityList, string outdatedHours, string profit, Location? location)
        {
            await Task.Run(async () =>
            {
                var blackMarketSellObjectList = new List<BlackMarketSellObject>();

                var items = await MarketAnalysisManager.GetItemListAsync(tiers, levels);

                await Dispatcher.InvokeAsync(() =>
                {
                    PbBlackMarketMode.Minimum = 0;
                    PbBlackMarketMode.Maximum = items.Count;
                    PbBlackMarketMode.Value = 0;
                    GridBlackMarketMode.IsEnabled = false;
                    LvBlackMarket.Visibility = Visibility.Hidden;
                    PbBlackMarketMode.Visibility = Visibility.Visible;
                });

                foreach (var item in items)
                {
                    var allItemPrices = await MarketAnalysisManager.GetItemPricesFromJsonAsync(item.UniqueName, true);
                    if (allItemPrices.FindAll(a => a.City == Locations.GetName(Location.BlackMarket)).Count <= 0)
                    {
                        await IncreaseBlackMarketProgressBar();
                        continue;
                    }

                    blackMarketSellObjectList.AddRange(await GetBlackMarketSellObjectList(item, quialityList, allItemPrices, outdatedHours, profit, location));

                    await IncreaseBlackMarketProgressBar();
                }

                await Dispatcher.InvokeAsync(() =>
                {
                    LvBlackMarket.ItemsSource = blackMarketSellObjectList;
                    PbBlackMarketMode.Visibility = Visibility.Hidden;
                    LvBlackMarket.Visibility = Visibility.Visible;
                    GridBlackMarketMode.IsEnabled = true;
                });
            });

        }
```

Currently it looks like he's only doing one thing at a time.

Run... 0

End... 0

Run... 1

End... 1

Run... 2

End... 2

答:
You will need to store the Tasks, not await them. Then you can wait for all of them.

Try this (replace your foreach with my code).

I would also advise you to use a real method instead of the annonymous one, it's much more readable.

```<code>List<Task> tasks = new List<Task>();
foreach (var item in items)
{
    tasks.Add(Task.Run(async () =>
    {
        var allItemPrices = await MarketAnalysisManager.GetItemPricesFromJsonAsync(item.UniqueName, true);
        if (allItemPrices.FindAll(a => a.City == Locations.GetName(Location.BlackMarket)).Count <= 0)
        {
            await IncreaseBlackMarketProgressBar();
            return;
        }

        blackMarketSellObjectList.AddRange(await GetBlackMarketSellObjectList(item, quialityList, allItemPrices, outdatedHours, profit, location));

        await IncreaseBlackMarketProgressBar();
    }));
}

await Task.WhenAll(tasks);
</code>```

Note: There is now a return instead of a continue since this is an annonymous function and you just have to end the function there instead of continuing with the foreach.

Body:
I would like to run several methods asyncron in a foreach. The return value should be written to a list.

The method is executed in a WPF application. The method GetItemPricesFromJsonAsync fetches from the web data.

public async Task LoadBlackMarketListView(List<MarketAnalysisManager.ItemTier> tiers, List<MarketAnalysisManager.ItemLevel> levels,
            List<MarketAnalysisManager.ItemQuality> quialityList, string outdatedHours, string profit, Location? location)
        {
            await Task.Run(async () =>
            {
                var blackMarketSellObjectList = new List<BlackMarketSellObject>();

                var items = await MarketAnalysisManager.GetItemListAsync(tiers, levels);

                await Dispatcher.InvokeAsync(() =>
                {
                    PbBlackMarketMode.Minimum = 0;
                    PbBlackMarketMode.Maximum = items.Count;
                    PbBlackMarketMode.Value = 0;
                    GridBlackMarketMode.IsEnabled = false;
                    LvBlackMarket.Visibility = Visibility.Hidden;
                    PbBlackMarketMode.Visibility = Visibility.Visible;
                });

                foreach (var item in items)
                {
                    var allItemPrices = await MarketAnalysisManager.GetItemPricesFromJsonAsync(item.UniqueName, true);
                    if (allItemPrices.FindAll(a => a.City == Locations.GetName(Location.BlackMarket)).Count <= 0)
                    {
                        await IncreaseBlackMarketProgressBar();
                        continue;
                    }

                    blackMarketSellObjectList.AddRange(await GetBlackMarketSellObjectList(item, quialityList, allItemPrices, outdatedHours, profit, location));

                    await IncreaseBlackMarketProgressBar();
                }

                await Dispatcher.InvokeAsync(() =>
                {
                    LvBlackMarket.ItemsSource = blackMarketSellObjectList;
                    PbBlackMarketMode.Visibility = Visibility.Hidden;
                    LvBlackMarket.Visibility = Visibility.Visible;
                    GridBlackMarketMode.IsEnabled = true;
                });
            });

        }

Currently it looks like he's only doing one thing at a time.

Run... 0

End... 0

Run... 1

End... 1

Run... 2

End... 2

Body:
You will need to store the Tasks, not await them. Then you can wait for all of them.

Try this (replace your foreach with my code).

I would also advise you to use a real method instead of the annonymous one, it's much more readable.

List<Task> tasks = new List<Task>();
foreach (var item in items)
{
    tasks.Add(Task.Run(async () =>
    {
        var allItemPrices = await MarketAnalysisManager.GetItemPricesFromJsonAsync(item.UniqueName, true);
        if (allItemPrices.FindAll(a => a.City == Locations.GetName(Location.BlackMarket)).Count <= 0)
        {
            await IncreaseBlackMarketProgressBar();
            return;
        }

        blackMarketSellObjectList.AddRange(await GetBlackMarketSellObjectList(item, quialityList, allItemPrices, outdatedHours, profit, location));

        await IncreaseBlackMarketProgressBar();
    }));
}

await Task.WhenAll(tasks);

Note: There is now a return instead of a continue since this is an annonymous function and you just have to end the function there instead of continuing with the foreach.


问:
Why is my xdebug not styled?
So I have Xdebug enabled on my local version of PHP, and I'm wondering if anyone can give me an answer as to why the output isn't styled in the default way (with the orange background, table design).  I can see the stack trace and everything, but it's all just text, no html wrapper around the message.

Thanks if you have any advice to give!

BTW, this is in my php.ini file:

```<code>zend_extension="C:\php\ext\php_xdebug.dll"
xdebug.show_local_vars=On
xdebug.dump.SERVER=*
xdebug.dump_globals=On
</code>```

答:
Make sure to have :

html_errors = On

set in php.ini

Title: Why is my xdebug not styled?

Body:
So I have Xdebug enabled on my local version of PHP, and I'm wondering if anyone can give me an answer as to why the output isn't styled in the default way (with the orange background, table design).  I can see the stack trace and everything, but it's all just text, no html wrapper around the message.

Thanks if you have any advice to give!

BTW, this is in my php.ini file:

zend_extension="C:\php\ext\php_xdebug.dll"
xdebug.show_local_vars=On
xdebug.dump.SERVER=*
xdebug.dump_globals=On


问:
Are there any rules for when a method changes an object "in place" or returns a new object?
I'm practicing for my exam and there are always questions asking whether a method changes an object in place or creates a new object. I wonder if there are any general rules applied to this or if I just have to memorise the outcome for different methods?

The examples from my exam are:

```<code>s = 'horse'
s.upper()
print(s)
</code>```

this will generate horse and not HORSE, and thereby s is not changed by .upper, however

```<code>l = [1, 3, 2]
l.sort()
print(l)
</code>```

will generate [1, 2, 3] and not [1, 3, 2], and thereby l is changed by .sort

Are there any ways to differentiate between these?

答:
There are no real generic ways to remember this. You need to remember on an individual basis. You can generally remember that strings are immutable and never change. And you can specifically remember that the .sort method explicitly returns None to remind people that it sorts in place, and that you need to use the sorted() function if you want a copy instead. But those are specific to strings and sorting, knowing this doesn't help you to generalise at all.

Generally speaking, such knowledge simply accumulates with usage. In practical everyday programming, nobody needs to know this by heart, since you'll always be thumping the documentation while you're coding and/or you'll try small snippets on the interactive command line to confirm their workings. Learning this by rote for a test has no practical purpose in later use; likely you're supposed to remember the few types and functions that were explicitly mentioned in your lessons, if you're presented with a heretofore unknown type, your guess will be as good as mine.

Body:
I'm practicing for my exam and there are always questions asking whether a method changes an object in place or creates a new object. I wonder if there are any general rules applied to this or if I just have to memorise the outcome for different methods?

The examples from my exam are:

s = 'horse'
s.upper()
print(s)

this will generate horse and not HORSE, and thereby s is not changed by .upper, however

l = [1, 3, 2]
l.sort()
print(l)

will generate [1, 2, 3] and not [1, 3, 2], and thereby l is changed by .sort

Are there any ways to differentiate between these?


问:
Convert array of Strings to Array list
I have a String array with name and id, I need to convert that String array to List of objects.

This is my code:

```<code>private List<ObjectAttribute> getDtls(String newVal) {
    ObjectAttribute object = new ObjectAttribute();
    List<ObjectAttribute> objLst = new ArrayList<ObjectAttribute>();
    String[] newImageVal = [step0005.jpg, 172B6846-0073-4E5B-B10A-DDD928994EA6, step0003.jpg, FBC8D143-2CD7-47E6-B323-31A0928A9338]
    for (int i = 0; i <= newImageVal.length - 1; i++) {
        object.setImageName(newImageVal[i]);
        object.setImageId(newImageVal[++i]);
        objLst.add(object);
    }
    return objLst;
}
</code>```

but there is a problem that it always returns only the last value in objList. Can anyone correct this code.

答:
```<code>private List<ObjectAttribute> getDtls(String newVal) {
    List<ObjectAttribute> objLst = new ArrayList<ObjectAttribute>();
    String[] newImageVal = [step0005.jpg, 172B6846-0073-4E5B-B10A-DDD928994EA6, step0003.jpg, FBC8D143-2CD7-47E6-B323-31A0928A9338]
//  String delimiter = ", ";
//  newImageVal = newVal.split(delimiter);
    for (int i = 0; i <= newImageVal.length - 1; i++) {
        ObjectAttribute object = new ObjectAttribute();
        object.setImageName(newImageVal[i]);
        object.setImageId(newImageVal[++i]);
        objLst.add(object);
    }
    return objLst;
}
</code>```

Title: Convert array of Strings to Array list

Body:
I have a String array with name and id, I need to convert that String array to List of objects.

This is my code:

private List<ObjectAttribute> getDtls(String newVal) {
    ObjectAttribute object = new ObjectAttribute();
    List<ObjectAttribute> objLst = new ArrayList<ObjectAttribute>();
    String[] newImageVal = [step0005.jpg, 172B6846-0073-4E5B-B10A-DDD928994EA6, step0003.jpg, FBC8D143-2CD7-47E6-B323-31A0928A9338]
    for (int i = 0; i <= newImageVal.length - 1; i++) {
        object.setImageName(newImageVal[i]);
        object.setImageId(newImageVal[++i]);
        objLst.add(object);
    }
    return objLst;
}

but there is a problem that it always returns only the last value in objList. Can anyone correct this code.


问:
How to properly display Pytorch's math notation inside docstring?
When looking at the docstring of Pytorch functions, the math notations are not properly displayed, e.g.:
https://pytorch.org/docs/stable/_modules/torch/nn/modules/loss.html

```<code>.. math::
    \text{loss}(x, class) = weight[class] \left(-x[class] + \log\left(\sum_j \exp(x[j])\right)\right)
</code>```

Only if I use my IDE to display the documentation, it renders the latex notation properly.

Is there any switch for displaying math on the website?

答:
The docs in source code won't render unless you try some script injection via Greasemonkey or so.
But first have a look at the standard docs where you can find the rendered formula.</p>

Body:
When looking at the docstring of Pytorch functions, the math notations are not properly displayed, e.g.:
https://pytorch.org/docs/stable/_modules/torch/nn/modules/loss.html

.. math::
    \text{loss}(x, class) = weight[class] \left(-x[class] + \log\left(\sum_j \exp(x[j])\right)\right)

Only if I use my IDE to display the documentation, it renders the latex notation properly.

Is there any switch for displaying math on the website?


问:
Extract data from kCBAdvDataManufacturerData on Swift
I have a TI sensor Tag as a peripheral that broadcasts BLE data in the form of kCBAdvDataManufacturerData. I would like to extract different values from this data in iOS.

I am executing the following in Swift:

```<code>func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber){
     for (index, foundPeripheral) in peripherals.enumerated(){
         if foundPeripheral.peripheral?.identifier == peripheral.identifier{
             peripherals[index].lastRSSI = RSSI
             print("AdvertisementData:\(advertisementData)")
             return

         }
     }

     let isConnectable = advertisementData["kCBAdvDataIsConnectable"] as! Bool
     let displayPeripheral = DisplayPeripheral(peripheral: peripheral, lastRSSI: RSSI, isConnectable: isConnectable)
     peripherals.append(displayPeripheral)
     tableView.reloadData()
    }
}
</code>```

And this is what I see in the console:

AdvertisementData:["kCBAdvDataIsConnectable": 0, "kCBAdvDataManufacturerData": <0d00fe05 0c6f32>, "kCBAdvDataLocalName": CLIMBC]

The data that I am interested in decoding is  kCBAdvDataManufacturerData : <0d00fe05 0c6f32> and displaying each field on the screen.
Specifically, this is what the numbers represent in my case:

0d00 - TI manufacturer ID

fe - the node ID that I have given

05 - state of the node (something that remains constant

c6f - is the sensor tag battery voltage

32- is the BLE packet counter.

In Android I am able to decode as following:

```<code>private static String getNodeIdFromRawPacket(byte[] manufSpecField) {
    if(manufSpecField != null && manufSpecField.length > 1) {
        return String.format("%02X", manufSpecField[0]);
    }else{
        return null;
    }
}
private static int getNodeBatteryVoltageFromRawPacket(byte[] manufSpecField){
    if(manufSpecField != null && manufSpecField.length > 4) {
        return (((((int) manufSpecField[manufSpecField.length - 3]) << 24) >>> 24) << 8) + ((((int) manufSpecField[manufSpecField.length - 2]) << 24) >>> 24);
    }else{
        return 0;
    }
}

private byte[] extractManufacturerSpecificData(byte[] scanRecord, int manufacturer_id){

     if(scanRecord != null) {
         int ptr = 0;
         while (ptr < scanRecord.length && scanRecord[ptr] != 0) {
             int field_length = scanRecord[ptr];
             if (scanRecord[ptr + 1] == (byte) (0xFF)) { //this is true when the manufacturer specific data field has been found
                 if (((scanRecord[ptr + 3] << 8) + scanRecord[ptr + 2]) == manufacturer_id) {
                    byte[] manufacturerSpecificData = new byte[field_length - 3];
                     System.arraycopy(scanRecord, ptr + 4, manufacturerSpecificData, 0, field_length - 3);
                     return manufacturerSpecificData;
                 }
             }
             ptr += (field_length + 1);
         }
         return null;
     }else{
        return null;
     }
  }
};
</code>```

How exactly can I achieve this? I am new to Swift that is why I am finding some difficulties. Any code snippet will be most welcome.

答:
Updated for Swift:</p>

```<code>let yourServiceUUIDString = "FFF0"
if let mAdvData = advertisementData["kCBAdvDataServiceUUIDs"] as? [AnyObject], (mAdvData.contains { ($0 as? CBUUID)?.uuidString == yourServiceUUIDString}) {
    print("BLE device found..!")
}
</code>```

Body:
I have a TI sensor Tag as a peripheral that broadcasts BLE data in the form of kCBAdvDataManufacturerData. I would like to extract different values from this data in iOS.

I am executing the following in Swift:

func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber){
     for (index, foundPeripheral) in peripherals.enumerated(){
         if foundPeripheral.peripheral?.identifier == peripheral.identifier{
             peripherals[index].lastRSSI = RSSI
             print("AdvertisementData:\(advertisementData)")
             return

         }
     }

     let isConnectable = advertisementData["kCBAdvDataIsConnectable"] as! Bool
     let displayPeripheral = DisplayPeripheral(peripheral: peripheral, lastRSSI: RSSI, isConnectable: isConnectable)
     peripherals.append(displayPeripheral)
     tableView.reloadData()
    }
}

And this is what I see in the console:

AdvertisementData:["kCBAdvDataIsConnectable": 0, "kCBAdvDataManufacturerData": <0d00fe05 0c6f32>, "kCBAdvDataLocalName": CLIMBC]

The data that I am interested in decoding is  kCBAdvDataManufacturerData : <0d00fe05 0c6f32> and displaying each field on the screen.
Specifically, this is what the numbers represent in my case:

0d00 - TI manufacturer ID

fe - the node ID that I have given

05 - state of the node (something that remains constant

c6f - is the sensor tag battery voltage

32- is the BLE packet counter.

In Android I am able to decode as following:

private static String getNodeIdFromRawPacket(byte[] manufSpecField) {
    if(manufSpecField != null && manufSpecField.length > 1) {
        return String.format("%02X", manufSpecField[0]);
    }else{
        return null;
    }
}
private static int getNodeBatteryVoltageFromRawPacket(byte[] manufSpecField){
    if(manufSpecField != null && manufSpecField.length > 4) {
        return (((((int) manufSpecField[manufSpecField.length - 3]) << 24) >>> 24) << 8) + ((((int) manufSpecField[manufSpecField.length - 2]) << 24) >>> 24);
    }else{
        return 0;
    }
}

private byte[] extractManufacturerSpecificData(byte[] scanRecord, int manufacturer_id){

     if(scanRecord != null) {
         int ptr = 0;
         while (ptr < scanRecord.length && scanRecord[ptr] != 0) {
             int field_length = scanRecord[ptr];
             if (scanRecord[ptr + 1] == (byte) (0xFF)) { //this is true when the manufacturer specific data field has been found
                 if (((scanRecord[ptr + 3] << 8) + scanRecord[ptr + 2]) == manufacturer_id) {
                    byte[] manufacturerSpecificData = new byte[field_length - 3];
                     System.arraycopy(scanRecord, ptr + 4, manufacturerSpecificData, 0, field_length - 3);
                     return manufacturerSpecificData;
                 }
             }
             ptr += (field_length + 1);
         }
         return null;
     }else{
        return null;
     }
  }
};

How exactly can I achieve this? I am new to Swift that is why I am finding some difficulties. Any code snippet will be most welcome.

Body:
Updated for Swift:

let yourServiceUUIDString = "FFF0"
if let mAdvData = advertisementData["kCBAdvDataServiceUUIDs"] as? [AnyObject], (mAdvData.contains { ($0 as? CBUUID)?.uuidString == yourServiceUUIDString}) {
    print("BLE device found..!")
}


问:
Programmatically mounting a FAT32 filesystem with UTF8
How can I mount a FAT/FAT32 device using "mount()" function (from "mount.h", see "man 2 mount") in a way that it will be mounted UTF8?

This is the relevant code I use to mount it 'til now:

```<code>mount_result = mount(device_node, device_mount_point, fstype, MS_NOATIME, "");
</code>```

Thanks,
Nicola

答:
From the manpage:

The data argument is interpreted by the different file systems. Typically it is a string of comma-separated options understood by this file system.

And from the manpage of mount(8), "Mount options for vfat":

utf8 :
  UTF8 is the filesystem safe 8-bit encoding of Unicode that is used by the console. It can be be enabled for the filesystem with this option. If 'uni_xlate' gets set, UTF8 gets disabled.

Therefore, this should give you the desired behavior:

```<code>mount_result = mount(device_node, device_mount_point, fstype, MS_NOATIME, "utf8");
</code>```

Body:
How can I mount a FAT/FAT32 device using "mount()" function (from "mount.h", see "man 2 mount") in a way that it will be mounted UTF8?

This is the relevant code I use to mount it 'til now:

mount_result = mount(device_node, device_mount_point, fstype, MS_NOATIME, "");

Thanks,
Nicola

Body:
From the manpage:

The data argument is interpreted by the different file systems. Typically it is a string of comma-separated options understood by this file system.

And from the manpage of mount(8), "Mount options for vfat":

utf8 :
  UTF8 is the filesystem safe 8-bit encoding of Unicode that is used by the console. It can be be enabled for the filesystem with this option. If 'uni_xlate' gets set, UTF8 gets disabled.

Therefore, this should give you the desired behavior:

mount_result = mount(device_node, device_mount_point, fstype, MS_NOATIME, "utf8");


问:
LSTM network expects target at last layer to have 2 dimensions, but got array with shape (996, 1, 1)
I am trying to train an LSTM with keras using TensorFlow backend on toy data and am getting this error:

ValueError: Error when checking target: expected dense_39 to have 2 dimensions, but got array with shape (996, 1, 1)

The error occurs immediately upon calling model.fit; nothing seems to run. It seems to me that Keras is checking dimensions, but ignoring the fact that it should be taking batches of my target with each batch of my input. The error shows the full dimension of my target array, which implies to me that it's never split into batches by Keras, at least while checking dimensions. For the life of me I can't figure out why this would be or anything else that might help.

My network definition with expected layer output shapes in comments:

```<code>batch_shape = (8, 5, 1)
x_in = Input(batch_shape=batch_shape, name='input')  # (8, 5, 1)
seq1 = LSTM(8, return_sequences=True, stateful=True)(x_in)  # (8, 5, 8)
dense1 = TimeDistributed(Dense(8))(seq1)  # (8, 5, 8)
seq2 = LSTM(8, return_sequences=False, stateful=True)(dense1)  # (8, 8)
dense2 = Dense(8)(seq2)  # (8, 8)
out = Dense(1)(dense2)  # (8, 1)

model = Model(inputs=x_in, outputs=out)
optimizer = Nadam()
model.compile(optimizer=optimizer, loss='mean_squared_error')
model.summary()
</code>```

The model summary, shapes as expected:

```<code>_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input (InputLayer)           (8, 5, 1)                 0
_________________________________________________________________
lstm_28 (LSTM)               (8, 5, 8)                 320
_________________________________________________________________
time_distributed_18 (TimeDis (8, 5, 8)                 72
_________________________________________________________________
lstm_29 (LSTM)               (8, 8)                    544
_________________________________________________________________
dense_38 (Dense)             (8, 8)                    72
_________________________________________________________________
dense_39 (Dense)             (8, 1)                    9
=================================================================
Total params: 1,017
Trainable params: 1,017
Non-trainable params: 0
_________________________________________________________________
</code>```

My toy data, where the target is just a line decreasing from 100 to 0, and the input is just an array of zeros. I want to do one-step-ahead prediction, so I create rolling windows of my input and target using a rolling_window() method defined below:

```<code>target = np.linspace(100, 0, num=1000)
target_rolling = rolling_window(target[4:], 1)[:, :, None]
target_rolling.shape  # (996, 1, 1)  <-- this seems to be the array that's causing the error
x_train = np.zeros((1000,))
x_train_rolling = rolling_window(x_train, 5)[:, :, None]
x_train_rolling.shape  # (996, 5, 1)
</code>```

The rolling_window() method:

```<code>def rolling_window(arr, window):
    shape = arr.shape[:-1] + (arr.shape[-1] - window + 1, window)
    strides = arr.strides + (arr.strides[-1],)
    return np.lib.stride_tricks.as_strided(arr, shape=shape, strides=strides)
</code>```

And my training loop:

```<code>reset_state = LambdaCallback(on_epoch_end=lambda _, _: model.reset_states())
callbacks = [reset_state]
history = model.fit(x_train_rolling, y_train_rolling,
                    batch_size=8,
                    epochs=100,
                    validation_split=0.,
                    callbacks=callbacks)
</code>```

I have tried:

Non-stateful LSTM, but I really need stateful for the eventual application. Same error.

return_sequence=True in the second LSTM with a Flatten layer after. Same error.

return_sequence=True without a Flatten layer. This gives a different error because it is expecting a target with the same shape as the output, which at that point is (batch_size, 5, 1) and not (batch_size, 1, 1).

Running the same architecture on the whole sequence at once (batch size of 1), without rolling windows. This works, but just learns to approximate the mean of my target and is useless for my purposes.

Note that none of these questions seem to directly answer mine, although I was really hopeful on a couple:

Error when checking target: expected time_distributed_5 to have 3 dimensions, but got array with shape (14724, 1)

LSTM and CNN: ValueError: Error when checking target: expected time_distributed_1 to have 3 dimensions, but got array with shape (400, 256)

ValueError: Error when checking target: expected lstm_27 to have 2 dimensions, but got array with shape (1, 11, 1)

expected dense_218_input to have 2 dimensions, but got array with shape (512, 28, 28, 1)

expected dense_1 to have 2 dimensions, but got array with shape (308, 1, 6)

答:
Posting the solution I wrote in the comments:
Since there is an extra dimension, the "-1" makes the dimension self adjust to what ever number it has to be to fit the other dimensions.  Since only two dimensions are give, "(-1,1)" would make it "(996, 1)".

```<code>target_rolling = target_rolling.reshape(-1,1)
</code>```

before

```<code>at target_rolling.shape # (996, 1, 1)
</code>```

Body:
I am trying to train an LSTM with keras using TensorFlow backend on toy data and am getting this error:

ValueError: Error when checking target: expected dense_39 to have 2 dimensions, but got array with shape (996, 1, 1)

The error occurs immediately upon calling model.fit; nothing seems to run. It seems to me that Keras is checking dimensions, but ignoring the fact that it should be taking batches of my target with each batch of my input. The error shows the full dimension of my target array, which implies to me that it's never split into batches by Keras, at least while checking dimensions. For the life of me I can't figure out why this would be or anything else that might help.

My network definition with expected layer output shapes in comments:

batch_shape = (8, 5, 1)
x_in = Input(batch_shape=batch_shape, name='input')  # (8, 5, 1)
seq1 = LSTM(8, return_sequences=True, stateful=True)(x_in)  # (8, 5, 8)
dense1 = TimeDistributed(Dense(8))(seq1)  # (8, 5, 8)
seq2 = LSTM(8, return_sequences=False, stateful=True)(dense1)  # (8, 8)
dense2 = Dense(8)(seq2)  # (8, 8)
out = Dense(1)(dense2)  # (8, 1)

model = Model(inputs=x_in, outputs=out)
optimizer = Nadam()
model.compile(optimizer=optimizer, loss='mean_squared_error')
model.summary()

The model summary, shapes as expected:

_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input (InputLayer)           (8, 5, 1)                 0
_________________________________________________________________
lstm_28 (LSTM)               (8, 5, 8)                 320
_________________________________________________________________
time_distributed_18 (TimeDis (8, 5, 8)                 72
_________________________________________________________________
lstm_29 (LSTM)               (8, 8)                    544
_________________________________________________________________
dense_38 (Dense)             (8, 8)                    72
_________________________________________________________________
dense_39 (Dense)             (8, 1)                    9
=================================================================
Total params: 1,017
Trainable params: 1,017
Non-trainable params: 0
_________________________________________________________________

My toy data, where the target is just a line decreasing from 100 to 0, and the input is just an array of zeros. I want to do one-step-ahead prediction, so I create rolling windows of my input and target using a rolling_window() method defined below:

target = np.linspace(100, 0, num=1000)
target_rolling = rolling_window(target[4:], 1)[:, :, None]
target_rolling.shape  # (996, 1, 1)  <-- this seems to be the array that's causing the error
x_train = np.zeros((1000,))
x_train_rolling = rolling_window(x_train, 5)[:, :, None]
x_train_rolling.shape  # (996, 5, 1)

The rolling_window() method:

def rolling_window(arr, window):
    shape = arr.shape[:-1] + (arr.shape[-1] - window + 1, window)
    strides = arr.strides + (arr.strides[-1],)
    return np.lib.stride_tricks.as_strided(arr, shape=shape, strides=strides)

And my training loop:

reset_state = LambdaCallback(on_epoch_end=lambda _, _: model.reset_states())
callbacks = [reset_state]
history = model.fit(x_train_rolling, y_train_rolling,
                    batch_size=8,
                    epochs=100,
                    validation_split=0.,
                    callbacks=callbacks)

I have tried:

Non-stateful LSTM, but I really need stateful for the eventual application. Same error.

return_sequence=True in the second LSTM with a Flatten layer after. Same error.

return_sequence=True without a Flatten layer. This gives a different error because it is expecting a target with the same shape as the output, which at that point is (batch_size, 5, 1) and not (batch_size, 1, 1).

Running the same architecture on the whole sequence at once (batch size of 1), without rolling windows. This works, but just learns to approximate the mean of my target and is useless for my purposes.

Note that none of these questions seem to directly answer mine, although I was really hopeful on a couple:

Error when checking target: expected time_distributed_5 to have 3 dimensions, but got array with shape (14724, 1)

LSTM and CNN: ValueError: Error when checking target: expected time_distributed_1 to have 3 dimensions, but got array with shape (400, 256)

ValueError: Error when checking target: expected lstm_27 to have 2 dimensions, but got array with shape (1, 11, 1)

expected dense_218_input to have 2 dimensions, but got array with shape (512, 28, 28, 1)

expected dense_1 to have 2 dimensions, but got array with shape (308, 1, 6)

Body:
Posting the solution I wrote in the comments:
Since there is an extra dimension, the "-1" makes the dimension self adjust to what ever number it has to be to fit the other dimensions.  Since only two dimensions are give, "(-1,1)" would make it "(996, 1)".

target_rolling = target_rolling.reshape(-1,1)

before

at target_rolling.shape # (996, 1, 1)


问:
How to fix Facebook integration with firebase and googleMobile Plugin
Stuck with the facebook unity plugin integration. I have been working on it since yesterday and did not find any workaround.

I am using facebook-unity-sdk-7.15.1 although I have also tried the previous version of facebook plugin that didn't work as well.

I am building a gradle build.
My project includes the following plugins
FireBase-6.0.0
GoogleMobileAds-7.41
GooglePlayGamesPlugin-0.9.64

Every time Build failed with an error which is:

System.NullReferenceException: Object reference not set to an instance
  of an object   at Google.VersionHandler.InvokeMethod (System.Type
  type, System.Object objectInstance, System.String methodName,
  System.Object[] args,
  System.Collections.Generic.Dictionary2[TKey,TValue] namedArgs)
  [0x00054] in
  Z:\tmp\tmp.7eOCFUaXh7\third_party\unity\unity_jar_resolver\source\VersionHandler\src\VersionHandler.cs:506
  at Google.VersionHandler.InvokeStaticMethod (System.Type type,
  System.String methodName, System.Object[] args,
  System.Collections.Generic.Dictionary`2[TKey,TValue] namedArgs)
  [0x00000] in
  Z:\tmp\tmp.7eOCFUaXh7\third_party\unity\unity_jar_resolver\source\VersionHandler\src\VersionHandler.cs:481
  at
  Facebook.Unity.Editor.AndroidSupportLibraryResolver.setupDependencies
  () [0x00034] in <1e648b4081db4625b06f95d668cd2dd4>:0    at
  Facebook.Unity.Editor.AndroidSupportLibraryResolver..cctor ()
  [0x00000] in <1e648b4081db4625b06f95d668cd2dd4>:0
  UnityEditor.EditorAssemblies:ProcessInitializeOnLoadAttributes()

答:
i have fixed this problem couple of days ago.There was some missing files of facebook. Just paste these following file in plugin and  we are all set to go.

```<code>com.android.support.animated-vector-drawable-25.3.1.aar
com.android.support.appcompat-v7-25.3.1.aar
com.android.support.cardview-v7-25.3.1.aar
com.android.support.support-vector-drawable-25.3.1.a
</code>```

rr

Body:
i have fixed this problem couple of days ago.There was some missing files of facebook. Just paste these following file in plugin and  we are all set to go.

com.android.support.animated-vector-drawable-25.3.1.aar
com.android.support.appcompat-v7-25.3.1.aar
com.android.support.cardview-v7-25.3.1.aar
com.android.support.support-vector-drawable-25.3.1.a

rr


问:
In the same search box search by multiple array object properties
```<code>searchTerm: any;

search() {

      this.records = this.records.filter((res: any)=>{
        return res.name.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase());
      });

  }
</code>```

I am making the search term with name which is the property or key in records array. In the same search box I also want to search by age and course.
How can I achieve this.

```<code><input type ="text" placeholder="search" (input)=" search();" [(ngModel)]="searchTerm">
</code>```

答:
Just expand you're search filter to include your extra criteria:

```<code>search() {
      this.records = this.records.filter((res: any)=>{
        return (res.name && res.name.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase())) ||
        (res.course && res.course.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase())) ||
        (res.age && res.age.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase())) ;
      });
  }
</code>```

This assumes that both course and age are strings in the records array.

Body:
searchTerm: any;

search() {

      this.records = this.records.filter((res: any)=>{
        return res.name.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase());
      });

  }

I am making the search term with name which is the property or key in records array. In the same search box I also want to search by age and course.
How can I achieve this.

<input type ="text" placeholder="search" (input)=" search();" [(ngModel)]="searchTerm">

Body:
Just expand you're search filter to include your extra criteria:

search() {
      this.records = this.records.filter((res: any)=>{
        return (res.name && res.name.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase())) ||
        (res.course && res.course.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase())) ||
        (res.age && res.age.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase())) ;
      });
  }

This assumes that both course and age are strings in the records array.


问:
How can i fix the dropdown menu when i scroll down on phone it goes away
On Windows small screen it works but on phone it goes away, I tried so many things but I can't find something to fix, or way to go around.

https://meedia-testomgeving.nu/index.html

I have followed a guides. and some youtube video's but it didnt work. About navigation menu. I don't know what kind of code I used it some time ago.

HTML

```<code><!doctype html>
<html>
<header>
<nav id="cssmenu">
<div class="logo"><img src="Meedia Producten PC & Hardware/Background/Home Page&Favicon&Footer/Meedia LOGO.png"></div>
<div id="head-mobile"></div>
<div class="button-nav"></div>
<ul>
<li class="active"><a href="index.html">HOME</a></li>
<li><a href="Over ons.html">OVER ONS</a>
   <ul>
       <li><a href="Voor Ouders.html" target="">Voor Ouders</a></li>
         <ul>
         </ul>
      </li>
             <li><a href="Voor Hulpverleners.html" target="">Voor Hulpverleners</a></li>
         <ul>
         </ul>
       </li>
   </ul>
</li>
<li><a href="Meedoen met meedia.html">MEEDOEN MET MEEDIA</a>
   <ul>
       <li><a href="ICT & Multimedia.html" target="">ICT & Multimedia</a></li>
         <ul>
         </ul>
      </li>
           <li><a href="Fashion & Lifestyle.html" target="">Fashion & Lifestyle</a></li>
         <ul>
         </ul>
      </li>

             <li><a href="Onderwijs Ondersteuning.html" target="">Onderwijs Ondersteuning</a></li>
         <ul>
         </ul>
       </li>
   </ul>
</li>
<li><a href="Producten.html">PRODUCTEN</a>
   <ul>
      <li><a href="PC & Hardware.html" target="">PC & Hardware</a>
         <ul>
            <li><a href="Meedia Market PC.html" target="_blank">PC</a></li>
            <li><a href="Meedia Market Laptop.html" target="_blank">Laptop</a></li>
            <li><a href="Meedia Market Monitoren.html" target="_blank">Monitoren</a></li>
            <li><a href="Meedia Market Randapparatuur.html" target="_blank">Randapparatuur</a></li>
            <li><a href="Meedia Market Hardware.html" target="_blank">Hardware</a></li>
            <li><a href="Meedia Market Onderdelen.html" target="_blank">Onderdelen</a></li>
            <li><a href="Meedia Market Netwerk.html" target="_blank">Netwerk</a></li>
            <li><a href="Meedia Market Printers.html" target="_blank">Printers</a></li>
         </ul>
      </li>
      <li><a href="Market Fashion & Lifestyle.html">Fashion & LifeStyle</a>
         <ul>
            <li><a href="Meedia Market Kasten.html" target="_blank">Kasten</a></li>
            <li><a href="Meedia Market Lampen.html" target="_blank">Lampen</a></li>
            <li><a href="Meedia Market Manden.html" target="_blank">Manden</a></li>
            <li><a href="Meedia Market Stoelen.html" target="_blank">Stoelen</a></li>
            <li><a href="Meedia Market Iets aan de wand.html" target="_blank">iets aan de Wand</a></li>
            <li><a href="Meedia Market sign borden.html" target="_blank">Sign Borden</a></li>
            <li><a href="Meedia Market Boekjes.html" target="_blank">Boekjes</a></li>
            <li><a href="Meedia Market Kleding.html" target="_blank">Kleding</a></li>
         </ul>
       </li>
   </ul>
</li>
<li><a href="Nieuws.html" target="">NIEUWS</a></li>
<li><a href="Foto's.html" target="">FOTO'S</a></li>
<li><a href="Contact.html">CONTACT</a>

  <ul>
       <li><a href="Contactformulier.html" target="">Contactformulier</a></li>
         <ul>
         </ul>
      </li>
         <ul>
         </ul>
      </li>
</ul>
</nav>

</header>
</code>```

CSS

```<code>*{margin:0;padding:0;text-decoration:none}
body{background:url(Images/.jpg)}
header{position:relative;width:100%;background:#333;}
.logo{position:relative;z-index:123;padding:10px;font:18px verdana;color:#31a3dd;float:left;width:19%}
.logo a{color:#31a3dd;}
nav{position:relative;width:1010px;margin:0 auto;}
#cssmenu,#cssmenu ul,#cssmenu ul li,#cssmenu ul li a,#cssmenu #head-mobile{border:0;list-style:none;line-height:1;display:block;position:relative;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}
#cssmenu:after,#cssmenu > ul:after{content:".";display:block;clear:both;visibility:hidden;line-height:0;height:0}
#cssmenu #head-mobile{display:none}
#cssmenu{font-family:sans-serif;background:#333}
#cssmenu > ul > li{float:left}
#cssmenu > ul > li > a{padding:17px;font-size:12px;letter-spacing:1px;text-decoration:none;color:#FFFFFF;font-weight:700;}
#cssmenu > ul > li:hover > a,#cssmenu ul li.active a{color:#fff}
#cssmenu > ul > li:hover,#cssmenu ul li.active:hover,#cssmenu ul li.active,#cssmenu ul li.has-sub.active:hover{background:#31a3dd!important;-webkit-transition:background .3s ease;-ms-transition:background .3s ease;transition:background .3s ease;}
#cssmenu > ul > li.has-sub > a{padding-right:30px}
#cssmenu > ul > li.has-sub > a:after{position:absolute;top:22px;right:11px;width:8px;height:2px;display:block;background:#ffffff;content:''}
#cssmenu > ul > li.has-sub > a:before{position:absolute;top:19px;right:14px;display:block;width:2px;height:8px;background:#ffffff;content:'';-webkit-transition:all .25s ease;-ms-transition:all .25s ease;transition:all .25s ease}
#cssmenu > ul > li.has-sub:hover > a:before{top:23px;height:0}
#cssmenu ul ul{position:absolute;left:-9999px}
#cssmenu ul ul li{height:0;-webkit-transition:all .25s ease;-ms-transition:all .25s ease;background:#333;transition:all .25s ease}
#cssmenu ul ul li:hover{}
#cssmenu li:hover > ul{left:auto}
#cssmenu li:hover > ul > li{height:35px}
#cssmenu ul ul ul{margin-left:100%;top:0}
#cssmenu ul ul li a{border-bottom:1px solid rgba(150,150,150,0.15);padding:11px 15px;width:170px;font-size:12px;text-decoration:none;color:#FFFFFF;font-weight:400;}
#cssmenu ul ul li:last-child > a,#cssmenu ul ul li.last-item > a{border-bottom:0}
#cssmenu ul ul li:hover > a,#cssmenu ul ul li a:hover{color:#fff}
#cssmenu ul ul li.has-sub > a:after{position:absolute;top:16px;right:11px;width:8px;height:2px;display:block;background:#ffffff;content:''}
#cssmenu ul ul li.has-sub > a:before{position:absolute;top:13px;right:14px;display:block;width:2px;height:8px;background:#ffffff;content:'';-webkit-transition:all .25s ease;-ms-transition:all .25s ease;transition:all .25s ease}
#cssmenu ul ul > li.has-sub:hover > a:before{top:17px;height:0}
#cssmenu ul ul li.has-sub:hover,#cssmenu ul li.has-sub ul li.has-sub ul li:hover{background:#363636;}
#cssmenu ul ul ul li.active a{border-left:1px solid #333}
#cssmenu > ul > li.has-sub > ul > li.active > a,#cssmenu > ul ul > li.has-sub > ul > li.active> a{border-top:1px solid #333}

@media screen and (max-width:1000px){
.logo{position:absolute;top:0;left: 0;width:100%;height:46px;text-align:center;padding:10px 0 0 0 ;float:none}
.logo2{display:none}
nav{width:100%;}
#cssmenu{width:100%}
#cssmenu ul{width:100%;display:none}
#cssmenu ul li{width:100%;border-top:1px solid #444}
#cssmenu ul li:hover{background:#363636;}
#cssmenu ul ul li,#cssmenu li:hover > ul > li{height:auto}
#cssmenu ul li a,#cssmenu ul ul li a{width:100%;border-bottom:0}
#cssmenu > ul > li{float:none}
#cssmenu ul ul li a{padding-left:25px}
#cssmenu ul ul li{background:#333!important;}
#cssmenu ul ul li:hover{background:#363636!important}
#cssmenu ul ul ul li a{padding-left:35px}
#cssmenu ul ul li a{color:#FFFFFF;background:none}
#cssmenu ul ul li:hover > a,#cssmenu ul ul li.active > a{color:#fff}
#cssmenu ul ul,#cssmenu ul ul ul{position:relative;left:0;width:100%;margin:0;text-align:left}
#cssmenu > ul > li.has-sub > a:after,#cssmenu > ul > li.has-sub > a:before,#cssmenu ul ul > li.has-sub > a:after,#cssmenu ul ul > li.has-sub > a:before{display:none}
#cssmenu #head-mobile{display:block;padding:23px;color:#FFFFFF;font-size:12px;font-weight:700}
.button-nav{width:55px;height:46px;position:absolute;right:0;top:0;cursor:pointer;z-index: 12399994;}
.button-nav:after{position:absolute;top:22px;right:20px;display:block;height:4px;width:20px;border-top:2px solid #FFFFFF;border-bottom:2px solid #FFFFFF;content:''}
.button-nav:before{-webkit-transition:all .3s ease;-ms-transition:all .3s ease;transition:all .3s ease;position:absolute;top:16px;right:20px;display:block;height:2px;width:20px;background:#FFFFFF;content:''}
.button-nav.menu-opened:after{-webkit-transition:all .3s ease;-ms-transition:all .3s ease;transition:all .3s ease;top:23px;border:0;height:2px;width:19px;background:#fff;-webkit-transform:rotate(45deg);-moz-transform:rotate(45deg);-ms-transform:rotate(45deg);-o-transform:rotate(45deg);transform:rotate(45deg)}
.button-nav.menu-opened:before{top:23px;background:#fff;width:19px;-webkit-transform:rotate(-45deg);-moz-transform:rotate(-45deg);-ms-transform:rotate(-45deg);-o-transform:rotate(-45deg);transform:rotate(-45deg)}
#cssmenu .submenu-button-nav{position:absolute;z-index:99;right:0;top:0;display:block;border-left:1px solid #444;height:46px;width:46px;cursor:pointer}
#cssmenu .submenu-button-nav.submenu-opened{background:#262626}
#cssmenu ul ul .submenu-button-nav{height:34px;width:34px}
#cssmenu .submenu-button-nav:after{position:absolute;top:22px;right:19px;width:8px;height:2px;display:block;background:#FFFFFF;content:''}
#cssmenu ul ul .submenu-button-nav:after{top:15px;right:13px}
#cssmenu .submenu-button-nav.submenu-opened:after{background:#fff}
#cssmenu .submenu-button-nav:before{position:absolute;top:19px;right:22px;display:block;width:2px;height:8px;background:#FFFFFF;content:''}
#cssmenu ul ul .submenu-button-nav:before{top:12px;right:16px}
#cssmenu .submenu-button-nav.submenu-opened:before{display:none}
#cssmenu ul ul ul li.active a{border-left:none}
#cssmenu > ul > li.has-sub > ul > li.active > a,#cssmenu > ul ul > li.has-sub > ul > li.active > a{border-top:none}
}

#cssmenu{
z-index: 1000;
position:relative;
}

#cssmnu {
  opacity: 1.1;
}
</code>```

JQuery

```<code>(function($) {
$.fn.menumaker = function(options) {
 var cssmenu = $(this), settings = $.extend({
   format: "dropdown",
   sticky: false
 }, options);
 return this.each(function() {
   $(this).find(".button-nav").on('click', function(){
     $(this).toggleClass('menu-opened');
     var mainmenu = $(this).next('ul');
     if (mainmenu.hasClass('open')) {
       mainmenu.slideToggle().removeClass('open');
     }
     else {
       mainmenu.slideToggle().addClass('open');
       if (settings.format === "dropdown") {
         mainmenu.find('ul').show();
       }
     }
   });
   cssmenu.find('li ul').parent().addClass('has-sub');
multiTg = function() {
     cssmenu.find(".has-sub").prepend('<span class="submenu-button-nav"></span>');
     cssmenu.find('.submenu-button-nav').on('click', function() {
       $(this).toggleClass('submenu-opened');
       if ($(this).siblings('ul').hasClass('open')) {
         $(this).siblings('ul').removeClass('open').slideToggle();
       }
       else {
         $(this).siblings('ul').addClass('open').slideToggle();
       }
     });
   };
   if (settings.format === 'multitoggle') multiTg();
   else cssmenu.addClass('dropdown');
   if (settings.sticky === true) cssmenu.css('position', 'fixed');
resizeFix = function() {
  var mediasize = 1000;
     if ($( window ).width() > mediasize) {
       cssmenu.find('ul').show();
     }
     if ($(window).width() <= mediasize) {
       cssmenu.find('ul').hide().removeClass('open');
     }
   };
   resizeFix();
   return $(window).on('resize', resizeFix);
 });
  };
})(jQuery);

(function($){
$(document).ready(function(){
$("#cssmenu").menumaker({
   format: "multitoggle"
});
});
})(jQuery);

</code>```

Thanks already

答:
Add This CSS</p>

```<code>@media screen and (max-width:1000px)
    #cssmenu {
        z-index: 1000;
        position: fixed;
    }
}
</code>```

Body:
On Windows small screen it works but on phone it goes away, I tried so many things but I can't find something to fix, or way to go around.

https://meedia-testomgeving.nu/index.html

I have followed a guides. and some youtube video's but it didnt work. About navigation menu. I don't know what kind of code I used it some time ago.

HTML

<!doctype html>

HOME

OVER ONS

Voor Ouders

Voor Hulpverleners

MEEDOEN MET MEEDIA

ICT & Multimedia

Fashion & Lifestyle

Onderwijs Ondersteuning

PRODUCTEN

PC & Hardware

PC

Laptop

Monitoren

Randapparatuur

Hardware

Onderdelen

Netwerk

Printers

Fashion & LifeStyle

Kasten

Lampen

Manden

Stoelen

iets aan de Wand

Sign Borden

Boekjes

Kleding

NIEUWS

FOTO'S

CONTACT

Contactformulier

CSS

*{margin:0;padding:0;text-decoration:none}
body{background:url(Images/.jpg)}
header{position:relative;width:100%;background:#333;}
.logo{position:relative;z-index:123;padding:10px;font:18px verdana;color:#31a3dd;float:left;width:19%}
.logo a{color:#31a3dd;}
nav{position:relative;width:1010px;margin:0 auto;}
#cssmenu,#cssmenu ul,#cssmenu ul li,#cssmenu ul li a,#cssmenu #head-mobile{border:0;list-style:none;line-height:1;display:block;position:relative;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}
#cssmenu:after,#cssmenu > ul:after{content:".";display:block;clear:both;visibility:hidden;line-height:0;height:0}
#cssmenu #head-mobile{display:none}
#cssmenu{font-family:sans-serif;background:#333}
#cssmenu > ul > li{float:left}
#cssmenu > ul > li > a{padding:17px;font-size:12px;letter-spacing:1px;text-decoration:none;color:#FFFFFF;font-weight:700;}
#cssmenu > ul > li:hover > a,#cssmenu ul li.active a{color:#fff}
#cssmenu > ul > li:hover,#cssmenu ul li.active:hover,#cssmenu ul li.active,#cssmenu ul li.has-sub.active:hover{background:#31a3dd!important;-webkit-transition:background .3s ease;-ms-transition:background .3s ease;transition:background .3s ease;}
#cssmenu > ul > li.has-sub > a{padding-right:30px}
#cssmenu > ul > li.has-sub > a:after{position:absolute;top:22px;right:11px;width:8px;height:2px;display:block;background:#ffffff;content:''}
#cssmenu > ul > li.has-sub > a:before{position:absolute;top:19px;right:14px;display:block;width:2px;height:8px;background:#ffffff;content:'';-webkit-transition:all .25s ease;-ms-transition:all .25s ease;transition:all .25s ease}
#cssmenu > ul > li.has-sub:hover > a:before{top:23px;height:0}
#cssmenu ul ul{position:absolute;left:-9999px}
#cssmenu ul ul li{height:0;-webkit-transition:all .25s ease;-ms-transition:all .25s ease;background:#333;transition:all .25s ease}
#cssmenu ul ul li:hover{}
#cssmenu li:hover > ul{left:auto}
#cssmenu li:hover > ul > li{height:35px}
#cssmenu ul ul ul{margin-left:100%;top:0}
#cssmenu ul ul li a{border-bottom:1px solid rgba(150,150,150,0.15);padding:11px 15px;width:170px;font-size:12px;text-decoration:none;color:#FFFFFF;font-weight:400;}
#cssmenu ul ul li:last-child > a,#cssmenu ul ul li.last-item > a{border-bottom:0}
#cssmenu ul ul li:hover > a,#cssmenu ul ul li a:hover{color:#fff}
#cssmenu ul ul li.has-sub > a:after{position:absolute;top:16px;right:11px;width:8px;height:2px;display:block;background:#ffffff;content:''}
#cssmenu ul ul li.has-sub > a:before{position:absolute;top:13px;right:14px;display:block;width:2px;height:8px;background:#ffffff;content:'';-webkit-transition:all .25s ease;-ms-transition:all .25s ease;transition:all .25s ease}
#cssmenu ul ul > li.has-sub:hover > a:before{top:17px;height:0}
#cssmenu ul ul li.has-sub:hover,#cssmenu ul li.has-sub ul li.has-sub ul li:hover{background:#363636;}
#cssmenu ul ul ul li.active a{border-left:1px solid #333}
#cssmenu > ul > li.has-sub > ul > li.active > a,#cssmenu > ul ul > li.has-sub > ul > li.active> a{border-top:1px solid #333}

@media screen and (max-width:1000px){
.logo{position:absolute;top:0;left: 0;width:100%;height:46px;text-align:center;padding:10px 0 0 0 ;float:none}
.logo2{display:none}
nav{width:100%;}
#cssmenu{width:100%}
#cssmenu ul{width:100%;display:none}
#cssmenu ul li{width:100%;border-top:1px solid #444}
#cssmenu ul li:hover{background:#363636;}
#cssmenu ul ul li,#cssmenu li:hover > ul > li{height:auto}
#cssmenu ul li a,#cssmenu ul ul li a{width:100%;border-bottom:0}
#cssmenu > ul > li{float:none}
#cssmenu ul ul li a{padding-left:25px}
#cssmenu ul ul li{background:#333!important;}
#cssmenu ul ul li:hover{background:#363636!important}
#cssmenu ul ul ul li a{padding-left:35px}
#cssmenu ul ul li a{color:#FFFFFF;background:none}
#cssmenu ul ul li:hover > a,#cssmenu ul ul li.active > a{color:#fff}
#cssmenu ul ul,#cssmenu ul ul ul{position:relative;left:0;width:100%;margin:0;text-align:left}
#cssmenu > ul > li.has-sub > a:after,#cssmenu > ul > li.has-sub > a:before,#cssmenu ul ul > li.has-sub > a:after,#cssmenu ul ul > li.has-sub > a:before{display:none}
#cssmenu #head-mobile{display:block;padding:23px;color:#FFFFFF;font-size:12px;font-weight:700}
.button-nav{width:55px;height:46px;position:absolute;right:0;top:0;cursor:pointer;z-index: 12399994;}
.button-nav:after{position:absolute;top:22px;right:20px;display:block;height:4px;width:20px;border-top:2px solid #FFFFFF;border-bottom:2px solid #FFFFFF;content:''}
.button-nav:before{-webkit-transition:all .3s ease;-ms-transition:all .3s ease;transition:all .3s ease;position:absolute;top:16px;right:20px;display:block;height:2px;width:20px;background:#FFFFFF;content:''}
.button-nav.menu-opened:after{-webkit-transition:all .3s ease;-ms-transition:all .3s ease;transition:all .3s ease;top:23px;border:0;height:2px;width:19px;background:#fff;-webkit-transform:rotate(45deg);-moz-transform:rotate(45deg);-ms-transform:rotate(45deg);-o-transform:rotate(45deg);transform:rotate(45deg)}
.button-nav.menu-opened:before{top:23px;background:#fff;width:19px;-webkit-transform:rotate(-45deg);-moz-transform:rotate(-45deg);-ms-transform:rotate(-45deg);-o-transform:rotate(-45deg);transform:rotate(-45deg)}
#cssmenu .submenu-button-nav{position:absolute;z-index:99;right:0;top:0;display:block;border-left:1px solid #444;height:46px;width:46px;cursor:pointer}
#cssmenu .submenu-button-nav.submenu-opened{background:#262626}
#cssmenu ul ul .submenu-button-nav{height:34px;width:34px}
#cssmenu .submenu-button-nav:after{position:absolute;top:22px;right:19px;width:8px;height:2px;display:block;background:#FFFFFF;content:''}
#cssmenu ul ul .submenu-button-nav:after{top:15px;right:13px}
#cssmenu .submenu-button-nav.submenu-opened:after{background:#fff}
#cssmenu .submenu-button-nav:before{position:absolute;top:19px;right:22px;display:block;width:2px;height:8px;background:#FFFFFF;content:''}
#cssmenu ul ul .submenu-button-nav:before{top:12px;right:16px}
#cssmenu .submenu-button-nav.submenu-opened:before{display:none}
#cssmenu ul ul ul li.active a{border-left:none}
#cssmenu > ul > li.has-sub > ul > li.active > a,#cssmenu > ul ul > li.has-sub > ul > li.active > a{border-top:none}
}

#cssmenu{
z-index: 1000;
position:relative;
}

#cssmnu {
  opacity: 1.1;
}

JQuery

(function($) {
$.fn.menumaker = function(options) {
 var cssmenu = $(this), settings = $.extend({
   format: "dropdown",
   sticky: false
 }, options);
 return this.each(function() {
   $(this).find(".button-nav").on('click', function(){
     $(this).toggleClass('menu-opened');
     var mainmenu = $(this).next('ul');
     if (mainmenu.hasClass('open')) {
       mainmenu.slideToggle().removeClass('open');
     }
     else {
       mainmenu.slideToggle().addClass('open');
       if (settings.format === "dropdown") {
         mainmenu.find('ul').show();
       }
     }
   });
   cssmenu.find('li ul').parent().addClass('has-sub');
multiTg = function() {
     cssmenu.find(".has-sub").prepend('');
     cssmenu.find('.submenu-button-nav').on('click', function() {
       $(this).toggleClass('submenu-opened');
       if ($(this).siblings('ul').hasClass('open')) {
         $(this).siblings('ul').removeClass('open').slideToggle();
       }
       else {
         $(this).siblings('ul').addClass('open').slideToggle();
       }
     });
   };
   if (settings.format === 'multitoggle') multiTg();
   else cssmenu.addClass('dropdown');
   if (settings.sticky === true) cssmenu.css('position', 'fixed');
resizeFix = function() {
  var mediasize = 1000;
     if ($( window ).width() > mediasize) {
       cssmenu.find('ul').show();
     }
     if ($(window).width() <= mediasize) {
       cssmenu.find('ul').hide().removeClass('open');
     }
   };
   resizeFix();
   return $(window).on('resize', resizeFix);
 });
  };
})(jQuery);

(function($){
$(document).ready(function(){
$("#cssmenu").menumaker({
   format: "multitoggle"
});
});
})(jQuery);

Thanks already

Body:
Add This CSS

@media screen and (max-width:1000px)
    #cssmenu {
        z-index: 1000;
        position: fixed;
    }
}


问:
EXC_BAD_ACCESS issue on iphone and simulator
I am getting an EXC_BAD_ACCESS out side of my own code. Currently my code gets a URL through a shareURLCache object and then starts url connection. Once I leave the method that starts the url connection I hit the EXC_BAD_ACCESS. I have tried using instruments to find any zombies and I have analysed for memory leaks and not turned up either. At this point I am completely stuck.

Here is the code that loads the url and starts the url connection

```<code>- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
       fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"At new location: %@",newLocation);

    MKCoordinateRegion region =
            MKCoordinateRegionMakeWithDistance([newLocation coordinate], 750, 750);

    [mapView setRegion:region animated:YES];
    [location stopUpdatingLocation];

    CLLocationCoordinate2D coord = [newLocation coordinate];
    NSURL *url = [urlCache getReccomendationForUID:@"12345" atLat:coord.latitude
                                         atLon:coord.longitude forCategories:nil];

    // Create the request.
    NSURLRequest *request = [NSURLRequest requestWithURL:url
                                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                                     timeoutInterval:60.0];

// create the connection with the request
// and start loading the data
    connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
    if (connection) {
        // Create the NSMutableData to hold the received data.
        // xmlData is an instance variable declared elsewhere.
        xmlData = [[NSMutableData alloc]init];
    } else {
        NSLog(@"Could not create connection");
    }
}
</code>```

Method from the sharedURLCache that returns the url

```<code>-(NSURL *)getReccomendationForUID:(NSString *)u atLat:(double)lat atLon:(double)lon forCategories:(NSArray *)cat
{
    if(remote) {
        NSMutableString *categories = [[NSMutableString alloc]init];
        for(NSString *s in cat) {
            [categories appendString:@"&cat="];
            [categories appendString:s];
        }
        NSString *s = [NSString stringWithFormat:@"%@/recommendation?uid=%@&psw=null&lat=%f&lon=%f?%@",
                   apiRoot,u,lat,lon,categories];
        [categories release];
        return [NSURL URLWithString:s];
    } else {
        return [[NSBundle mainBundle] URLForResource:@"XMLTest" withExtension:@"xml"];;
    }
}
</code>```

答:
Just start by commenting out code and running to see if you can get the mem error to disappear then start adding code again until it appears, then you have a better idea where the issue is. it could be anywhere in your code since you seem to have a number of objects in there that are not passed in e.g. 'location'.</p>

```<code>[location stopUpdatingLocation];
</code>```

Body:
I am getting an EXC_BAD_ACCESS out side of my own code. Currently my code gets a URL through a shareURLCache object and then starts url connection. Once I leave the method that starts the url connection I hit the EXC_BAD_ACCESS. I have tried using instruments to find any zombies and I have analysed for memory leaks and not turned up either. At this point I am completely stuck.

Here is the code that loads the url and starts the url connection

- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
       fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"At new location: %@",newLocation);

    MKCoordinateRegion region =
            MKCoordinateRegionMakeWithDistance([newLocation coordinate], 750, 750);

    [mapView setRegion:region animated:YES];
    [location stopUpdatingLocation];

    CLLocationCoordinate2D coord = [newLocation coordinate];
    NSURL *url = [urlCache getReccomendationForUID:@"12345" atLat:coord.latitude
                                         atLon:coord.longitude forCategories:nil];

    // Create the request.
    NSURLRequest *request = [NSURLRequest requestWithURL:url
                                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                                     timeoutInterval:60.0];

// create the connection with the request
// and start loading the data
    connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
    if (connection) {
        // Create the NSMutableData to hold the received data.
        // xmlData is an instance variable declared elsewhere.
        xmlData = [[NSMutableData alloc]init];
    } else {
        NSLog(@"Could not create connection");
    }
}

Method from the sharedURLCache that returns the url

-(NSURL *)getReccomendationForUID:(NSString *)u atLat:(double)lat atLon:(double)lon forCategories:(NSArray *)cat
{
    if(remote) {
        NSMutableString *categories = [[NSMutableString alloc]init];
        for(NSString *s in cat) {
            [categories appendString:@"&cat="];
            [categories appendString:s];
        }
        NSString *s = [NSString stringWithFormat:@"%@/recommendation?uid=%@&psw=null&lat=%f&lon=%f?%@",
                   apiRoot,u,lat,lon,categories];
        [categories release];
        return [NSURL URLWithString:s];
    } else {
        return [[NSBundle mainBundle] URLForResource:@"XMLTest" withExtension:@"xml"];;
    }
}

Body:
Just start by commenting out code and running to see if you can get the mem error to disappear then start adding code again until it appears, then you have a better idea where the issue is. it could be anywhere in your code since you seem to have a number of objects in there that are not passed in e.g. 'location'.

[location stopUpdatingLocation];


答:
You can try using || operator with the same return statement as below :</p>

```<code>this.records = this.records.filter((res: any)=>{
        return (res.name.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase()) || res.age.match(this.searchTerm) || res.course.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase()));
});
</code>```

Title: In the same search box search by multiple array object properties

Body:
You can try using || operator with the same return statement as below :

this.records = this.records.filter((res: any)=>{
        return (res.name.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase()) || res.age.match(this.searchTerm) || res.course.toLocaleLowerCase().match(this.searchTerm.toLocaleLowerCase()));
});


问:
Ember JS : Lazy load Model data
I'm trying to render ember model data which has more than 1000 records. This will take more than 2 min to finish the rendering part.

So, I have a plan to optimize it. I want to load the first 100 records in the first time. Once they go to the end then I need to load the second 100 records.

How can I do that?

答:
Retrieving pages of data

The concept is paging and depends on how your backend handles paging. But in the generic case, something like:

```<code>let result = this.store.query('post', {
  limit: 10,
  offset: 0
});
</code>```

once processed by the backend would result in a query to a relational database like:

```<code>SELECT * FROM post LIMIT 10 OFFSET 0;
</code>```

So, you will need to keep track of the current page you are showing. Each time you want to fetch a new page, you will simply increment your offset by page * limit where page is the current page index. So the next query when page = 1 would be:

```<code>let result = this.store.query('post', {
  limit: 10,
  offset: 10 // 1 * 10
});
</code>```

It's probably a good idea for you backend to return the total result count, which you can access via some kind metadata key on your JSON responses (or however you want since it depends on the way your backend speaks collections). This way you know when to stop trying to fetch the next page.

UX around retrieval

You will need to choose whether you want to do simple paging, which supplies a next and previous button that the user clicks on to retrieve the next / previous page. Probably best UX to manage the page with query params so that the forward/back buttons in the browser move pages and refreshing does not lose the page. You should also disable / enable the previous and next buttons when there are no pages to fetch in either direction.

Pros

easy to develop

user never loses their place

since only ever showing one page at a time, no memory / performance concerns

Cons

users have to click buttons and may choose not to / not realize how

Addons

ember-cli-pagination

The alternative would be using infinite scrolling (a la Facebook news feed). You must pay attention to the scrolling position to know when to fetch the next view (which requires math around the sizes of the current items). Alternatively, you evaluate whether item n - 2 or something like that is in the view port and then prefetch the next page.

Pros

users never think about paging and continue seeing new content with ease

Cons

horrible for returning to ones spot on page change / refresh

horrible for searching

requires a great deal of attention to the amount of data you are showing or else you will run into overconsumption of memory and performance degradation.

more difficult to write since you must handle scrolling events, view port detection, etc

addons

ember-in-viewport

vertical-collection

ember-infinity

Title: Ember JS : Lazy load Model data

Body:
Retrieving pages of data

The concept is paging and depends on how your backend handles paging. But in the generic case, something like:

let result = this.store.query('post', {
  limit: 10,
  offset: 0
});

once processed by the backend would result in a query to a relational database like:

SELECT * FROM post LIMIT 10 OFFSET 0;

So, you will need to keep track of the current page you are showing. Each time you want to fetch a new page, you will simply increment your offset by page * limit where page is the current page index. So the next query when page = 1 would be:

let result = this.store.query('post', {
  limit: 10,
  offset: 10 // 1 * 10
});

It's probably a good idea for you backend to return the total result count, which you can access via some kind metadata key on your JSON responses (or however you want since it depends on the way your backend speaks collections). This way you know when to stop trying to fetch the next page.

UX around retrieval

You will need to choose whether you want to do simple paging, which supplies a next and previous button that the user clicks on to retrieve the next / previous page. Probably best UX to manage the page with query params so that the forward/back buttons in the browser move pages and refreshing does not lose the page. You should also disable / enable the previous and next buttons when there are no pages to fetch in either direction.

Pros

easy to develop

user never loses their place

since only ever showing one page at a time, no memory / performance concerns

Cons

users have to click buttons and may choose not to / not realize how

Addons

ember-cli-pagination

The alternative would be using infinite scrolling (a la Facebook news feed). You must pay attention to the scrolling position to know when to fetch the next view (which requires math around the sizes of the current items). Alternatively, you evaluate whether item n - 2 or something like that is in the view port and then prefetch the next page.

Pros

users never think about paging and continue seeing new content with ease

Cons

horrible for returning to ones spot on page change / refresh

horrible for searching

requires a great deal of attention to the amount of data you are showing or else you will run into overconsumption of memory and performance degradation.

more difficult to write since you must handle scrolling events, view port detection, etc

addons

ember-in-viewport

vertical-collection

ember-infinity


问:
How to implement a global loader in Angular
I have a global loader which is implemented like this:

CoreModule:

```<code>router.events.pipe(
  filter(x => x instanceof NavigationStart)
).subscribe(() => loaderService.show());

router.events.pipe(
  filter(x => x instanceof NavigationEnd || x instanceof NavigationCancel || x instanceof NavigationError)
).subscribe(() => loaderService.hide());
</code>```

LoaderService:

```<code>@Injectable({
    providedIn: 'root'
})
export class LoaderService {

    overlayRef: OverlayRef;
    componentFactory: ComponentFactory<LoaderComponent>;
    componentPortal: ComponentPortal<LoaderComponent>;
    componentRef: ComponentRef<LoaderComponent>;

    constructor(
        private overlay: Overlay,
        private componentFactoryResolver: ComponentFactoryResolver
    ) {
        this.overlayRef = this.overlay.create(
            {
                hasBackdrop: true,
                positionStrategy: this.overlay.position().global().centerHorizontally().centerVertically()
            }
        );

        this.componentFactory = this.componentFactoryResolver.resolveComponentFactory(LoaderComponent);

        this.componentPortal = new ComponentPortal(this.componentFactory.componentType);
    }

    show(message?: string) {
        this.componentRef = this.overlayRef.attach<LoaderComponent>(this.componentPortal);
        this.componentRef.instance.message = message;
    }

    hide() {
        this.overlayRef.detach();
    }
}
</code>```

When running with Angular 7.0.2, the behavior (which I wanted) was:

Show loader while resolving data attached to a route, and while loading a lazy module

Don't show loader when navigating to a route without any resolver

I have updated to Angular 7.2, now the behavior is:

Show loader while resolving data attached to a route, and while loading a lazy module

Show the Overlay whithout the LoaderComponent when navigating to a route without any resolver

I have added some logs on the NavigationStart and NavigationEnd events and I found that NavigationEnd is triggered immediately after NavigationStart (which is normal), while Overlay disappears about 0.5s after.

I have read the CHANGELOG.md but I found nothing that might explain this problem. Any idea is welcome.

Edit:

After further research, I have restored the previous behavior by setting package.json like this:

```<code>"@angular/cdk": "~7.0.0",
"@angular/material": "~7.0.0",
</code>```

instead of this:

```<code>"@angular/cdk": "~7.2.0",
"@angular/material": "~7.2.0",
</code>```

I have identified the faulty commit which has been released in version 7.1.0 and I posted my problem on the related GitHub issue. It fixes the fade out animation of the Overlay.

What is the v7.1+ compliant way to get the desired behavior?
According to me, the best thing to do would be: show the loader only when necessary, but NavigationStart doesn't hold the needed information.
I'd like to avoid ending up with some debounce behavior.

答:
The way we implement loader in our system with exception list:

```<code>export class LoaderInterceptor implements HttpInterceptor {
  requestCount = 0;

  constructor(private loaderService: LoaderService) {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    if (!(REQUEST_LOADER_EXCEPTIONS.find(r => request.url.includes(r)))) {
      this.loaderService.setLoading(true);
      this.requestCount++;
    }

    return next.handle(request).pipe(
      tap(res => {
        if (res instanceof HttpResponse) {
          if (!(REQUEST_LOADER_EXCEPTIONS.find(r => request.url.includes(r)))) {
            this.requestCount--;
          }
          if (this.requestCount <= 0) {
            this.loaderService.setLoading(false);
          }
        }
      }),
      catchError(err => {
        this.loaderService.setLoading(false);
        this.requestCount = 0;
        throw err;
      })
    );
  }
}
</code>```

and loader service is just (300ms delay prevents loader from just flashing on the screen when response is fast):

```<code>export class LoaderService {
  loadingRequest = new BehaviorSubject(false);
  private timeout: any;

  setLoading(val: boolean): void {
    if (!val) {
      this.timeout = setTimeout(() => {
        this.loadingRequest.next(val);
      }, 300);
    } else {
      clearTimeout(this.timeout);
      this.loadingRequest.next(val);
    }
  }
}
</code>```

Body:
I have a global loader which is implemented like this:

CoreModule:

router.events.pipe(
  filter(x => x instanceof NavigationStart)
).subscribe(() => loaderService.show());

router.events.pipe(
  filter(x => x instanceof NavigationEnd || x instanceof NavigationCancel || x instanceof NavigationError)
).subscribe(() => loaderService.hide());

LoaderService:

@Injectable({
    providedIn: 'root'
})
export class LoaderService {

    overlayRef: OverlayRef;
    componentFactory: ComponentFactory<LoaderComponent>;
    componentPortal: ComponentPortal<LoaderComponent>;
    componentRef: ComponentRef<LoaderComponent>;

    constructor(
        private overlay: Overlay,
        private componentFactoryResolver: ComponentFactoryResolver
    ) {
        this.overlayRef = this.overlay.create(
            {
                hasBackdrop: true,
                positionStrategy: this.overlay.position().global().centerHorizontally().centerVertically()
            }
        );

        this.componentFactory = this.componentFactoryResolver.resolveComponentFactory(LoaderComponent);

        this.componentPortal = new ComponentPortal(this.componentFactory.componentType);
    }

    show(message?: string) {
        this.componentRef = this.overlayRef.attach<LoaderComponent>(this.componentPortal);
        this.componentRef.instance.message = message;
    }

    hide() {
        this.overlayRef.detach();
    }
}

When running with Angular 7.0.2, the behavior (which I wanted) was:

Show loader while resolving data attached to a route, and while loading a lazy module

Don't show loader when navigating to a route without any resolver

I have updated to Angular 7.2, now the behavior is:

Show loader while resolving data attached to a route, and while loading a lazy module

Show the Overlay whithout the LoaderComponent when navigating to a route without any resolver

I have added some logs on the NavigationStart and NavigationEnd events and I found that NavigationEnd is triggered immediately after NavigationStart (which is normal), while Overlay disappears about 0.5s after.

I have read the CHANGELOG.md but I found nothing that might explain this problem. Any idea is welcome.

Edit:

After further research, I have restored the previous behavior by setting package.json like this:

"@angular/cdk": "~7.0.0",
"@angular/material": "~7.0.0",

instead of this:

"@angular/cdk": "~7.2.0",
"@angular/material": "~7.2.0",

I have identified the faulty commit which has been released in version 7.1.0 and I posted my problem on the related GitHub issue. It fixes the fade out animation of the Overlay.

What is the v7.1+ compliant way to get the desired behavior?
According to me, the best thing to do would be: show the loader only when necessary, but NavigationStart doesn't hold the needed information.
I'd like to avoid ending up with some debounce behavior.

Body:
The way we implement loader in our system with exception list:

export class LoaderInterceptor implements HttpInterceptor {
  requestCount = 0;

  constructor(private loaderService: LoaderService) {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    if (!(REQUEST_LOADER_EXCEPTIONS.find(r => request.url.includes(r)))) {
      this.loaderService.setLoading(true);
      this.requestCount++;
    }

    return next.handle(request).pipe(
      tap(res => {
        if (res instanceof HttpResponse) {
          if (!(REQUEST_LOADER_EXCEPTIONS.find(r => request.url.includes(r)))) {
            this.requestCount--;
          }
          if (this.requestCount <= 0) {
            this.loaderService.setLoading(false);
          }
        }
      }),
      catchError(err => {
        this.loaderService.setLoading(false);
        this.requestCount = 0;
        throw err;
      })
    );
  }
}

and loader service is just (300ms delay prevents loader from just flashing on the screen when response is fast):

export class LoaderService {
  loadingRequest = new BehaviorSubject(false);
  private timeout: any;

  setLoading(val: boolean): void {
    if (!val) {
      this.timeout = setTimeout(() => {
        this.loadingRequest.next(val);
      }, 300);
    } else {
      clearTimeout(this.timeout);
      this.loadingRequest.next(val);
    }
  }
}


问:
Delete a second row if it's found in Mysql
Im trying to delete a row in MySql if there are 2 rows for a merchant. It doesn't matter which row is deleted.

When I run:

```<code>SELECT * FROM products.merchant_configs WHERE `configKey` = 'CHECK_BALANCE_SUBJECT'
AND merchantId = 6;
</code>```

I see:

Now I try to delete one of the rows:

```<code>DELETE FROM products.merchant_configs
WHERE id = (
    SELECT id FROM products.merchant_configs WHERE `configKey` = 'CHECK_BALANCE_SUBJECT'
    AND merchantId = 6
    LIMIT 2 OFFSET 1
);
</code>```

I receive the error:

```<code>Error Code: 1093. You can't specify target table 'merchant_configs' for update in FROM clause
</code>```

What's going on?

答:
Nest the query inside another select statement:

```<code>DELETE FROM products.merchant_configs
WHERE id = (SELECT t.id FROM (
    SELECT id FROM products.merchant_configs WHERE `configKey` = 'CHECK_BALANCE_SUBJECT'
    AND merchantId = 6
    LIMIT 2 OFFSET 1
) t);
</code>```

See the demo.

Body:
Im trying to delete a row in MySql if there are 2 rows for a merchant. It doesn't matter which row is deleted.

When I run:

SELECT * FROM products.merchant_configs WHERE `configKey` = 'CHECK_BALANCE_SUBJECT'
AND merchantId = 6;

I see:

Now I try to delete one of the rows:

DELETE FROM products.merchant_configs
WHERE id = (
    SELECT id FROM products.merchant_configs WHERE `configKey` = 'CHECK_BALANCE_SUBJECT'
    AND merchantId = 6
    LIMIT 2 OFFSET 1
);

I receive the error:

Error Code: 1093. You can't specify target table 'merchant_configs' for update in FROM clause

What's going on?

Body:
Nest the query inside another select statement:

DELETE FROM products.merchant_configs
WHERE id = (SELECT t.id FROM (
    SELECT id FROM products.merchant_configs WHERE `configKey` = 'CHECK_BALANCE_SUBJECT'
    AND merchantId = 6
    LIMIT 2 OFFSET 1
) t);

See the demo.