qid
int64
1
74.7M
question
stringlengths
0
58.3k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
2
48.3k
response_k
stringlengths
2
40.5k
41,283,816
Not able to grasp the concept behind these two different terms. Can anyone please help out with an example?
2016/12/22
[ "https://Stackoverflow.com/questions/41283816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2739470/" ]
You can try with this code : ``` <?php $contact='[contact-form-7 id="1442" title="Service 1 "]'?> <?php echo do_shortcode($contact);?> ```
your method is correct but you can also try this `apply_filters('the_content','[contact-form-7 id="1442" title="Service 1"]')` also please make sure there is a contact form 7 exists with the id, '1442'
41,283,816
Not able to grasp the concept behind these two different terms. Can anyone please help out with an example?
2016/12/22
[ "https://Stackoverflow.com/questions/41283816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2739470/" ]
I tried to insert an URL and it worked: <a href="https://[contact-form-7 id="10742" title="Register"]"> Hope it resolves your problem
your method is correct but you can also try this `apply_filters('the_content','[contact-form-7 id="1442" title="Service 1"]')` also please make sure there is a contact form 7 exists with the id, '1442'
41,283,816
Not able to grasp the concept behind these two different terms. Can anyone please help out with an example?
2016/12/22
[ "https://Stackoverflow.com/questions/41283816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2739470/" ]
You can try with this code : ``` <?php $contact='[contact-form-7 id="1442" title="Service 1 "]'?> <?php echo do_shortcode($contact);?> ```
You can't embed it into a HTML file, you need to have a .PHP file connected to a server with wordpress installed on it so the php functions and wordpress functions could work.
41,283,816
Not able to grasp the concept behind these two different terms. Can anyone please help out with an example?
2016/12/22
[ "https://Stackoverflow.com/questions/41283816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2739470/" ]
I tried to insert an URL and it worked: <a href="https://[contact-form-7 id="10742" title="Register"]"> Hope it resolves your problem
You can't embed it into a HTML file, you need to have a .PHP file connected to a server with wordpress installed on it so the php functions and wordpress functions could work.
41,283,816
Not able to grasp the concept behind these two different terms. Can anyone please help out with an example?
2016/12/22
[ "https://Stackoverflow.com/questions/41283816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2739470/" ]
You can try with this code : ``` <?php $contact='[contact-form-7 id="1442" title="Service 1 "]'?> <?php echo do_shortcode($contact);?> ```
I tried to insert an URL and it worked: <a href="https://[contact-form-7 id="10742" title="Register"]"> Hope it resolves your problem
64,731
Why are questions allowed to have two similar tags? For example, the following question has two tags assigned, [.net](/questions/tagged/.net "show questions tagged '.net'") and [.net3.5](/questions/tagged/.net3.5 "show questions tagged '.net3.5'"). <https://stackoverflow.com/posts/3726446/revisions>, revision 5 or earlier.
2010/09/16
[ "https://meta.stackexchange.com/questions/64731", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/147192/" ]
The `.net` tag is for questions generally concerning the .NET Framework, independent of the version, while the `.net3.5` tag should indicate a question is specific to that version. In this case I guess the OP wasn't certain whether his question applies to all versions or not, someone knowing should adequately retag.
Well the tags aren't the same are they. The `.net` refers to the .NET Framework as a whole. The `.net3.5` refers specifically to version 3.5 of the Framework. It should probably be retagged to just `.net3.5`
64,731
Why are questions allowed to have two similar tags? For example, the following question has two tags assigned, [.net](/questions/tagged/.net "show questions tagged '.net'") and [.net3.5](/questions/tagged/.net3.5 "show questions tagged '.net3.5'"). <https://stackoverflow.com/posts/3726446/revisions>, revision 5 or earlier.
2010/09/16
[ "https://meta.stackexchange.com/questions/64731", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/147192/" ]
Contrary to the answers posted so far tagging with both tags is correct. * The `.net3.5` tag is needed to indicate that either the question is about a specific feature of the version 3.5 of the .NET framework or to indicate that the user is using that specific version, and thus solutions that are not compatible with it are unacceptable. * The `.net` tag is also needed for several reasons: + The answers qualify for the `.net` badge which indicates a knowledge about the entire .NET framework, including the specific 3.5 version + Many people favorite the main tag but not the version specific tag. + Similarly, many people ignore the main tag but not the specific tag. + Someone searching for a similar problem is very likely to search for `[.net] text` instead of `[.net3.5] text`.
Well the tags aren't the same are they. The `.net` refers to the .NET Framework as a whole. The `.net3.5` refers specifically to version 3.5 of the Framework. It should probably be retagged to just `.net3.5`
64,731
Why are questions allowed to have two similar tags? For example, the following question has two tags assigned, [.net](/questions/tagged/.net "show questions tagged '.net'") and [.net3.5](/questions/tagged/.net3.5 "show questions tagged '.net3.5'"). <https://stackoverflow.com/posts/3726446/revisions>, revision 5 or earlier.
2010/09/16
[ "https://meta.stackexchange.com/questions/64731", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/147192/" ]
Contrary to the answers posted so far tagging with both tags is correct. * The `.net3.5` tag is needed to indicate that either the question is about a specific feature of the version 3.5 of the .NET framework or to indicate that the user is using that specific version, and thus solutions that are not compatible with it are unacceptable. * The `.net` tag is also needed for several reasons: + The answers qualify for the `.net` badge which indicates a knowledge about the entire .NET framework, including the specific 3.5 version + Many people favorite the main tag but not the version specific tag. + Similarly, many people ignore the main tag but not the specific tag. + Someone searching for a similar problem is very likely to search for `[.net] text` instead of `[.net3.5] text`.
The `.net` tag is for questions generally concerning the .NET Framework, independent of the version, while the `.net3.5` tag should indicate a question is specific to that version. In this case I guess the OP wasn't certain whether his question applies to all versions or not, someone knowing should adequately retag.
166,616
Is there a word to describe the fear of never again seeing one's mother (or at least any person)? I have already checked the list of phobias that Wikipedia offers but could not find anything that fits the specific meaning I am looking for; perhaps there is such a word, but it does not have the word *phobia* attached to it. Thanks.
2014/04/28
[ "https://english.stackexchange.com/questions/166616", "https://english.stackexchange.com", "https://english.stackexchange.com/users/60619/" ]
Is "[separation anxiety disorder](http://en.wikipedia.org/wiki/Separation_anxiety_disorder)" the expression you're looking for? > > *SAD (Separation Anxiety Disorder) is a condition in which an individual experiments excessive anxiety regarding separation from home or from people to whom the individual has a strong emotional attachment, i.e. a parent, grandparents, or siblings.* > > >
The ***fear of not seeing one's mother ever again*** also refers to the ***fear of death or*** ***dead things*** and is called **NECROPHOBIA**.
7,914,579
Say I have a table of data that looks like: ``` ItemNo | ItemCount | Proportion ------------------------------------------ 1 3 0.15 2 2 0.10 3 3 0.15 4 0 0.00 5 2 0.10 6 1 0.05 7 5 0.25 8 4 0.20 ``` In other words, there are a total of 20 items, and the cumulative proportion of each `ItemNo` sums to 100%. The ordering of the table rows is important here. Is it possible to perform a SQL query ***without loops or cursors*** to return the **first** `ItemNo` which exceeds a cumulative proportion? In other words if the 'proportion' I wanted to check was 35%, the first row which exceeds that is `ItemNo 3`, because 0.15 + 0.10 + 0.15 = 0.40 Similarly, if I wanted to find the first row which exceeded 75%, that would be `ItemNo 7`, as the sum of all `Proportion` up until that row is less than 0.75.
2011/10/27
[ "https://Stackoverflow.com/questions/7914579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/694652/" ]
``` select top 1 t1.ItemNo from MyTable t1 where ((select sum(t2.Proportion) from MyTable t2 where t2.ItemNo <= t1.ItemNo) >= 0.35) order by t1.ItemNo ```
A classic for a window function: ``` SELECT * FROM ( SELECT ItemNo ,ItemCount ,sum(Proportion) OVER (ORDER BY ItemNo) AS running_sum FROM tbl) y WHERE running_sum > 0.35 LIMIT 1; ``` Works in **PostgreSQL**, among others. Or, in **tSQL** notation (which you seem to use): SELECT TOP 1 \* FROM ( SELECT ItemNo ,ItemCount ,sum(Proportion) OVER (ORDER BY ItemNo) AS running\_sum FROM tbl) y WHERE running\_sum > 0.35; Doesn't work in tSQL as commented below.
16,716,474
I'm using SonataAdminBundle and I'm triying to change the edit link of and entity by the show link. I want to do this because I need the entity couldn't be modified but I want you can show the entity by clicking in the Identifier field of the list page. I need to show the entity by clicking in the Identifier, and not using the show action buttom. So I tried in the ClassAdmin: ``` protected function configureRoutes(RouteCollection $collection){ $collection->add('edit', $this->getRouterIdParameter().'/show'); } ``` Despite the url is generated with the show correctly, the Identifier in the list page redirect to the edit page. Really, wathever I change in the edit link doesn't take efect and always redirect to the edit page. Thansk a lot!
2013/05/23
[ "https://Stackoverflow.com/questions/16716474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2132206/" ]
You can give the default action like this (in your admin classes): ``` protected function configureListFields(ListMapper $listMapper) { $listMapper ->addIdentifier('id', null, ['route' => ['name' => 'show']]) ; } ```
Finally, it works by: ``` protected function configureRoutes(RouteCollection $collection){ $collection->remove('edit'); $collection->add('edit', $this->getRouterIdParameter().'/show'); } ``` I don't know why I have to remove the edit link first... but it works.
4,151,589
When I define a dictionary which use list as key ``` collections.defaultdict(list) ``` When I print it out, it shows itself is using tuple as key. May I know why? ``` import collections tuple_as_dict_key = collections.defaultdict(tuple) tuple_as_dict_key['abc', 1, 2] = 999 tuple_as_dict_key['abc', 3, 4] = 999 tuple_as_dict_key['abc', 5, 6] = 888 # defaultdict(<type 'tuple'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999}) print tuple_as_dict_key list_as_dict_key = collections.defaultdict(list) list_as_dict_key['abc', 1, 2] = 999 list_as_dict_key['abc', 3, 4] = 999 list_as_dict_key['abc', 5, 6] = 888 # defaultdict(<type 'list'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999}) # Isn't it should be defaultdict(<type 'list'>, {['abc', 5, 6]: 888, ... print list_as_dict_key ```
2010/11/11
[ "https://Stackoverflow.com/questions/4151589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/72437/" ]
There's a nice article explaining the answer to why you can't use a list as key [here](http://wiki.python.org/moin/DictionaryKeys).
Dictionary keys can only be [immutable types](http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences). Since a list is a mutable type it must be converted to an immutable type such as a tuple to be used as a dictionary key, and this conversion is being done automatically.
4,151,589
When I define a dictionary which use list as key ``` collections.defaultdict(list) ``` When I print it out, it shows itself is using tuple as key. May I know why? ``` import collections tuple_as_dict_key = collections.defaultdict(tuple) tuple_as_dict_key['abc', 1, 2] = 999 tuple_as_dict_key['abc', 3, 4] = 999 tuple_as_dict_key['abc', 5, 6] = 888 # defaultdict(<type 'tuple'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999}) print tuple_as_dict_key list_as_dict_key = collections.defaultdict(list) list_as_dict_key['abc', 1, 2] = 999 list_as_dict_key['abc', 3, 4] = 999 list_as_dict_key['abc', 5, 6] = 888 # defaultdict(<type 'list'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999}) # Isn't it should be defaultdict(<type 'list'>, {['abc', 5, 6]: 888, ... print list_as_dict_key ```
2010/11/11
[ "https://Stackoverflow.com/questions/4151589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/72437/" ]
When you're adding values to your dictionary you're doing it the same way in both cases and they're treated as a tuple. What you're passing to the constructor is the default value for any keys that are not present. Your default value in this case happens to be of type "type", but that has absolutely nothing to do with how other keys are treated.
Dictionary keys can only be [immutable types](http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences). Since a list is a mutable type it must be converted to an immutable type such as a tuple to be used as a dictionary key, and this conversion is being done automatically.
4,151,589
When I define a dictionary which use list as key ``` collections.defaultdict(list) ``` When I print it out, it shows itself is using tuple as key. May I know why? ``` import collections tuple_as_dict_key = collections.defaultdict(tuple) tuple_as_dict_key['abc', 1, 2] = 999 tuple_as_dict_key['abc', 3, 4] = 999 tuple_as_dict_key['abc', 5, 6] = 888 # defaultdict(<type 'tuple'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999}) print tuple_as_dict_key list_as_dict_key = collections.defaultdict(list) list_as_dict_key['abc', 1, 2] = 999 list_as_dict_key['abc', 3, 4] = 999 list_as_dict_key['abc', 5, 6] = 888 # defaultdict(<type 'list'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999}) # Isn't it should be defaultdict(<type 'list'>, {['abc', 5, 6]: 888, ... print list_as_dict_key ```
2010/11/11
[ "https://Stackoverflow.com/questions/4151589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/72437/" ]
The parameter to `defaultdict` is not the type of the key, it is a function that creates default data. Your test cases don't exercise this because you're filling the dict with defined values and not using any defaults. If you were to try to get the value `list_as_dict_key['abc', 7, 8]` it would return an empty list, since that is what you defined as a default value and you never set the value at that index.
Dictionary keys can only be [immutable types](http://docs.python.org/tutorial/datastructures.html#tuples-and-sequences). Since a list is a mutable type it must be converted to an immutable type such as a tuple to be used as a dictionary key, and this conversion is being done automatically.
4,151,589
When I define a dictionary which use list as key ``` collections.defaultdict(list) ``` When I print it out, it shows itself is using tuple as key. May I know why? ``` import collections tuple_as_dict_key = collections.defaultdict(tuple) tuple_as_dict_key['abc', 1, 2] = 999 tuple_as_dict_key['abc', 3, 4] = 999 tuple_as_dict_key['abc', 5, 6] = 888 # defaultdict(<type 'tuple'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999}) print tuple_as_dict_key list_as_dict_key = collections.defaultdict(list) list_as_dict_key['abc', 1, 2] = 999 list_as_dict_key['abc', 3, 4] = 999 list_as_dict_key['abc', 5, 6] = 888 # defaultdict(<type 'list'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999}) # Isn't it should be defaultdict(<type 'list'>, {['abc', 5, 6]: 888, ... print list_as_dict_key ```
2010/11/11
[ "https://Stackoverflow.com/questions/4151589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/72437/" ]
There's a nice article explaining the answer to why you can't use a list as key [here](http://wiki.python.org/moin/DictionaryKeys).
`defaultdict` is **not** setting the *key* as a list. It's setting the default *value*. ``` >>> from collections import defaultdict >>> d1 = collections.defaultdict(list) >>> d1['foo'] [] >>> d1['foo'] = 37 >>> d1['foo'] 37 >>> d1['bar'] [] >>> d1['bar'].append(37) >>> d1['bar'] [37] ``` The way that you're getting a tuple as the key type is normal dict behaviour: ``` >>> d2 = dict() >>> d2[37, 19, 2] = [14, 19] >>> d2 {(37, 19, 2): [14, 19]} ``` The way Python works with subscripting is that `a` is `a`, `a, b` is a tuple, `a:b` is a slice object. See how it works with a list: ``` >>> mylist = [1, 2, 3] >>> mylist[4, 5] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: list indices must be integers, not tuple ``` It's taken `4, 5` as a tuple. The dict has done the same.
4,151,589
When I define a dictionary which use list as key ``` collections.defaultdict(list) ``` When I print it out, it shows itself is using tuple as key. May I know why? ``` import collections tuple_as_dict_key = collections.defaultdict(tuple) tuple_as_dict_key['abc', 1, 2] = 999 tuple_as_dict_key['abc', 3, 4] = 999 tuple_as_dict_key['abc', 5, 6] = 888 # defaultdict(<type 'tuple'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999}) print tuple_as_dict_key list_as_dict_key = collections.defaultdict(list) list_as_dict_key['abc', 1, 2] = 999 list_as_dict_key['abc', 3, 4] = 999 list_as_dict_key['abc', 5, 6] = 888 # defaultdict(<type 'list'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999}) # Isn't it should be defaultdict(<type 'list'>, {['abc', 5, 6]: 888, ... print list_as_dict_key ```
2010/11/11
[ "https://Stackoverflow.com/questions/4151589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/72437/" ]
The parameter to `defaultdict` is not the type of the key, it is a function that creates default data. Your test cases don't exercise this because you're filling the dict with defined values and not using any defaults. If you were to try to get the value `list_as_dict_key['abc', 7, 8]` it would return an empty list, since that is what you defined as a default value and you never set the value at that index.
There's a nice article explaining the answer to why you can't use a list as key [here](http://wiki.python.org/moin/DictionaryKeys).
4,151,589
When I define a dictionary which use list as key ``` collections.defaultdict(list) ``` When I print it out, it shows itself is using tuple as key. May I know why? ``` import collections tuple_as_dict_key = collections.defaultdict(tuple) tuple_as_dict_key['abc', 1, 2] = 999 tuple_as_dict_key['abc', 3, 4] = 999 tuple_as_dict_key['abc', 5, 6] = 888 # defaultdict(<type 'tuple'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999}) print tuple_as_dict_key list_as_dict_key = collections.defaultdict(list) list_as_dict_key['abc', 1, 2] = 999 list_as_dict_key['abc', 3, 4] = 999 list_as_dict_key['abc', 5, 6] = 888 # defaultdict(<type 'list'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999}) # Isn't it should be defaultdict(<type 'list'>, {['abc', 5, 6]: 888, ... print list_as_dict_key ```
2010/11/11
[ "https://Stackoverflow.com/questions/4151589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/72437/" ]
When you're adding values to your dictionary you're doing it the same way in both cases and they're treated as a tuple. What you're passing to the constructor is the default value for any keys that are not present. Your default value in this case happens to be of type "type", but that has absolutely nothing to do with how other keys are treated.
`defaultdict` is **not** setting the *key* as a list. It's setting the default *value*. ``` >>> from collections import defaultdict >>> d1 = collections.defaultdict(list) >>> d1['foo'] [] >>> d1['foo'] = 37 >>> d1['foo'] 37 >>> d1['bar'] [] >>> d1['bar'].append(37) >>> d1['bar'] [37] ``` The way that you're getting a tuple as the key type is normal dict behaviour: ``` >>> d2 = dict() >>> d2[37, 19, 2] = [14, 19] >>> d2 {(37, 19, 2): [14, 19]} ``` The way Python works with subscripting is that `a` is `a`, `a, b` is a tuple, `a:b` is a slice object. See how it works with a list: ``` >>> mylist = [1, 2, 3] >>> mylist[4, 5] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: list indices must be integers, not tuple ``` It's taken `4, 5` as a tuple. The dict has done the same.
4,151,589
When I define a dictionary which use list as key ``` collections.defaultdict(list) ``` When I print it out, it shows itself is using tuple as key. May I know why? ``` import collections tuple_as_dict_key = collections.defaultdict(tuple) tuple_as_dict_key['abc', 1, 2] = 999 tuple_as_dict_key['abc', 3, 4] = 999 tuple_as_dict_key['abc', 5, 6] = 888 # defaultdict(<type 'tuple'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999}) print tuple_as_dict_key list_as_dict_key = collections.defaultdict(list) list_as_dict_key['abc', 1, 2] = 999 list_as_dict_key['abc', 3, 4] = 999 list_as_dict_key['abc', 5, 6] = 888 # defaultdict(<type 'list'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999}) # Isn't it should be defaultdict(<type 'list'>, {['abc', 5, 6]: 888, ... print list_as_dict_key ```
2010/11/11
[ "https://Stackoverflow.com/questions/4151589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/72437/" ]
The parameter to `defaultdict` is not the type of the key, it is a function that creates default data. Your test cases don't exercise this because you're filling the dict with defined values and not using any defaults. If you were to try to get the value `list_as_dict_key['abc', 7, 8]` it would return an empty list, since that is what you defined as a default value and you never set the value at that index.
When you're adding values to your dictionary you're doing it the same way in both cases and they're treated as a tuple. What you're passing to the constructor is the default value for any keys that are not present. Your default value in this case happens to be of type "type", but that has absolutely nothing to do with how other keys are treated.
4,151,589
When I define a dictionary which use list as key ``` collections.defaultdict(list) ``` When I print it out, it shows itself is using tuple as key. May I know why? ``` import collections tuple_as_dict_key = collections.defaultdict(tuple) tuple_as_dict_key['abc', 1, 2] = 999 tuple_as_dict_key['abc', 3, 4] = 999 tuple_as_dict_key['abc', 5, 6] = 888 # defaultdict(<type 'tuple'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999}) print tuple_as_dict_key list_as_dict_key = collections.defaultdict(list) list_as_dict_key['abc', 1, 2] = 999 list_as_dict_key['abc', 3, 4] = 999 list_as_dict_key['abc', 5, 6] = 888 # defaultdict(<type 'list'>, {('abc', 5, 6): 888, ('abc', 1, 2): 999, ('abc', 3, 4): 999}) # Isn't it should be defaultdict(<type 'list'>, {['abc', 5, 6]: 888, ... print list_as_dict_key ```
2010/11/11
[ "https://Stackoverflow.com/questions/4151589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/72437/" ]
The parameter to `defaultdict` is not the type of the key, it is a function that creates default data. Your test cases don't exercise this because you're filling the dict with defined values and not using any defaults. If you were to try to get the value `list_as_dict_key['abc', 7, 8]` it would return an empty list, since that is what you defined as a default value and you never set the value at that index.
`defaultdict` is **not** setting the *key* as a list. It's setting the default *value*. ``` >>> from collections import defaultdict >>> d1 = collections.defaultdict(list) >>> d1['foo'] [] >>> d1['foo'] = 37 >>> d1['foo'] 37 >>> d1['bar'] [] >>> d1['bar'].append(37) >>> d1['bar'] [37] ``` The way that you're getting a tuple as the key type is normal dict behaviour: ``` >>> d2 = dict() >>> d2[37, 19, 2] = [14, 19] >>> d2 {(37, 19, 2): [14, 19]} ``` The way Python works with subscripting is that `a` is `a`, `a, b` is a tuple, `a:b` is a slice object. See how it works with a list: ``` >>> mylist = [1, 2, 3] >>> mylist[4, 5] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: list indices must be integers, not tuple ``` It's taken `4, 5` as a tuple. The dict has done the same.
601,613
What I am attempting to do is combine all of the files within a subdirectory into a new file, and give the new combined file the same name as the subdirectory, and I have no idea how to do this in Bash. Here's how I approached it: I have a number of directories, each with a unique file name (with spaces!). Within each of these directories, there are a number of numerically named files, like thus: ``` Home/Unique name/1.pdf Home/Unique name/2.pdf Home/Unique name/3.pdf Home/Unique name/4.pdf .... Home/Other Unique name/1.pdf Home/Other Unique name/2.pdf Home/Other Unique name/3.pdf Home/Other Unique name/4.pdf ``` What I would like to do is write a bash script (from the `Home` directory) to: 1. Go into each unique directory, and perform a command on each of the files within that directory (in my case, copy them all to a different directory). 2. I have then written a different script `script.sh` that will perform another command (in this case, combine all the PDFs into a single file, `temp.pdf`). I would then like to rename that `temp.pdf` file after the directory `Unique name.pdf` (with spaces). 3. I will have to follow this process for a number of subdirectories. I have attempted a solution with a number of for loops, while loops and using the find command, but I am not comfortable enough with bash to debug comfortably or use these variables with any degree of confidence. I am also certain that there is a more efficient way to do what I am doing, but I have bootstrapped the script together over a period of time.
2013/05/30
[ "https://superuser.com/questions/601613", "https://superuser.com", "https://superuser.com/users/227856/" ]
The POSIX way is to use `print . -type d ... | while read f; do`, but unless you're obsessed with 100% portability, I wouldn't bother with that. If you have bash 4+ and `pdfunite` (installed by default on my Ubuntu 13.04), you can do this in two lines: ``` shopt -s globstar for f in ./**/; do pdfunite "$f"/*.pdf "$f"/"$(basename "$f").pdf"; done ``` Note that `shopt -s globstar` needs to be on a separate line to the rest of it. With globstar enabled, `**` expands to all files and directories in the current directory, recursively. Since files cannot contain `/` in their names, `**/` will expand to only the directories. I use `./**/` in the unlikely event that your directories begin with a hyphen (`-`), as this can cause problems, since many programs treat anything beginning with a `-` as an option. As written, this will not copy the PDFs to another directory, but that's pretty trivial to add in: ``` for f in ./**/; do cp "$f"/*.pdf /target/dir/; pdfunite "$f"/*.pdf "$f"/"$(basename "$f").pdf"; done ``` If you want to use your own custom pdf-combining script, then simply change the line to suit - but remember that the essence of shell scripting is putting together pre-existing commands. Here's a somewhat more portable version: ``` print . -type d -print0 | while read -d $'\0' f; do pdfunite "$f"/*.pdf "$f"/"$(basename "$f").pdf" done ```
1. Create `for` loop with `find /home/ -type f -name "*.pdf"` as a variable 2. Copy files to where you need them to, take $VARIABLE and process it through sed/awk to remove "/". Post your script and we can help you to improve it. You can always run scripts with `bash -x` to debug them or you can set `!#/bin/bash -x` to always execute in debug (verbose) mode.
1,021,338
Is there anyway by which we can read a value from an .xls file using nant scripts.The nant scripts should ask the input from the user and based on the inputs the nant.build should search the .xls file and when it sees the match,it should copy the corresponding mail ID and echo that mail ID to some other file and that echoed value should be placed in the mail section of the cruise control.NET . Please get back to me for any more clarifications Thanks GNR
2009/06/20
[ "https://Stackoverflow.com/questions/1021338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You should write an NAnt extension. It is relatively easy to do. See this tutorial [here](http://www.atalasoft.com/cs/blogs/jake/archive/2008/05/07/writing-custom-nant-tasks.aspx) As an example project see my question [here](https://stackoverflow.com/questions/851203/nant-vault-windows-integrated-authentication) and [here](http://support.sourcegear.com/viewtopic.php?f=5&t=11663).
I'll re-phrase my answer : "Is there anyway by which we can read a value from an .xls file using nant scripts" If you are talking about using the 'core' NAnt functionality, which is that funcationality that is provided within the basic installation of NAnt, then I would say "No" or "Not very easily". You can however extend NAnt using .NET libraries to perform whatever function you want, as long as you can code that function in a .NET language. So, for you to solve your problems, the steps you need to under-take in my view are : (a) Write a .NET library with methods that undertake the function(s) you describe (b) Use the 'extensibility' of NAnt to turn your library in (a) into a custom task you can then call directly from your NAnt script Obviously, you need to be able to break your problem down so that you can code it for part (a). Once you have done that, part (b) is reasonably trivial, and the tutorial I supplied in the link should easily walk you through this.
38,560,437
I'm making an android application that will inject touch events based on motions that I make. So far, I can use instrumentations to inject events but only within my application. I want to be able to use this service in other apps as well. I've read that this is possible with root but is there a way without it? Thank you!
2016/07/25
[ "https://Stackoverflow.com/questions/38560437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6633432/" ]
It is possible from a platform signed application/service to inject the keys/events to other applications. But I suppose the platform signatures change for different manufacturers !!
No, it isn't. And the reason for this is security. If you could do that, you could screw up or access all sorts of data in the other apps. They try to avoid that.
18,237,519
I am trying to print some Information to the Console in a Symfony Console Command. Regularly you would do something like this: ``` protected function execute(InputInterface $input, OutputInterface $output) { $name = $input->getArgument('name'); if ($name) { $text = 'Hello '.$name; } else { $text = 'Hello'; } if ($input->getOption('yell')) { $text = strtoupper($text); } $output->writeln($text); } ``` [For the full Code of the Example - Symfony Documentation](http://symfony.com/doc/current/components/console/introduction.html#creating-a-basic-command) Unfortunately I can't access the `OutputInterface`. Is it possible to print a Message to the Console? Unfortunately I can't pass the `OutputInterface` to the Class where I want to print some Output.
2013/08/14
[ "https://Stackoverflow.com/questions/18237519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1548788/" ]
Understanding the matter of ponctual debugging, you can always print debug messages with `echo` or `var_dump` If you plan to use a command without Symfony's application with global debug messages, here's a way to do this. Symfony offers 3 different `OutputInterface`s * [NullOutput](http://api.symfony.com/2.3/Symfony/Component/Console/Output/NullOutput.html) - Will result in no output at all and keep the command quiet * [ConsoleOutput](http://api.symfony.com/2.3/Symfony/Component/Console/Output/ConsoleOutput.html) - Will result in console messages * [StreamOutput](http://api.symfony.com/2.3/Symfony/Component/Console/Output/StreamOutput.html) - Will result in printing messages into a given stream Debugging to a file ------------------- Doing such, whenever you call `$output->writeln()` in your command, it will write a new line in `/path/to/debug/file.log` ``` use Symfony\Component\Console\Output\StreamOutput; use Symfony\Component\Console\Input\ArrayInput; use Acme\FooBundle\Command\MyCommand; $params = array(); $input = new ArrayInput($params); $file = '/path/to/debug/file.log'; $handle = fopen($file, 'w+'); $output = new StreamOutput($handle); $command = new MyCommand; $command->run($input, $output); fclose($handle); ``` Debugging in the console ------------------------ It is quietly the same process, except that you use `ConsoleOutput` instead ``` use Symfony\Component\Console\Output\ConsoleOutput; use Symfony\Component\Console\Input\ArrayInput; use Acme\FooBundle\Command\MyCommand; $params = array(); $input = new ArrayInput($params); $output = new ConsoleOutput(); $command = new MyCommand; $command->run($input, $output); ``` No debugging ------------ No message will be printed ``` use Symfony\Component\Console\Output\NullOutput; use Symfony\Component\Console\Input\ArrayInput; use Acme\FooBundle\Command\MyCommand; $params = array(); $input = new ArrayInput($params); $output = new NullOutput(); $command = new MyCommand; $command->run($input, $output); ```
Look at JMSAopBundle <https://github.com/schmittjoh/JMSAopBundle> and check out this great article <http://php-and-symfony.matthiasnoback.nl/2013/07/symfony2-rich-console-command-output-using-aop/>
140
I have rabbits that routinely build nests in my yard. How can I get rid of the rabbits legally? I don't want some officer from the DNR knocking on my door because I improperly hunted or poisoned them. The rabbits cause several problems: 1. Our dog goes absolutely nuts barking at them through the window, chases them when she can in the back yard, and gently removes the young from their nest to play with (or tend to as a mother) when she finds a nest. 2. The nests are basically a hole in the ground about the size of a softball. They're easily big enough to cause a twisted ankle when stepped in while walking in the yard. 3. I'd like to start planting tomatoes and other vegetables, but I'm fearful the rabbits will have their way with my crops. I've recently started using [Liquid Fence](http://www.liquidfence.com/), but it's hard to say if that's had much of an effect. I've certainly still had some rabbits, but maybe not as often. What's the best course of action for me?
2011/06/08
[ "https://gardening.stackexchange.com/questions/140", "https://gardening.stackexchange.com", "https://gardening.stackexchange.com/users/105/" ]
I've heard of dried blood working well as a repellent for rabbits as well as deer. If you were to plant a vegetable garden you could sprinkle some of this around the plants as a sort of combination fertilizer/pest deterrent.
To try to get rid of nature, is like living in a bubble. Try to work with it and you'll probably be surprised. Last summer I was fortunate enough to flush out 4 baby rabbits before I ran over them with the lawn mower! I got them one by one and put them over in the woods-phew! I've seen a few in the back yard, but none bother my flower garden, mostly feed on certain weeds that are out there. Another deterrent is tabasco mixed with water, spray on or around the plants. As far as moles go, I've used a store bought repellent. They were so bad I had them in my flower beds. Eventually they've gone from the front yard towards the back. Stay diligent.
140
I have rabbits that routinely build nests in my yard. How can I get rid of the rabbits legally? I don't want some officer from the DNR knocking on my door because I improperly hunted or poisoned them. The rabbits cause several problems: 1. Our dog goes absolutely nuts barking at them through the window, chases them when she can in the back yard, and gently removes the young from their nest to play with (or tend to as a mother) when she finds a nest. 2. The nests are basically a hole in the ground about the size of a softball. They're easily big enough to cause a twisted ankle when stepped in while walking in the yard. 3. I'd like to start planting tomatoes and other vegetables, but I'm fearful the rabbits will have their way with my crops. I've recently started using [Liquid Fence](http://www.liquidfence.com/), but it's hard to say if that's had much of an effect. I've certainly still had some rabbits, but maybe not as often. What's the best course of action for me?
2011/06/08
[ "https://gardening.stackexchange.com/questions/140", "https://gardening.stackexchange.com", "https://gardening.stackexchange.com/users/105/" ]
After just reading the title, I was going to suggest get a dog. Our dog has killed a couple rabbits already this year. Perhaps you could simply leave your dog in the yard more often, letting him/her out when she's barking at them through the window. I guess this depends if your dog is fast enough to catch them. You could consider getting another dog, perhaps a bigger, faster one. Another note: when putting in vegetables, make sure you have a sure method of keeping your dog out of them. Our dog ate quite a few of our green beans last year (didn't bother the tomatoes, though), so we had to put up a higher fence this year.
Not to sound too glib, but we had rabbits and voles in our yard when we moved in 2.5 years ago. Then the foxes and owls came, and no more rabbits and voles. Maybe you can figure out some way to make that work for you.
140
I have rabbits that routinely build nests in my yard. How can I get rid of the rabbits legally? I don't want some officer from the DNR knocking on my door because I improperly hunted or poisoned them. The rabbits cause several problems: 1. Our dog goes absolutely nuts barking at them through the window, chases them when she can in the back yard, and gently removes the young from their nest to play with (or tend to as a mother) when she finds a nest. 2. The nests are basically a hole in the ground about the size of a softball. They're easily big enough to cause a twisted ankle when stepped in while walking in the yard. 3. I'd like to start planting tomatoes and other vegetables, but I'm fearful the rabbits will have their way with my crops. I've recently started using [Liquid Fence](http://www.liquidfence.com/), but it's hard to say if that's had much of an effect. I've certainly still had some rabbits, but maybe not as often. What's the best course of action for me?
2011/06/08
[ "https://gardening.stackexchange.com/questions/140", "https://gardening.stackexchange.com", "https://gardening.stackexchange.com/users/105/" ]
Deer and rabbits both have a very keen sense of smell. I use a mixture of garlic powder, chili powder and water to keep the deer out of the garden. I am pretty sure that would work for rabbits as well. Spray it around where they are nesting and see if they move. If they do make up a large batch and spray the whole yard. I spray once a week on average. If it rains I spray again as soon as it's dry.
After just reading the title, I was going to suggest get a dog. Our dog has killed a couple rabbits already this year. Perhaps you could simply leave your dog in the yard more often, letting him/her out when she's barking at them through the window. I guess this depends if your dog is fast enough to catch them. You could consider getting another dog, perhaps a bigger, faster one. Another note: when putting in vegetables, make sure you have a sure method of keeping your dog out of them. Our dog ate quite a few of our green beans last year (didn't bother the tomatoes, though), so we had to put up a higher fence this year.
140
I have rabbits that routinely build nests in my yard. How can I get rid of the rabbits legally? I don't want some officer from the DNR knocking on my door because I improperly hunted or poisoned them. The rabbits cause several problems: 1. Our dog goes absolutely nuts barking at them through the window, chases them when she can in the back yard, and gently removes the young from their nest to play with (or tend to as a mother) when she finds a nest. 2. The nests are basically a hole in the ground about the size of a softball. They're easily big enough to cause a twisted ankle when stepped in while walking in the yard. 3. I'd like to start planting tomatoes and other vegetables, but I'm fearful the rabbits will have their way with my crops. I've recently started using [Liquid Fence](http://www.liquidfence.com/), but it's hard to say if that's had much of an effect. I've certainly still had some rabbits, but maybe not as often. What's the best course of action for me?
2011/06/08
[ "https://gardening.stackexchange.com/questions/140", "https://gardening.stackexchange.com", "https://gardening.stackexchange.com/users/105/" ]
Every product I've tried hasn't worked for long. I finally put up chicken wire. That's the only thing that worked. What didn't work - Don't waste your money. An owl with light up eyes, moved every couple of days to a different spot. Many different brands of rabbit repellant, including Liquid Fence. Crushed up egg shells. Plastic snakes. All different colors. Spraying the bunnies with a garden hose - they come right back. What did work - I had three places to fence in. Once I got the hang of it, a 20' by 15' bed took me around an hour to install. I used 24" tall cheap chicken wire. It was around $10.00 for a 50 foot roll. I bought 8-foot 2" x 1" lumber for $1.00 apiece. I had each one cut into four 2-foot pieces. I used plastic zip ties to attach the chicken wire to the stakes. I spaced the stakes about 4 to 6 feet apart. On the first fence I buried the chicken wire a few inches. That worked. Then I tried bending the wire outward a few inches. That worked too. For the last bed I didn't bother burying it or bending it. That worked fine too. I thought they might chew through wood or the zip ties or burrow under the fences but they didn't. Good luck!
To try to get rid of nature, is like living in a bubble. Try to work with it and you'll probably be surprised. Last summer I was fortunate enough to flush out 4 baby rabbits before I ran over them with the lawn mower! I got them one by one and put them over in the woods-phew! I've seen a few in the back yard, but none bother my flower garden, mostly feed on certain weeds that are out there. Another deterrent is tabasco mixed with water, spray on or around the plants. As far as moles go, I've used a store bought repellent. They were so bad I had them in my flower beds. Eventually they've gone from the front yard towards the back. Stay diligent.
140
I have rabbits that routinely build nests in my yard. How can I get rid of the rabbits legally? I don't want some officer from the DNR knocking on my door because I improperly hunted or poisoned them. The rabbits cause several problems: 1. Our dog goes absolutely nuts barking at them through the window, chases them when she can in the back yard, and gently removes the young from their nest to play with (or tend to as a mother) when she finds a nest. 2. The nests are basically a hole in the ground about the size of a softball. They're easily big enough to cause a twisted ankle when stepped in while walking in the yard. 3. I'd like to start planting tomatoes and other vegetables, but I'm fearful the rabbits will have their way with my crops. I've recently started using [Liquid Fence](http://www.liquidfence.com/), but it's hard to say if that's had much of an effect. I've certainly still had some rabbits, but maybe not as often. What's the best course of action for me?
2011/06/08
[ "https://gardening.stackexchange.com/questions/140", "https://gardening.stackexchange.com", "https://gardening.stackexchange.com/users/105/" ]
I've heard of dried blood working well as a repellent for rabbits as well as deer. If you were to plant a vegetable garden you could sprinkle some of this around the plants as a sort of combination fertilizer/pest deterrent.
Not to sound too glib, but we had rabbits and voles in our yard when we moved in 2.5 years ago. Then the foxes and owls came, and no more rabbits and voles. Maybe you can figure out some way to make that work for you.
140
I have rabbits that routinely build nests in my yard. How can I get rid of the rabbits legally? I don't want some officer from the DNR knocking on my door because I improperly hunted or poisoned them. The rabbits cause several problems: 1. Our dog goes absolutely nuts barking at them through the window, chases them when she can in the back yard, and gently removes the young from their nest to play with (or tend to as a mother) when she finds a nest. 2. The nests are basically a hole in the ground about the size of a softball. They're easily big enough to cause a twisted ankle when stepped in while walking in the yard. 3. I'd like to start planting tomatoes and other vegetables, but I'm fearful the rabbits will have their way with my crops. I've recently started using [Liquid Fence](http://www.liquidfence.com/), but it's hard to say if that's had much of an effect. I've certainly still had some rabbits, but maybe not as often. What's the best course of action for me?
2011/06/08
[ "https://gardening.stackexchange.com/questions/140", "https://gardening.stackexchange.com", "https://gardening.stackexchange.com/users/105/" ]
After just reading the title, I was going to suggest get a dog. Our dog has killed a couple rabbits already this year. Perhaps you could simply leave your dog in the yard more often, letting him/her out when she's barking at them through the window. I guess this depends if your dog is fast enough to catch them. You could consider getting another dog, perhaps a bigger, faster one. Another note: when putting in vegetables, make sure you have a sure method of keeping your dog out of them. Our dog ate quite a few of our green beans last year (didn't bother the tomatoes, though), so we had to put up a higher fence this year.
Truly, having dogs around gets rid of rabbits, feral cats, deer, bobcat, fishers, voles, moles...etc. You don't have to allow the dogs to kill them. Helloooo! Rabies and all kinds of disease could be transferred. It takes a few months but works just fine! I have all of the above and more. That and freezing temperatures at night any night of the year. I just went with a greenhouse and solves most of those problems. I've shot one animal one time at 100 yards with a 22, it was a rabbit. It screamed! I'll never forget it. Made myself eat the poor thing. I have no problem with hunting and killing done correctly and humanely. I love my meat-sigh-but it'll be vegetarianism for me until I get hungry enough to kill. Lots of meat around here! This area is full of squirrels (I love them!!), rabbits, rodents, feral cats not to mention lots of coyote, bobcat and cougar. I've two dogs I don't allow freedom to roam. My cats forever and always will be indoor cats. Yup, I have to exercise to exercise my dogs. Oh well! I've got two horses as well and I have to exercise them or be a heartless, self-centered and overweight person. This is my first garden here and it is a tough place. The greenhouses solved 90% of these problems. Having dogs, just having them here, pooping, peeing and occasionally barking has scared away most of these animals. The point is, if you kill one, there are thousands waiting in line to fill in the niche. They do belong and it is up to us to figure out how to live together. That is why we have this so-called intelligence we think makes us so special. Killing should only be done for food. Period. Period!! I've made it happen and most of my life I've been a single parent with all of the responsibilities and work. It is not tough. Killing and pesticides are a last, last resort. They only make more trouble. Think of it this way; you are training your environment (including your animals, varmints) to live in harmony with you. You start killing them and then you have to teach the new guys the 'rules' all over again. You allow your dogs to start killing and the next thing you know is they'll kill your neighbor's cats, little yappy dogs or bite kids. You don't need that heartache nor the expense! Relax! If you are going to be a gardener then you should know you can't control anything!!! Orchestrating harmony is vastly superior, humility and education is a must! We are not more important nor more special than any other form of life. Asking questions on this site, studying, researching, going to school are the best ways to show we humans have something going for us. Kudos to you!!
140
I have rabbits that routinely build nests in my yard. How can I get rid of the rabbits legally? I don't want some officer from the DNR knocking on my door because I improperly hunted or poisoned them. The rabbits cause several problems: 1. Our dog goes absolutely nuts barking at them through the window, chases them when she can in the back yard, and gently removes the young from their nest to play with (or tend to as a mother) when she finds a nest. 2. The nests are basically a hole in the ground about the size of a softball. They're easily big enough to cause a twisted ankle when stepped in while walking in the yard. 3. I'd like to start planting tomatoes and other vegetables, but I'm fearful the rabbits will have their way with my crops. I've recently started using [Liquid Fence](http://www.liquidfence.com/), but it's hard to say if that's had much of an effect. I've certainly still had some rabbits, but maybe not as often. What's the best course of action for me?
2011/06/08
[ "https://gardening.stackexchange.com/questions/140", "https://gardening.stackexchange.com", "https://gardening.stackexchange.com/users/105/" ]
Truly, having dogs around gets rid of rabbits, feral cats, deer, bobcat, fishers, voles, moles...etc. You don't have to allow the dogs to kill them. Helloooo! Rabies and all kinds of disease could be transferred. It takes a few months but works just fine! I have all of the above and more. That and freezing temperatures at night any night of the year. I just went with a greenhouse and solves most of those problems. I've shot one animal one time at 100 yards with a 22, it was a rabbit. It screamed! I'll never forget it. Made myself eat the poor thing. I have no problem with hunting and killing done correctly and humanely. I love my meat-sigh-but it'll be vegetarianism for me until I get hungry enough to kill. Lots of meat around here! This area is full of squirrels (I love them!!), rabbits, rodents, feral cats not to mention lots of coyote, bobcat and cougar. I've two dogs I don't allow freedom to roam. My cats forever and always will be indoor cats. Yup, I have to exercise to exercise my dogs. Oh well! I've got two horses as well and I have to exercise them or be a heartless, self-centered and overweight person. This is my first garden here and it is a tough place. The greenhouses solved 90% of these problems. Having dogs, just having them here, pooping, peeing and occasionally barking has scared away most of these animals. The point is, if you kill one, there are thousands waiting in line to fill in the niche. They do belong and it is up to us to figure out how to live together. That is why we have this so-called intelligence we think makes us so special. Killing should only be done for food. Period. Period!! I've made it happen and most of my life I've been a single parent with all of the responsibilities and work. It is not tough. Killing and pesticides are a last, last resort. They only make more trouble. Think of it this way; you are training your environment (including your animals, varmints) to live in harmony with you. You start killing them and then you have to teach the new guys the 'rules' all over again. You allow your dogs to start killing and the next thing you know is they'll kill your neighbor's cats, little yappy dogs or bite kids. You don't need that heartache nor the expense! Relax! If you are going to be a gardener then you should know you can't control anything!!! Orchestrating harmony is vastly superior, humility and education is a must! We are not more important nor more special than any other form of life. Asking questions on this site, studying, researching, going to school are the best ways to show we humans have something going for us. Kudos to you!!
To try to get rid of nature, is like living in a bubble. Try to work with it and you'll probably be surprised. Last summer I was fortunate enough to flush out 4 baby rabbits before I ran over them with the lawn mower! I got them one by one and put them over in the woods-phew! I've seen a few in the back yard, but none bother my flower garden, mostly feed on certain weeds that are out there. Another deterrent is tabasco mixed with water, spray on or around the plants. As far as moles go, I've used a store bought repellent. They were so bad I had them in my flower beds. Eventually they've gone from the front yard towards the back. Stay diligent.
140
I have rabbits that routinely build nests in my yard. How can I get rid of the rabbits legally? I don't want some officer from the DNR knocking on my door because I improperly hunted or poisoned them. The rabbits cause several problems: 1. Our dog goes absolutely nuts barking at them through the window, chases them when she can in the back yard, and gently removes the young from their nest to play with (or tend to as a mother) when she finds a nest. 2. The nests are basically a hole in the ground about the size of a softball. They're easily big enough to cause a twisted ankle when stepped in while walking in the yard. 3. I'd like to start planting tomatoes and other vegetables, but I'm fearful the rabbits will have their way with my crops. I've recently started using [Liquid Fence](http://www.liquidfence.com/), but it's hard to say if that's had much of an effect. I've certainly still had some rabbits, but maybe not as often. What's the best course of action for me?
2011/06/08
[ "https://gardening.stackexchange.com/questions/140", "https://gardening.stackexchange.com", "https://gardening.stackexchange.com/users/105/" ]
I've heard of dried blood working well as a repellent for rabbits as well as deer. If you were to plant a vegetable garden you could sprinkle some of this around the plants as a sort of combination fertilizer/pest deterrent.
Truly, having dogs around gets rid of rabbits, feral cats, deer, bobcat, fishers, voles, moles...etc. You don't have to allow the dogs to kill them. Helloooo! Rabies and all kinds of disease could be transferred. It takes a few months but works just fine! I have all of the above and more. That and freezing temperatures at night any night of the year. I just went with a greenhouse and solves most of those problems. I've shot one animal one time at 100 yards with a 22, it was a rabbit. It screamed! I'll never forget it. Made myself eat the poor thing. I have no problem with hunting and killing done correctly and humanely. I love my meat-sigh-but it'll be vegetarianism for me until I get hungry enough to kill. Lots of meat around here! This area is full of squirrels (I love them!!), rabbits, rodents, feral cats not to mention lots of coyote, bobcat and cougar. I've two dogs I don't allow freedom to roam. My cats forever and always will be indoor cats. Yup, I have to exercise to exercise my dogs. Oh well! I've got two horses as well and I have to exercise them or be a heartless, self-centered and overweight person. This is my first garden here and it is a tough place. The greenhouses solved 90% of these problems. Having dogs, just having them here, pooping, peeing and occasionally barking has scared away most of these animals. The point is, if you kill one, there are thousands waiting in line to fill in the niche. They do belong and it is up to us to figure out how to live together. That is why we have this so-called intelligence we think makes us so special. Killing should only be done for food. Period. Period!! I've made it happen and most of my life I've been a single parent with all of the responsibilities and work. It is not tough. Killing and pesticides are a last, last resort. They only make more trouble. Think of it this way; you are training your environment (including your animals, varmints) to live in harmony with you. You start killing them and then you have to teach the new guys the 'rules' all over again. You allow your dogs to start killing and the next thing you know is they'll kill your neighbor's cats, little yappy dogs or bite kids. You don't need that heartache nor the expense! Relax! If you are going to be a gardener then you should know you can't control anything!!! Orchestrating harmony is vastly superior, humility and education is a must! We are not more important nor more special than any other form of life. Asking questions on this site, studying, researching, going to school are the best ways to show we humans have something going for us. Kudos to you!!
140
I have rabbits that routinely build nests in my yard. How can I get rid of the rabbits legally? I don't want some officer from the DNR knocking on my door because I improperly hunted or poisoned them. The rabbits cause several problems: 1. Our dog goes absolutely nuts barking at them through the window, chases them when she can in the back yard, and gently removes the young from their nest to play with (or tend to as a mother) when she finds a nest. 2. The nests are basically a hole in the ground about the size of a softball. They're easily big enough to cause a twisted ankle when stepped in while walking in the yard. 3. I'd like to start planting tomatoes and other vegetables, but I'm fearful the rabbits will have their way with my crops. I've recently started using [Liquid Fence](http://www.liquidfence.com/), but it's hard to say if that's had much of an effect. I've certainly still had some rabbits, but maybe not as often. What's the best course of action for me?
2011/06/08
[ "https://gardening.stackexchange.com/questions/140", "https://gardening.stackexchange.com", "https://gardening.stackexchange.com/users/105/" ]
Deer and rabbits both have a very keen sense of smell. I use a mixture of garlic powder, chili powder and water to keep the deer out of the garden. I am pretty sure that would work for rabbits as well. Spray it around where they are nesting and see if they move. If they do make up a large batch and spray the whole yard. I spray once a week on average. If it rains I spray again as soon as it's dry.
Every product I've tried hasn't worked for long. I finally put up chicken wire. That's the only thing that worked. What didn't work - Don't waste your money. An owl with light up eyes, moved every couple of days to a different spot. Many different brands of rabbit repellant, including Liquid Fence. Crushed up egg shells. Plastic snakes. All different colors. Spraying the bunnies with a garden hose - they come right back. What did work - I had three places to fence in. Once I got the hang of it, a 20' by 15' bed took me around an hour to install. I used 24" tall cheap chicken wire. It was around $10.00 for a 50 foot roll. I bought 8-foot 2" x 1" lumber for $1.00 apiece. I had each one cut into four 2-foot pieces. I used plastic zip ties to attach the chicken wire to the stakes. I spaced the stakes about 4 to 6 feet apart. On the first fence I buried the chicken wire a few inches. That worked. Then I tried bending the wire outward a few inches. That worked too. For the last bed I didn't bother burying it or bending it. That worked fine too. I thought they might chew through wood or the zip ties or burrow under the fences but they didn't. Good luck!
140
I have rabbits that routinely build nests in my yard. How can I get rid of the rabbits legally? I don't want some officer from the DNR knocking on my door because I improperly hunted or poisoned them. The rabbits cause several problems: 1. Our dog goes absolutely nuts barking at them through the window, chases them when she can in the back yard, and gently removes the young from their nest to play with (or tend to as a mother) when she finds a nest. 2. The nests are basically a hole in the ground about the size of a softball. They're easily big enough to cause a twisted ankle when stepped in while walking in the yard. 3. I'd like to start planting tomatoes and other vegetables, but I'm fearful the rabbits will have their way with my crops. I've recently started using [Liquid Fence](http://www.liquidfence.com/), but it's hard to say if that's had much of an effect. I've certainly still had some rabbits, but maybe not as often. What's the best course of action for me?
2011/06/08
[ "https://gardening.stackexchange.com/questions/140", "https://gardening.stackexchange.com", "https://gardening.stackexchange.com/users/105/" ]
After just reading the title, I was going to suggest get a dog. Our dog has killed a couple rabbits already this year. Perhaps you could simply leave your dog in the yard more often, letting him/her out when she's barking at them through the window. I guess this depends if your dog is fast enough to catch them. You could consider getting another dog, perhaps a bigger, faster one. Another note: when putting in vegetables, make sure you have a sure method of keeping your dog out of them. Our dog ate quite a few of our green beans last year (didn't bother the tomatoes, though), so we had to put up a higher fence this year.
Every product I've tried hasn't worked for long. I finally put up chicken wire. That's the only thing that worked. What didn't work - Don't waste your money. An owl with light up eyes, moved every couple of days to a different spot. Many different brands of rabbit repellant, including Liquid Fence. Crushed up egg shells. Plastic snakes. All different colors. Spraying the bunnies with a garden hose - they come right back. What did work - I had three places to fence in. Once I got the hang of it, a 20' by 15' bed took me around an hour to install. I used 24" tall cheap chicken wire. It was around $10.00 for a 50 foot roll. I bought 8-foot 2" x 1" lumber for $1.00 apiece. I had each one cut into four 2-foot pieces. I used plastic zip ties to attach the chicken wire to the stakes. I spaced the stakes about 4 to 6 feet apart. On the first fence I buried the chicken wire a few inches. That worked. Then I tried bending the wire outward a few inches. That worked too. For the last bed I didn't bother burying it or bending it. That worked fine too. I thought they might chew through wood or the zip ties or burrow under the fences but they didn't. Good luck!
24,517
As title above, how to play vs. ``` [fen ""] 1.e4 e5 2.Nf3 Nc6 3.Bc4 d6 ``` I see that this move (3...d6) is generally considered inferior in books, or not even mentioned in books about 3.Bc4, but I cannot see a clear way to obtain advantage.
2019/05/18
[ "https://chess.stackexchange.com/questions/24517", "https://chess.stackexchange.com", "https://chess.stackexchange.com/users/8291/" ]
The game will get the characteristics of the Philidor Defense rather than the Italian Game. Wikipedia calls it the [Semi-Italian Opening](https://en.wikipedia.org/wiki/Semi-Italian_Opening). > > I. A. Horowitz called the defence "solid", also writing: "It does not seem quite sufficient for equality." > > > The Wikipedia article notes several possible continuations for White, with 4. d4 probably the best bet for advantage.
There is no way to "crush" that move. You just play! Develop your pieces, get space in the center and obtain a small advantage. Your opponent won't be losing a piece or something like that. I assume 3...d6 may have some ideas related to a pin on g4 (for instance, 4.d4 Bg4) A c3 pawn advance can be useful to prevent some ...Nd4. I think you'll be fine after 4.0-0 Bg4 5.c3, but also 4.Nc3 Bg4 5.h3 or many other sequences In short, I don't know what the best answer is. I doubt anyone in the world actually does. Analyze your games and find what works best for yourself
24,517
As title above, how to play vs. ``` [fen ""] 1.e4 e5 2.Nf3 Nc6 3.Bc4 d6 ``` I see that this move (3...d6) is generally considered inferior in books, or not even mentioned in books about 3.Bc4, but I cannot see a clear way to obtain advantage.
2019/05/18
[ "https://chess.stackexchange.com/questions/24517", "https://chess.stackexchange.com", "https://chess.stackexchange.com/users/8291/" ]
1.e4 e5 2.Nf3 Nc6 3.Bc4 d6: 365chess.com database shows: ``` MOVE | games | year | White + Draw + Black -------+-------+------+--------+--------+------- 4. d4 | 491 | 2018 | 50.3 % | 24.4 % | 25.3 % 4. c3 | 359 | 2018 | 53.5 % | 20.6 % | 25.9 % 4. d3 | 357 | 2018 | 45.4 % | 22.7 % | 31.9 % 4. h3 | 323 | 2016 | 42.7 % | 25.7 % | 31.6 % 4. Nc3 | 289 | 2018 | 50.9 % | 16.3 % | 32.9 % 4. O-O | 249 | 2019 | 50.6 % | 22.1 % | 27.3 % ``` White will get a space advantage and freer development after d4 (whether delayed or played immediately). Or White can play the pawn to d3 and the fact that his Bishop is outside the pawn chain (and Blacks Bf8 is inside) gives White an easier position. There is no knock-out blow for White as Black is accepting a slightly passive but solid position.
There is no way to "crush" that move. You just play! Develop your pieces, get space in the center and obtain a small advantage. Your opponent won't be losing a piece or something like that. I assume 3...d6 may have some ideas related to a pin on g4 (for instance, 4.d4 Bg4) A c3 pawn advance can be useful to prevent some ...Nd4. I think you'll be fine after 4.0-0 Bg4 5.c3, but also 4.Nc3 Bg4 5.h3 or many other sequences In short, I don't know what the best answer is. I doubt anyone in the world actually does. Analyze your games and find what works best for yourself
72,902,209
how to create a regex that replaces a space with an underscore and adds spaces between semicolons? Replacing a space with a underscore in the entire text can be solved: ``` data.replace(/ /g, "_"); ``` But how to solve the situation with semicolons at the same time? The point is that I have a text file that separates individual texts with an underscore. If it does not contain any data, it simply continues in the next semicolons: ``` data;data;;data;;;data ``` I need it to add a blank space between the semicolons in each case. The problem is that the number of semicolons is irregular and I always need to add a space: ``` data;data; ;data; ; ;data ``` There are more than 10,000 such lines in the text file. Is there a solution for my case? ```js const data = "red;;I WW2;123;;;error;more;;blue;;;;123;I love you"; const replaceData = data.replace(/ /g, "_"); /* // //This is not a solution for me, as the number of semicolons is not always the same. And I also can't combine this regex into one. // //const replaceData2 = data.replace(/;;/g, "; ;"); */ console.log(replaceData); ``` The result should be like this: ``` red; ;I_WW2;123; ; ;error;more; ;blue; ; ; ;123;I_love_you ``` Thanks
2022/07/07
[ "https://Stackoverflow.com/questions/72902209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12648892/" ]
You can call `.replace` twice: ```js const data = "red;;I WW2;123;;;error;more;;blue;;;;123;I love you"; var repl = data.replace(/ +/g, "_").replace(/;(?=;)/g, "$& "); console.log(repl); ``` But make sure to replace spaces with `_` before inserting spaces between `;`s. * `.replace(/ +/g, "_")`: Replace 1+ spaces with `_` * `.replace(/;(?=;)/g, "$& ")`: Insert space between 2 adjacent semicolons
If you want to do it with one regex, it can be done with a callback argument, but this will also cost execution time. Like I wrote in comments, it may turn out to be better to stick with 2 `replace` calls. Just see how it performs in your environment, and on your data. Here is how it would work with callback: ```js const data = "red;;I WW2;123;;;error;more;;blue;;;;123;I love you"; const result = data.replace(/ |(?<=;)(?=;)/g, m => " _"[m.length]); console.log(result); ``` The regex has a zero-length match between two semi-colons, so when it matches that, `m` will be the empty string (in the callback). So the size of `m` can be used to distinguish the two cases, and `length` can then serve to select the replacement character (either a space or an underscore).
72,902,209
how to create a regex that replaces a space with an underscore and adds spaces between semicolons? Replacing a space with a underscore in the entire text can be solved: ``` data.replace(/ /g, "_"); ``` But how to solve the situation with semicolons at the same time? The point is that I have a text file that separates individual texts with an underscore. If it does not contain any data, it simply continues in the next semicolons: ``` data;data;;data;;;data ``` I need it to add a blank space between the semicolons in each case. The problem is that the number of semicolons is irregular and I always need to add a space: ``` data;data; ;data; ; ;data ``` There are more than 10,000 such lines in the text file. Is there a solution for my case? ```js const data = "red;;I WW2;123;;;error;more;;blue;;;;123;I love you"; const replaceData = data.replace(/ /g, "_"); /* // //This is not a solution for me, as the number of semicolons is not always the same. And I also can't combine this regex into one. // //const replaceData2 = data.replace(/;;/g, "; ;"); */ console.log(replaceData); ``` The result should be like this: ``` red; ;I_WW2;123; ; ;error;more; ;blue; ; ; ;123;I_love_you ``` Thanks
2022/07/07
[ "https://Stackoverflow.com/questions/72902209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12648892/" ]
You can call `.replace` twice: ```js const data = "red;;I WW2;123;;;error;more;;blue;;;;123;I love you"; var repl = data.replace(/ +/g, "_").replace(/;(?=;)/g, "$& "); console.log(repl); ``` But make sure to replace spaces with `_` before inserting spaces between `;`s. * `.replace(/ +/g, "_")`: Replace 1+ spaces with `_` * `.replace(/;(?=;)/g, "$& ")`: Insert space between 2 adjacent semicolons
this will help you to get your desire output. 1. Positive Lookbehind (?<=;) 2. Positive Lookahead (?=;) and we replace it with `" "` `space`. ```js const data = "red;;I WW2;123;;;error;more;;blue;;;;123;I love you"; const replaceData = data.replace(/(?<=;)(?=;)/g, " "); console.log(replaceData) ```
26,339
Every `Account` has its owner who is `Person` The bank has list of owners. I am not sure if my destructors are right and `delete bank` will delete all elements of `list<Account*>* v` nad the list itself. Please help. ``` #include <iostream> #include <vector> #include <list> using namespace std; class Person{ public: char* name; int age; Person(char* name, int age){ this->name = name; this->age = age; } ~Person(){ } void show(){ cout<<name<<" "<<age<<" yo"; } }; class Account{ public: Person& owner; double money; Account(Person* owner, double money): owner(*owner) , // this->owner = *owner; money(money) { //Uninitialized reference member } void show(){ cout<<"\n-------------\n"; owner.show(); cout<<endl; cout<<money<<"USD\n-------------"; } ~Account(){ } }; class Bank{ public: list<Account*>* v; Bank(){ v = new list<Account*>(); } Account* openNewAccount(Person* client, double money){ Account* r = new Account(client, money); v->push_back(r); return r; } void zmienWlasciciela(Person& o, Account* r){ r->owner = o; } void usunRachunek(Account* r){ cout<<"\n\n\nUSUNALEM"<<endl; v->remove(r); delete r; } void show(){ for (list<Account*>::iterator it = v->begin(); it != v->end(); ++it){ (*it)->show(); } } ~Bank(){ delete v; } }; int main(){ Bank* bank = new Bank(); Person* thomas = new Person("thomas", 34); Account* r1 = bank->openNewAccount(thomas, 64363.32); Account* r2 = bank->openNewAccount(thomas, 41251.54); Account* r3 = bank->openNewAccount(thomas, 3232.32); bank->show(); Person* margaret = new Person("Margaret", 23); bank->zmienWlasciciela(*margaret, r2); cout<<"I have changed owner of account r2"<<endl; bank->show(); cout<<"I have deleted account r3"<<endl; bank->usunRachunek(r3); bank->show(); delete bank; return 0; } ```
2013/05/19
[ "https://codereview.stackexchange.com/questions/26339", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/25235/" ]
General Comment on Style ------------------------ This is probably not what you want. ``` Bank* bank = new Bank(); Person* thomas = new Person("thomas", 34); ``` You actually want: ``` Bank bank; Person thomas("thomas", 34); ``` This creates automatic variables. That are properly destroyed automatically at the end of scope. It is very rare to use RAW pointers in C++ `Bank*` or `Person*`. When you dynamically allocate objects using `new` you want to make sure that the returned pointer is put into an object that controls their lifespan and garbage collects the values when you are finished using them. ``` std::shared_ptr<Bank> bank = new Bank; // This is the closest to a Java object // that C++ has. It allows multiple users // and it is correctly destroyed when nobody // has a reference to it anymore. ``` Looking at the code: -------------------- Don't do this: ``` using namespace std; ``` I know all the shitty C++ books you read have it in. Its fine for 10 line long programs you type out of a book. But once you get past those programs it can cause problems with namespace pollution. Its thus a very bad habit and one you should break as soon as possible. See: <https://stackoverflow.com/q/1452721/14065> ### Person Pointers are bad. ``` char* name; ``` Unless you do a lot of validation and know the ownership of the thing you are pointing at and it is not going to be cleaned up behind you then you should be very weary of using pointers. I have checked your code and you are fine in this simple program but this is not a good design outside of a small toy project. C++ also has its own string type `std::string` so you don't need to know or use C-String. So I would change this to ``` std::string name; ``` In constructors prefer to use the initializer list to initialize the members. ``` Person(char* name, int age){ this->name = name; this->age = age; } ``` Second point about pointers here. Its not normal to pass pointers to around in C++ (this is very common in C but modern C++ you should basically never do it (with a few exceptions that you will work out when you have more experience)). Pass objects by reference if you want to retain ownership; otherwise pass a smart\_pointer to transfer ownership of the object. In this case you want to pass a `std::string`. As you don't want to change the original but make your own copy pass a const reference (if you are in C++11 you may want to also add a move constructor (but this is advanced so don't worry about it)). So it should look more like: ``` Person(std::string const& name, int age) : name(name) , age(age) {} ``` If a destructor does not do anything then don't declare it. ``` ~Person(){ } ``` Its fine to have a public `show()` method. But any method that does not change the state of the object should be declared as `const`. This allows you to call the object from const objects (useful technique later). And if you add a parameter so it can be any stream it makes it more versatile. But you should also declare a stream operator for your Person type. Thus you can stream your person just like any other type. ``` void show(std::ostream& out = std::cout) const { // ^^^^^ Does not change the state // so make the method const. // ^^^^^^^^^^^^^^^^^ Pass stream to print on. // You may want to print in other places. // rather than std::cout (like a file). out<<name<<" "<<age<<" yo"; // A few spaces to make it readable // would be nice. } // Pass person by const reference so the compiler // knows you are not going to modify the object. // This means you can only call const methods (so `show()` must be const. std::ostream& operator<<(std::stream& stream, Person const& person) { person.show(stream); return stream; } int main() { std::cout << Perons("Loki", 962) << "\n"; } ``` ### Account This is fine. ``` Person& owner; ``` It means you have a reference to a person that is stored somewhere else. But you need to be careful of lifetimes. Make sure the `Person` object is still alive while you are alive. Passing by pointer again. ``` Account(Person* owner, double money): ``` This is dangerous. Especially since you de-reference without checking. Since you are storing a reference. Pass the value in by reference. ``` Account(Person& owner, double money) : owner(owner) , money(money) {} ``` Make the `show()` method const and pass a stream. ``` void show(std::ostream& out = std::cout) const { // ^^^^^ out<<"\n-------------\n" << owner << std::endl << money<<"USD\n-------------"; return out; } ``` Add a stream operator ``` std::ostream& operator<<(std::stream& stream, Account const& account) { account.show(stream); } ``` Destructor does nothing so remove it. ``` ~Account(){ } ``` ### Bank Ok. Obviously a java (or java inspired language user). ``` list<Account*>* v; ``` You don't want to use pointers here. By making this a pointer you need to do all sorts of memory management (and make sure you obey the rule of three (look it up)). But you don't need to do that just make it a normal object and all those problems go away. list v; When the bank object is created. It automatically creates a list now. When the bank is destroyed it automatically cleans up its members (including the list). When the back is copied it automatically copies the accounts to the new Bank. Second; don't make the Account's inside the list pointers. Again you will need to manage the each object and control its lifespan. Much easier to put Account objects into the list. list v; There is also a principle called `Separation of Concerns`. Basically this says that an type should either be `Business Logic` or `Resource Management` you should not do both in the same type. Since `Bank` is obviously business logic you should not be doing resource management in the Bank. If you were using pointers then you would delegate the memory management of those pointers to anther type that would correctly do the clean up. C++ already has a whole bunch of smart pointers explicitly for managing pointers. **BUT** in this situation I would defiantly sidestep the memory management by using automatic objects and make the changes I described above as **ALL** your memory management issues disappear. Remember use initializer list. ``` Bank(){ v = new list<Account*>(); } ``` But if you change the type as (described above) you don't need to do anything. The object automatically creates and initializes all members. Again passing pointers is bad: ``` Account* openNewAccount(Person* client, double money){ Account* r = new Account(client, money); v->push_back(r); return r; } ``` If you return a pointer `Account*` you don't specify any ownership semantics. If you don't specify ownership semantics then you are very liable to leak as nobody knows who is supposed to clean up. In this situation the `Account` obviously belongs to the Bank object (The Bank will do the memory management). So here you should return a reference. This is an indication you can use the account. But the account will be managed by the Bank. ``` Account& openNewAccount(Person const& client, double money) { Account newAccount(client, money); // Create a new account. v->push_back(newAccount); // Not when you push objects into containers // they make a copy of the object. // So you have a copy of `newAccount` return v.last(); // return a reference to the last member of `v` // that you just pushed there via `push_back` // The user can now operate on the referenc // Also the reference will never be NULL // so the user needs to check for that. } ``` Pass by reference. You don't need to check for NULL ``` void zmienWlasciciela(Person& o, Account* r) // Becomes. void zmienWlasciciela(Person& o, Account& r){ r.owner = o; } ``` Pass by reference (that's how it was given to you). ``` void usunRachunek(Account* r) // Becomes void usunRachunek(Account* r){ cout<<"\n\n\nUSUNALEM"<<endl; v.remove(r); } ``` Make `show()` const and take a stream ``` void show(std::ostream& out = std::cout ) const { for (list<Account*>::iterator it = v.begin(); it != v.end(); ++it){ (*it)->show(out); } ``` You could use a simple algorithm to copy the Account to the stream. ``` void show(std::ostream& out = std::cout ) const { // for this to work Account must have operator<< defined. std::copy(v.begin(), v.end(), std::ostream_iterator(out)); } } ``` This is correct **BUT NOT ENOUGH** for your original definition where v is a pointer. If you use objects you don't need to do anything. ``` ~Bank(){ delete v; } ``` If you were using pointers then you also need to define a copy constructor and assignment operator to make sure you are not violating the rule of three. If you are using objects the compiler generated defaults work perfectly fine.
Deleting the vector will only delete the pointers in the vector, not the things to which they point. You need to iterate though the vector deleting the accounts before deleting the vector.
27,070,425
I have been working on this form and can't get past the CalculateTotal. I am completely lost on how to get this to add up and display in the box. Can anyone help? Here is my jsfiddle <http://jsfiddle.net/clbacon70/x6kjqbop/1/> ```js var gc_fSandwichPrice = 5.99; // Price for each sandwich var gc_fExtrasPrice = 1.50; // Price for each extra item // GLOBAL VARS // Global object vars var divErrors; var radSandwich; var radSize; var chkExtras; // Other global vars var g_fTotal; var g_sSandwich; var g_sSize; var g_sExtras; window.addEventListener('load', Init); function Init() { document.getElementById("h1Title").innerHTML = "Dirty Deli 1.0"; var spanExtrasPrice = document.getElementById("spanExtrasPrice"); var btnCalculateTotal = document.getElementById("btnCalculateTotal"); divErrors = document.getElementById("divErrors"); radSandwich = document.getElementsByName('radSandwich'); radSize = document.getElementsByName('radSize'); chkExtras = document.getElementsByName('chkExtras'); spanExtrasPrice.innerHTML = gc_fExtrasPrice.toFixed(2); btnCalculateTotal.addEventListener('click', CalculateTotal); } // function Init() function CalculateTotal() { divErrors.innerHTML = ''; if (radSandwich[0].checked) { g_sSandwich = radSandwich[0].value; } else if (radSandwich[1].checked) { g_sSandwich = radSandwich[1].value; } else if (radSandwich[2].checked) { g_sSandwich = radSandwich[2].value; } else if (radSandwich[3].checked) { g_sSandwich = radSandwich[3].value; } else { divErrors.innerHTML = "Select a Sandwich"; return; } if (radSize[0].checked){ g_fTotal = radSize[0].title; } else if (radSize[1].checked) { g_fTotal = radSize[1].title; } else if (radSize[2].checked) { g_fTotal = radSize[2].title; } else { divErrors.innerHTML = "Please choose a size"; return; } if (chkExtras[0].checked) { g_sExtras = chkExtras[0].value; g_fTotal = g_fTotal + gc_fExtrasPrice; } if (chkExtras[1].checked) { g_sExtras = g_sExtras + ',' + chkExtras[1].value; g_fTotal = g_fTotal + gc_fExtrasPrice; } if (chkExtras[2].checked) { g_sExtras = g_sExtras +', ' + chkExtras[2].value; g_fTotal = g_fTotal + gc_fExtrasPrice; } var textTotal = document.getElementById('textTotal'); textTotal.value = g_fTotal; } // function CalculateTotal function ProcessOrder() { } // function ProcessOrder ``` ```css * { margin: 0; padding: 0; } body { background-color: #333; } #divWrapper { background-color: #efe; width: 40em; border: solid black; border-radius: 0 0 20px 20px; border-width: 0 1px 1px 1px; margin: 0 auto; padding: 2em 1em; } h2 { font-style: italic; font-size: 1.3em; color: #666; margin-top: 0px; } input { margin-right: 0.3em; } h3, p { margin: 0.5em 0; } div#divErrors { font-size: 110%; color: white; background: #f00; margin-bottom: 0.5em; } #divPaymentInfo { margin: 10px 0 20px 0; padding-bottom: 10px; border: solid black; border-width: 1px 0; } #divCreditCardInfo { font-size: .8em; visibility: hidden; margin-left: 1em; display: inline; } #divOrder { background: white; min-height: 10em; width: 25em; border: 1px solid black; margin: 0.5em 0; padding: 10px; } ``` ```html <body> <div id="divWrapper"> <form name="frmMain"> <h1 id="h1Title">Deli Form</h1> <h2>Part 1</h2> <h3>Sandwich</h3> <label><input type="radio" name="radSandwich" value="Breast of Chicken">Breast of Chicken</label><br> <label><input type="radio" name="radSandwich" value="Leg of Lamb">Leg of Lamb</label><br> <label><input type="radio" name="radSandwich" value="Loin of Ham">Loin of Ham</label><br> <label><input type="radio" name="radSandwich" value="ReelMeat&reg;">ReelMeat&reg;</label><br> <br> <h3>Size</h3> <label><input type="radio" name="radSize" value="Manly Man" title="$4.99">Manly Man</label>&nbsp;&nbsp; <label><input type="radio" name="radSize" value="Girly Man" title="$5.99">Girly Man</label>&nbsp;&nbsp; <label><input type="radio" name="radSize" value="Super Girly Man" title="$6.99">Super Girly Man</label> <br><br> <h3>Extras ($<span id="spanExtrasPrice"></span> each)</h3> <label><input type="checkbox" name="chkExtras" value="Deep-Fried Spam">Deep-Fried Spam</label><br> <label><input type="checkbox" name="chkExtras" value="Toenails">Toenails</label><br> <label><input type="checkbox" name="chkExtras" value="Secret Sauce">Secret Sauce</label><br> <br><br> Total: <input type="text" id="txtTotal" size="5"> <input type="button" id="btnCalculateTotal" value="Calculate Total"> <br><br> <div id="divErrors"></div> <div id="divPaymentInfo"> <h2>Part 2</h2> <strong>Customer's Name:</strong> <input type="text" id="txtName"> <br><br> <strong>Payment:</strong> <select id="selPayment"> <option value="Cash" selected="selected">Cash</option> <option value="Check">Check</option> <option value="Credit Card">Credit Card</option> </select> <div id="divCreditCardInfo"> Card Number: <input type="text" id="txtCreditCardNbr" size="20">&nbsp;&nbsp; Month: <input type="text" id="txtMonth" size="2">&nbsp;&nbsp;Year: <select id="selYear"> <option value="" selected="selected"></option> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> <option value="2010">2017</option> <option value="2011">2018</option> </select> </div><!-- divCreditCardInfo --> </div><!-- divPaymentInfo --> <input type="button" id="btnProcessOrder" value="Process Order"> <div id="divOrder"></div> <input type="reset" value="Reset"> </form> </div> <!-- divWrapper --> </body> ```
2014/11/21
[ "https://Stackoverflow.com/questions/27070425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3381376/" ]
You have a typo in your javascript. You are attempting to fetch an html element with id `textTotal`, when the field you're interesting in is actually given the id `txtTotal`. Fix that typo and it will work.
You have to add brackets after 'Init'. ``` window.addEventListener('load', Init()); ``` And also there was a typo in the end of CalculateTotal function. Here is working example: <http://jsfiddle.net/x6kjqbop/3/>
27,070,425
I have been working on this form and can't get past the CalculateTotal. I am completely lost on how to get this to add up and display in the box. Can anyone help? Here is my jsfiddle <http://jsfiddle.net/clbacon70/x6kjqbop/1/> ```js var gc_fSandwichPrice = 5.99; // Price for each sandwich var gc_fExtrasPrice = 1.50; // Price for each extra item // GLOBAL VARS // Global object vars var divErrors; var radSandwich; var radSize; var chkExtras; // Other global vars var g_fTotal; var g_sSandwich; var g_sSize; var g_sExtras; window.addEventListener('load', Init); function Init() { document.getElementById("h1Title").innerHTML = "Dirty Deli 1.0"; var spanExtrasPrice = document.getElementById("spanExtrasPrice"); var btnCalculateTotal = document.getElementById("btnCalculateTotal"); divErrors = document.getElementById("divErrors"); radSandwich = document.getElementsByName('radSandwich'); radSize = document.getElementsByName('radSize'); chkExtras = document.getElementsByName('chkExtras'); spanExtrasPrice.innerHTML = gc_fExtrasPrice.toFixed(2); btnCalculateTotal.addEventListener('click', CalculateTotal); } // function Init() function CalculateTotal() { divErrors.innerHTML = ''; if (radSandwich[0].checked) { g_sSandwich = radSandwich[0].value; } else if (radSandwich[1].checked) { g_sSandwich = radSandwich[1].value; } else if (radSandwich[2].checked) { g_sSandwich = radSandwich[2].value; } else if (radSandwich[3].checked) { g_sSandwich = radSandwich[3].value; } else { divErrors.innerHTML = "Select a Sandwich"; return; } if (radSize[0].checked){ g_fTotal = radSize[0].title; } else if (radSize[1].checked) { g_fTotal = radSize[1].title; } else if (radSize[2].checked) { g_fTotal = radSize[2].title; } else { divErrors.innerHTML = "Please choose a size"; return; } if (chkExtras[0].checked) { g_sExtras = chkExtras[0].value; g_fTotal = g_fTotal + gc_fExtrasPrice; } if (chkExtras[1].checked) { g_sExtras = g_sExtras + ',' + chkExtras[1].value; g_fTotal = g_fTotal + gc_fExtrasPrice; } if (chkExtras[2].checked) { g_sExtras = g_sExtras +', ' + chkExtras[2].value; g_fTotal = g_fTotal + gc_fExtrasPrice; } var textTotal = document.getElementById('textTotal'); textTotal.value = g_fTotal; } // function CalculateTotal function ProcessOrder() { } // function ProcessOrder ``` ```css * { margin: 0; padding: 0; } body { background-color: #333; } #divWrapper { background-color: #efe; width: 40em; border: solid black; border-radius: 0 0 20px 20px; border-width: 0 1px 1px 1px; margin: 0 auto; padding: 2em 1em; } h2 { font-style: italic; font-size: 1.3em; color: #666; margin-top: 0px; } input { margin-right: 0.3em; } h3, p { margin: 0.5em 0; } div#divErrors { font-size: 110%; color: white; background: #f00; margin-bottom: 0.5em; } #divPaymentInfo { margin: 10px 0 20px 0; padding-bottom: 10px; border: solid black; border-width: 1px 0; } #divCreditCardInfo { font-size: .8em; visibility: hidden; margin-left: 1em; display: inline; } #divOrder { background: white; min-height: 10em; width: 25em; border: 1px solid black; margin: 0.5em 0; padding: 10px; } ``` ```html <body> <div id="divWrapper"> <form name="frmMain"> <h1 id="h1Title">Deli Form</h1> <h2>Part 1</h2> <h3>Sandwich</h3> <label><input type="radio" name="radSandwich" value="Breast of Chicken">Breast of Chicken</label><br> <label><input type="radio" name="radSandwich" value="Leg of Lamb">Leg of Lamb</label><br> <label><input type="radio" name="radSandwich" value="Loin of Ham">Loin of Ham</label><br> <label><input type="radio" name="radSandwich" value="ReelMeat&reg;">ReelMeat&reg;</label><br> <br> <h3>Size</h3> <label><input type="radio" name="radSize" value="Manly Man" title="$4.99">Manly Man</label>&nbsp;&nbsp; <label><input type="radio" name="radSize" value="Girly Man" title="$5.99">Girly Man</label>&nbsp;&nbsp; <label><input type="radio" name="radSize" value="Super Girly Man" title="$6.99">Super Girly Man</label> <br><br> <h3>Extras ($<span id="spanExtrasPrice"></span> each)</h3> <label><input type="checkbox" name="chkExtras" value="Deep-Fried Spam">Deep-Fried Spam</label><br> <label><input type="checkbox" name="chkExtras" value="Toenails">Toenails</label><br> <label><input type="checkbox" name="chkExtras" value="Secret Sauce">Secret Sauce</label><br> <br><br> Total: <input type="text" id="txtTotal" size="5"> <input type="button" id="btnCalculateTotal" value="Calculate Total"> <br><br> <div id="divErrors"></div> <div id="divPaymentInfo"> <h2>Part 2</h2> <strong>Customer's Name:</strong> <input type="text" id="txtName"> <br><br> <strong>Payment:</strong> <select id="selPayment"> <option value="Cash" selected="selected">Cash</option> <option value="Check">Check</option> <option value="Credit Card">Credit Card</option> </select> <div id="divCreditCardInfo"> Card Number: <input type="text" id="txtCreditCardNbr" size="20">&nbsp;&nbsp; Month: <input type="text" id="txtMonth" size="2">&nbsp;&nbsp;Year: <select id="selYear"> <option value="" selected="selected"></option> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> <option value="2010">2017</option> <option value="2011">2018</option> </select> </div><!-- divCreditCardInfo --> </div><!-- divPaymentInfo --> <input type="button" id="btnProcessOrder" value="Process Order"> <div id="divOrder"></div> <input type="reset" value="Reset"> </form> </div> <!-- divWrapper --> </body> ```
2014/11/21
[ "https://Stackoverflow.com/questions/27070425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3381376/" ]
``` var textTotal = document.getElementById('textTotal'); ``` Your selector is wrong. The element id of your textbox is `txtTotal` so the following should work: ``` var textTotal = document.getElementById('txtTotal'); ```
You have to add brackets after 'Init'. ``` window.addEventListener('load', Init()); ``` And also there was a typo in the end of CalculateTotal function. Here is working example: <http://jsfiddle.net/x6kjqbop/3/>
27,070,425
I have been working on this form and can't get past the CalculateTotal. I am completely lost on how to get this to add up and display in the box. Can anyone help? Here is my jsfiddle <http://jsfiddle.net/clbacon70/x6kjqbop/1/> ```js var gc_fSandwichPrice = 5.99; // Price for each sandwich var gc_fExtrasPrice = 1.50; // Price for each extra item // GLOBAL VARS // Global object vars var divErrors; var radSandwich; var radSize; var chkExtras; // Other global vars var g_fTotal; var g_sSandwich; var g_sSize; var g_sExtras; window.addEventListener('load', Init); function Init() { document.getElementById("h1Title").innerHTML = "Dirty Deli 1.0"; var spanExtrasPrice = document.getElementById("spanExtrasPrice"); var btnCalculateTotal = document.getElementById("btnCalculateTotal"); divErrors = document.getElementById("divErrors"); radSandwich = document.getElementsByName('radSandwich'); radSize = document.getElementsByName('radSize'); chkExtras = document.getElementsByName('chkExtras'); spanExtrasPrice.innerHTML = gc_fExtrasPrice.toFixed(2); btnCalculateTotal.addEventListener('click', CalculateTotal); } // function Init() function CalculateTotal() { divErrors.innerHTML = ''; if (radSandwich[0].checked) { g_sSandwich = radSandwich[0].value; } else if (radSandwich[1].checked) { g_sSandwich = radSandwich[1].value; } else if (radSandwich[2].checked) { g_sSandwich = radSandwich[2].value; } else if (radSandwich[3].checked) { g_sSandwich = radSandwich[3].value; } else { divErrors.innerHTML = "Select a Sandwich"; return; } if (radSize[0].checked){ g_fTotal = radSize[0].title; } else if (radSize[1].checked) { g_fTotal = radSize[1].title; } else if (radSize[2].checked) { g_fTotal = radSize[2].title; } else { divErrors.innerHTML = "Please choose a size"; return; } if (chkExtras[0].checked) { g_sExtras = chkExtras[0].value; g_fTotal = g_fTotal + gc_fExtrasPrice; } if (chkExtras[1].checked) { g_sExtras = g_sExtras + ',' + chkExtras[1].value; g_fTotal = g_fTotal + gc_fExtrasPrice; } if (chkExtras[2].checked) { g_sExtras = g_sExtras +', ' + chkExtras[2].value; g_fTotal = g_fTotal + gc_fExtrasPrice; } var textTotal = document.getElementById('textTotal'); textTotal.value = g_fTotal; } // function CalculateTotal function ProcessOrder() { } // function ProcessOrder ``` ```css * { margin: 0; padding: 0; } body { background-color: #333; } #divWrapper { background-color: #efe; width: 40em; border: solid black; border-radius: 0 0 20px 20px; border-width: 0 1px 1px 1px; margin: 0 auto; padding: 2em 1em; } h2 { font-style: italic; font-size: 1.3em; color: #666; margin-top: 0px; } input { margin-right: 0.3em; } h3, p { margin: 0.5em 0; } div#divErrors { font-size: 110%; color: white; background: #f00; margin-bottom: 0.5em; } #divPaymentInfo { margin: 10px 0 20px 0; padding-bottom: 10px; border: solid black; border-width: 1px 0; } #divCreditCardInfo { font-size: .8em; visibility: hidden; margin-left: 1em; display: inline; } #divOrder { background: white; min-height: 10em; width: 25em; border: 1px solid black; margin: 0.5em 0; padding: 10px; } ``` ```html <body> <div id="divWrapper"> <form name="frmMain"> <h1 id="h1Title">Deli Form</h1> <h2>Part 1</h2> <h3>Sandwich</h3> <label><input type="radio" name="radSandwich" value="Breast of Chicken">Breast of Chicken</label><br> <label><input type="radio" name="radSandwich" value="Leg of Lamb">Leg of Lamb</label><br> <label><input type="radio" name="radSandwich" value="Loin of Ham">Loin of Ham</label><br> <label><input type="radio" name="radSandwich" value="ReelMeat&reg;">ReelMeat&reg;</label><br> <br> <h3>Size</h3> <label><input type="radio" name="radSize" value="Manly Man" title="$4.99">Manly Man</label>&nbsp;&nbsp; <label><input type="radio" name="radSize" value="Girly Man" title="$5.99">Girly Man</label>&nbsp;&nbsp; <label><input type="radio" name="radSize" value="Super Girly Man" title="$6.99">Super Girly Man</label> <br><br> <h3>Extras ($<span id="spanExtrasPrice"></span> each)</h3> <label><input type="checkbox" name="chkExtras" value="Deep-Fried Spam">Deep-Fried Spam</label><br> <label><input type="checkbox" name="chkExtras" value="Toenails">Toenails</label><br> <label><input type="checkbox" name="chkExtras" value="Secret Sauce">Secret Sauce</label><br> <br><br> Total: <input type="text" id="txtTotal" size="5"> <input type="button" id="btnCalculateTotal" value="Calculate Total"> <br><br> <div id="divErrors"></div> <div id="divPaymentInfo"> <h2>Part 2</h2> <strong>Customer's Name:</strong> <input type="text" id="txtName"> <br><br> <strong>Payment:</strong> <select id="selPayment"> <option value="Cash" selected="selected">Cash</option> <option value="Check">Check</option> <option value="Credit Card">Credit Card</option> </select> <div id="divCreditCardInfo"> Card Number: <input type="text" id="txtCreditCardNbr" size="20">&nbsp;&nbsp; Month: <input type="text" id="txtMonth" size="2">&nbsp;&nbsp;Year: <select id="selYear"> <option value="" selected="selected"></option> <option value="2012">2012</option> <option value="2013">2013</option> <option value="2014">2014</option> <option value="2015">2015</option> <option value="2016">2016</option> <option value="2010">2017</option> <option value="2011">2018</option> </select> </div><!-- divCreditCardInfo --> </div><!-- divPaymentInfo --> <input type="button" id="btnProcessOrder" value="Process Order"> <div id="divOrder"></div> <input type="reset" value="Reset"> </form> </div> <!-- divWrapper --> </body> ```
2014/11/21
[ "https://Stackoverflow.com/questions/27070425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3381376/" ]
Here's a fixed copy of your jsFiddle: <http://jsfiddle.net/dcseekcw/> What I fixed: * You were passing in `$` along with values you were trying to add as floats. Removed them from your title values and only put it back in after the total is calculated. * Put in parseFloat so values could be added together instead of being concatenated as strings. * Initialised your `g_fTotal` and `chkExtras` variables. * Put in some basic checking so that `radSize` doesn't cause problems when it's not selected.
You have to add brackets after 'Init'. ``` window.addEventListener('load', Init()); ``` And also there was a typo in the end of CalculateTotal function. Here is working example: <http://jsfiddle.net/x6kjqbop/3/>
5,813,823
I am working for Translate animation of two images overlapping each other and both Images should translate from top to middle of the screen. plesee share some sample programmes for this Help is always appreciated, ....Thanks!
2011/04/28
[ "https://Stackoverflow.com/questions/5813823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
anim.xml ``` <?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"> <translate android:fromYDelta="0" android:toYDelta="50%p" android:duration="1000"/> </set> ``` in java file.. ``` Animation anim = AnimationUtils.loadAnimation(activity, R.anim.anim); anim.setInterpolator((new AccelerateDecelerateInterpolator())); anim.setFillAfter(true); ImageView.setAnimation(anim); ```
To animate from **Top to middle** of screen it should be something like this **anmation.xml** ``` <?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"> <translate android:fromYDelta="-50%p" android:toYDelta="0%p" android:duration="2000" /> </set> ``` And to use this animation ``` Animation bottomUp = AnimationUtils.loadAnimation(this, R.anim.animation); tv_logo.startAnimation(bottomUp); ```
40,803,051
When i was run patch install command by CLI i see this below error. Please suggest me where i am wrong. I have install below version Patchs only here i am facing this problem. ``` sh PATCH_SUPEE-8788_CE_1.9.1.0_v2-2016-10-14-09-38-31.sh Checking if patch can be applied/reverted successfully... ERROR: Patch can't be applied/reverted successfully. patching file app/code/core/Mage/Adminhtml/Block/Catalog/Product/Helper/Form/Gallery/Content.php patching file app/code/core/Mage/Adminhtml/Block/Cms/Wysiwyg/Images/Content/Uploader.php patching file app/code/core/Mage/Adminhtml/Block/Media/Uploader.php patching file app/code/core/Mage/Adminhtml/Block/Urlrewrite/Category/Tree.php patching file app/code/core/Mage/Adminhtml/Model/System/Config/Backend/Serialized.php patching file app/code/core/Mage/Adminhtml/controllers/DashboardController.php patching file app/code/core/Mage/Adminhtml/controllers/IndexController.php patching file app/code/core/Mage/Adminhtml/controllers/Media/UploaderController.php patching file app/code/core/Mage/Catalog/Helper/Image.php patching file app/code/core/Mage/Catalog/etc/config.xml patching file app/code/core/Mage/Catalog/etc/system.xml patching file app/code/core/Mage/Centinel/Model/Api.php patching file app/code/core/Mage/Centinel/Model/Api/Client.php patching file app/code/core/Mage/Core/Block/Abstract.php patching file app/code/core/Mage/Core/Helper/Url.php patching file app/code/core/Mage/Core/Model/Encryption.php patching file app/code/core/Mage/Core/Model/Input/Filter/MaliciousCode.php patching file app/code/core/Mage/Core/functions.php patching file app/code/core/Mage/Customer/Block/Address/Book.php patching file app/code/core/Mage/Customer/controllers/AddressController.php patching file app/code/core/Mage/Dataflow/Model/Profile.php patching file app/code/core/Mage/Downloadable/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/Links.php patching file app/code/core/Mage/Downloadable/Block/Adminhtml/Catalog/Product/Edit/Tab/Downloadable/Samples.php patching file app/code/core/Mage/Downloadable/Helper/File.php patching file app/code/core/Mage/Oauth/Model/Server.php patching file app/code/core/Mage/Paygate/Model/Authorizenet.php patching file app/code/core/Mage/Payment/Block/Info/Checkmo.php patching file app/code/core/Mage/Paypal/Model/Express/Checkout.php patching file app/code/core/Mage/Paypal/Model/Resource/Payment/Transaction.php patching file app/code/core/Mage/Sales/Model/Resource/Order/Payment.php patching file app/code/core/Mage/Sales/Model/Resource/Order/Payment/Transaction.php patching file app/code/core/Mage/Sales/Model/Resource/Quote/Payment.php patching file app/code/core/Mage/Sales/Model/Resource/Recurring/Profile.php patching file app/code/core/Mage/Uploader/Block/Abstract.php patching file app/code/core/Mage/Uploader/Block/Multiple.php patching file app/code/core/Mage/Uploader/Block/Single.php patching file app/code/core/Mage/Uploader/Helper/Data.php patching file app/code/core/Mage/Uploader/Helper/File.php patching file app/code/core/Mage/Uploader/Model/Config/Abstract.php patching file app/code/core/Mage/Uploader/Model/Config/Browsebutton.php patching file app/code/core/Mage/Uploader/Model/Config/Misc.php patching file app/code/core/Mage/Uploader/Model/Config/Uploader.php patching file app/code/core/Mage/Uploader/etc/config.xml patching file app/code/core/Mage/Uploader/etc/jstranslator.xml patching file app/code/core/Mage/Usa/Model/Shipping/Carrier/Dhl.php patching file app/code/core/Mage/Usa/Model/Shipping/Carrier/Dhl/International.php patching file app/code/core/Mage/Usa/Model/Shipping/Carrier/Fedex.php patching file app/code/core/Mage/Usa/Model/Shipping/Carrier/Ups.php patching file app/code/core/Mage/Usa/etc/config.xml patching file app/code/core/Mage/Usa/etc/system.xml patching file app/code/core/Mage/Wishlist/Helper/Data.php patching file app/code/core/Mage/Wishlist/controllers/IndexController.php patching file app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Design.php patching file app/code/core/Mage/XmlConnect/Block/Adminhtml/Mobile/Edit/Tab/Design/Images.php patching file app/code/core/Mage/XmlConnect/controllers/Adminhtml/MobileController.php patching file app/design/adminhtml/default/default/layout/cms.xml patching file app/design/adminhtml/default/default/layout/main.xml patching file app/design/adminhtml/default/default/layout/xmlconnect.xml patching file app/design/adminhtml/default/default/template/catalog/product/helper/gallery.phtml patching file app/design/adminhtml/default/default/template/cms/browser/content/uploader.phtml patching file app/design/adminhtml/default/default/template/downloadable/product/edit/downloadable.phtml patching file app/design/adminhtml/default/default/template/downloadable/product/edit/downloadable/links.phtml patching file app/design/adminhtml/default/default/template/downloadable/product/edit/downloadable/samples.phtml patching file app/design/adminhtml/default/default/template/media/uploader.phtml patching file app/design/adminhtml/default/default/template/xmlconnect/edit/tab/design.phtml patching file app/etc/modules/Mage_All.xml patching file app/locale/en_US/Mage_Media.csv patching file app/locale/en_US/Mage_Uploader.csv patching file downloader/lib/Mage/HTTP/Client/Curl.php patching file js/lib/uploader/flow.min.js patching file js/lib/uploader/fusty-flow-factory.js patching file js/lib/uploader/fusty-flow.js patching file js/mage/adminhtml/product.js patching file js/mage/adminhtml/uploader/instance.js patching file lib/Unserialize/Parser.php patching file lib/Unserialize/Reader/Arr.php patching file lib/Unserialize/Reader/ArrValue.php patching file lib/Unserialize/Reader/Null.php patching file skin/adminhtml/default/default/boxes.css patching file skin/adminhtml/default/default/media/flex.swf Reversed (or previously applied) patch detected! Assume -R? [n] Apply anyway? [n] Skipping patch. 1 out of 1 hunk ignored -- saving rejects to file skin/adminhtml/default/default/media/flex.swf.rej patching file skin/adminhtml/default/default/media/uploader.swf Reversed (or previously applied) patch detected! Assume -R? [n] Apply anyway? [n] Skipping patch. 1 out of 1 hunk ignored -- saving rejects to file skin/adminhtml/default/default/media/uploader.swf.rej patching file skin/adminhtml/default/default/media/uploaderSingle.swf Reversed (or previously applied) patch detected! Assume -R? [n] Apply anyway? [n] Skipping patch. 1 out of 1 hunk ignored -- saving rejects to file skin/adminhtml/default/default/media/uploaderSingle.swf.rej patching file skin/adminhtml/default/default/xmlconnect/boxes.css ```
2016/11/25
[ "https://Stackoverflow.com/questions/40803051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2185477/" ]
These error you can see when you run the command. It means the file is conflicted with patches. You can replace with your version and again run your command. or Simply you can go through- <https://magentary.com/kb/install-supee-8788-without-ssh/> download file and implement to your magento in mage report 8788 not detected you need to delete. ``` /skin/adminhtml/default/default/media/flex.swf /skin/adminhtml/default/default/media/uploader.swf /skin/adminhtml/default/default/media/uploaderSingle.swf ``` Note: Please take backup of your website before do this.
**First read carefully after that apply following steps.** I got the solution if you have changed in core files then this error will come. here have very easy solution download any upgrated version of magento and replace your current core files with upgrated files, after that excute the frontend URL it will automatically update magento with availble patches. Note: you can note degrate you upgrated version so that please take a backup of files and database so that your data will save.
7,588
hi, i was asked to do sound design / processing for a live performance-art act. specifically, i need to be able to pick up live sounds from several locations across the stage, mix and process them simultaneously. one challenging scenario is this: the performer/dancer will be crawling on the surface of some sort of round metal container (about 4 meter diameter) full of gravel (about 1 meter deep). what i want to do is install a few microphones inside the gravel pool (say place them 20-30cm deep), in order to pick up and amplify the friction sound produced by the gravel as the performer will crawl on its surface. additionally, i'd like to be able to pick up and amplify the performer's breathings as he crawls. question 1: what would be the best type of microphones to use in order to pick up the gravel sound? question 2: what would be the best way to pick up the performer's breathings? - the solution must not involve attaching a mike to the performer's body. thanks, K.
2011/04/28
[ "https://sound.stackexchange.com/questions/7588", "https://sound.stackexchange.com", "https://sound.stackexchange.com/users/596/" ]
The only thing I'd put in a gravel pit is an SM-57 or 58. Those things are crazy durable. anything less robust will be seriously damaged. Sound quality is kind of crap though. My next thought is that you could rent 4 wireless mic kits and set them around the edge of the pool (or just two on opposite sides from each other). I'm assuming that the performer will have a particular way of doing the gravel sequence since it's part of a larger routine. In that case you can get down to one if they're really consistent in rehearsal.
for gravels, i would opt for contact mics / piezo strips. for breathings.. well, if you can't attach anything to the performer's body, you can only try with a shotgun mic placed on top of it (if he will stay in the same place for the whole performance).
7,588
hi, i was asked to do sound design / processing for a live performance-art act. specifically, i need to be able to pick up live sounds from several locations across the stage, mix and process them simultaneously. one challenging scenario is this: the performer/dancer will be crawling on the surface of some sort of round metal container (about 4 meter diameter) full of gravel (about 1 meter deep). what i want to do is install a few microphones inside the gravel pool (say place them 20-30cm deep), in order to pick up and amplify the friction sound produced by the gravel as the performer will crawl on its surface. additionally, i'd like to be able to pick up and amplify the performer's breathings as he crawls. question 1: what would be the best type of microphones to use in order to pick up the gravel sound? question 2: what would be the best way to pick up the performer's breathings? - the solution must not involve attaching a mike to the performer's body. thanks, K.
2011/04/28
[ "https://sound.stackexchange.com/questions/7588", "https://sound.stackexchange.com", "https://sound.stackexchange.com/users/596/" ]
for gravels, i would opt for contact mics / piezo strips. for breathings.. well, if you can't attach anything to the performer's body, you can only try with a shotgun mic placed on top of it (if he will stay in the same place for the whole performance).
It might be worth discussing a wireless with the performer otherwise you are going to have cables everywhere. If they are really anti-wireless then you could rent a parabolic dish and connect it to a wireless transmitter and follow the artist round with that. When I have had to do unusual events like this I mic everything with Audio Technica cardioid lavalier mics in AT8418 Unimounts and have attached them successfully to all sorts of objects. The unimount has a built in pop screen which also acts partially as a suspension mount, as the foam completely encases the mic isolating it from the support.
7,588
hi, i was asked to do sound design / processing for a live performance-art act. specifically, i need to be able to pick up live sounds from several locations across the stage, mix and process them simultaneously. one challenging scenario is this: the performer/dancer will be crawling on the surface of some sort of round metal container (about 4 meter diameter) full of gravel (about 1 meter deep). what i want to do is install a few microphones inside the gravel pool (say place them 20-30cm deep), in order to pick up and amplify the friction sound produced by the gravel as the performer will crawl on its surface. additionally, i'd like to be able to pick up and amplify the performer's breathings as he crawls. question 1: what would be the best type of microphones to use in order to pick up the gravel sound? question 2: what would be the best way to pick up the performer's breathings? - the solution must not involve attaching a mike to the performer's body. thanks, K.
2011/04/28
[ "https://sound.stackexchange.com/questions/7588", "https://sound.stackexchange.com", "https://sound.stackexchange.com/users/596/" ]
The only thing I'd put in a gravel pit is an SM-57 or 58. Those things are crazy durable. anything less robust will be seriously damaged. Sound quality is kind of crap though. My next thought is that you could rent 4 wireless mic kits and set them around the edge of the pool (or just two on opposite sides from each other). I'm assuming that the performer will have a particular way of doing the gravel sequence since it's part of a larger routine. In that case you can get down to one if they're really consistent in rehearsal.
It might be worth discussing a wireless with the performer otherwise you are going to have cables everywhere. If they are really anti-wireless then you could rent a parabolic dish and connect it to a wireless transmitter and follow the artist round with that. When I have had to do unusual events like this I mic everything with Audio Technica cardioid lavalier mics in AT8418 Unimounts and have attached them successfully to all sorts of objects. The unimount has a built in pop screen which also acts partially as a suspension mount, as the foam completely encases the mic isolating it from the support.
224,503
I bought a cheap Blackview BV5900 running on Android 9.0 (I assume a custom ROM) as I needed something rugged and with long battery life for testing purposes. I'm struggling to find any answers as to why apps won't auto start when they are supposed to. The app in question primarily is Grandstream Wave - Video which is effectively a SIP client. It auto starts just fine on an old Samsung Galaxy V6. I've tried various auto-start apps to see if I could get around it, but it would seem they fail to load as well on boot, so they don't do the task they are intended to perform. I've been in contact with the manufacturer and their answer is it just won't do it. As it's a test phone I'm quite happy to root it, although I'm completely new to Android, I'm sure I'll find enough info to get started with a bit of googling. What I'm after is a bit of help on what to look for and how to find it. From what I gather, the app is looking for a `BOOT_COMPLETE` message of some sort, so I'm guessing that is disabled somewhere? Any answers, please assume I know nothing, you will be correct. **EDIT 11May2020** Tried the shell command as requested [here](https://android.stackexchange.com/a/224547/322004) - no Joy. Result from shell below. Not sure whether this just means I don't have enough privilege to run it or it's disabled in some way? ``` Broadcasting: Intent { act=android.intent.action.BOOT_COMPLETED flg=0x400000 pkg=com.grandstream.wave } Security exception: Permission Denial: not allowed to send broadcast android.intent.action.BOOT_COMPLETED from pid=5834, uid=2000 java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.intent.action.BOOT_COMPLETED from pid=5834, uid=2000 at com.android.server.am.ActivityManagerService.broadcastIntentLocked(ActivityManagerService.java:21774) at com.android.server.am.ActivityManagerService.broadcastIntent(ActivityManagerService.java:22411) at com.android.server.am.ActivityManagerShellCommand.runSendBroadcast(ActivityManagerShellCommand.java:690) at com.android.server.am.ActivityManagerShellCommand.onCommand(ActivityManagerShellCommand.java:174) at android.os.ShellCommand.exec(ShellCommand.java:103) at com.android.server.am.ActivityManagerService.onShellCommand(ActivityManagerService.java:16434) at android.os.Binder.shellCommand(Binder.java:634) at android.os.Binder.onTransact(Binder.java:532) at android.app.IActivityManager$Stub.onTransact(IActivityManager.java:3551) at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:3397) at android.os.Binder.execTransact(Binder.java:731) ```
2020/04/29
[ "https://android.stackexchange.com/questions/224503", "https://android.stackexchange.com", "https://android.stackexchange.com/users/321904/" ]
I solved it by swiping down the lock icon on my android 10 device. Hope this helps
Not sure if you're still having this issue, but recently suffered the same (different app) and managed to resolve it completely by accident: Go to the recent apps menu (as shown in image) and simple do a (quick) swipe to the right on the app you want to lock/unlock, starting point doesn't seem to matter much but make sure to swipe all the way to (or over) the edge. If you do it too slow or not far enough it doesn't work. I haven't been able to find this in any official documentation or if/where it can be configured/disabled, it's not listed in the System->Gestures menu. It also seems to be fairly tenacious since 'locking' an app persists after a reboot or force stop via developer menu's 'running services'. It seems to be something similar to Windows' 'Pin to Taskbar' or Apple's 'Keep in Dock'. Phone: Alcatel 1S (2019) running Android 9 (build 01001)
233,673
While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python: ``` flist = [] for i in xrange(3): def func(x): return x * i flist.append(func) for f in flist: print f(2) ``` Note that this example mindfully avoids `lambda`. It prints "4 4 4", which is surprising. I'd expect "0 2 4". This equivalent Perl code does it right: ``` my @flist = (); foreach my $i (0 .. 2) { push(@flist, sub {$i * $_[0]}); } foreach my $f (@flist) { print $f->(2), "\n"; } ``` "0 2 4" is printed. Can you please explain the difference ? --- Update: The problem **is not** with `i` being global. This displays the same behavior: ``` flist = [] def outer(): for i in xrange(3): def inner(x): return x * i flist.append(inner) outer() #~ print i # commented because it causes an error for f in flist: print f(2) ``` As the commented line shows, `i` is unknown at that point. Still, it prints "4 4 4".
2008/10/24
[ "https://Stackoverflow.com/questions/233673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
What is happening is that the variable i is captured, and the functions are returning the value it is bound to at the time it is called. In functional languages this kind of situation never arises, as i wouldn't be rebound. However with python, and also as you've seen with lisp, this is no longer true. The difference with your scheme example is to do with the semantics of the do loop. Scheme is effectively creating a new i variable each time through the loop, rather than reusing an existing i binding as with the other languages. If you use a different variable created external to the loop and mutate it, you'll see the same behaviour in scheme. Try replacing your loop with: ``` (let ((ii 1)) ( (do ((i 1 (+ 1 i))) ((>= i 4)) (set! flist (cons (lambda (x) (* ii x)) flist)) (set! ii i)) )) ``` Take a look [here](http://lambda-the-ultimate.org/node/2648) for some further discussion of this. [Edit] Possibly a better way to describe it is to think of the do loop as a macro which performs the following steps: 1. Define a lambda taking a single parameter (i), with a body defined by the body of the loop, 2. An immediate call of that lambda with appropriate values of i as its parameter. ie. the equivalent to the below python: ``` flist = [] def loop_body(i): # extract body of the for loop to function def func(x): return x*i flist.append(func) map(loop_body, xrange(3)) # for i in xrange(3): body ``` The i is no longer the one from the parent scope but a brand new variable in its own scope (ie. the parameter to the lambda) and so you get the behaviour you observe. Python doesn't have this implicit new scope, so the body of the for loop just shares the i variable.
I'm still not entirely convinced why in some languages this works one way, and in some another way. In Common Lisp it's like Python: ``` (defvar *flist* '()) (dotimes (i 3 t) (setf *flist* (cons (lambda (x) (* x i)) *flist*))) (dolist (f *flist*) (format t "~a~%" (funcall f 2))) ``` Prints "6 6 6" (note that here the list is from 1 to 3, and built in reverse"). While in Scheme it works like in Perl: ``` (define flist '()) (do ((i 1 (+ 1 i))) ((>= i 4)) (set! flist (cons (lambda (x) (* i x)) flist))) (map (lambda (f) (printf "~a~%" (f 2))) flist) ``` Prints "6 4 2" And as I've mentioned already, Javascript is in the Python/CL camp. It appears there is an implementation decision here, which different languages approach in distinct ways. I would love to understand what is the decision, exactly.
233,673
While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python: ``` flist = [] for i in xrange(3): def func(x): return x * i flist.append(func) for f in flist: print f(2) ``` Note that this example mindfully avoids `lambda`. It prints "4 4 4", which is surprising. I'd expect "0 2 4". This equivalent Perl code does it right: ``` my @flist = (); foreach my $i (0 .. 2) { push(@flist, sub {$i * $_[0]}); } foreach my $f (@flist) { print $f->(2), "\n"; } ``` "0 2 4" is printed. Can you please explain the difference ? --- Update: The problem **is not** with `i` being global. This displays the same behavior: ``` flist = [] def outer(): for i in xrange(3): def inner(x): return x * i flist.append(inner) outer() #~ print i # commented because it causes an error for f in flist: print f(2) ``` As the commented line shows, `i` is unknown at that point. Still, it prints "4 4 4".
2008/10/24
[ "https://Stackoverflow.com/questions/233673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
What is happening is that the variable i is captured, and the functions are returning the value it is bound to at the time it is called. In functional languages this kind of situation never arises, as i wouldn't be rebound. However with python, and also as you've seen with lisp, this is no longer true. The difference with your scheme example is to do with the semantics of the do loop. Scheme is effectively creating a new i variable each time through the loop, rather than reusing an existing i binding as with the other languages. If you use a different variable created external to the loop and mutate it, you'll see the same behaviour in scheme. Try replacing your loop with: ``` (let ((ii 1)) ( (do ((i 1 (+ 1 i))) ((>= i 4)) (set! flist (cons (lambda (x) (* ii x)) flist)) (set! ii i)) )) ``` Take a look [here](http://lambda-the-ultimate.org/node/2648) for some further discussion of this. [Edit] Possibly a better way to describe it is to think of the do loop as a macro which performs the following steps: 1. Define a lambda taking a single parameter (i), with a body defined by the body of the loop, 2. An immediate call of that lambda with appropriate values of i as its parameter. ie. the equivalent to the below python: ``` flist = [] def loop_body(i): # extract body of the for loop to function def func(x): return x*i flist.append(func) map(loop_body, xrange(3)) # for i in xrange(3): body ``` The i is no longer the one from the parent scope but a brand new variable in its own scope (ie. the parameter to the lambda) and so you get the behaviour you observe. Python doesn't have this implicit new scope, so the body of the for loop just shares the i variable.
I didn't like how solutions above created `wrappers` in the loop. Note: python 3.xx ``` flist = [] def func(i): return lambda x: x * i for i in range(3): flist.append(func(i)) for f in flist: print f(2) ```
233,673
While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python: ``` flist = [] for i in xrange(3): def func(x): return x * i flist.append(func) for f in flist: print f(2) ``` Note that this example mindfully avoids `lambda`. It prints "4 4 4", which is surprising. I'd expect "0 2 4". This equivalent Perl code does it right: ``` my @flist = (); foreach my $i (0 .. 2) { push(@flist, sub {$i * $_[0]}); } foreach my $f (@flist) { print $f->(2), "\n"; } ``` "0 2 4" is printed. Can you please explain the difference ? --- Update: The problem **is not** with `i` being global. This displays the same behavior: ``` flist = [] def outer(): for i in xrange(3): def inner(x): return x * i flist.append(inner) outer() #~ print i # commented because it causes an error for f in flist: print f(2) ``` As the commented line shows, `i` is unknown at that point. Still, it prints "4 4 4".
2008/10/24
[ "https://Stackoverflow.com/questions/233673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
The functions defined in the loop keep accessing the same variable `i` while its value changes. At the end of the loop, all the functions point to the same variable, which is holding the last value in the loop: the effect is what reported in the example. In order to evaluate `i` and use its value, a common pattern is to set it as a parameter default: parameter defaults are evaluated when the `def` statement is executed, and thus the value of the loop variable is frozen. The following works as expected: ``` flist = [] for i in xrange(3): def func(x, i=i): # the *value* of i is copied in func() environment return x * i flist.append(func) for f in flist: print f(2) ```
I didn't like how solutions above created `wrappers` in the loop. Note: python 3.xx ``` flist = [] def func(i): return lambda x: x * i for i in range(3): flist.append(func(i)) for f in flist: print f(2) ```
233,673
While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python: ``` flist = [] for i in xrange(3): def func(x): return x * i flist.append(func) for f in flist: print f(2) ``` Note that this example mindfully avoids `lambda`. It prints "4 4 4", which is surprising. I'd expect "0 2 4". This equivalent Perl code does it right: ``` my @flist = (); foreach my $i (0 .. 2) { push(@flist, sub {$i * $_[0]}); } foreach my $f (@flist) { print $f->(2), "\n"; } ``` "0 2 4" is printed. Can you please explain the difference ? --- Update: The problem **is not** with `i` being global. This displays the same behavior: ``` flist = [] def outer(): for i in xrange(3): def inner(x): return x * i flist.append(inner) outer() #~ print i # commented because it causes an error for f in flist: print f(2) ``` As the commented line shows, `i` is unknown at that point. Still, it prints "4 4 4".
2008/10/24
[ "https://Stackoverflow.com/questions/233673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
Python is actually behaving as defined. **Three separate functions** are created, but they each have the **closure of the environment they're defined in** - in this case, the global environment (or the outer function's environment if the loop is placed inside another function). This is exactly the problem, though - in this environment, **i is modified**, and the closures all **refer to the same i**. Here is the best solution I can come up with - create a function creater and invoke *that* instead. This will force **different environments** for each of the functions created, with a **different i** in each one. ``` flist = [] for i in xrange(3): def funcC(j): def func(x): return x * j return func flist.append(funcC(i)) for f in flist: print f(2) ``` This is what happens when you mix side effects and functional programming.
look at this: ``` for f in flist: print f.func_closure (<cell at 0x00C980B0: int object at 0x009864B4>,) (<cell at 0x00C980B0: int object at 0x009864B4>,) (<cell at 0x00C980B0: int object at 0x009864B4>,) ``` It means they all point to the same i variable instance, which will have a value of 2 once the loop is over. A readable solution: ``` for i in xrange(3): def ffunc(i): def func(x): return x * i return func flist.append(ffunc(i)) ```
233,673
While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python: ``` flist = [] for i in xrange(3): def func(x): return x * i flist.append(func) for f in flist: print f(2) ``` Note that this example mindfully avoids `lambda`. It prints "4 4 4", which is surprising. I'd expect "0 2 4". This equivalent Perl code does it right: ``` my @flist = (); foreach my $i (0 .. 2) { push(@flist, sub {$i * $_[0]}); } foreach my $f (@flist) { print $f->(2), "\n"; } ``` "0 2 4" is printed. Can you please explain the difference ? --- Update: The problem **is not** with `i` being global. This displays the same behavior: ``` flist = [] def outer(): for i in xrange(3): def inner(x): return x * i flist.append(inner) outer() #~ print i # commented because it causes an error for f in flist: print f(2) ``` As the commented line shows, `i` is unknown at that point. Still, it prints "4 4 4".
2008/10/24
[ "https://Stackoverflow.com/questions/233673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
What is happening is that the variable i is captured, and the functions are returning the value it is bound to at the time it is called. In functional languages this kind of situation never arises, as i wouldn't be rebound. However with python, and also as you've seen with lisp, this is no longer true. The difference with your scheme example is to do with the semantics of the do loop. Scheme is effectively creating a new i variable each time through the loop, rather than reusing an existing i binding as with the other languages. If you use a different variable created external to the loop and mutate it, you'll see the same behaviour in scheme. Try replacing your loop with: ``` (let ((ii 1)) ( (do ((i 1 (+ 1 i))) ((>= i 4)) (set! flist (cons (lambda (x) (* ii x)) flist)) (set! ii i)) )) ``` Take a look [here](http://lambda-the-ultimate.org/node/2648) for some further discussion of this. [Edit] Possibly a better way to describe it is to think of the do loop as a macro which performs the following steps: 1. Define a lambda taking a single parameter (i), with a body defined by the body of the loop, 2. An immediate call of that lambda with appropriate values of i as its parameter. ie. the equivalent to the below python: ``` flist = [] def loop_body(i): # extract body of the for loop to function def func(x): return x*i flist.append(func) map(loop_body, xrange(3)) # for i in xrange(3): body ``` The i is no longer the one from the parent scope but a brand new variable in its own scope (ie. the parameter to the lambda) and so you get the behaviour you observe. Python doesn't have this implicit new scope, so the body of the for loop just shares the i variable.
The reasoning behind the behavior has already been explained, and multiple solutions have been posted, but I think this is the most pythonic (remember, everything in Python is an object!): ``` flist = [] for i in xrange(3): def func(x): return x * func.i func.i=i flist.append(func) for f in flist: print f(2) ``` Claudiu's answer is pretty good, using a function generator, but piro's answer is a hack, to be honest, as it's making i into a "hidden" argument with a default value (it'll work fine, but it's not "pythonic").
233,673
While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python: ``` flist = [] for i in xrange(3): def func(x): return x * i flist.append(func) for f in flist: print f(2) ``` Note that this example mindfully avoids `lambda`. It prints "4 4 4", which is surprising. I'd expect "0 2 4". This equivalent Perl code does it right: ``` my @flist = (); foreach my $i (0 .. 2) { push(@flist, sub {$i * $_[0]}); } foreach my $f (@flist) { print $f->(2), "\n"; } ``` "0 2 4" is printed. Can you please explain the difference ? --- Update: The problem **is not** with `i` being global. This displays the same behavior: ``` flist = [] def outer(): for i in xrange(3): def inner(x): return x * i flist.append(inner) outer() #~ print i # commented because it causes an error for f in flist: print f(2) ``` As the commented line shows, `i` is unknown at that point. Still, it prints "4 4 4".
2008/10/24
[ "https://Stackoverflow.com/questions/233673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
The problem is that all of the local functions bind to the same environment and thus to the same `i` variable. The solution (workaround) is to create separate environments (stack frames) for each function (or lambda): ``` t = [ (lambda x: lambda y : x*y)(x) for x in range(5)] >>> t[1](2) 2 >>> t[2](2) 4 ```
I didn't like how solutions above created `wrappers` in the loop. Note: python 3.xx ``` flist = [] def func(i): return lambda x: x * i for i in range(3): flist.append(func(i)) for f in flist: print f(2) ```
233,673
While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python: ``` flist = [] for i in xrange(3): def func(x): return x * i flist.append(func) for f in flist: print f(2) ``` Note that this example mindfully avoids `lambda`. It prints "4 4 4", which is surprising. I'd expect "0 2 4". This equivalent Perl code does it right: ``` my @flist = (); foreach my $i (0 .. 2) { push(@flist, sub {$i * $_[0]}); } foreach my $f (@flist) { print $f->(2), "\n"; } ``` "0 2 4" is printed. Can you please explain the difference ? --- Update: The problem **is not** with `i` being global. This displays the same behavior: ``` flist = [] def outer(): for i in xrange(3): def inner(x): return x * i flist.append(inner) outer() #~ print i # commented because it causes an error for f in flist: print f(2) ``` As the commented line shows, `i` is unknown at that point. Still, it prints "4 4 4".
2008/10/24
[ "https://Stackoverflow.com/questions/233673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
Python is actually behaving as defined. **Three separate functions** are created, but they each have the **closure of the environment they're defined in** - in this case, the global environment (or the outer function's environment if the loop is placed inside another function). This is exactly the problem, though - in this environment, **i is modified**, and the closures all **refer to the same i**. Here is the best solution I can come up with - create a function creater and invoke *that* instead. This will force **different environments** for each of the functions created, with a **different i** in each one. ``` flist = [] for i in xrange(3): def funcC(j): def func(x): return x * j return func flist.append(funcC(i)) for f in flist: print f(2) ``` This is what happens when you mix side effects and functional programming.
What is happening is that the variable i is captured, and the functions are returning the value it is bound to at the time it is called. In functional languages this kind of situation never arises, as i wouldn't be rebound. However with python, and also as you've seen with lisp, this is no longer true. The difference with your scheme example is to do with the semantics of the do loop. Scheme is effectively creating a new i variable each time through the loop, rather than reusing an existing i binding as with the other languages. If you use a different variable created external to the loop and mutate it, you'll see the same behaviour in scheme. Try replacing your loop with: ``` (let ((ii 1)) ( (do ((i 1 (+ 1 i))) ((>= i 4)) (set! flist (cons (lambda (x) (* ii x)) flist)) (set! ii i)) )) ``` Take a look [here](http://lambda-the-ultimate.org/node/2648) for some further discussion of this. [Edit] Possibly a better way to describe it is to think of the do loop as a macro which performs the following steps: 1. Define a lambda taking a single parameter (i), with a body defined by the body of the loop, 2. An immediate call of that lambda with appropriate values of i as its parameter. ie. the equivalent to the below python: ``` flist = [] def loop_body(i): # extract body of the for loop to function def func(x): return x*i flist.append(func) map(loop_body, xrange(3)) # for i in xrange(3): body ``` The i is no longer the one from the parent scope but a brand new variable in its own scope (ie. the parameter to the lambda) and so you get the behaviour you observe. Python doesn't have this implicit new scope, so the body of the for loop just shares the i variable.
233,673
While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python: ``` flist = [] for i in xrange(3): def func(x): return x * i flist.append(func) for f in flist: print f(2) ``` Note that this example mindfully avoids `lambda`. It prints "4 4 4", which is surprising. I'd expect "0 2 4". This equivalent Perl code does it right: ``` my @flist = (); foreach my $i (0 .. 2) { push(@flist, sub {$i * $_[0]}); } foreach my $f (@flist) { print $f->(2), "\n"; } ``` "0 2 4" is printed. Can you please explain the difference ? --- Update: The problem **is not** with `i` being global. This displays the same behavior: ``` flist = [] def outer(): for i in xrange(3): def inner(x): return x * i flist.append(inner) outer() #~ print i # commented because it causes an error for f in flist: print f(2) ``` As the commented line shows, `i` is unknown at that point. Still, it prints "4 4 4".
2008/10/24
[ "https://Stackoverflow.com/questions/233673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
Python is actually behaving as defined. **Three separate functions** are created, but they each have the **closure of the environment they're defined in** - in this case, the global environment (or the outer function's environment if the loop is placed inside another function). This is exactly the problem, though - in this environment, **i is modified**, and the closures all **refer to the same i**. Here is the best solution I can come up with - create a function creater and invoke *that* instead. This will force **different environments** for each of the functions created, with a **different i** in each one. ``` flist = [] for i in xrange(3): def funcC(j): def func(x): return x * j return func flist.append(funcC(i)) for f in flist: print f(2) ``` This is what happens when you mix side effects and functional programming.
The variable `i` is a global, whose value is 2 at each time the function `f` is called. I would be inclined to implement the behavior you're after as follows: ``` >>> class f: ... def __init__(self, multiplier): self.multiplier = multiplier ... def __call__(self, multiplicand): return self.multiplier*multiplicand ... >>> flist = [f(i) for i in range(3)] >>> [g(2) for g in flist] [0, 2, 4] ``` **Response to your update**: It's not the globalness of `i` *per se* which is causing this behavior, it's the fact that it's a variable from an enclosing scope which has a fixed value over the times when f is called. In your second example, the value of `i` is taken from the scope of the `kkk` function, and nothing is changing that when you call the functions on `flist`.
233,673
While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python: ``` flist = [] for i in xrange(3): def func(x): return x * i flist.append(func) for f in flist: print f(2) ``` Note that this example mindfully avoids `lambda`. It prints "4 4 4", which is surprising. I'd expect "0 2 4". This equivalent Perl code does it right: ``` my @flist = (); foreach my $i (0 .. 2) { push(@flist, sub {$i * $_[0]}); } foreach my $f (@flist) { print $f->(2), "\n"; } ``` "0 2 4" is printed. Can you please explain the difference ? --- Update: The problem **is not** with `i` being global. This displays the same behavior: ``` flist = [] def outer(): for i in xrange(3): def inner(x): return x * i flist.append(inner) outer() #~ print i # commented because it causes an error for f in flist: print f(2) ``` As the commented line shows, `i` is unknown at that point. Still, it prints "4 4 4".
2008/10/24
[ "https://Stackoverflow.com/questions/233673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
Here's how you do it using the `functools` library (which I'm not sure was available at the time the question was posed). ``` from functools import partial flist = [] def func(i, x): return x * i for i in range(3): flist.append(partial(func, i)) for f in flist: print(f(2)) ``` Outputs 0 2 4, as expected.
What is happening is that the variable i is captured, and the functions are returning the value it is bound to at the time it is called. In functional languages this kind of situation never arises, as i wouldn't be rebound. However with python, and also as you've seen with lisp, this is no longer true. The difference with your scheme example is to do with the semantics of the do loop. Scheme is effectively creating a new i variable each time through the loop, rather than reusing an existing i binding as with the other languages. If you use a different variable created external to the loop and mutate it, you'll see the same behaviour in scheme. Try replacing your loop with: ``` (let ((ii 1)) ( (do ((i 1 (+ 1 i))) ((>= i 4)) (set! flist (cons (lambda (x) (* ii x)) flist)) (set! ii i)) )) ``` Take a look [here](http://lambda-the-ultimate.org/node/2648) for some further discussion of this. [Edit] Possibly a better way to describe it is to think of the do loop as a macro which performs the following steps: 1. Define a lambda taking a single parameter (i), with a body defined by the body of the loop, 2. An immediate call of that lambda with appropriate values of i as its parameter. ie. the equivalent to the below python: ``` flist = [] def loop_body(i): # extract body of the for loop to function def func(x): return x*i flist.append(func) map(loop_body, xrange(3)) # for i in xrange(3): body ``` The i is no longer the one from the parent scope but a brand new variable in its own scope (ie. the parameter to the lambda) and so you get the behaviour you observe. Python doesn't have this implicit new scope, so the body of the for loop just shares the i variable.
233,673
While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python: ``` flist = [] for i in xrange(3): def func(x): return x * i flist.append(func) for f in flist: print f(2) ``` Note that this example mindfully avoids `lambda`. It prints "4 4 4", which is surprising. I'd expect "0 2 4". This equivalent Perl code does it right: ``` my @flist = (); foreach my $i (0 .. 2) { push(@flist, sub {$i * $_[0]}); } foreach my $f (@flist) { print $f->(2), "\n"; } ``` "0 2 4" is printed. Can you please explain the difference ? --- Update: The problem **is not** with `i` being global. This displays the same behavior: ``` flist = [] def outer(): for i in xrange(3): def inner(x): return x * i flist.append(inner) outer() #~ print i # commented because it causes an error for f in flist: print f(2) ``` As the commented line shows, `i` is unknown at that point. Still, it prints "4 4 4".
2008/10/24
[ "https://Stackoverflow.com/questions/233673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
look at this: ``` for f in flist: print f.func_closure (<cell at 0x00C980B0: int object at 0x009864B4>,) (<cell at 0x00C980B0: int object at 0x009864B4>,) (<cell at 0x00C980B0: int object at 0x009864B4>,) ``` It means they all point to the same i variable instance, which will have a value of 2 once the loop is over. A readable solution: ``` for i in xrange(3): def ffunc(i): def func(x): return x * i return func flist.append(ffunc(i)) ```
I didn't like how solutions above created `wrappers` in the loop. Note: python 3.xx ``` flist = [] def func(i): return lambda x: x * i for i in range(3): flist.append(func(i)) for f in flist: print f(2) ```
19,916,907
I need to handle a **large** list of objects (in that case, sprites in a game) **in a particular order**, determined by one of their property (in that case, the `zIndex` of the sprite). I acquire the objects one-by-one, in a random order, but not so far from the perfect one. At the moment, I push naively each object I acquire in an array, and I sort it before the operation (with the [`orderBy`](http://docs.angularjs.org/api/ng.filter%3aorderBy) filter of AngularJS). But the operation is really slow (50% of the total calculation time). What can I do to speed up the process? I've try to use a sparse array, whose keys are the `zIndex` of my objects, but for a mysterious reason: * [`angular.forEach`](http://docs.angularjs.org/api/angular.forEach) is really slow on the sparse array, * the order doesn't seem to be preserved when I iterate over the array with a `for ... in` loop.
2013/11/11
[ "https://Stackoverflow.com/questions/19916907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2057033/" ]
What about using `array.sort()`. The closer you get to the native browser JavaScript the quicker you're going to get. See <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort>
I wouldn't use a `for ... in` loop. From Mozilla: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in> `Iterates over the enumerable properties of an object, in arbitrary order.` `for ... in` will usually iterate over an array in the order that the array properties were defined, which is why sorting doesn't work. Not sure if it will solve your problem, but doing a `var i = 0, l = items.length; for (; i < l; i++) { // do stuff }` will preserve array order, and most likely be the fastest way as it uses native javascript. If this is the only issue that you're facing, and using a sparse array works with this, then it should be fine.
2,370,273
I have a binary tree class that is created with a root node and nodes can be added to it as needed in the code, however I am having trouble in deleting the nodes because I point to them with TNodePtr and it is an incompatible type with TNode. At the moment I have this recursive method of deleting nodes which should work once the incompatible types is sorted. Thanks. ``` Destructor TTree.Destroy; procedure FreeSubnodes(Node: TNodePtr); begin if Assigned(Node.Left) then FreeSubnodes(Node.Left); if Assigned(Node.Right) then FreeSubnodes(Node.Right); Delete(Node); end; begin FreeSubnodes(Root); inherited; end; ``` Edit 04/03/2010: The error given is this: [Warning] SystemBuild.pas(50): Method 'Destroy' hides virtual method of base type 'TObject' [Error] SystemBuild.pas(84): Incompatible types Line 84 is Delete(Node); I declared the node like this: ``` type TNodePtr = ^TNode; TNode = Record Data:String; Left:TNodePtr; Right:TNodePtr; end; ``` And the tree like this: ``` Type TTree = Class Private Root:TNodePtr; Public Function GetRoot:TNodePtr; Constructor Create; Destructor Destroy; end; ```
2010/03/03
[ "https://Stackoverflow.com/questions/2370273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/193785/" ]
``` Destructor TTree.Destroy; procedure FreeSubnodes(Node: TNodePtr); var ThisNode:TNode; begin ThisNode := Node^; if Assigned(ThisNode.Left) then FreeSubnodes(ThisNode.Left); if Assigned(ThisNode.Right) then FreeSubnodes(ThisNode.Right); Dispose(Node); end; begin FreeSubnodes(Root); inherited; end; ```
to dereference the pointer use Node^
2,370,273
I have a binary tree class that is created with a root node and nodes can be added to it as needed in the code, however I am having trouble in deleting the nodes because I point to them with TNodePtr and it is an incompatible type with TNode. At the moment I have this recursive method of deleting nodes which should work once the incompatible types is sorted. Thanks. ``` Destructor TTree.Destroy; procedure FreeSubnodes(Node: TNodePtr); begin if Assigned(Node.Left) then FreeSubnodes(Node.Left); if Assigned(Node.Right) then FreeSubnodes(Node.Right); Delete(Node); end; begin FreeSubnodes(Root); inherited; end; ``` Edit 04/03/2010: The error given is this: [Warning] SystemBuild.pas(50): Method 'Destroy' hides virtual method of base type 'TObject' [Error] SystemBuild.pas(84): Incompatible types Line 84 is Delete(Node); I declared the node like this: ``` type TNodePtr = ^TNode; TNode = Record Data:String; Left:TNodePtr; Right:TNodePtr; end; ``` And the tree like this: ``` Type TTree = Class Private Root:TNodePtr; Public Function GetRoot:TNodePtr; Constructor Create; Destructor Destroy; end; ```
2010/03/03
[ "https://Stackoverflow.com/questions/2370273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/193785/" ]
The error you see is because of a mistake I made in the answer I gave to [your previous question](https://stackoverflow.com/questions/2306696/creating-a-binary-tree-for-a-knockout-tournament). [I wrote `Delete`](https://stackoverflow.com/posts/2309918/revisions) when I should have written `Dispose`. I apologize. Here, then, is the correct destructor implementation: ``` destructor TTree.Destroy; procedure FreeSubnodes(Node: PNode); begin if Assigned(Node.Left) then FreeSubnodes(Node.Left); if Assigned(Node.Right) then FreeSubnodes(Node.Right); Dispose(Node); end; begin FreeSubnodes(Root); inherited; end; ``` The error is not saying that `TNodePtr` is incompatible with `TNode`. The error just says "incompatible types" because the compiler doesn't know what type `Delete` is supposed to receive. It's a compiler-magic function that accepts several different parameter types, none of which is compatible with `TNodePtr`. The first compiler message you see is about your `Destroy` method hiding the method from the base class. It's not responsible for the problem you were seeing, but you'd eventually notice a problem because your destructor would never get called. When you call `Free`, it will call *TObject's* `Destroy` method, not your new version. To make yours get called instead, you need to mark yours as *overriding* the inherited version. Then, when `TObject.Free` calls `Destroy`, control will go to your version first, and then go to the base class's version when you call `inherited`. Change the declaration to this: ``` destructor Destroy; override; ```
to dereference the pointer use Node^
2,370,273
I have a binary tree class that is created with a root node and nodes can be added to it as needed in the code, however I am having trouble in deleting the nodes because I point to them with TNodePtr and it is an incompatible type with TNode. At the moment I have this recursive method of deleting nodes which should work once the incompatible types is sorted. Thanks. ``` Destructor TTree.Destroy; procedure FreeSubnodes(Node: TNodePtr); begin if Assigned(Node.Left) then FreeSubnodes(Node.Left); if Assigned(Node.Right) then FreeSubnodes(Node.Right); Delete(Node); end; begin FreeSubnodes(Root); inherited; end; ``` Edit 04/03/2010: The error given is this: [Warning] SystemBuild.pas(50): Method 'Destroy' hides virtual method of base type 'TObject' [Error] SystemBuild.pas(84): Incompatible types Line 84 is Delete(Node); I declared the node like this: ``` type TNodePtr = ^TNode; TNode = Record Data:String; Left:TNodePtr; Right:TNodePtr; end; ``` And the tree like this: ``` Type TTree = Class Private Root:TNodePtr; Public Function GetRoot:TNodePtr; Constructor Create; Destructor Destroy; end; ```
2010/03/03
[ "https://Stackoverflow.com/questions/2370273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/193785/" ]
The error you see is because of a mistake I made in the answer I gave to [your previous question](https://stackoverflow.com/questions/2306696/creating-a-binary-tree-for-a-knockout-tournament). [I wrote `Delete`](https://stackoverflow.com/posts/2309918/revisions) when I should have written `Dispose`. I apologize. Here, then, is the correct destructor implementation: ``` destructor TTree.Destroy; procedure FreeSubnodes(Node: PNode); begin if Assigned(Node.Left) then FreeSubnodes(Node.Left); if Assigned(Node.Right) then FreeSubnodes(Node.Right); Dispose(Node); end; begin FreeSubnodes(Root); inherited; end; ``` The error is not saying that `TNodePtr` is incompatible with `TNode`. The error just says "incompatible types" because the compiler doesn't know what type `Delete` is supposed to receive. It's a compiler-magic function that accepts several different parameter types, none of which is compatible with `TNodePtr`. The first compiler message you see is about your `Destroy` method hiding the method from the base class. It's not responsible for the problem you were seeing, but you'd eventually notice a problem because your destructor would never get called. When you call `Free`, it will call *TObject's* `Destroy` method, not your new version. To make yours get called instead, you need to mark yours as *overriding* the inherited version. Then, when `TObject.Free` calls `Destroy`, control will go to your version first, and then go to the base class's version when you call `inherited`. Change the declaration to this: ``` destructor Destroy; override; ```
``` Destructor TTree.Destroy; procedure FreeSubnodes(Node: TNodePtr); var ThisNode:TNode; begin ThisNode := Node^; if Assigned(ThisNode.Left) then FreeSubnodes(ThisNode.Left); if Assigned(ThisNode.Right) then FreeSubnodes(ThisNode.Right); Dispose(Node); end; begin FreeSubnodes(Root); inherited; end; ```
2,370,273
I have a binary tree class that is created with a root node and nodes can be added to it as needed in the code, however I am having trouble in deleting the nodes because I point to them with TNodePtr and it is an incompatible type with TNode. At the moment I have this recursive method of deleting nodes which should work once the incompatible types is sorted. Thanks. ``` Destructor TTree.Destroy; procedure FreeSubnodes(Node: TNodePtr); begin if Assigned(Node.Left) then FreeSubnodes(Node.Left); if Assigned(Node.Right) then FreeSubnodes(Node.Right); Delete(Node); end; begin FreeSubnodes(Root); inherited; end; ``` Edit 04/03/2010: The error given is this: [Warning] SystemBuild.pas(50): Method 'Destroy' hides virtual method of base type 'TObject' [Error] SystemBuild.pas(84): Incompatible types Line 84 is Delete(Node); I declared the node like this: ``` type TNodePtr = ^TNode; TNode = Record Data:String; Left:TNodePtr; Right:TNodePtr; end; ``` And the tree like this: ``` Type TTree = Class Private Root:TNodePtr; Public Function GetRoot:TNodePtr; Constructor Create; Destructor Destroy; end; ```
2010/03/03
[ "https://Stackoverflow.com/questions/2370273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/193785/" ]
``` Destructor TTree.Destroy; procedure FreeSubnodes(Node: TNodePtr); var ThisNode:TNode; begin ThisNode := Node^; if Assigned(ThisNode.Left) then FreeSubnodes(ThisNode.Left); if Assigned(ThisNode.Right) then FreeSubnodes(ThisNode.Right); Dispose(Node); end; begin FreeSubnodes(Root); inherited; end; ```
use TComponent instead of Record. Record type(Pointer) is old and unsafe . TComponent is easier and more abstract. your issue similar to <https://stackoverflow.com/a/1032252/528588> .
2,370,273
I have a binary tree class that is created with a root node and nodes can be added to it as needed in the code, however I am having trouble in deleting the nodes because I point to them with TNodePtr and it is an incompatible type with TNode. At the moment I have this recursive method of deleting nodes which should work once the incompatible types is sorted. Thanks. ``` Destructor TTree.Destroy; procedure FreeSubnodes(Node: TNodePtr); begin if Assigned(Node.Left) then FreeSubnodes(Node.Left); if Assigned(Node.Right) then FreeSubnodes(Node.Right); Delete(Node); end; begin FreeSubnodes(Root); inherited; end; ``` Edit 04/03/2010: The error given is this: [Warning] SystemBuild.pas(50): Method 'Destroy' hides virtual method of base type 'TObject' [Error] SystemBuild.pas(84): Incompatible types Line 84 is Delete(Node); I declared the node like this: ``` type TNodePtr = ^TNode; TNode = Record Data:String; Left:TNodePtr; Right:TNodePtr; end; ``` And the tree like this: ``` Type TTree = Class Private Root:TNodePtr; Public Function GetRoot:TNodePtr; Constructor Create; Destructor Destroy; end; ```
2010/03/03
[ "https://Stackoverflow.com/questions/2370273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/193785/" ]
The error you see is because of a mistake I made in the answer I gave to [your previous question](https://stackoverflow.com/questions/2306696/creating-a-binary-tree-for-a-knockout-tournament). [I wrote `Delete`](https://stackoverflow.com/posts/2309918/revisions) when I should have written `Dispose`. I apologize. Here, then, is the correct destructor implementation: ``` destructor TTree.Destroy; procedure FreeSubnodes(Node: PNode); begin if Assigned(Node.Left) then FreeSubnodes(Node.Left); if Assigned(Node.Right) then FreeSubnodes(Node.Right); Dispose(Node); end; begin FreeSubnodes(Root); inherited; end; ``` The error is not saying that `TNodePtr` is incompatible with `TNode`. The error just says "incompatible types" because the compiler doesn't know what type `Delete` is supposed to receive. It's a compiler-magic function that accepts several different parameter types, none of which is compatible with `TNodePtr`. The first compiler message you see is about your `Destroy` method hiding the method from the base class. It's not responsible for the problem you were seeing, but you'd eventually notice a problem because your destructor would never get called. When you call `Free`, it will call *TObject's* `Destroy` method, not your new version. To make yours get called instead, you need to mark yours as *overriding* the inherited version. Then, when `TObject.Free` calls `Destroy`, control will go to your version first, and then go to the base class's version when you call `inherited`. Change the declaration to this: ``` destructor Destroy; override; ```
use TComponent instead of Record. Record type(Pointer) is old and unsafe . TComponent is easier and more abstract. your issue similar to <https://stackoverflow.com/a/1032252/528588> .
44,557,759
Here is in Detail. I have a file which contains hidden BOM Characters as Shown Below 2225612|22225200240|STACKOVERFLOW|HELPSDEVELOPERS - LINE 1 **þÿ**2225612|22225200240|KIRK|CAPTAIN - LINE 2 2225612|22225200240|THANKS**þÿ**|INADVANCE - LINE 3 Now I have script where each row gets processed. As Per my assumption first line has to be processed since it doesn't have any BOM Character. But when second line starts processing it should raise an error since BOM Character is identified. Not only at the beginning of line the BOM Character can be anywhere in the row.For your reference the highlighted one is the BOM Character. When I use regex **/[^[:print]]/** using **gsub** it is considering space or new line as an BOM Character. I want only BOM characters to be detected. Can anyone writer script for this ? Thanks in advance guys
2017/06/15
[ "https://Stackoverflow.com/questions/44557759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6807825/" ]
I think this regex should work: ``` if line =~ /\xEF\xBB\xBF/ # If line contains BOM character fail "Line contains a BOM char!" end ``` If you have encoding issues, it might help to force both the line and regex to UTF-8, something like this: ``` regexp = Regexp.new("\xEF\xBB\xBF".force_encoding("UTF-8"), Regexp::FIXEDENCODING) if line.force_encoding("UTF-8") =~ regexp # ... ```
You can specify encoding with the File.read method. ``` File.read('your_file.txt', encoding: 'bom|utf-8') ``` or ``` File.readlines('your_file.txt', "r:utf-8") ```
12,912,770
How do I remove the white space that are in front and back of & <http://chemist.com:8080/eShop/search_results.jsp?IDNUMBER=BB55-7344> & Source=BuildingBlocks
2012/10/16
[ "https://Stackoverflow.com/questions/12912770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310156/" ]
``` String newUrl = oldUrl.replaceAll(" ", ""); ``` Hope this helps.
``` if(result.contains(" and "){ resultnew = result.replace(" and ","&amp").toString(); } ``` You don't really need the "if" check, although it is faster (unless result ***always*** contains " and ") as replace() will return the input string if " and " is not found. You also don't need the toString() since replace() returns a String.
12,912,770
How do I remove the white space that are in front and back of & <http://chemist.com:8080/eShop/search_results.jsp?IDNUMBER=BB55-7344> & Source=BuildingBlocks
2012/10/16
[ "https://Stackoverflow.com/questions/12912770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310156/" ]
Try : ``` urlString = urlString.replaceAll(" ", "%20"); ``` This code replaces all the white space.
``` String newUrl = oldUrl.replaceAll(" ", ""); ``` Hope this helps.
12,912,770
How do I remove the white space that are in front and back of & <http://chemist.com:8080/eShop/search_results.jsp?IDNUMBER=BB55-7344> & Source=BuildingBlocks
2012/10/16
[ "https://Stackoverflow.com/questions/12912770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310156/" ]
Try: ``` String newURI = oldURI.replaceAll("\\s+", ""); ```
``` if(result.contains(" and "){ resultnew = result.replace(" and ","&amp").toString(); } ``` You don't really need the "if" check, although it is faster (unless result ***always*** contains " and ") as replace() will return the input string if " and " is not found. You also don't need the toString() since replace() returns a String.
12,912,770
How do I remove the white space that are in front and back of & <http://chemist.com:8080/eShop/search_results.jsp?IDNUMBER=BB55-7344> & Source=BuildingBlocks
2012/10/16
[ "https://Stackoverflow.com/questions/12912770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310156/" ]
Try : ``` urlString = urlString.replaceAll(" ", "%20"); ``` This code replaces all the white space.
Try: ``` String newURI = oldURI.replaceAll("\\s+", ""); ```
12,912,770
How do I remove the white space that are in front and back of & <http://chemist.com:8080/eShop/search_results.jsp?IDNUMBER=BB55-7344> & Source=BuildingBlocks
2012/10/16
[ "https://Stackoverflow.com/questions/12912770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310156/" ]
Try : ``` urlString = urlString.replaceAll(" ", "%20"); ``` This code replaces all the white space.
``` if(result.contains(" and "){ resultnew = result.replace(" and ","&amp").toString(); } ``` You don't really need the "if" check, although it is faster (unless result ***always*** contains " and ") as replace() will return the input string if " and " is not found. You also don't need the toString() since replace() returns a String.
1,163
How should I describe a guy who moves to a city or urban area, but does not know much about how things work in those cities, and make an ass of themselves? The closest word I came up with is *unsophisticated*, but it is a broad term.
2013/02/07
[ "https://ell.stackexchange.com/questions/1163", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/299/" ]
Interesting question! *Make* and *Let* have subtly different meanings in certain cases, and are not interchangeable at all in others. To look at your examples: > > Don't make me feel alone. > > > *Make* here implies that the person you're talking to is intentionally trying to cause you to feel alone. They are making you feel this way, and by stopping their behavior you wouldn't feel alone anymore. Changing this to *let*, on the other hand: > > Don't let me feel alone. > > > *Let* here means that you already do feel alone, and are asking someone to help make you not feel alone. In this case their action will stop you from feeling alone, and if they do nothing you will continue to feel alone. So here the small difference between *make* and *let* actually completely changes the meaning of the sentence. > > Make me understand what you mean to say. > > > This is a command; you want to understand what they're saying, and you insist that they make it so you understand. This is perfectly acceptable, though a bit authoritarian; it's more likely one would say "Help me understand what you mean to say" as a request than to pose this command. That aside, *let* is not at all appropriate here. > > Let me understand what you mean to say. > > > This doesn't really make sense; asking someone to *let* you understand implies that they are currently preventing you from understanding and you would like them to stop. This seems an unlikely circumstance, and probably doesn't convey the meaning you're searching for. Now for your last case: > > You are requested not to let me feel alone. > > > This sounds oddly stilted and formal, but is grammatically correct. It carries the same meaning as "Don't let me feel alone", except it is phrased as a request rather than a command. If you're trying to politely ask someone to keep you company, for example, you might try saying: > > Please don't let me feel alone. > > > Or if you specifically don't want the person to leave because this is the action that will make you feel alone, you'd most commonly say: > > Please don't leave me alone. > > >
I would say the two have overlapping meanings, but *let* is more "passive," and *make* is more "active". IMPORTANT NOTE: by "passive" and "active," I am **not** referring to the [passive and active voice](http://owl.english.purdue.edu/owl/resource/539/01/). One definition of *passive* is "accepting or allowing what happens or what others do, without active response or resistance" (NOAD). So, in the instance of: > > Please don't let me feel alone. > > > I would interpret that to mean, *"I'm about to start feeling lonely; if you don't do something, I will start feeling lonely, so please do something."* Note that it is the hearer's *inaction* that will start the loneliness. However, with: > > Please don't make me feel alone. > > > I would interpret that to mean, *"You're about to do something; if you do that, then I will start feeling lonely, so please don't do that."* Here, it's the hearer's impending *action* that will cause the bout of loneliness. In both cases, the hearer is in a position to thwart the upcoming feelings of loneliness, which is why I said these words had "overlapping" meanings. However, one request solicits help through active intervention, while the other is a plea that the hearer not allow something to happen. The dictionary, it seems, would back up my interpretation. Again, from NOAD: > > **let** (*v.*) not prevent or forbid; allow > > > **make** (*v.*) cause (something) to exist or come about; bring about > > > Here's a similar example with a different verb pair: > > Please let the dog out. > > > is a request to open the door, so the dog can go outside. However: > > Please take the dog out. > > > is a request to make the dog go outside, even if the dog wants to stay inside.
37,683
**Wave soldering** I am trying to understand how wave soldering works. Unfortunately the [Wikipedia article](http://en.wikipedia.org/wiki/Wave_soldering) has has left me unsure about the process: 1. Is the entire board with its components quasi-immersed in liquid solder while it passes through the wave? (If not, the following question probably make no sense.) 2. If the board cuts into the wave, how is the wave maintained? 3. Why does this not leave superflous solder residue on the board? **Double-Sided SMT soldering** How are double sided boards with SMT components soldered? How is it prevented that the components on one side fall off?
2012/08/11
[ "https://electronics.stackexchange.com/questions/37683", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/8534/" ]
The wave only contacts the bottom side of the PCB. Once upon a time, a wave solder machine was used to solder SMT parts on the bottom side of the PCB but this is not used as much anymore in favor of more modern techniques. Here is the rough process for soldering PCB's with SMT parts on both sides, and through hole (TH) parts on the top side only. A. The bare PCB is turned "bottom side up". A solder paste is pressed through a stencil and onto the pads of the PCB. A pick and place machine places the parts onto the bottom side. The PCB is ran through an oven (hot-air convection or an IR oven) to melt the solder and attach the parts. An optional step is to place a small drop of glue under the parts. Solder paste first, then glue, then the parts are put onto the PCB and soldered. This glue helps keep the parts from falling off during a later step. B. The board is turned over (top side up), and the same process is repeated for all SMT parts on the top side of the PCB. By that I mean solder paste, parts placed, then through the oven. No glue is needed. During step B, the parts on the bottom of the PCB don't fall off. Obviously if they are glued down then they are stuck there, but most companies do not use glue. Without glue, the surface tension from the molten solder is enough to hold the parts in place. Some parts, particularly heavy parts without many pins, might not work with this technique since there is not enough surface tension to hold the parts on. C. All of the through-hole parts are then placed on the top side of the PCB. A solder pallet is attached to the bottom of the PCB. The PCB is ran through a wave solder machine to solder all the TH parts. Note: A solder pallet is basically a shield to protect the SMT parts from being removed in the wave. They are custom made for each PCB, and have holes and contours to expose the TH parts while shielding the SMT parts. The PCB must be designed with the solder pallet in mind, since you can't place the bottom side SMT parts too close to the TH parts and the SMT parts cannot be too tall. A relatively new technique for TH parts is to skip the wave solder machine completely. Back in step B, solder paste is placed on the TH pads (and in the holes) and the TH parts are inserted and soldered in the oven with the rest of the SMT parts. Some companies, like Motorola, have gotten rid of their wave solder machines in favor of this method. But most companies still use the older technique of using a wave solder machine with solder pallet. There are, of course, many variations of this entire process. I have just given a simple and brief overview. But it is fairly consistent with the way current manufacturing processes work today (things were different even just 10 years ago).
I do not know what you have pictured in your mind about solder wave, but it is a relatively simple process. The circuit board is set between 2 conveyor chains. The chains are simple roller chains but have "fingers" about 2 inches long. One conveyor is movable to accept different size circuit boards. They are also inclined maybe 7 degrees. The circuit boards are set on one end of the conveyor, they pass over a fluxer that applies solder flux to the connections to be soldered. The solder is contained in a tank that is HOT and the solder is in a liquid state. There are pumps that actually pump the solder within its own tank and creates the wave. Surface tension is very visible and the bottom of the circuit being soldered comes in contact with the solder as it passes over the wave. This is for through-hole soldering only and is not used for SMT components. Any flux residue is washed off in a commercial board washer. SMT components are a different story. The bare circuit board is run through a type of screen printer and solder paste is applied through a stencil. The components are placed with a Pick & Place machine, then the boards are run through a reflow oven. If the board is double-sided, a small amount of epoxy is placed under each component so it will not fall off the board during the reflow (oven) process of the second side. Hope I was able to answer your questions.
37,683
**Wave soldering** I am trying to understand how wave soldering works. Unfortunately the [Wikipedia article](http://en.wikipedia.org/wiki/Wave_soldering) has has left me unsure about the process: 1. Is the entire board with its components quasi-immersed in liquid solder while it passes through the wave? (If not, the following question probably make no sense.) 2. If the board cuts into the wave, how is the wave maintained? 3. Why does this not leave superflous solder residue on the board? **Double-Sided SMT soldering** How are double sided boards with SMT components soldered? How is it prevented that the components on one side fall off?
2012/08/11
[ "https://electronics.stackexchange.com/questions/37683", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/8534/" ]
The wave only contacts the bottom side of the PCB. Once upon a time, a wave solder machine was used to solder SMT parts on the bottom side of the PCB but this is not used as much anymore in favor of more modern techniques. Here is the rough process for soldering PCB's with SMT parts on both sides, and through hole (TH) parts on the top side only. A. The bare PCB is turned "bottom side up". A solder paste is pressed through a stencil and onto the pads of the PCB. A pick and place machine places the parts onto the bottom side. The PCB is ran through an oven (hot-air convection or an IR oven) to melt the solder and attach the parts. An optional step is to place a small drop of glue under the parts. Solder paste first, then glue, then the parts are put onto the PCB and soldered. This glue helps keep the parts from falling off during a later step. B. The board is turned over (top side up), and the same process is repeated for all SMT parts on the top side of the PCB. By that I mean solder paste, parts placed, then through the oven. No glue is needed. During step B, the parts on the bottom of the PCB don't fall off. Obviously if they are glued down then they are stuck there, but most companies do not use glue. Without glue, the surface tension from the molten solder is enough to hold the parts in place. Some parts, particularly heavy parts without many pins, might not work with this technique since there is not enough surface tension to hold the parts on. C. All of the through-hole parts are then placed on the top side of the PCB. A solder pallet is attached to the bottom of the PCB. The PCB is ran through a wave solder machine to solder all the TH parts. Note: A solder pallet is basically a shield to protect the SMT parts from being removed in the wave. They are custom made for each PCB, and have holes and contours to expose the TH parts while shielding the SMT parts. The PCB must be designed with the solder pallet in mind, since you can't place the bottom side SMT parts too close to the TH parts and the SMT parts cannot be too tall. A relatively new technique for TH parts is to skip the wave solder machine completely. Back in step B, solder paste is placed on the TH pads (and in the holes) and the TH parts are inserted and soldered in the oven with the rest of the SMT parts. Some companies, like Motorola, have gotten rid of their wave solder machines in favor of this method. But most companies still use the older technique of using a wave solder machine with solder pallet. There are, of course, many variations of this entire process. I have just given a simple and brief overview. But it is fairly consistent with the way current manufacturing processes work today (things were different even just 10 years ago).
**wave soldering** For wave soldering the PCB passes over a bath of molten solder where the solder is pushed up so that it strikes along the bottom side of the PCB. You'll need a solder resist mask to prevent to have solder over all the copper. Note that also SMDs can be wave soldered, but then the orientation of the parts is important. Some parts have to be placed perpendicular to the wave direction. Fine pitch parts like 0.4 mm QFPs can't be wave soldered because all the pins will be shorted, but QFPs with a higher pitch can. They need "solder thieves", which are solder pads at the end of a row of pins to gather residual solder. ![enter image description here](https://i.stack.imgur.com/3aAyb.gif) A QFP may have to be placed at a 45° angle, and will have the solder thieves at one of the corners: ![enter image description here](https://i.stack.imgur.com/VZiCf.png) The wave direction is important during PCB layout and panelization, and the production engineer should get clear instructions on it. **reflow soldering** SMDs for two-sided placement are glued on one side. After solder paste is applied with a stencil a glue dot machine places glue dots for the parts (at an incredible rate of more than 10 per second). Then the parts are placed, the panel is flipped over, and the other side gets solder paste and component placement.
37,683
**Wave soldering** I am trying to understand how wave soldering works. Unfortunately the [Wikipedia article](http://en.wikipedia.org/wiki/Wave_soldering) has has left me unsure about the process: 1. Is the entire board with its components quasi-immersed in liquid solder while it passes through the wave? (If not, the following question probably make no sense.) 2. If the board cuts into the wave, how is the wave maintained? 3. Why does this not leave superflous solder residue on the board? **Double-Sided SMT soldering** How are double sided boards with SMT components soldered? How is it prevented that the components on one side fall off?
2012/08/11
[ "https://electronics.stackexchange.com/questions/37683", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/8534/" ]
The wave only contacts the bottom side of the PCB. Once upon a time, a wave solder machine was used to solder SMT parts on the bottom side of the PCB but this is not used as much anymore in favor of more modern techniques. Here is the rough process for soldering PCB's with SMT parts on both sides, and through hole (TH) parts on the top side only. A. The bare PCB is turned "bottom side up". A solder paste is pressed through a stencil and onto the pads of the PCB. A pick and place machine places the parts onto the bottom side. The PCB is ran through an oven (hot-air convection or an IR oven) to melt the solder and attach the parts. An optional step is to place a small drop of glue under the parts. Solder paste first, then glue, then the parts are put onto the PCB and soldered. This glue helps keep the parts from falling off during a later step. B. The board is turned over (top side up), and the same process is repeated for all SMT parts on the top side of the PCB. By that I mean solder paste, parts placed, then through the oven. No glue is needed. During step B, the parts on the bottom of the PCB don't fall off. Obviously if they are glued down then they are stuck there, but most companies do not use glue. Without glue, the surface tension from the molten solder is enough to hold the parts in place. Some parts, particularly heavy parts without many pins, might not work with this technique since there is not enough surface tension to hold the parts on. C. All of the through-hole parts are then placed on the top side of the PCB. A solder pallet is attached to the bottom of the PCB. The PCB is ran through a wave solder machine to solder all the TH parts. Note: A solder pallet is basically a shield to protect the SMT parts from being removed in the wave. They are custom made for each PCB, and have holes and contours to expose the TH parts while shielding the SMT parts. The PCB must be designed with the solder pallet in mind, since you can't place the bottom side SMT parts too close to the TH parts and the SMT parts cannot be too tall. A relatively new technique for TH parts is to skip the wave solder machine completely. Back in step B, solder paste is placed on the TH pads (and in the holes) and the TH parts are inserted and soldered in the oven with the rest of the SMT parts. Some companies, like Motorola, have gotten rid of their wave solder machines in favor of this method. But most companies still use the older technique of using a wave solder machine with solder pallet. There are, of course, many variations of this entire process. I have just given a simple and brief overview. But it is fairly consistent with the way current manufacturing processes work today (things were different even just 10 years ago).
This is a somewhat archaic method where the entire bottom of the board is drawn along a flowing pool of solder: <https://www.youtube.com/watch?v=inHzaJIE7-4> Newer methods include a small cnc solder fountain that is applied to the individual solder points on the board, rather than a bath that the entire unit runs through. The pros and cons of each, I'm not entirely sure. Also, here's a video of a pick and place machine: <https://www.youtube.com/watch?v=tn0EKtLOVx4>
37,683
**Wave soldering** I am trying to understand how wave soldering works. Unfortunately the [Wikipedia article](http://en.wikipedia.org/wiki/Wave_soldering) has has left me unsure about the process: 1. Is the entire board with its components quasi-immersed in liquid solder while it passes through the wave? (If not, the following question probably make no sense.) 2. If the board cuts into the wave, how is the wave maintained? 3. Why does this not leave superflous solder residue on the board? **Double-Sided SMT soldering** How are double sided boards with SMT components soldered? How is it prevented that the components on one side fall off?
2012/08/11
[ "https://electronics.stackexchange.com/questions/37683", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/8534/" ]
I do not know what you have pictured in your mind about solder wave, but it is a relatively simple process. The circuit board is set between 2 conveyor chains. The chains are simple roller chains but have "fingers" about 2 inches long. One conveyor is movable to accept different size circuit boards. They are also inclined maybe 7 degrees. The circuit boards are set on one end of the conveyor, they pass over a fluxer that applies solder flux to the connections to be soldered. The solder is contained in a tank that is HOT and the solder is in a liquid state. There are pumps that actually pump the solder within its own tank and creates the wave. Surface tension is very visible and the bottom of the circuit being soldered comes in contact with the solder as it passes over the wave. This is for through-hole soldering only and is not used for SMT components. Any flux residue is washed off in a commercial board washer. SMT components are a different story. The bare circuit board is run through a type of screen printer and solder paste is applied through a stencil. The components are placed with a Pick & Place machine, then the boards are run through a reflow oven. If the board is double-sided, a small amount of epoxy is placed under each component so it will not fall off the board during the reflow (oven) process of the second side. Hope I was able to answer your questions.
This is a somewhat archaic method where the entire bottom of the board is drawn along a flowing pool of solder: <https://www.youtube.com/watch?v=inHzaJIE7-4> Newer methods include a small cnc solder fountain that is applied to the individual solder points on the board, rather than a bath that the entire unit runs through. The pros and cons of each, I'm not entirely sure. Also, here's a video of a pick and place machine: <https://www.youtube.com/watch?v=tn0EKtLOVx4>
37,683
**Wave soldering** I am trying to understand how wave soldering works. Unfortunately the [Wikipedia article](http://en.wikipedia.org/wiki/Wave_soldering) has has left me unsure about the process: 1. Is the entire board with its components quasi-immersed in liquid solder while it passes through the wave? (If not, the following question probably make no sense.) 2. If the board cuts into the wave, how is the wave maintained? 3. Why does this not leave superflous solder residue on the board? **Double-Sided SMT soldering** How are double sided boards with SMT components soldered? How is it prevented that the components on one side fall off?
2012/08/11
[ "https://electronics.stackexchange.com/questions/37683", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/8534/" ]
**wave soldering** For wave soldering the PCB passes over a bath of molten solder where the solder is pushed up so that it strikes along the bottom side of the PCB. You'll need a solder resist mask to prevent to have solder over all the copper. Note that also SMDs can be wave soldered, but then the orientation of the parts is important. Some parts have to be placed perpendicular to the wave direction. Fine pitch parts like 0.4 mm QFPs can't be wave soldered because all the pins will be shorted, but QFPs with a higher pitch can. They need "solder thieves", which are solder pads at the end of a row of pins to gather residual solder. ![enter image description here](https://i.stack.imgur.com/3aAyb.gif) A QFP may have to be placed at a 45° angle, and will have the solder thieves at one of the corners: ![enter image description here](https://i.stack.imgur.com/VZiCf.png) The wave direction is important during PCB layout and panelization, and the production engineer should get clear instructions on it. **reflow soldering** SMDs for two-sided placement are glued on one side. After solder paste is applied with a stencil a glue dot machine places glue dots for the parts (at an incredible rate of more than 10 per second). Then the parts are placed, the panel is flipped over, and the other side gets solder paste and component placement.
This is a somewhat archaic method where the entire bottom of the board is drawn along a flowing pool of solder: <https://www.youtube.com/watch?v=inHzaJIE7-4> Newer methods include a small cnc solder fountain that is applied to the individual solder points on the board, rather than a bath that the entire unit runs through. The pros and cons of each, I'm not entirely sure. Also, here's a video of a pick and place machine: <https://www.youtube.com/watch?v=tn0EKtLOVx4>
694,723
I just built a PC for my wife; i3-4130 / B85 / 8GB RAM / Radeon 7730 1GB GDDR5 / 120GB Intel 330 SSD / 22" HP IPS Monitor. She's an interior designer and she uses this software, 20-20 Design. She's satisfied with its performance over her Samsung laptop with i5-2430M with integrated graphics (the new desktop renders significantly quicker and has a lot better image quality), although even quicker render times will always be nice. Of course I am on a budget. My questions are: 1. Would it be better if I instead purchased a cheaper but 2GB video card? Perhaps a Radeon 7730 2GB DDR3? 2. If she wanted to render quicker for a similar price, would it be better if I purchased an AMD processor with more cores? Or will the Intel Haswell still do a better job with its 2 cores? 3. Is it the Haswell i3-4130 that renders much faster than the Sandy Bridge i5-2430m? They're both dual-cores (although 3.4Ghz vs 2.4Ghz), or does the video card also help in rendering times?
2013/12/30
[ "https://superuser.com/questions/694723", "https://superuser.com", "https://superuser.com/users/257654/" ]
Just looking at the [System Requirements](http://www.2020technologies.com/home/interior-design/kitchen-bath-and-home-organization/2020-design#&panel1-1), I would say that if you want it faster, I'd go for a CPU upgrade. However, an easy way to see if it's the CPU or GPU holding you back, you could have a peek in the task manager to see whether the CPU is maxing out when a render is being done. If it's maxing out, then upgrading the CPU will help. If it's not, then the GPU is what's holding the speed back. --- In response to your questions > > Would it be better if I instead purchased a cheaper but 2GB video card? Perhaps a Radeon 7730 2GB DDR3? > > > In this case, they're much the sameness. The amount of RAM is important to your needs, not the speed. > > If she wanted to render quicker for a similar price, would it be better if I purchased an AMD processor with more cores? Or will the Intel Haswell still do a better job with its 2 cores? > > > That would be hard to say. It would depend on how the application is designed. Generally however, Intel CPUs perform better than AMD CPUs. > > Is it the Haswell i3-4130 that renders much faster than the Sandy Bridge i5-2430m? They're both dual-cores (although 3.4Ghz vs 2.4Ghz), or does the video card also help in rendering times? > > > I'd say it's the graphics card that helps it render faster. But that's just an educated guess. The graphics card can do a lot of the heavy lifting when it comes to rendering 3D scenes. Lighting, reflections, transparency etc would likely be done by the graphics card.
I almost commented on Lawrence's answer, but reconsidered as my thoughts stand as an answer on their own. I've been down this journey a few times via various paths... and I'm still not exactly satisfied with the results. *Now, on to the arms race of "graphics" performance:* **CPU** Start with Lawrence's advice on checking the CPU in performance monitor. Most programs are sadly single threaded. If this is the case, then more cores just empties your wallet. I use Rhinoceros 3D for CAD and it is almost always single threaded (only uses 1 core). When your app is single threaded and can't use more cores, you need the newest architecture you can afford, the fastest clock speed possible, but with the least cores available. That means get a Core i3 with 3GHz+ clock speed. Mentioning Core i3 may not be the most current advice: google site:overclock.net about CPU performance. And Intel all the way. IMHO, AMD is great for servers (I have a 1055t in mine) but Intel for desktops. Caveat: when you're maxing out that program and only have 2 cores, make sure THAT is the only program running. You can alt-tab over to your Firefox with 30 tabs open and play candy crush. My Experience: I've gone from dual core to core 2 duo to 6 core to xeon 4 core (dual thread), all of them overclocked. I like to punish the program than switch to something else and stay productive while my task has the CAD program go all white. **RAM** I consider 4G to be insufficient for anything more than having a browser and one or two office programs open. Check out the performance monitor, you'll see. The problem is, you need to pay attention to the Windows OS version and its RAM limits. Right off, you need to be on 64 bit version of the OS. You can get 8GB in Win7 Home Basic. That's a great first step. ([Reference](http://msdn.microsoft.com/en-us/library/windows/desktop/aa366778%28v=vs.85%29.aspx#physical_memory_limits_windows_7)) Sadly, Home Premium limits you to 16G, so anything at work that does more than office-y stuff has to run Win 7 64 Pro. Speed or version of RAM is almost irrelevant imho. You're not overclocking or benchmarking. If 2G or 4G is holding you back, the cheapest 8G is going to feel like a Ferrari. **GPU** This is the tough one. Once the above two are assuredly not holding you back, this is the last continent to explore. If I hadn't personally seen what a Quadro workstation card can do, I would not be a believer in graphics cards. I had a pretty good on-board HDMI output on my CAD box of the moment and was taking my computer back and forth with me to work. I had spare peripherals at home and work, so it was only the box. At work I was using a 24" DVI monitor and at home is a higher end 42" Sony HDTV. I was given (*as in for free, like free beer*) a Quadro FX3800. It was waaay more than I needed, but a customer saw me talk about my problems and gave me a factory hook-up. I'm in the 2nd or 3rd week working on my CAD project at home and I see something... off the corner of my model... zoom zoom zoom zoom oh wow, there's trash hanging out there I didn't notice before! Those last two zooms were impossible to "see" before the new card. *But*, I didn't talk about rendering per-se, zooming in and re-drawing is a cousin to rendering, so we could be talking about the same thing or semantics has us in separate topics when it comes to GPU performance. You need to talk to technical support at the manufacturer of the software you're using and find out exactly what video hardware they have observed in their own lab to appear to be the best performance at realistic pricing. From my experience, they'll do their best to help because then you'll like them more and keep on buying their products. **GUI** When doing CAD-like stuff, see if the [3D Connexion Space Navigator](http://www.3dconnexion.com/products/spacenavigator.html) works in your software! OMG, I love it so much I bought a 2nd one to sit at home for the few times I do CAD at home on my laptop. It is like flying a helicopter through your drawing; you can get the view exactly on what you're doing! I have found so many minuscule defects where edges don't meet up properly via this + a good GPU. **My System** OK, so I gave all this advice. Here's [my CAD computer](http://www.overclock.net/lists/display/view/id/5217451/version/5217453). What's sad is that I humbly say "yeah it's ok", when it's a stonkin epic computer. The only thing(s) I bought new for it were the RAM and the AMD GPU. The rest was legacy stuff from other computers. The core i7 was from a Gateway store-box computer. It was the only thing worth beans in that whole computer. I bought a core i3 for it and it's a spare workstation for guests now. The Motherboard had only 2 slots and I recall was limited to 4G of RAM. :P I ganked it's CPU when I saw a core i3 on OCN for sale, which I put in my CAD box. The AMD GPU was on a special sale where they gave me a gift card for buying it. The only reason I bought it was when I moved my Quadro to the latest build, it stopped working. Got me why. I researched and the W5000 was the best performance for the money at the moment. RAM? 16G was enough for a long while. Then I got the laser scanner which upped the ante a LOT for filesize. :P There are 4 slots in the motherboard with 4 4GB sticks. So I went to 4 8GB sticks. If you buy memory, buy 8GB sticks so you only need to buy TWO to upgrade from 16G to 32G!! \*Next time\*\* I'm buying a server-type motherboard that can have even more RAM. The more ram you've got, the less programs need to "think" it seems. Get enough and you can make a RAM disk and save your files there, too. Win7Pro goes up to 192G; that's bigger than my SSD! After that, I'd get whatever processor has the highest "boost" speed and not care about cores. 4 or more are all the same unless you're certain your tasks are using those extra cores.
49,825,329
I want to shuffle non-zero elements of each column in a matrix but keep the zero elements at the same place. Like I have this: ``` A = [10 0 30 40 50 60 11 0 31 41 0 61 0 22 32 42 0 62 13 23 0 43 0 63 0 24 34 44 54 64 15 0 35 0 0 65 16 26 36 46 56 66] ``` And I want this: ``` B = [13 0 32 44 54 64 11 0 35 42 0 63 0 24 36 40 0 61 16 23 0 43 0 62 0 22 31 41 56 60 10 0 30 0 0 66 15 26 34 46 50 65] ``` So herein I have the zeros at the exact same place (i.e. ~A = ~B) and the non-zero elements are shuffled. Obviously shuffling the columns using 'randperm' does not work as it does not allow me to keep zeroes at the same place!
2018/04/13
[ "https://Stackoverflow.com/questions/49825329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7867604/" ]
This is a solution that works for one column: Making a new vector `C` containing the nonzero entries, shuffling those, and pasting them back into the nonzero entries of `B` should do exactly that. Now you can adjust this to work for matrices by looping over all columns. ```matlab A = [10, 11, 0, 13, 0, 15, 16]; B = A; C = A(A~=0); B(A~=0) = C(randperm(numel(C))); A B ``` [Try it online!](https://tio.run/##y08uSSxL/f/fUcFWQSHa0EBHwdBQRwFEGUMoUyA2i7XmcgIqcLTmcgZRGo51tgaaQDEIAyjkrFGUmJdSkFqUq5FXmpuao@GsqQlU4Mjl9P8/AA "Octave – Try It Online")
I wrote a function for you ``` function a=shuffle(src) [rows, cols] = size(src); a = zeros(rows,cols); for c = 1:cols lastIndex = 1; col = []; for r = 1:rows if(src(r,c) ~= 0) col(lastIndex) = src(r,c); lastIndex = lastIndex + 1; end end indexes = randperm(length(col)); lastIndex = 1; for r = 1:rows if(src(r,c) == 0) a(r,c) = 0; else a(r,c) = col(indexes(lastIndex)); lastIndex = lastIndex + 1; end end end end ``` It's not optimized, I leave it to You. It extracts the non-zeros to a vector, and takes randperm values from this vector to the new matrix, if the old matrix didnt have 0 there.
49,825,329
I want to shuffle non-zero elements of each column in a matrix but keep the zero elements at the same place. Like I have this: ``` A = [10 0 30 40 50 60 11 0 31 41 0 61 0 22 32 42 0 62 13 23 0 43 0 63 0 24 34 44 54 64 15 0 35 0 0 65 16 26 36 46 56 66] ``` And I want this: ``` B = [13 0 32 44 54 64 11 0 35 42 0 63 0 24 36 40 0 61 16 23 0 43 0 62 0 22 31 41 56 60 10 0 30 0 0 66 15 26 34 46 50 65] ``` So herein I have the zeros at the exact same place (i.e. ~A = ~B) and the non-zero elements are shuffled. Obviously shuffling the columns using 'randperm' does not work as it does not allow me to keep zeroes at the same place!
2018/04/13
[ "https://Stackoverflow.com/questions/49825329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7867604/" ]
Here's an alternative to the explicit loop-over-columns approach: ``` [~, jj, vv] = find(A); s = accumarray(jj, vv, [], @(x){x(randperm(numel(x)))}); B = A; B(B~=0) = cell2mat(s); ```
This is a solution that works for one column: Making a new vector `C` containing the nonzero entries, shuffling those, and pasting them back into the nonzero entries of `B` should do exactly that. Now you can adjust this to work for matrices by looping over all columns. ```matlab A = [10, 11, 0, 13, 0, 15, 16]; B = A; C = A(A~=0); B(A~=0) = C(randperm(numel(C))); A B ``` [Try it online!](https://tio.run/##y08uSSxL/f/fUcFWQSHa0EBHwdBQRwFEGUMoUyA2i7XmcgIqcLTmcgZRGo51tgaaQDEIAyjkrFGUmJdSkFqUq5FXmpuao@GsqQlU4Mjl9P8/AA "Octave – Try It Online")
49,825,329
I want to shuffle non-zero elements of each column in a matrix but keep the zero elements at the same place. Like I have this: ``` A = [10 0 30 40 50 60 11 0 31 41 0 61 0 22 32 42 0 62 13 23 0 43 0 63 0 24 34 44 54 64 15 0 35 0 0 65 16 26 36 46 56 66] ``` And I want this: ``` B = [13 0 32 44 54 64 11 0 35 42 0 63 0 24 36 40 0 61 16 23 0 43 0 62 0 22 31 41 56 60 10 0 30 0 0 66 15 26 34 46 50 65] ``` So herein I have the zeros at the exact same place (i.e. ~A = ~B) and the non-zero elements are shuffled. Obviously shuffling the columns using 'randperm' does not work as it does not allow me to keep zeroes at the same place!
2018/04/13
[ "https://Stackoverflow.com/questions/49825329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7867604/" ]
Here's an alternative to the explicit loop-over-columns approach: ``` [~, jj, vv] = find(A); s = accumarray(jj, vv, [], @(x){x(randperm(numel(x)))}); B = A; B(B~=0) = cell2mat(s); ```
I wrote a function for you ``` function a=shuffle(src) [rows, cols] = size(src); a = zeros(rows,cols); for c = 1:cols lastIndex = 1; col = []; for r = 1:rows if(src(r,c) ~= 0) col(lastIndex) = src(r,c); lastIndex = lastIndex + 1; end end indexes = randperm(length(col)); lastIndex = 1; for r = 1:rows if(src(r,c) == 0) a(r,c) = 0; else a(r,c) = col(indexes(lastIndex)); lastIndex = lastIndex + 1; end end end end ``` It's not optimized, I leave it to You. It extracts the non-zeros to a vector, and takes randperm values from this vector to the new matrix, if the old matrix didnt have 0 there.
57,830,632
i have a spinner in add new data, I want the selected data to be an image in the item of recyclerview anyone knows how to make like that like this but spinner that is from activity not item recycler view and thats the problem, how to get id spinner in adapter ``` holder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { String item = parent.getItemAtPosition(position).toString(); if (item == important){ holder.img_category.setImageResource(R.drawable.important); }else if (item == notImportant){ holder.img_category.setImageResource(R.drawable.notimportant); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); ```
2019/09/07
[ "https://Stackoverflow.com/questions/57830632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11863128/" ]
Hi look updated answer ``` selectImageType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { if(i!=0) { selectedItem=binding.selectImageType.getSelectedItem().toString(); Log.e(TAG, "onItemSelected: "+selectedItem); if(!selectedItem.equalsIgnoreCase("")) { spinnerDemoAdapter=new SpinnerDemoAdapter(dataImageList,selectedItem,SpinnerDemoActivity.this); binding.recycleSpinnerDemo.setHasFixedSize(true); binding.recycleSpinnerDemo.setLayoutManager(new LinearLayoutManager(SpinnerDemoActivity.this, RecyclerView.VERTICAL,false)); binding.recycleSpinnerDemo.setAdapter(spinnerDemoAdapter); spinnerDemoAdapter.notifyDataSetChanged(); } } } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); ``` And this below is your adapter code I take arraylist here and add random values for testing purpose ``` public SpinnerDemoAdapter(ArrayList<String> arrayList, String selectedItem, Context mContext) { this.arrayList = arrayList; this.selectedItem = selectedItem; this.mContext = mContext; } public void onBindViewHolder(@NonNull ViewHolder holder, int position) { if (!selectedItem.equalsIgnoreCase("")) { Log.e(TAG, "onBindViewHolder: "+selectedItem); if (selectedItem.equalsIgnoreCase("important")) { Glide.with(mContext).load(R.drawable.woman).into(holder.imageview); } else if (selectedItem.equalsIgnoreCase("notimportant")) { Glide.with(mContext).load(R.drawable.man).into(holder.imageview); } } } ```
use Glide for image set in imageView check below code. add -> 'implementation 'com.github.bumptech.glide:glide:4.9.0' into your app.gradle yes check that item getting your desired values using log and use `if(item.equalsIgnoreCase(important))` to check your if condition. ``` holder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { String item = parent.getItemAtPosition(position).toString(); log.e("TAG","Selected ITEM :"+item); if(item.equalsIgnoreCase(important)){ Glide.with(context).load(R.drawable.important).into(holder.img_category); //here }else if(item.equalsIgnoreCase(notImportant)){ Glide.with(context).load(R.drawable.notimportant).into(holder.img_category); // here } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); ```
15,405,667
The following applies: ``` var rounded = Decimal.Round(7.635m, 2); //rounded: 7.63 ``` This, to me, is wrong and unexpected behavior. I would assume the value of *rounded* to be **7.64**. To achieve this, I can do: ``` var rounded = Decimal.Round(7.635m, 2, MidpointRounding.AwayFromZero); //rounded: 7.64 ``` How can this **not** be the default behavior of `Decimal.Round`? Any good reason for this?
2013/03/14
[ "https://Stackoverflow.com/questions/15405667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/896348/" ]
> > How can this not be the default behavior of Decimal.Round? Any good > reason for this? > > > If you look at the documentation of [Decimal.Round Method (Decimal)](http://msdn.microsoft.com/en-us/library/k4e2bye2.aspx) > > The **behavior of this method follows IEEE Standard 754, section 4**. > This kind of rounding is sometimes called *round half to even* or > *banker's rounding*. It minimizes rounding errors that result from > consistently rounding a midpoint value in a single direction. It is > equivalent to calling the Round(Decimal, MidpointRounding) method with > a mode argument of MidpointRounding.ToEven. > > >
From [`Math.Round(Decimal, Int32)`](http://msdn.microsoft.com/en-us/library/vstudio/zy06z30k%28v=vs.90%29.aspx) Method > > The behavior of this method follows IEEE Standard 754, section 4. This > kind of rounding is sometimes called rounding to nearest, or banker's > rounding. It minimizes rounding errors that result from consistently > rounding a midpoint value in a single direction. > > > This method is equivalent to calling the Round method with a mode > argument of MidpointRounding.ToEven. If there is a single non-zero > digit in d to the right of the decimals decimal position and its value > is 5, the digit in the decimals position is rounded up if it is odd, > or left unchanged if it is even. If d has fewer fractional digits than > decimals, d is returned unchanged. > > >
15,405,667
The following applies: ``` var rounded = Decimal.Round(7.635m, 2); //rounded: 7.63 ``` This, to me, is wrong and unexpected behavior. I would assume the value of *rounded* to be **7.64**. To achieve this, I can do: ``` var rounded = Decimal.Round(7.635m, 2, MidpointRounding.AwayFromZero); //rounded: 7.64 ``` How can this **not** be the default behavior of `Decimal.Round`? Any good reason for this?
2013/03/14
[ "https://Stackoverflow.com/questions/15405667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/896348/" ]
> > How can this not be the default behavior of Decimal.Round? Any good > reason for this? > > > If you look at the documentation of [Decimal.Round Method (Decimal)](http://msdn.microsoft.com/en-us/library/k4e2bye2.aspx) > > The **behavior of this method follows IEEE Standard 754, section 4**. > This kind of rounding is sometimes called *round half to even* or > *banker's rounding*. It minimizes rounding errors that result from > consistently rounding a midpoint value in a single direction. It is > equivalent to calling the Round(Decimal, MidpointRounding) method with > a mode argument of MidpointRounding.ToEven. > > >
The reason is they implemented a method following IEEE Standard 754, section 4. This is called rounding to nearest or sometimes bankers rounding. It's just one of many ways to do rounding and they choose this one. See: <http://en.wikipedia.org/wiki/Bankers_rounding> And for more information: [Why does .NET use banker's rounding as default?](https://stackoverflow.com/questions/311696/why-does-net-use-bankers-rounding-as-default)
15,405,667
The following applies: ``` var rounded = Decimal.Round(7.635m, 2); //rounded: 7.63 ``` This, to me, is wrong and unexpected behavior. I would assume the value of *rounded* to be **7.64**. To achieve this, I can do: ``` var rounded = Decimal.Round(7.635m, 2, MidpointRounding.AwayFromZero); //rounded: 7.64 ``` How can this **not** be the default behavior of `Decimal.Round`? Any good reason for this?
2013/03/14
[ "https://Stackoverflow.com/questions/15405667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/896348/" ]
From [`Math.Round(Decimal, Int32)`](http://msdn.microsoft.com/en-us/library/vstudio/zy06z30k%28v=vs.90%29.aspx) Method > > The behavior of this method follows IEEE Standard 754, section 4. This > kind of rounding is sometimes called rounding to nearest, or banker's > rounding. It minimizes rounding errors that result from consistently > rounding a midpoint value in a single direction. > > > This method is equivalent to calling the Round method with a mode > argument of MidpointRounding.ToEven. If there is a single non-zero > digit in d to the right of the decimals decimal position and its value > is 5, the digit in the decimals position is rounded up if it is odd, > or left unchanged if it is even. If d has fewer fractional digits than > decimals, d is returned unchanged. > > >
The reason is they implemented a method following IEEE Standard 754, section 4. This is called rounding to nearest or sometimes bankers rounding. It's just one of many ways to do rounding and they choose this one. See: <http://en.wikipedia.org/wiki/Bankers_rounding> And for more information: [Why does .NET use banker's rounding as default?](https://stackoverflow.com/questions/311696/why-does-net-use-bankers-rounding-as-default)
20,378,733
I have building a web site but i have a error code and i couldnt fould a fix it Error > > Parse error: syntax error, unexpected T\_PAAMAYIM\_NEKUDOTAYIM in /home/eneskura/public\_html/administrator/components/com\_tz\_portfolio/helpers/tz\_portfolio.php on line 42 > > > line 42- ``` $class::addEntry(JText::('COM_TZ_PORTFOLIO_SUBMENU_GROUP_FIELDS'), 'index.php?option=com_tz_portfolio&view=fieldsgroup', $vName == 'fieldsgroup'); ``` how i can i fix it? Site: eneskuray.com php 5.2.17 litespeed full php ``` <?php // No direct access defined('_JEXEC') or die; class TZ_PortfolioHelper { public static $extension = 'com_content'; /** * Configure the Linkbar. * * @param string $vName The name of the active view. * * @return void * @since 1.6 */ public static function addSubmenu($vName) { $class = 'JHtmlSidebar'; if(!COM_TZ_PORTFOLIO_JVERSION_COMPARE){ $class = 'JSubMenuHelper'; } $class::addEntry( JText::_('COM_TZ_PORTFOLIO_SUBMENU_GROUP_FIELDS'), 'index.php?option=com_tz_portfolio&view=fieldsgroup', $vName == 'fieldsgroup'); $class::addEntry( JText::_('COM_TZ_PORTFOLIO_SUBMENU_FIELDS'), 'index.php?option=com_tz_portfolio&view=fields', $vName == 'fields' ); $class::addEntry( JText::_('COM_TZ_PORTFOLIO_SUBMENU_CATEGORIES'), 'index.php?option=com_tz_portfolio&view=categories', $vName == 'categories'); $class::addEntry( JText::_('COM_TZ_PORTFOLIO_SUBMENU_ARTICLES'), 'index.php?option=com_tz_portfolio&view=articles', $vName == 'articles' ); $class::addEntry( JText::_('COM_TZ_PORTFOLIO_SUBMENU_FEATURED_ARTICLES'), 'index.php?option=com_tz_portfolio&view=featured', $vName == 'featured' ); $class::addEntry( JText::_('COM_TZ_PORTFOLIO_SUBMENU_TAGS'), 'index.php?option=com_tz_portfolio&view=tags', $vName == 'tags'); $class::addEntry( JText::_('COM_TZ_PORTFOLIO_SUBMENU_USERS'), 'index.php?option=com_tz_portfolio&view=users', $vName == 'users'); } /** * Gets a list of the actions that can be performed. * * @param int The category ID. * @param int The article ID. * * @return JObject * @since 1.6 */ public static function getActions($categoryId = 0, $articleId = 0) { $user = JFactory::getUser(); $result = new JObject; if (empty($articleId) && empty($categoryId)) { $assetName = 'com_tz_portfolio'; } elseif (empty($articleId)) { $assetName = 'com_tz_portfolio.category.'.(int) $categoryId; } else { $assetName = 'com_tz_portfolio.article.'.(int) $articleId; } $actions = array( 'core.admin', 'core.manage', 'core.create', 'core.edit', 'core.edit.own', 'core.edit.state', 'core.delete' ); foreach ($actions as $action) { $result->set($action, $user->authorise($action, $assetName)); } return $result; } /** * Applies the content tag filters to arbitrary text as per settings for current user group * @param text The string to filter * @return string The filtered string */ public static function filterText($text) { // Filter settings $config = JComponentHelper::getParams('com_config'); $user = JFactory::getUser(); $userGroups = JAccess::getGroupsByUser($user->get('id')); $filters = $config->get('filters'); $blackListTags = array(); $blackListAttributes = array(); $customListTags = array(); $customListAttributes = array(); $whiteListTags = array(); $whiteListAttributes = array(); $noHtml = false; $whiteList = false; $blackList = false; $customList = false; $unfiltered = false; // Cycle through each of the user groups the user is in. // Remember they are included in the Public group as well. foreach ($userGroups as $groupId) { // May have added a group but not saved the filters. if (!isset($filters->$groupId)) { continue; } // Each group the user is in could have different filtering properties. $filterData = $filters->$groupId; $filterType = strtoupper($filterData->filter_type); if ($filterType == 'NH') { // Maximum HTML filtering. $noHtml = true; } elseif ($filterType == 'NONE') { // No HTML filtering. $unfiltered = true; } else { // Black, white or custom list. // Preprocess the tags and attributes. $tags = explode(',', $filterData->filter_tags); $attributes = explode(',', $filterData->filter_attributes); $tempTags = array(); $tempAttributes = array(); foreach ($tags as $tag) { $tag = trim($tag); if ($tag) { $tempTags[] = $tag; } } foreach ($attributes as $attribute) { $attribute = trim($attribute); if ($attribute) { $tempAttributes[] = $attribute; } } // Collect the black or white list tags and attributes. // Each lists is cummulative. if ($filterType == 'BL') { $blackList = true; $blackListTags = array_merge($blackListTags, $tempTags); $blackListAttributes = array_merge($blackListAttributes, $tempAttributes); } elseif ($filterType == 'CBL') { // Only set to true if Tags or Attributes were added if ($tempTags || $tempAttributes) { $customList = true; $customListTags = array_merge($customListTags, $tempTags); $customListAttributes = array_merge($customListAttributes, $tempAttributes); } } elseif ($filterType == 'WL') { $whiteList = true; $whiteListTags = array_merge($whiteListTags, $tempTags); $whiteListAttributes = array_merge($whiteListAttributes, $tempAttributes); } } } // Remove duplicates before processing (because the black list uses both sets of arrays). $blackListTags = array_unique($blackListTags); $blackListAttributes = array_unique($blackListAttributes); $customListTags = array_unique($customListTags); $customListAttributes = array_unique($customListAttributes); $whiteListTags = array_unique($whiteListTags); $whiteListAttributes = array_unique($whiteListAttributes); // Unfiltered assumes first priority. if ($unfiltered) { // Dont apply filtering. } else { // Custom blacklist precedes Default blacklist if ($customList) { $filter = JFilterInput::getInstance(array(), array(), 1, 1); // Override filter's default blacklist tags and attributes if ($customListTags) { $filter->tagBlacklist = $customListTags; } if ($customListAttributes) { $filter->attrBlacklist = $customListAttributes; } } // Black lists take third precedence. elseif ($blackList) { // Remove the white-listed attributes from the black-list. $filter = JFilterInput::getInstance( array_diff($blackListTags, $whiteListTags), // blacklisted tags array_diff($blackListAttributes, $whiteListAttributes), // blacklisted attributes 1, // blacklist tags 1 // blacklist attributes ); // Remove white listed tags from filter's default blacklist if ($whiteListTags) { $filter->tagBlacklist = array_diff($filter->tagBlacklist, $whiteListTags); } // Remove white listed attributes from filter's default blacklist if ($whiteListAttributes) { $filter->attrBlacklist = array_diff($filter->attrBlacklist); } } // White lists take fourth precedence. elseif ($whiteList) { $filter = JFilterInput::getInstance($whiteListTags, $whiteListAttributes, 0, 0, 0); // turn off xss auto clean } // No HTML takes last place. else { $filter = JFilterInput::getInstance(); } $text = $filter->clean($text, 'html'); } return $text; } } ``` ATTETION : some texts deleted for privacy.
2013/12/04
[ "https://Stackoverflow.com/questions/20378733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The [scope resolution operator](http://www.php.net/manual/en/language.oop5.paamayim-nekudotayim.php) (::) can only be used on a class referenced using a variable from PHP 5.3 -- you're using 5.2. You'd have to do `JHtmlSidebar::addEntry` or `JSubMenuHelper::addEntry`; you can't do `$class::addEntry`.
`JText::('COM_TZ_PORTFOLIO_SUBMENU_GROUP_FIELDS')` is not calling a method. It should be: ``` JText::_('COM_TZ_PORTFOLIO_SUBMENU_GROUP_FIELDS') ``` See [`JText`](http://docs.joomla.org/JText/).
20,378,733
I have building a web site but i have a error code and i couldnt fould a fix it Error > > Parse error: syntax error, unexpected T\_PAAMAYIM\_NEKUDOTAYIM in /home/eneskura/public\_html/administrator/components/com\_tz\_portfolio/helpers/tz\_portfolio.php on line 42 > > > line 42- ``` $class::addEntry(JText::('COM_TZ_PORTFOLIO_SUBMENU_GROUP_FIELDS'), 'index.php?option=com_tz_portfolio&view=fieldsgroup', $vName == 'fieldsgroup'); ``` how i can i fix it? Site: eneskuray.com php 5.2.17 litespeed full php ``` <?php // No direct access defined('_JEXEC') or die; class TZ_PortfolioHelper { public static $extension = 'com_content'; /** * Configure the Linkbar. * * @param string $vName The name of the active view. * * @return void * @since 1.6 */ public static function addSubmenu($vName) { $class = 'JHtmlSidebar'; if(!COM_TZ_PORTFOLIO_JVERSION_COMPARE){ $class = 'JSubMenuHelper'; } $class::addEntry( JText::_('COM_TZ_PORTFOLIO_SUBMENU_GROUP_FIELDS'), 'index.php?option=com_tz_portfolio&view=fieldsgroup', $vName == 'fieldsgroup'); $class::addEntry( JText::_('COM_TZ_PORTFOLIO_SUBMENU_FIELDS'), 'index.php?option=com_tz_portfolio&view=fields', $vName == 'fields' ); $class::addEntry( JText::_('COM_TZ_PORTFOLIO_SUBMENU_CATEGORIES'), 'index.php?option=com_tz_portfolio&view=categories', $vName == 'categories'); $class::addEntry( JText::_('COM_TZ_PORTFOLIO_SUBMENU_ARTICLES'), 'index.php?option=com_tz_portfolio&view=articles', $vName == 'articles' ); $class::addEntry( JText::_('COM_TZ_PORTFOLIO_SUBMENU_FEATURED_ARTICLES'), 'index.php?option=com_tz_portfolio&view=featured', $vName == 'featured' ); $class::addEntry( JText::_('COM_TZ_PORTFOLIO_SUBMENU_TAGS'), 'index.php?option=com_tz_portfolio&view=tags', $vName == 'tags'); $class::addEntry( JText::_('COM_TZ_PORTFOLIO_SUBMENU_USERS'), 'index.php?option=com_tz_portfolio&view=users', $vName == 'users'); } /** * Gets a list of the actions that can be performed. * * @param int The category ID. * @param int The article ID. * * @return JObject * @since 1.6 */ public static function getActions($categoryId = 0, $articleId = 0) { $user = JFactory::getUser(); $result = new JObject; if (empty($articleId) && empty($categoryId)) { $assetName = 'com_tz_portfolio'; } elseif (empty($articleId)) { $assetName = 'com_tz_portfolio.category.'.(int) $categoryId; } else { $assetName = 'com_tz_portfolio.article.'.(int) $articleId; } $actions = array( 'core.admin', 'core.manage', 'core.create', 'core.edit', 'core.edit.own', 'core.edit.state', 'core.delete' ); foreach ($actions as $action) { $result->set($action, $user->authorise($action, $assetName)); } return $result; } /** * Applies the content tag filters to arbitrary text as per settings for current user group * @param text The string to filter * @return string The filtered string */ public static function filterText($text) { // Filter settings $config = JComponentHelper::getParams('com_config'); $user = JFactory::getUser(); $userGroups = JAccess::getGroupsByUser($user->get('id')); $filters = $config->get('filters'); $blackListTags = array(); $blackListAttributes = array(); $customListTags = array(); $customListAttributes = array(); $whiteListTags = array(); $whiteListAttributes = array(); $noHtml = false; $whiteList = false; $blackList = false; $customList = false; $unfiltered = false; // Cycle through each of the user groups the user is in. // Remember they are included in the Public group as well. foreach ($userGroups as $groupId) { // May have added a group but not saved the filters. if (!isset($filters->$groupId)) { continue; } // Each group the user is in could have different filtering properties. $filterData = $filters->$groupId; $filterType = strtoupper($filterData->filter_type); if ($filterType == 'NH') { // Maximum HTML filtering. $noHtml = true; } elseif ($filterType == 'NONE') { // No HTML filtering. $unfiltered = true; } else { // Black, white or custom list. // Preprocess the tags and attributes. $tags = explode(',', $filterData->filter_tags); $attributes = explode(',', $filterData->filter_attributes); $tempTags = array(); $tempAttributes = array(); foreach ($tags as $tag) { $tag = trim($tag); if ($tag) { $tempTags[] = $tag; } } foreach ($attributes as $attribute) { $attribute = trim($attribute); if ($attribute) { $tempAttributes[] = $attribute; } } // Collect the black or white list tags and attributes. // Each lists is cummulative. if ($filterType == 'BL') { $blackList = true; $blackListTags = array_merge($blackListTags, $tempTags); $blackListAttributes = array_merge($blackListAttributes, $tempAttributes); } elseif ($filterType == 'CBL') { // Only set to true if Tags or Attributes were added if ($tempTags || $tempAttributes) { $customList = true; $customListTags = array_merge($customListTags, $tempTags); $customListAttributes = array_merge($customListAttributes, $tempAttributes); } } elseif ($filterType == 'WL') { $whiteList = true; $whiteListTags = array_merge($whiteListTags, $tempTags); $whiteListAttributes = array_merge($whiteListAttributes, $tempAttributes); } } } // Remove duplicates before processing (because the black list uses both sets of arrays). $blackListTags = array_unique($blackListTags); $blackListAttributes = array_unique($blackListAttributes); $customListTags = array_unique($customListTags); $customListAttributes = array_unique($customListAttributes); $whiteListTags = array_unique($whiteListTags); $whiteListAttributes = array_unique($whiteListAttributes); // Unfiltered assumes first priority. if ($unfiltered) { // Dont apply filtering. } else { // Custom blacklist precedes Default blacklist if ($customList) { $filter = JFilterInput::getInstance(array(), array(), 1, 1); // Override filter's default blacklist tags and attributes if ($customListTags) { $filter->tagBlacklist = $customListTags; } if ($customListAttributes) { $filter->attrBlacklist = $customListAttributes; } } // Black lists take third precedence. elseif ($blackList) { // Remove the white-listed attributes from the black-list. $filter = JFilterInput::getInstance( array_diff($blackListTags, $whiteListTags), // blacklisted tags array_diff($blackListAttributes, $whiteListAttributes), // blacklisted attributes 1, // blacklist tags 1 // blacklist attributes ); // Remove white listed tags from filter's default blacklist if ($whiteListTags) { $filter->tagBlacklist = array_diff($filter->tagBlacklist, $whiteListTags); } // Remove white listed attributes from filter's default blacklist if ($whiteListAttributes) { $filter->attrBlacklist = array_diff($filter->attrBlacklist); } } // White lists take fourth precedence. elseif ($whiteList) { $filter = JFilterInput::getInstance($whiteListTags, $whiteListAttributes, 0, 0, 0); // turn off xss auto clean } // No HTML takes last place. else { $filter = JFilterInput::getInstance(); } $text = $filter->clean($text, 'html'); } return $text; } } ``` ATTETION : some texts deleted for privacy.
2013/12/04
[ "https://Stackoverflow.com/questions/20378733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The [scope resolution operator](http://www.php.net/manual/en/language.oop5.paamayim-nekudotayim.php) (::) can only be used on a class referenced using a variable from PHP 5.3 -- you're using 5.2. You'd have to do `JHtmlSidebar::addEntry` or `JSubMenuHelper::addEntry`; you can't do `$class::addEntry`.
`T_PAAMAYIM_NEKUDOTAYIM` refers to the two colons in a row like this `::`. Looking at your code sample: ``` $class::addEntry( JText::('COM_TZ_PORTFOLIO_SUBMENU_GROUP_FIELDS'), 'index.php?option=com_tz_portfolio&view=fieldsgroup', $vName == 'fieldsgroup'); ``` I believe the issue is with `JText::(`. As per [Joomla documentation](http://docs.joomla.org/JText/) that should be formatted with an underscore so it is `JText::_(` so your code would be: ``` $class::addEntry( JText::_('COM_TZ_PORTFOLIO_SUBMENU_GROUP_FIELDS'), 'index.php?option=com_tz_portfolio&view=fieldsgroup', $vName == 'fieldsgroup'); ``` Not 100% clear on Joomla internals, but that underscore (`_`) is actually a function/method of some sort within the `JText` class. So when you were calling it as `JText::(` PHP choked because it had no idea what you were trying to do with `JText`. By adding that underscore (`_`), it will now actually call a function within a class & do what it has to do.
68,589,876
I have API endpoint /department/getManagersList?department\_name=IT which is returning this ``` { "status": "success", "managersList": [ { "id": "6103d29974535fac35286aff", "name": "axe deo", "role": "Associate React Developer" }, { "id": "6103d1e274535fac35286afe", "name": "aakash kumar", "role": "Vice President Engineering" }, { "id": "6103d36074535fac35286b0a", "name": "atanu paul", "role": "Senior Software Enginner" }, { "id": "6103d7c1f2bba5af7cad4083", "name": "sam winchester", "role": "Junior Node JS Developer" } ] } ``` now "sam Winchester" is a new user who just created his profile I want to exclude him or in a nutshell, remove the newly created user from this list. The purpose is to return the names of all the employees of the department excluding the newly created user so that the new user can choose his/her reporting manager. Any idea how to do this? This is the current code that is returning the above JSON object ``` adminController.getManagersList = async (req, res) => { try { var manager_list = []; var department_data = {}; var employees_list = []; var manager_details = {}; var department_name = req.query.department_name; if (isEmpty(department_name)) return res.status(400).json({ status: "failure", message: `Department name ${emptyField}`, }); department_data = await DepartmentData.findOne({ department_name: department_name, }) .populate("employees") .exec(); if (isEmpty(department_data)) return res .status(400) .json({ status: "failure", message: `Department ${dataNotFound}` }); employees_list = department_data.employees; employees_list.forEach((empList) => { let department_data = empList.department; department_data.forEach((depList) => { if (depList.name == department_name) { manager_details = {}; // * Making the object empty for next value manager_details.id = empList._id; manager_details.name = empList.full_name; manager_details.role = depList.role; manager_list.push(manager_details); } }); }); res.status(200).json({ status: "success", managersList: manager_list }); } catch (err) { console.log(err); res .status(500) .json({ status: "failure", message: "Internal Server Error" }); } }; ```
2021/07/30
[ "https://Stackoverflow.com/questions/68589876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15556024/" ]
To remove the last item from your array you could use: ``` const arr = [1,2,3]; arr.pop(); // arr -> [1,2] ```
Generally speaking you already answered your question here: > > The purpose is to return the names of all the employees of the department excluding the newly created user so that the new user can choose his/her reporting manager. > > > So that you need find all employees who do not have managers yet. I assume that you have relationship between managers and users as `one-to-many`, (one manager can have many employees). Not sure what database are you using, but should be something like this: ``` department_data = await DepartmentData.findOne({ department_name: department_name, }) .populate({ path: 'employees', match: { managerId: { $eq: null }}, }) .exec(); ``` also rename "getManagersList" to "getEmployeesList"
4,444,870
I recently just started to migrate over a CI application to Amazon's EC2 service. To test I set up a micro instance of ubuntu and a LAMP stack. PHP, MySQL, HTTPD are all working beautifully. The one issue i'm having now is that when I run my application I receive an error saying that my helpers won't load. The helpers in particular that aren't loading are the ones in subdirectories in the helpers directory ie: /var/www/system/application/helpers/subdirectory/foo\_helper.php The helpers are being autoloaded and in my autoload.php config file they are written like: ``` $autoload['helper'] = array('subdirectory/foo', 'foo2',...); ``` Has anyone run into this issue, or have any pointers on where I could go look in my configuration to resolve this? Thanks for the help!
2010/12/14
[ "https://Stackoverflow.com/questions/4444870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135881/" ]
I ran into the same issue while trying to install MySQL 5.5.15 in Lion using homebrew and resolved the issue with: ``` mysql_install_db --verbose --user=`whoami` --basedir="$(brew --prefix mysql)" --datadir=/usr/local/var/mysql --tmpdir=/tmp ``` and creating a the file ~/my.cnf with the content: ``` [mysqld] basedir=/usr/local/Cellar/mysql/5.5.15 datadir=/usr/local/var/mysql ``` basedir - should be your current MySQL instalation dir datadir - should be the location of MySQL data You can figure out that too location by watching the make command during the "brew install mysql" searching for something like this: ``` -DCMAKE_INSTALL_PREFIX=/usr/local/Cellar/mysql/5.5.15 -DMYSQL_DATADIR=/usr/local/var/mysql -DINSTALL_MANDIR=/usr/local/Cellar/mysql ``` Where DCMAKE\_INSTALL\_PREFIX = basedir and DMYSQL\_DATADIR = datadir
1. `brew postinstall mysql` 2. `delete document /opt/homebrew/var/mysql` 3. `brew postinstall mysql`
4,444,870
I recently just started to migrate over a CI application to Amazon's EC2 service. To test I set up a micro instance of ubuntu and a LAMP stack. PHP, MySQL, HTTPD are all working beautifully. The one issue i'm having now is that when I run my application I receive an error saying that my helpers won't load. The helpers in particular that aren't loading are the ones in subdirectories in the helpers directory ie: /var/www/system/application/helpers/subdirectory/foo\_helper.php The helpers are being autoloaded and in my autoload.php config file they are written like: ``` $autoload['helper'] = array('subdirectory/foo', 'foo2',...); ``` Has anyone run into this issue, or have any pointers on where I could go look in my configuration to resolve this? Thanks for the help!
2010/12/14
[ "https://Stackoverflow.com/questions/4444870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135881/" ]
I ran into this same problem when installing via homebrew. Make sure you run these commands (which are listed during install but easy to miss): ``` unset TMPDIR mysql_install_db ```
Nothing else really helped, but the following worked: ``` $ ps aux | grep mysql tagir 27260 0.0 1.0 3562356 175120 ?? S 2:52PM 0:00.42 mysqld --skip-grant-tables tagir 42704 0.0 0.0 2434840 784 s000 S+ 3:04PM 0:00.00 grep mysql $ kill 27260 # Careful! This might erase your existing data $ rm -rf /usr/local/var/mysql $ mysqld --initialize $ mysql.server start ```
4,444,870
I recently just started to migrate over a CI application to Amazon's EC2 service. To test I set up a micro instance of ubuntu and a LAMP stack. PHP, MySQL, HTTPD are all working beautifully. The one issue i'm having now is that when I run my application I receive an error saying that my helpers won't load. The helpers in particular that aren't loading are the ones in subdirectories in the helpers directory ie: /var/www/system/application/helpers/subdirectory/foo\_helper.php The helpers are being autoloaded and in my autoload.php config file they are written like: ``` $autoload['helper'] = array('subdirectory/foo', 'foo2',...); ``` Has anyone run into this issue, or have any pointers on where I could go look in my configuration to resolve this? Thanks for the help!
2010/12/14
[ "https://Stackoverflow.com/questions/4444870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135881/" ]
I ran into this same problem when installing via homebrew. Make sure you run these commands (which are listed during install but easy to miss): ``` unset TMPDIR mysql_install_db ```
I am adding this here because I encountered this problem several times after installing other software. MySQL was working fine for days, then suddenly I get this error. It seems to happen when I install something (eg. elasticsearch or Puma web server). The MySql permissions get reverted again (back to me, and not `_mysql`). No idea why. * MacOS Sierra * Homebrew 1.0.5-43-g41b2df8 (2016-10-02) * MySQL 5.7.15 So I have found that one cause of this is the permissions on the location where MySQL stores your databases, which by default is here: ``` /usr/local/var/mysql ``` If you look in that folder you will see a file ``` <your computer name>.err ``` If you look inside that file (`more` it or `cat` it) you will probably see this error: ``` [ERROR] InnoDB: The innodb_system data file 'ibdata1' must be writable ``` If so then you know it is a permissions issue. If you don't care, you can probably just run MySQL by just running `mysqld` (and leave that terminal open). If you do care: `ls -al /usr/local/var/mysql` you will notice that the permissions are probably all set to you (your user account). This means mysql cannot mount your databases when you run it using the homebrew shortcut `sudo mysql.server start` [even though you are using sudo to run in 'admin' mode]. So, change the permissions: ``` $ sudo chown -R _mysql /usr/local/var/mysql $ sudo chmod -R o+rwx /usr/local/var/mysql ``` Then it will work.
4,444,870
I recently just started to migrate over a CI application to Amazon's EC2 service. To test I set up a micro instance of ubuntu and a LAMP stack. PHP, MySQL, HTTPD are all working beautifully. The one issue i'm having now is that when I run my application I receive an error saying that my helpers won't load. The helpers in particular that aren't loading are the ones in subdirectories in the helpers directory ie: /var/www/system/application/helpers/subdirectory/foo\_helper.php The helpers are being autoloaded and in my autoload.php config file they are written like: ``` $autoload['helper'] = array('subdirectory/foo', 'foo2',...); ``` Has anyone run into this issue, or have any pointers on where I could go look in my configuration to resolve this? Thanks for the help!
2010/12/14
[ "https://Stackoverflow.com/questions/4444870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135881/" ]
Nothing else really helped, but the following worked: ``` $ ps aux | grep mysql tagir 27260 0.0 1.0 3562356 175120 ?? S 2:52PM 0:00.42 mysqld --skip-grant-tables tagir 42704 0.0 0.0 2434840 784 s000 S+ 3:04PM 0:00.00 grep mysql $ kill 27260 # Careful! This might erase your existing data $ rm -rf /usr/local/var/mysql $ mysqld --initialize $ mysql.server start ```
1. `brew postinstall mysql` 2. `delete document /opt/homebrew/var/mysql` 3. `brew postinstall mysql`
4,444,870
I recently just started to migrate over a CI application to Amazon's EC2 service. To test I set up a micro instance of ubuntu and a LAMP stack. PHP, MySQL, HTTPD are all working beautifully. The one issue i'm having now is that when I run my application I receive an error saying that my helpers won't load. The helpers in particular that aren't loading are the ones in subdirectories in the helpers directory ie: /var/www/system/application/helpers/subdirectory/foo\_helper.php The helpers are being autoloaded and in my autoload.php config file they are written like: ``` $autoload['helper'] = array('subdirectory/foo', 'foo2',...); ``` Has anyone run into this issue, or have any pointers on where I could go look in my configuration to resolve this? Thanks for the help!
2010/12/14
[ "https://Stackoverflow.com/questions/4444870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135881/" ]
These following two commands should solve your issue. ``` > unset TMPDIR > mysql_install_db --verbose --user=\`whoami\` --basedir="$(brew --prefix mysql)" --datadir=/usr/local/var/mysql --tmpdir=/tmp ```
1. `brew postinstall mysql` 2. `delete document /opt/homebrew/var/mysql` 3. `brew postinstall mysql`
4,444,870
I recently just started to migrate over a CI application to Amazon's EC2 service. To test I set up a micro instance of ubuntu and a LAMP stack. PHP, MySQL, HTTPD are all working beautifully. The one issue i'm having now is that when I run my application I receive an error saying that my helpers won't load. The helpers in particular that aren't loading are the ones in subdirectories in the helpers directory ie: /var/www/system/application/helpers/subdirectory/foo\_helper.php The helpers are being autoloaded and in my autoload.php config file they are written like: ``` $autoload['helper'] = array('subdirectory/foo', 'foo2',...); ``` Has anyone run into this issue, or have any pointers on where I could go look in my configuration to resolve this? Thanks for the help!
2010/12/14
[ "https://Stackoverflow.com/questions/4444870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135881/" ]
You probably need to ensure that you're running mysql as the `root` user -- otherwise it won't have permission to write the PID file (thus the error you're receiving). Try this: ``` sudo mysql.server start ``` You'll be prompted for your password. (this assumes that your user account has permissions to "sudo" -- which it should, unless it's setup as a restricted user account in OS X). This may not be the only issue -- but it should get you to the next step anyway.
1. `brew postinstall mysql` 2. `delete document /opt/homebrew/var/mysql` 3. `brew postinstall mysql`
4,444,870
I recently just started to migrate over a CI application to Amazon's EC2 service. To test I set up a micro instance of ubuntu and a LAMP stack. PHP, MySQL, HTTPD are all working beautifully. The one issue i'm having now is that when I run my application I receive an error saying that my helpers won't load. The helpers in particular that aren't loading are the ones in subdirectories in the helpers directory ie: /var/www/system/application/helpers/subdirectory/foo\_helper.php The helpers are being autoloaded and in my autoload.php config file they are written like: ``` $autoload['helper'] = array('subdirectory/foo', 'foo2',...); ``` Has anyone run into this issue, or have any pointers on where I could go look in my configuration to resolve this? Thanks for the help!
2010/12/14
[ "https://Stackoverflow.com/questions/4444870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135881/" ]
I ran into this same problem when installing via homebrew. Make sure you run these commands (which are listed during install but easy to miss): ``` unset TMPDIR mysql_install_db ```
It appears that for whatever reason I can't comment below Immendes above, but on 10.8.2 with mySQL 5.6.10, in addition to verifying the db\_install and adding the my.cnf, I also had to chown -R myusername /tmp/mysql.sock. It appears that allowing mySQL to run under the user (as apposed to root or www as I woudl do on linux) is not the best idea in this regard (though Homebrew could update the formula -- beyond my scope and time).
4,444,870
I recently just started to migrate over a CI application to Amazon's EC2 service. To test I set up a micro instance of ubuntu and a LAMP stack. PHP, MySQL, HTTPD are all working beautifully. The one issue i'm having now is that when I run my application I receive an error saying that my helpers won't load. The helpers in particular that aren't loading are the ones in subdirectories in the helpers directory ie: /var/www/system/application/helpers/subdirectory/foo\_helper.php The helpers are being autoloaded and in my autoload.php config file they are written like: ``` $autoload['helper'] = array('subdirectory/foo', 'foo2',...); ``` Has anyone run into this issue, or have any pointers on where I could go look in my configuration to resolve this? Thanks for the help!
2010/12/14
[ "https://Stackoverflow.com/questions/4444870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135881/" ]
I ran into this same problem when installing via homebrew. Make sure you run these commands (which are listed during install but easy to miss): ``` unset TMPDIR mysql_install_db ```
These following two commands should solve your issue. ``` > unset TMPDIR > mysql_install_db --verbose --user=\`whoami\` --basedir="$(brew --prefix mysql)" --datadir=/usr/local/var/mysql --tmpdir=/tmp ```
4,444,870
I recently just started to migrate over a CI application to Amazon's EC2 service. To test I set up a micro instance of ubuntu and a LAMP stack. PHP, MySQL, HTTPD are all working beautifully. The one issue i'm having now is that when I run my application I receive an error saying that my helpers won't load. The helpers in particular that aren't loading are the ones in subdirectories in the helpers directory ie: /var/www/system/application/helpers/subdirectory/foo\_helper.php The helpers are being autoloaded and in my autoload.php config file they are written like: ``` $autoload['helper'] = array('subdirectory/foo', 'foo2',...); ``` Has anyone run into this issue, or have any pointers on where I could go look in my configuration to resolve this? Thanks for the help!
2010/12/14
[ "https://Stackoverflow.com/questions/4444870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135881/" ]
You probably need to ensure that you're running mysql as the `root` user -- otherwise it won't have permission to write the PID file (thus the error you're receiving). Try this: ``` sudo mysql.server start ``` You'll be prompted for your password. (this assumes that your user account has permissions to "sudo" -- which it should, unless it's setup as a restricted user account in OS X). This may not be the only issue -- but it should get you to the next step anyway.
Nothing else really helped, but the following worked: ``` $ ps aux | grep mysql tagir 27260 0.0 1.0 3562356 175120 ?? S 2:52PM 0:00.42 mysqld --skip-grant-tables tagir 42704 0.0 0.0 2434840 784 s000 S+ 3:04PM 0:00.00 grep mysql $ kill 27260 # Careful! This might erase your existing data $ rm -rf /usr/local/var/mysql $ mysqld --initialize $ mysql.server start ```
4,444,870
I recently just started to migrate over a CI application to Amazon's EC2 service. To test I set up a micro instance of ubuntu and a LAMP stack. PHP, MySQL, HTTPD are all working beautifully. The one issue i'm having now is that when I run my application I receive an error saying that my helpers won't load. The helpers in particular that aren't loading are the ones in subdirectories in the helpers directory ie: /var/www/system/application/helpers/subdirectory/foo\_helper.php The helpers are being autoloaded and in my autoload.php config file they are written like: ``` $autoload['helper'] = array('subdirectory/foo', 'foo2',...); ``` Has anyone run into this issue, or have any pointers on where I could go look in my configuration to resolve this? Thanks for the help!
2010/12/14
[ "https://Stackoverflow.com/questions/4444870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135881/" ]
I ran into this same problem when installing via homebrew. Make sure you run these commands (which are listed during install but easy to miss): ``` unset TMPDIR mysql_install_db ```
I ran into the same issue while trying to install MySQL 5.5.15 in Lion using homebrew and resolved the issue with: ``` mysql_install_db --verbose --user=`whoami` --basedir="$(brew --prefix mysql)" --datadir=/usr/local/var/mysql --tmpdir=/tmp ``` and creating a the file ~/my.cnf with the content: ``` [mysqld] basedir=/usr/local/Cellar/mysql/5.5.15 datadir=/usr/local/var/mysql ``` basedir - should be your current MySQL instalation dir datadir - should be the location of MySQL data You can figure out that too location by watching the make command during the "brew install mysql" searching for something like this: ``` -DCMAKE_INSTALL_PREFIX=/usr/local/Cellar/mysql/5.5.15 -DMYSQL_DATADIR=/usr/local/var/mysql -DINSTALL_MANDIR=/usr/local/Cellar/mysql ``` Where DCMAKE\_INSTALL\_PREFIX = basedir and DMYSQL\_DATADIR = datadir
17,654,302
Range slider ``` $("#slider-range").slider({ range: true, min: 0, max: 420, values: [0, 420], slide: slideTime, change: toSpin }); ``` and text fields ``` $('#min').val(ui.values[ 0 ]); $('#max').val(ui.values[ 1 ]); ``` and I would like to call a function when the value of each field changes, like ``` $('input').on('input propertychange', function() { ``` but since the mouse is never in the field it won't work. Maybe local storage is the answer, but before getting into it I thought I would see if I can just bind the slider handles instead. I can use #slider-range like this: ``` var $leftslider = $("#slider-range"); $leftslider.bind("mouseup", sliderHandler); function sliderHandler() { ``` but I guess I would need to bind mouseups to each handle, left and right separately, to call a different function for each. So, after the slider changes #min, the left handle mouseup would call a function that uses the value of #min. Variations on this theme ``` $(#slider-range).children('.ui-slider-handle').first().offset(); ``` seem not to work.
2013/07/15
[ "https://Stackoverflow.com/questions/17654302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1877124/" ]
Sitecore confirmed that they can reproduce the issue. When setting dynamicCompressionBeforeCache="true", the encoding does not work correctly for some reason. One solution is to remove this setting. After applying dynamicCompressionBeforeCache="false" it works fine.
You should probably enable gzip in your web.config ``` <system.webServer> <httpCompression directory="%SystemDrive%\inetpub\ temp\IIS Temporary Compressed Files"> <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll"/> <dynamicTypes> <add mimeType="text/*" enabled="true"/> <add mimeType="message/*" enabled="true"/> <add mimeType="application/javascript" enabled="true"/> <add mimeType="*/*" enabled="false"/> </dynamicTypes> <staticTypes> <add mimeType="text/*" enabled="true"/> <add mimeType="message/*" enabled="true"/> <add mimeType="application/javascript" enabled="true"/> <add mimeType="*/*" enabled="false"/> </staticTypes> </httpCompression> <urlCompression doStaticCompression="true" doDynamicCompression="true"/> </system.webServer> ``` There are a few more tricks here [Setting the gzip compression in asp.net](https://stackoverflow.com/questions/1324481/setting-the-gzip-compression-in-asp-net)
9,119,572
I am using bootstrap-sass, formtastic-bootstrap, rails 3.2, and ruby 1.9.3p0 on a new project. I want create a multi-column form and multi-column media grid for the list of products. Code below. I used two separate methods. The first is using the row < .span for the form and the second is by adding my own multi-column css code to the media-grid and that's not working either. Help? **First method on form:** ``` <%= semantic_form_for @product do |f| %> <%= f.inputs do %> <div class="row"> <div class="span8"> <%= f.input :name %> <%= ... %> </div> </div> <div class="row"> <div class="span8"> <%= f.input :description %> <%= ... %> </div> </div> <% end %> <% end %> ``` **Second method on media-grid:** ``` <div class="row multi-column"> <ul class="media-grid span4"> <% @products.each do |prod| %> <li class="media-grid"> <div class="well"> <%= link_to prod.name, prod, :class => "strong" %></br> $<%= prod.price %></br> <%= prod.available ? "Available" : "Out of Stock" %> </div> </li> <% end %> </ul> </div> ``` Here's the code for the multi-column css: ``` .multi-column { -moz-column-count: 3; -webkit-column-count: 3; column-count: 3;} ``` Help...
2012/02/02
[ "https://Stackoverflow.com/questions/9119572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/793116/" ]
Do you have a `float:left` on anything in there? I was just playing around with a multi-column thing in Twitter Bootstrap today and noticed that that broke it.
I'm currently working on a helper to do this for rails, im extracting from the following code: ``` - (0..items.size - 1).each do |i| - if i % 3 == 0 \<div class="row"> =render "items/show_small", item: items.at(i) - if i % 3 == 2 || i == items.size - 1 \</div> ``` and ``` .span4.show-small ``` i think i did my mods correct there...
43,540,159
I am trying to build an executable out of my .py script using Pyinstaller. The problem is that it builds it using Python 2.7 instead of Python 3.5, so my executable won't even run. ``` cali@californiki-pc ~/Desktop $ pyinstaller --onefile Vocabulary.py 25 INFO: PyInstaller: 3.2.1 25 INFO: Python: 2.7.12 26 INFO: Platform: Linux-4.4.0-72-generic-x86_64-with-LinuxMint-18.1-serena 26 INFO: wrote /home/cali/Desktop/Vocabulary.spec 31 INFO: UPX is not available. 32 INFO: Extending PYTHONPATH with paths ['/home/cali/Desktop', '/home/cali/Desktop'] 32 INFO: checking Analysis 33 INFO: Building Analysis because out00-Analysis.toc is non existent 33 INFO: Initializing module dependency graph... 34 INFO: Initializing module graph hooks... 139 INFO: running Analysis out00-Analysis.toc 160 INFO: Caching module hooks... 164 INFO: Analyzing /home/cali/Desktop/Vocabulary.py 246 INFO: Processing pre-safe import module hook _xmlplus 1991 INFO: Processing pre-find module path hook distutils 2209 INFO: Loading module hooks... 2209 INFO: Loading module hook "hook-distutils.py"... 2210 INFO: Loading module hook "hook-xml.py"... 2959 INFO: Loading module hook "hook-httplib.py"... 2960 INFO: Loading module hook "hook-encodings.py"... 3427 INFO: Looking for ctypes DLLs 3428 INFO: Analyzing run-time hooks ... 3435 INFO: Looking for dynamic libraries 3663 INFO: Looking for eggs 3663 INFO: Python library not in binary depedencies. Doing additional searching... 3707 INFO: Using Python library /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0 3710 INFO: Warnings written to /home/cali/Desktop/build/Vocabulary/warnVocabulary.txt 3768 INFO: checking PYZ 3768 INFO: Building PYZ because out00-PYZ.toc is non existent 3768 INFO: Building PYZ (ZlibArchive) /home/cali/Desktop/build/Vocabulary/out00-PYZ.pyz 4122 INFO: Building PYZ (ZlibArchive) /home/cali/Desktop/build/Vocabulary/out00-PYZ.pyz completed successfully. 4172 INFO: checking PKG 4172 INFO: Building PKG because out00-PKG.toc is non existent 4172 INFO: Building PKG (CArchive) out00-PKG.pkg 7322 INFO: Building PKG (CArchive) out00-PKG.pkg completed successfully. 7336 INFO: Bootloader /usr/local/lib/python2.7/dist-packages/PyInstaller/bootloader/Linux-64bit/run 7336 INFO: checking EXE 7336 INFO: Building EXE because out00-EXE.toc is non existent 7336 INFO: Building EXE from out00-EXE.toc 7337 INFO: Appending archive to ELF section in EXE /home/cali/Desktop/dist/Vocabulary 7352 INFO: Building EXE from out00-EXE.toc completed successfully. ``` How can I overcome the issue? @EDIT: I tried to install Pyinstaller using `pip3 install pyinstaller` as Claudio suggested, but I am getting: ``` cali@californiki-pc ~/Desktop $ pip3 install pyinstaller Collecting pyinstaller Using cached PyInstaller-3.2.1.tar.bz2 Collecting setuptools (from pyinstaller) Using cached setuptools-35.0.1-py2.py3-none-any.whl Collecting appdirs>=1.4.0 (from setuptools->pyinstaller) Using cached appdirs-1.4.3-py2.py3-none-any.whl Collecting packaging>=16.8 (from setuptools->pyinstaller) Using cached packaging-16.8-py2.py3-none-any.whl Collecting six>=1.6.0 (from setuptools->pyinstaller) Using cached six-1.10.0-py2.py3-none-any.whl Collecting pyparsing (from packaging>=16.8->setuptools->pyinstaller) Using cached pyparsing-2.2.0-py2.py3-none-any.whl Building wheels for collected packages: pyinstaller Running setup.py bdist_wheel for pyinstaller ... error Complete output from command /usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-42qpk7iy/pyinstaller/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d /tmp/tmpmmn5007ppip-wheel- --python-tag cp35: usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: -c --help [cmd1 cmd2 ...] or: -c --help-commands or: -c cmd --help error: invalid command 'bdist_wheel' ---------------------------------------- Failed building wheel for pyinstaller Running setup.py clean for pyinstaller Failed to build pyinstaller Installing collected packages: appdirs, six, pyparsing, packaging, setuptools, pyinstaller Running setup.py install for pyinstaller ... done Successfully installed appdirs-1.4.3 packaging-16.8 pyinstaller-3.2.1 pyparsing-2.2.0 setuptools-35.0.1 six-1.10.0 You are using pip version 8.1.1, however version 9.0.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. ```
2017/04/21
[ "https://Stackoverflow.com/questions/43540159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
To overcome the problem you face install PyInstaller using: > > pip3 install pyinstaller > > > Then take care that you run the right one (there will then be two of them in different locations, one in the path of Python2.7 modules and one in the path of Python3.5 modules) Just installed PyInstaller for Python 3.5 on my machine: ``` $ pip3 install pyinstaller Collecting pyinstaller Collecting setuptools (from pyinstaller) Using cached setuptools-35.0.1-py2.py3-none-any.whl Collecting six>=1.6.0 (from setuptools->pyinstaller) Using cached six-1.10.0-py2.py3-none-any.whl Collecting appdirs>=1.4.0 (from setuptools->pyinstaller) Using cached appdirs-1.4.3-py2.py3-none-any.whl Collecting packaging>=16.8 (from setuptools->pyinstaller) Using cached packaging-16.8-py2.py3-none-any.whl Collecting pyparsing (from packaging>=16.8->setuptools->pyinstaller) Using cached pyparsing-2.2.0-py2.py3-none-any.whl Installing collected packages: six, appdirs, pyparsing, packaging, setuptools, pyinstaller Successfully installed appdirs-1.4.3 packaging-16.8 pyinstaller-3.2.1 pyparsing-2.0.3 setuptools-20.7.0 six-1.10.0 ``` It installs without problems ... Hmmm ... Try: ``` sudo -H pip3 install setuptools --upgrade ``` (see for more [here](https://stackoverflow.com/questions/34819221/why-is-python-setup-py-saying-invalid-command-bdist-wheel-on-travis-ci) - you are not alone with this problem)
Just set an option -upx-dir in pyinstaller specifying your path for python 3.5. It can be the virtual environment too. For instance: ``` pyinstaller --upx-dir="$HOME/virtual-envs/<your-virtual-env>/lib/python3.5/site-packages/" <your-script>.py' ```
43,540,159
I am trying to build an executable out of my .py script using Pyinstaller. The problem is that it builds it using Python 2.7 instead of Python 3.5, so my executable won't even run. ``` cali@californiki-pc ~/Desktop $ pyinstaller --onefile Vocabulary.py 25 INFO: PyInstaller: 3.2.1 25 INFO: Python: 2.7.12 26 INFO: Platform: Linux-4.4.0-72-generic-x86_64-with-LinuxMint-18.1-serena 26 INFO: wrote /home/cali/Desktop/Vocabulary.spec 31 INFO: UPX is not available. 32 INFO: Extending PYTHONPATH with paths ['/home/cali/Desktop', '/home/cali/Desktop'] 32 INFO: checking Analysis 33 INFO: Building Analysis because out00-Analysis.toc is non existent 33 INFO: Initializing module dependency graph... 34 INFO: Initializing module graph hooks... 139 INFO: running Analysis out00-Analysis.toc 160 INFO: Caching module hooks... 164 INFO: Analyzing /home/cali/Desktop/Vocabulary.py 246 INFO: Processing pre-safe import module hook _xmlplus 1991 INFO: Processing pre-find module path hook distutils 2209 INFO: Loading module hooks... 2209 INFO: Loading module hook "hook-distutils.py"... 2210 INFO: Loading module hook "hook-xml.py"... 2959 INFO: Loading module hook "hook-httplib.py"... 2960 INFO: Loading module hook "hook-encodings.py"... 3427 INFO: Looking for ctypes DLLs 3428 INFO: Analyzing run-time hooks ... 3435 INFO: Looking for dynamic libraries 3663 INFO: Looking for eggs 3663 INFO: Python library not in binary depedencies. Doing additional searching... 3707 INFO: Using Python library /usr/lib/x86_64-linux-gnu/libpython2.7.so.1.0 3710 INFO: Warnings written to /home/cali/Desktop/build/Vocabulary/warnVocabulary.txt 3768 INFO: checking PYZ 3768 INFO: Building PYZ because out00-PYZ.toc is non existent 3768 INFO: Building PYZ (ZlibArchive) /home/cali/Desktop/build/Vocabulary/out00-PYZ.pyz 4122 INFO: Building PYZ (ZlibArchive) /home/cali/Desktop/build/Vocabulary/out00-PYZ.pyz completed successfully. 4172 INFO: checking PKG 4172 INFO: Building PKG because out00-PKG.toc is non existent 4172 INFO: Building PKG (CArchive) out00-PKG.pkg 7322 INFO: Building PKG (CArchive) out00-PKG.pkg completed successfully. 7336 INFO: Bootloader /usr/local/lib/python2.7/dist-packages/PyInstaller/bootloader/Linux-64bit/run 7336 INFO: checking EXE 7336 INFO: Building EXE because out00-EXE.toc is non existent 7336 INFO: Building EXE from out00-EXE.toc 7337 INFO: Appending archive to ELF section in EXE /home/cali/Desktop/dist/Vocabulary 7352 INFO: Building EXE from out00-EXE.toc completed successfully. ``` How can I overcome the issue? @EDIT: I tried to install Pyinstaller using `pip3 install pyinstaller` as Claudio suggested, but I am getting: ``` cali@californiki-pc ~/Desktop $ pip3 install pyinstaller Collecting pyinstaller Using cached PyInstaller-3.2.1.tar.bz2 Collecting setuptools (from pyinstaller) Using cached setuptools-35.0.1-py2.py3-none-any.whl Collecting appdirs>=1.4.0 (from setuptools->pyinstaller) Using cached appdirs-1.4.3-py2.py3-none-any.whl Collecting packaging>=16.8 (from setuptools->pyinstaller) Using cached packaging-16.8-py2.py3-none-any.whl Collecting six>=1.6.0 (from setuptools->pyinstaller) Using cached six-1.10.0-py2.py3-none-any.whl Collecting pyparsing (from packaging>=16.8->setuptools->pyinstaller) Using cached pyparsing-2.2.0-py2.py3-none-any.whl Building wheels for collected packages: pyinstaller Running setup.py bdist_wheel for pyinstaller ... error Complete output from command /usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-42qpk7iy/pyinstaller/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d /tmp/tmpmmn5007ppip-wheel- --python-tag cp35: usage: -c [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: -c --help [cmd1 cmd2 ...] or: -c --help-commands or: -c cmd --help error: invalid command 'bdist_wheel' ---------------------------------------- Failed building wheel for pyinstaller Running setup.py clean for pyinstaller Failed to build pyinstaller Installing collected packages: appdirs, six, pyparsing, packaging, setuptools, pyinstaller Running setup.py install for pyinstaller ... done Successfully installed appdirs-1.4.3 packaging-16.8 pyinstaller-3.2.1 pyparsing-2.2.0 setuptools-35.0.1 six-1.10.0 You are using pip version 8.1.1, however version 9.0.1 is available. You should consider upgrading via the 'pip install --upgrade pip' command. ```
2017/04/21
[ "https://Stackoverflow.com/questions/43540159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Try: ``` py -3.5 -m PyInstaller Vocabulary.py --onefile ``` I think it is case sensitive
Just set an option -upx-dir in pyinstaller specifying your path for python 3.5. It can be the virtual environment too. For instance: ``` pyinstaller --upx-dir="$HOME/virtual-envs/<your-virtual-env>/lib/python3.5/site-packages/" <your-script>.py' ```