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
22,094,668
I have a database, I mapped it via Ado.net entity model, now I want to expose a single class from my model via WCF service. How can it be achieved?
2014/02/28
[ "https://Stackoverflow.com/questions/22094668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2606389/" ]
I like the CSS solution of A.Wolff best, but here's an alternative. The changes are only made in your jQuery code. ``` $(function() { $("#example-one").append("<div id='slider'></div>"); var $slider = $("#slider"); $slider .width($(".current_page").width()) .css("left", $(".current_page a").position().left) .data("origColor", $slider.css("background-color")) .data("origLeft", $slider.position().left) .data("origWidth", $slider.width()); $("#example-one div").find("a").hover(function() { $el = $(this); elColor = $el.css("color"); leftPos = $el.position().left; newWidth = $el.parent().width(); $slider.stop().animate({ left: leftPos, width: newWidth }).css('background-color', $el.css("color")); }, function() { $slider.stop().animate({ left: $slider.data("origLeft"), width: $slider.data("origWidth") }).css('background-color', $slider.data("origColor"));; }); }); ``` Check your [**updated Fiddle**](http://jsfiddle.net/GJQA5/8/).
Here is something much more simple: [Fiddle](http://jsfiddle.net/tomanow/GJQA5/7/) ``` $(function() { $("#example-one").append("<div id='slider'></div>"); var $slider = $("#slider"); $slider .width($(".current_page").width()) .css("left", $(".current_page a").position().left) .data("origLeft", $slider.position().left) .data("origWidth", $slider.width()); $("#example-one div").find("a").hover(function() { $el = $(this); leftPos = $el.position().left; newWidth = $el.parent().width(); $slider.stop().animate({ left: leftPos, width: newWidth }); $slider.css('background', $(this).parent().prop('class')); }, function() { $slider.stop().animate({ left: $slider.data("origLeft"), width: $slider.data("origWidth") }); $slider.css('background', 'red'); }); }); ```
22,094,668
I have a database, I mapped it via Ado.net entity model, now I want to expose a single class from my model via WCF service. How can it be achieved?
2014/02/28
[ "https://Stackoverflow.com/questions/22094668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2606389/" ]
I like the CSS solution of A.Wolff best, but here's an alternative. The changes are only made in your jQuery code. ``` $(function() { $("#example-one").append("<div id='slider'></div>"); var $slider = $("#slider"); $slider .width($(".current_page").width()) .css("left", $(".current_page a").position().left) .data("origColor", $slider.css("background-color")) .data("origLeft", $slider.position().left) .data("origWidth", $slider.width()); $("#example-one div").find("a").hover(function() { $el = $(this); elColor = $el.css("color"); leftPos = $el.position().left; newWidth = $el.parent().width(); $slider.stop().animate({ left: leftPos, width: newWidth }).css('background-color', $el.css("color")); }, function() { $slider.stop().animate({ left: $slider.data("origLeft"), width: $slider.data("origWidth") }).css('background-color', $slider.data("origColor"));; }); }); ``` Check your [**updated Fiddle**](http://jsfiddle.net/GJQA5/8/).
Here is the update code: **new CSS** ``` #slider.blue { background-color: blue; } #slider.orange { background-color: orange; } #slider.yellow { background-color: yellow; } #slider.lime { background-color: lime; } ``` **JS COde** ``` $(function() { $("#example-one").append("<div id='slider'></div>"); var $slider = $("#slider"); $slider .width($(".current_page").width()) .css("left", $(".current_page a").position().left) .data("origLeft", $slider.position().left) .data("origWidth", $slider.width()); $("#example-one div").find("a").hover(function() { $el = $(this); leftPos = $el.position().left; newWidth = $el.parent().width(); $slider.stop().animate({ left: leftPos, width: newWidth, }).addClass($(this).parent().attr('class')); }, function() { $slider.stop().animate({ left: $slider.data("origLeft"), width: $slider.data("origWidth") }).removeAttr('class'); }); }); ``` [**Updated Fiddle**](http://jsfiddle.net/GJQA5/6/)
30,546,943
``` <form id="jtable-edit-form" class="jtable-dialog-form jtable-edit-form"> <div class="jtable-input-field-container"> <div class="jtable-input-label">Type</div> <div class="jtable-input jtable-text-input"> <input class="" id="Edit-configType" type="text" name="configType"> </div> </div> <div class="jtable-input-field-container"> <div class="jtable-input-label">Key</div> <div class="jtable-input jtable-text-input"> <input class="" id="Edit-configKey" type="text" name="configKey"> </div> </div> <div class="jtable-input-field-container"> <div class="jtable-input-label">Value</div> <div class="jtable-input jtable-text-input"> <input class="" id="Edit-configValue" type="text" name="configValue"> </div> </div> <div class="jtable-input-field-container"> <div class="jtable-input-label">Description</div> <div class="jtable-input jtable-text-input"> <input class="" id="Edit-description" type="text" name="description"> </div> </div> ``` I need to hide 1 div out of 4 div. I want to hide only div which has inner div as value 'Key'. Please note that I am not allowed to changed HTML content. I can just write Jquery for it.
2015/05/30
[ "https://Stackoverflow.com/questions/30546943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1993534/" ]
You can try this: ``` $( "div.jtable-input-label:contains('Key')" ) .closest( "div.jtable-input-field-container" ) .css( "display", "none" ); ```
Because IDs must be unique on document context, you should target specific parent element containing `#Edit-configKey` DIV instead: ``` $('#Edit-configKey').closest('.jtable-input-field-container').hide(); ```
30,546,943
``` <form id="jtable-edit-form" class="jtable-dialog-form jtable-edit-form"> <div class="jtable-input-field-container"> <div class="jtable-input-label">Type</div> <div class="jtable-input jtable-text-input"> <input class="" id="Edit-configType" type="text" name="configType"> </div> </div> <div class="jtable-input-field-container"> <div class="jtable-input-label">Key</div> <div class="jtable-input jtable-text-input"> <input class="" id="Edit-configKey" type="text" name="configKey"> </div> </div> <div class="jtable-input-field-container"> <div class="jtable-input-label">Value</div> <div class="jtable-input jtable-text-input"> <input class="" id="Edit-configValue" type="text" name="configValue"> </div> </div> <div class="jtable-input-field-container"> <div class="jtable-input-label">Description</div> <div class="jtable-input jtable-text-input"> <input class="" id="Edit-description" type="text" name="description"> </div> </div> ``` I need to hide 1 div out of 4 div. I want to hide only div which has inner div as value 'Key'. Please note that I am not allowed to changed HTML content. I can just write Jquery for it.
2015/05/30
[ "https://Stackoverflow.com/questions/30546943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1993534/" ]
You can try this: ``` $( "div.jtable-input-label:contains('Key')" ) .closest( "div.jtable-input-field-container" ) .css( "display", "none" ); ```
Try this code ``` $(document).ready(function(){ $( "div.jtable-input-label:contains('Key')" ).parent().hide(); }); ``` Hope this will help you.
30,546,943
``` <form id="jtable-edit-form" class="jtable-dialog-form jtable-edit-form"> <div class="jtable-input-field-container"> <div class="jtable-input-label">Type</div> <div class="jtable-input jtable-text-input"> <input class="" id="Edit-configType" type="text" name="configType"> </div> </div> <div class="jtable-input-field-container"> <div class="jtable-input-label">Key</div> <div class="jtable-input jtable-text-input"> <input class="" id="Edit-configKey" type="text" name="configKey"> </div> </div> <div class="jtable-input-field-container"> <div class="jtable-input-label">Value</div> <div class="jtable-input jtable-text-input"> <input class="" id="Edit-configValue" type="text" name="configValue"> </div> </div> <div class="jtable-input-field-container"> <div class="jtable-input-label">Description</div> <div class="jtable-input jtable-text-input"> <input class="" id="Edit-description" type="text" name="description"> </div> </div> ``` I need to hide 1 div out of 4 div. I want to hide only div which has inner div as value 'Key'. Please note that I am not allowed to changed HTML content. I can just write Jquery for it.
2015/05/30
[ "https://Stackoverflow.com/questions/30546943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1993534/" ]
try this, ``` $("#jtable-edit-form .jtable-input-label:contains('Key')" ).parent().hide(); ``` See this jsfiddle <https://jsfiddle.net/cL4wsL3q/1/>
Because IDs must be unique on document context, you should target specific parent element containing `#Edit-configKey` DIV instead: ``` $('#Edit-configKey').closest('.jtable-input-field-container').hide(); ```
30,546,943
``` <form id="jtable-edit-form" class="jtable-dialog-form jtable-edit-form"> <div class="jtable-input-field-container"> <div class="jtable-input-label">Type</div> <div class="jtable-input jtable-text-input"> <input class="" id="Edit-configType" type="text" name="configType"> </div> </div> <div class="jtable-input-field-container"> <div class="jtable-input-label">Key</div> <div class="jtable-input jtable-text-input"> <input class="" id="Edit-configKey" type="text" name="configKey"> </div> </div> <div class="jtable-input-field-container"> <div class="jtable-input-label">Value</div> <div class="jtable-input jtable-text-input"> <input class="" id="Edit-configValue" type="text" name="configValue"> </div> </div> <div class="jtable-input-field-container"> <div class="jtable-input-label">Description</div> <div class="jtable-input jtable-text-input"> <input class="" id="Edit-description" type="text" name="description"> </div> </div> ``` I need to hide 1 div out of 4 div. I want to hide only div which has inner div as value 'Key'. Please note that I am not allowed to changed HTML content. I can just write Jquery for it.
2015/05/30
[ "https://Stackoverflow.com/questions/30546943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1993534/" ]
try this, ``` $("#jtable-edit-form .jtable-input-label:contains('Key')" ).parent().hide(); ``` See this jsfiddle <https://jsfiddle.net/cL4wsL3q/1/>
Try this code ``` $(document).ready(function(){ $( "div.jtable-input-label:contains('Key')" ).parent().hide(); }); ``` Hope this will help you.
33,904,005
I'm trying to modify elements of an array in a function. This works fine when kept in main but when I port it to a function it segfaults after accessing the first member of the array. The code below is just a reduced version of my actual code to show where I'm getting the segfault. ``` #include <stdio.h> #include <stdlib.h> typedef struct { unsigned short id; } voter; void initialise(voter** votersPtr, unsigned short *numOfVoters) { *votersPtr = malloc(sizeof(voter)*(*numOfVoters)); for(int i = 0; i < *numOfVoters; i++) { votersPtr[i]->id = (unsigned short) i; printf("%hu \n", votersPtr[i]->id); } } int main(void) { unsigned short numOfVoters = 480; voter* voters = NULL; initialise(&voters, &numOfVoters); return EXIT_SUCCESS; } ``` Any help would be greatly appreciated, thank you.
2015/11/24
[ "https://Stackoverflow.com/questions/33904005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5601548/" ]
`votersPtr[i]->id`, which is the same as `(*votersPtr[i]).id` should be `(*votersPtr)[i].id`.
Remember that `votersPtr` is a pointer to a pointer of an array. So shouldn't the following line: ``` votersPtr[i]->id = (unsigned short) i; ``` Instead be: ``` (*votersPtr)[i].id = (unsigned short) i; ```
33,904,005
I'm trying to modify elements of an array in a function. This works fine when kept in main but when I port it to a function it segfaults after accessing the first member of the array. The code below is just a reduced version of my actual code to show where I'm getting the segfault. ``` #include <stdio.h> #include <stdlib.h> typedef struct { unsigned short id; } voter; void initialise(voter** votersPtr, unsigned short *numOfVoters) { *votersPtr = malloc(sizeof(voter)*(*numOfVoters)); for(int i = 0; i < *numOfVoters; i++) { votersPtr[i]->id = (unsigned short) i; printf("%hu \n", votersPtr[i]->id); } } int main(void) { unsigned short numOfVoters = 480; voter* voters = NULL; initialise(&voters, &numOfVoters); return EXIT_SUCCESS; } ``` Any help would be greatly appreciated, thank you.
2015/11/24
[ "https://Stackoverflow.com/questions/33904005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5601548/" ]
The type `voter **` is ambiguously either a *pointer to an array of pointers to `voter` objects* or a *pointer to a pointer to an array of `voter` objects*. Your code is using it as the first, but should be using it as the second. Change ``` votersPtr[i]->id = ... ``` to ``` (*votersPtr)[i].id = ... ``` and everything should work.
Remember that `votersPtr` is a pointer to a pointer of an array. So shouldn't the following line: ``` votersPtr[i]->id = (unsigned short) i; ``` Instead be: ``` (*votersPtr)[i].id = (unsigned short) i; ```
33,904,005
I'm trying to modify elements of an array in a function. This works fine when kept in main but when I port it to a function it segfaults after accessing the first member of the array. The code below is just a reduced version of my actual code to show where I'm getting the segfault. ``` #include <stdio.h> #include <stdlib.h> typedef struct { unsigned short id; } voter; void initialise(voter** votersPtr, unsigned short *numOfVoters) { *votersPtr = malloc(sizeof(voter)*(*numOfVoters)); for(int i = 0; i < *numOfVoters; i++) { votersPtr[i]->id = (unsigned short) i; printf("%hu \n", votersPtr[i]->id); } } int main(void) { unsigned short numOfVoters = 480; voter* voters = NULL; initialise(&voters, &numOfVoters); return EXIT_SUCCESS; } ``` Any help would be greatly appreciated, thank you.
2015/11/24
[ "https://Stackoverflow.com/questions/33904005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5601548/" ]
`votersPtr[i]->id`, which is the same as `(*votersPtr[i]).id` should be `(*votersPtr)[i].id`.
The type `voter **` is ambiguously either a *pointer to an array of pointers to `voter` objects* or a *pointer to a pointer to an array of `voter` objects*. Your code is using it as the first, but should be using it as the second. Change ``` votersPtr[i]->id = ... ``` to ``` (*votersPtr)[i].id = ... ``` and everything should work.
397,446
I want to draw complete binary tree with some portion highlighted. I am able to draw the complete binary tree, but not able to highlight the specified portion. I want to draw the digram given below: [![enter image description here](https://i.stack.imgur.com/mj9OZ.jpg)](https://i.stack.imgur.com/mj9OZ.jpg) Till now I'm able to do this much: ``` \documentclass[border=2pt]{standalone} \usepackage{forest} \begin{document} \begin{forest} for tree={l+=0.07cm} % increase level distance [1 [2[4][5]] [3[6][7]] ] \end{forest} \end{document} ```
2017/10/22
[ "https://tex.stackexchange.com/questions/397446", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/142684/" ]
I think, in theory, that this should be possible by adding ``` tikz={\node[draw,circle,red,fit=()(!1)(!2)} ``` to the root of the node that you want to circle. Here `()` refers to the node and `(!1)` and `(!2)` its children. Unfortunately, this doesn't quite work because it gives: [![enter image description here](https://i.stack.imgur.com/KCO35.png)](https://i.stack.imgur.com/KCO35.png) So, in practice, it looks better with a little extra tweaking: [![enter image description here](https://i.stack.imgur.com/sDvdp.png)](https://i.stack.imgur.com/sDvdp.png) See section 2.3 of the manual for more details. Here is the full code: ``` \documentclass[border=4pt]{standalone} \usepackage{forest} \begin{document} \begin{forest} for tree={l+=0.08cm} % increase level distance [1 [2,tikz={\node[draw,circle,red,fit=()(!1),inner sep=0mm,xshift=1mm]{};} [4][5] ] [3 [6][7] ] ] \end{forest} \end{document} ``` Another option, which might be preferable, is to use ``` tikz={\node[draw,circle,red,fit=()(!1)(!2),inner sep=0mm]{};} ``` giving [![enter image description here](https://i.stack.imgur.com/grkG9.png)](https://i.stack.imgur.com/grkG9.png)
Here is another solution to use the [`istgame`](https://ctan.org/pkg/istgame) package. Since the `istgame` environment is (almost) the same as the `tikzpicture` environment, you can use any `TikZ` macros in the `istgame` environment. [![enter image description here](https://i.stack.imgur.com/04UeA.jpg)](https://i.stack.imgur.com/04UeA.jpg) ``` \documentclass{standalone} \usepackage{istgame} \usepackage{makecell} \begin{document} \begin{istgame} % tree (istgame macros) \xtdistance{15mm}{30mm} \istroot(1){1} \istb \istb \endist \xtdistance{15mm}{15mm} \istroot(2)(1-1)<180>{2} \istb*{}{4} \istb*{}{5} \endist \istroot(3)(1-2)<0>{3} \istb*{}{6} \istb*{}{7} \endist \xtSubgameOval(2){(2-1)(2-2)}[circle,solid,red,inner sep=10pt] % comments (tikz macros) \coordinate (aa) at ([shift={(-2.5,-.5)}]2); \draw [->] (aa) node [left] {Block} -- + (1,0); \coordinate (bb) at ([shift={(2,.3)}]3); \draw [->] (bb) node [right] {\makecell[l]{Complete \\ binary \\ tree}} -- + (-1,0); \end{istgame} \end{document} ```
67,715,975
I have a website for a project that needs to summarize all of the budget categories in one column. For example I have a column which contains: Categories: Water,Electricity,Gas,Rentals,Hospital Fees,Medicine,Personal Care,Fitness, I want to select the sum of water,electricity,gas,rentals and name it as utility bills. Same as sum of hospital fees, medicine, personal care, fitness as healthcare. What sql statement should i use? Any help will be appreciated
2021/05/27
[ "https://Stackoverflow.com/questions/67715975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16044580/" ]
You'd have some other table perhaps, or another column on this table, that maps the specific bills to a general group or category You would then run a query like (if you put the category group in the main table) ``` SELECT categorygroup, sum(amount) FROM bills GROUP BY categorygroup ``` Or (if you have a separate table you join in) ``` SELECT bcg.categorygroup, sum(amount) FROM bills b INNER JOIN billcategorygroups bcg ON b.category=bcg.category GROUP BY bcg.categorygroup ``` You would then maintain the tables, either like (category in main table style): ``` Bills Category, CategoryGroup, Amount --- Electricity, Utility, 123 Water, Utility, 456 ``` Or (separate table to map categories with groups style) ``` BillCategoryGroups Category, CategoryGroup --- Water, Utility Electricity, Utility ``` Etc Something has to map electricity -> utility, water -> utility etc. I'd probably have a separate table because it is easy to reorganize. If you decide that Cellular is no longer Utility but instead Personal then just changing it in the mapping table will change all the reporting. It also helps prevent typos and data entry errors affecting reports - if you use the single table route and put even one Electricity bill down as Utitily then it gets its own line on the report. Adding new categories is easy with a separate table too. All these things can be done with single table and big update statements etc but we have "normalization" of data for good reasons
You may use conditional aggregation. Like ```sql SELECT project, SUM(CASE WHEN category IN ('water','electricity','gas','rentals') THEN spent ELSE 0 END) AS bills, SUM(CASE WHEN category IN ('hospital fees','medicine','personal care','fitness') THEN spent ELSE 0 END) AS healthcare FROM datatable GROUP BY project; ``` But the data normalization is the best option. All categories must be moved to separate table. See [Caius Jard](https://stackoverflow.com/users/1410664/caius-jard)'s answer.
381,278
Since I have osxfuse installed it would be nice if I could use it. There are a [lot of](https://apple.stackexchange.com/questions/73156/) (heavily) outdated [articles](https://apple.stackexchange.com/questions/140536/) here, saying that it is not [possible](https://apple.stackexchange.com/questions/128060/). Is this still the case?
2020/02/04
[ "https://apple.stackexchange.com/questions/381278", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/66939/" ]
> > **Update**: According to this [document in homebrew-core](https://github.com/Homebrew/homebrew-core/pull/64491) from November 2020, Homebrew maintainers no longer update or support macFUSE formulae, and Homebrew's continuous integration doesn't test them. macFUSE formulae will eventually be removed in the indeterminate future. > > > Specifically, `ext4fuse` (mentioned below in the post) is disabled: > > > > ``` > brew install ext4fuse > Error: ext4fuse has been disabled because it requires closed-source macFUSE! > > ``` > > The reason for this is that FUSE for macOS does not have a license that is compatible with Homebrew. > > > Mac does not support ext4 file system. If you plug in a hard drive, Mac won't recognize it. Fortunately, there are several ways to handle this situation. **1. Temporary options: Use VM** Just install a version of Ubuntu, or whatever your Linux distribution of choice is, in a virtual machine host like VirtualBox, then mount the drive as you would any other and read away. **2. Add ext4 support for macOS** If you regularly use ext4 formatted drives and / or need to copy multiple files from there to the macOS drive, you need a better option. You need to install [macFUSE](https://osxfuse.github.io/) (`osxfuse` has been succeeded by `macfuse` as of version 4.0.0) and `ext4fuse`. The easiest way to install `ext4fuse` is to use Homebrew. Note that `ext4fuse` us a read-only implementation of ext4 for FUSE to browse ext4 volumes and it cannot be used to write into ext4 volumes. First, download and install macFUSE from their [releases page](https://github.com/osxfuse/osxfuse/releases) or install it using Homebrew. ```bash brew install --cask macfuse ``` Then use Homebrew to install `ext4fuse`. ```bash brew install ext4fuse ``` After installing the ext4 support software, you now need to determine the hard drive you want to mount. To do this, run the following command: ```bash diskutil list ``` Save the partition ID (will look like `/dev/disk3s1`). Then, run the following command to mount the hard drive: ```bash sudo ext4fuse /dev/disk3s1 ~/tmp/ext4_support_PARTITION -o allow_other ``` `ext4_support` above can be any name you choose. Now, navigate to the '/ tmp /' directory in the Finder and you will see the contents of the partition listed. If your drive has multiple partitions, you can mount them using the same steps as above. Just make sure to use different directory names to mount them. **Update** Attempting to install `ext4fuse` with brew results in an error. (See [issue #66 on GitHub](https://github.com/gerard/ext4fuse/issues/66)), so instead use the following commands to install it: ```bash curl -s -o ext4fuse.rb https://gist.githubusercontent.com/n-stone/413e407c8fd73683e7e926e10e27dd4e/raw/12b463eb0be3421bdda5db8ef967bfafbaa915c5/ext4fuse.rb brew install --formula --build-from-source ./ext4fuse.rb rm ./ext4fuse.rb ``` **Warning** Although these tools can help you read ext4 formatted hard drives, they are not stable. As long as you are mounting read-only drives, as what is being done in this solution, you will not have many risks. If you try to use these tools to *write* to an ext4 drive, you may lose data. If you need to move files back and forth on a shared drive with Linux, this method is not recommended. Instead, use another file system like ExFAT or try the commercial option listed below **3. Use Paid Software** Software such as [Paragon](https://www.paragon-software.com/home/extfs-mac/) offers a free trial version, but to be safe, you should back up your hard drive first, in case there is a problem. If you want to buy software, it is available for 40$ **Note**: I haven't used this tool and can't say anything about what they have promised. Although reading ext4 format on macOS is no longer an impossible task, it is frustrating when Apple does not support this format. Try it on your own risk but I strongly recommend the first solution which is easy and convenient.
With regards to the prior answer by @Udhy only the VM option has any chance of working but with a major caveat that it is VERY slow (I never got better than 30mb/sec). Paragon simply does not work, refuses to mount any of my EXT4 disks. Not sure why, maybe a Catalina issue? However I'm not going to pay them so they can tell me we're SOL. ext4fuse is a waste of time, it has not supported the last 3 versions of OSX so unless you're pre-Sierra this is not an option. There's an open issue in the Github: <https://github.com/gerard/ext4fuse/issues/36> It's five year's old and his last reply was 3 years ago, so don't get your hopes up.
381,278
Since I have osxfuse installed it would be nice if I could use it. There are a [lot of](https://apple.stackexchange.com/questions/73156/) (heavily) outdated [articles](https://apple.stackexchange.com/questions/140536/) here, saying that it is not [possible](https://apple.stackexchange.com/questions/128060/). Is this still the case?
2020/02/04
[ "https://apple.stackexchange.com/questions/381278", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/66939/" ]
> > **Update**: According to this [document in homebrew-core](https://github.com/Homebrew/homebrew-core/pull/64491) from November 2020, Homebrew maintainers no longer update or support macFUSE formulae, and Homebrew's continuous integration doesn't test them. macFUSE formulae will eventually be removed in the indeterminate future. > > > Specifically, `ext4fuse` (mentioned below in the post) is disabled: > > > > ``` > brew install ext4fuse > Error: ext4fuse has been disabled because it requires closed-source macFUSE! > > ``` > > The reason for this is that FUSE for macOS does not have a license that is compatible with Homebrew. > > > Mac does not support ext4 file system. If you plug in a hard drive, Mac won't recognize it. Fortunately, there are several ways to handle this situation. **1. Temporary options: Use VM** Just install a version of Ubuntu, or whatever your Linux distribution of choice is, in a virtual machine host like VirtualBox, then mount the drive as you would any other and read away. **2. Add ext4 support for macOS** If you regularly use ext4 formatted drives and / or need to copy multiple files from there to the macOS drive, you need a better option. You need to install [macFUSE](https://osxfuse.github.io/) (`osxfuse` has been succeeded by `macfuse` as of version 4.0.0) and `ext4fuse`. The easiest way to install `ext4fuse` is to use Homebrew. Note that `ext4fuse` us a read-only implementation of ext4 for FUSE to browse ext4 volumes and it cannot be used to write into ext4 volumes. First, download and install macFUSE from their [releases page](https://github.com/osxfuse/osxfuse/releases) or install it using Homebrew. ```bash brew install --cask macfuse ``` Then use Homebrew to install `ext4fuse`. ```bash brew install ext4fuse ``` After installing the ext4 support software, you now need to determine the hard drive you want to mount. To do this, run the following command: ```bash diskutil list ``` Save the partition ID (will look like `/dev/disk3s1`). Then, run the following command to mount the hard drive: ```bash sudo ext4fuse /dev/disk3s1 ~/tmp/ext4_support_PARTITION -o allow_other ``` `ext4_support` above can be any name you choose. Now, navigate to the '/ tmp /' directory in the Finder and you will see the contents of the partition listed. If your drive has multiple partitions, you can mount them using the same steps as above. Just make sure to use different directory names to mount them. **Update** Attempting to install `ext4fuse` with brew results in an error. (See [issue #66 on GitHub](https://github.com/gerard/ext4fuse/issues/66)), so instead use the following commands to install it: ```bash curl -s -o ext4fuse.rb https://gist.githubusercontent.com/n-stone/413e407c8fd73683e7e926e10e27dd4e/raw/12b463eb0be3421bdda5db8ef967bfafbaa915c5/ext4fuse.rb brew install --formula --build-from-source ./ext4fuse.rb rm ./ext4fuse.rb ``` **Warning** Although these tools can help you read ext4 formatted hard drives, they are not stable. As long as you are mounting read-only drives, as what is being done in this solution, you will not have many risks. If you try to use these tools to *write* to an ext4 drive, you may lose data. If you need to move files back and forth on a shared drive with Linux, this method is not recommended. Instead, use another file system like ExFAT or try the commercial option listed below **3. Use Paid Software** Software such as [Paragon](https://www.paragon-software.com/home/extfs-mac/) offers a free trial version, but to be safe, you should back up your hard drive first, in case there is a problem. If you want to buy software, it is available for 40$ **Note**: I haven't used this tool and can't say anything about what they have promised. Although reading ext4 format on macOS is no longer an impossible task, it is frustrating when Apple does not support this format. Try it on your own risk but I strongly recommend the first solution which is easy and convenient.
The only way I have been able to read/write ext4 is by using a virtual machine such as Virtual Box, running Linux (e.g., Linuxmint). It's odd that Paragon doesn't work in Catalina. Ext4fuse only gave me errors.
381,278
Since I have osxfuse installed it would be nice if I could use it. There are a [lot of](https://apple.stackexchange.com/questions/73156/) (heavily) outdated [articles](https://apple.stackexchange.com/questions/140536/) here, saying that it is not [possible](https://apple.stackexchange.com/questions/128060/). Is this still the case?
2020/02/04
[ "https://apple.stackexchange.com/questions/381278", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/66939/" ]
For newer macs, e.g. Catalina, `brew install macfuse` instead of `brew install osxfuse` will work
With regards to the prior answer by @Udhy only the VM option has any chance of working but with a major caveat that it is VERY slow (I never got better than 30mb/sec). Paragon simply does not work, refuses to mount any of my EXT4 disks. Not sure why, maybe a Catalina issue? However I'm not going to pay them so they can tell me we're SOL. ext4fuse is a waste of time, it has not supported the last 3 versions of OSX so unless you're pre-Sierra this is not an option. There's an open issue in the Github: <https://github.com/gerard/ext4fuse/issues/36> It's five year's old and his last reply was 3 years ago, so don't get your hopes up.
381,278
Since I have osxfuse installed it would be nice if I could use it. There are a [lot of](https://apple.stackexchange.com/questions/73156/) (heavily) outdated [articles](https://apple.stackexchange.com/questions/140536/) here, saying that it is not [possible](https://apple.stackexchange.com/questions/128060/). Is this still the case?
2020/02/04
[ "https://apple.stackexchange.com/questions/381278", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/66939/" ]
For newer macs, e.g. Catalina, `brew install macfuse` instead of `brew install osxfuse` will work
The only way I have been able to read/write ext4 is by using a virtual machine such as Virtual Box, running Linux (e.g., Linuxmint). It's odd that Paragon doesn't work in Catalina. Ext4fuse only gave me errors.
584,665
In Excel, if I have two lines in A1: ``` Hello World ``` but if I go over to A2 and type `=lower(A1)`, I get: ``` helloworld ``` How can I preserve the newline between *Hello* and *World*?
2013/04/18
[ "https://superuser.com/questions/584665", "https://superuser.com", "https://superuser.com/users/210559/" ]
Use `=lower(A1)` and then turn on `Wrap Text` for that cell.
Oddly enough, the newline is still there in A2, but the formatting of the cell is not showing it. If you click on A1, click `Format Painter` and the click on A2 then the newline will appear. You can also right click and select Format > Text I don't think you can apply the right format as part of the formula though
49,572,567
I'm trying to filter a simple `HTML` table with the filter being determined by multiple radio buttons. The goal is to show/hide any rows that contain/don't contain the words in the filter. For example if I select "**yes**" on the "`auto`" filter and "**no**" on the "manually" filter it should look in the column named "auto" for the "yes" value and on the "manually" column for the "no" value. I tried it with [this question](https://stackoverflow.com/questions/19420792/filter-table-with-multiple-radio-inputs) but it filters with the logical OR and not the logical AND. Also i don't quite know how to set the filter inactive when the user wants to deactivate the according filter. Here is my HTML code: ``` <html> <head> <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script> </head> <body> <form name="FilterForm" id="FilterForm" action="" method=""> <label>Auto:</label> <input type="radio" name="auto" value="yes" /> <label>yes</label> <input type="radio" name="auto" value="no" /> <label>no</label> <input type="radio" name="auto" value="inactive" /> <label>inactive</label> <br> <label>Manually:</label> <input type="radio" name="manually" value="yes" /> <label>yes</label> <input type="radio" name="manually" value="no" /> <label>no</label> <input type="radio" name="manually" value="inactive" /> <label>inactive</label> <br> <label>Downgrade:</label> <input type="radio" name="downgrade" value="yes" /> <label>yes</label> <input type="radio" name="downgrade" value="no" /> <label>no</label> <input type="radio" name="downgrade" value="inactive" /> <label>inactive</label> <br> </form> <table border="1" id="ExampleTable"> <thead> <tr> <th>name</th> <th>auto</th> <th>manually</th> <th>downgrade</th> </tr> </thead> <tbody> <tr> <td class="name">Name1</td> <td class="auto">yes</td> <td class="manually">yes</td> <td class="downgrade">yes</td> </tr> <tr> <td class="name">Name2</td> <td class="auto">no</td> <td class="manually">no</td> <td class="downgrade">yes</td> </tr> <tr> <td class="name">Name3</td> <td class="auto">no</td> <td class="manually">yes</td> <td class="downgrade">no</td> </tr> <tr> <td class="name">Name4</td> <td class="auto">yes</td> <td class="manually">no</td> <td class="downgrade">yes</td> </tr> </tbody> </table> </body> </html> ``` And here is the Javascript i did with the help of the previous mentioned question: ``` <script> $('input[type="radio"]').change(function () { var firstRow = 'name'; var auto = $('input[name="auto"]:checked').prop('value') || ''; var manually = $('input[name="manually"]:checked').prop('value') || ''; var downgrade = $('input[name="downgrade"]:checked').prop('value') || ''; $('tr').hide(); $('tr:contains(' + firstRow + ')').show(); $('tr:contains(' + auto + ')').show(); $('tr').not(':contains(' + manually + ')').hide(); $('tr').not(':contains(' + downgrade + ')').hide(); }); </script> ``` Here is also an image for better understanding: [![project_image](https://i.stack.imgur.com/l9uAx.jpg)](https://i.stack.imgur.com/l9uAx.jpg) Since i usually don't use JS and JQuery I couldn't quite figure out the problem and the time is short. I would be very grateful for a push in the right direction, thanks in advance.
2018/03/30
[ "https://Stackoverflow.com/questions/49572567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8641691/" ]
I am not sure what do you want to do with Inactive Radio button, Without inactive following code will solve your problem. ``` $(document).ready(function(){ $('input[type="radio"]').change(function () { var firstRow = 'name'; var auto = $('input[name="auto"]:checked').prop('value') || ''; var manually = $('input[name="manually"]:checked').prop('value') || ''; var downgrade = $('input[name="downgrade"]:checked').prop('value') || ''; $('tr').hide(); $('tr:contains(' + firstRow + ')').show(); var chks = $('input[type="radio"]:checked'); var trs ; if(auto!= '' && auto != 'inactive'){ var chkName = $('input[name="auto"]:checked').prop('name'); trs = $("tr").find("."+chkName+':contains('+auto+')').parent(); } if(manually!= '' && manually != 'inactive'){ var chkName = $('input[name="manually"]:checked').prop('name'); trs = $(trs).find("."+chkName+':contains('+manually+')').parent(); } if(downgrade!= '' && downgrade!= 'inactive'){ var chkName = $('input[name="downgrade"]:checked').prop('name'); trs = $(trs).find("."+chkName+':contains('+downgrade+')').parent(); } $(trs).show(); }); }); ```
**HTML** ``` ... <tr class="header"> // added class here <th>name</th> <th>auto</th> <th>manually</th> <th>downgrade</th> </tr> ... ``` **Script** ``` $('input[type="radio"]').change(function () { var auto = $('input[name="auto"]:checked').prop('value') || ''; var manually = $('input[name="manually"]:checked').prop('value') || ''; var downgrade = $('input[name="downgrade"]:checked').prop('value') || ''; $('tr:not("[class=header]")').each(function(){ var hide = true; if(auto) { hide = $(this).find('td.auto').html() != auto; } if(manually && !hide) { hide = $(this).find('td.manually').html() != manually; } if(downgrade && !hide) { hide = hide && $(this).find('td.downgrade').html() != downgrade; } if(hide) { $(this).hide(); } else { $(this).show(); } }); }); ```
49,572,567
I'm trying to filter a simple `HTML` table with the filter being determined by multiple radio buttons. The goal is to show/hide any rows that contain/don't contain the words in the filter. For example if I select "**yes**" on the "`auto`" filter and "**no**" on the "manually" filter it should look in the column named "auto" for the "yes" value and on the "manually" column for the "no" value. I tried it with [this question](https://stackoverflow.com/questions/19420792/filter-table-with-multiple-radio-inputs) but it filters with the logical OR and not the logical AND. Also i don't quite know how to set the filter inactive when the user wants to deactivate the according filter. Here is my HTML code: ``` <html> <head> <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script> </head> <body> <form name="FilterForm" id="FilterForm" action="" method=""> <label>Auto:</label> <input type="radio" name="auto" value="yes" /> <label>yes</label> <input type="radio" name="auto" value="no" /> <label>no</label> <input type="radio" name="auto" value="inactive" /> <label>inactive</label> <br> <label>Manually:</label> <input type="radio" name="manually" value="yes" /> <label>yes</label> <input type="radio" name="manually" value="no" /> <label>no</label> <input type="radio" name="manually" value="inactive" /> <label>inactive</label> <br> <label>Downgrade:</label> <input type="radio" name="downgrade" value="yes" /> <label>yes</label> <input type="radio" name="downgrade" value="no" /> <label>no</label> <input type="radio" name="downgrade" value="inactive" /> <label>inactive</label> <br> </form> <table border="1" id="ExampleTable"> <thead> <tr> <th>name</th> <th>auto</th> <th>manually</th> <th>downgrade</th> </tr> </thead> <tbody> <tr> <td class="name">Name1</td> <td class="auto">yes</td> <td class="manually">yes</td> <td class="downgrade">yes</td> </tr> <tr> <td class="name">Name2</td> <td class="auto">no</td> <td class="manually">no</td> <td class="downgrade">yes</td> </tr> <tr> <td class="name">Name3</td> <td class="auto">no</td> <td class="manually">yes</td> <td class="downgrade">no</td> </tr> <tr> <td class="name">Name4</td> <td class="auto">yes</td> <td class="manually">no</td> <td class="downgrade">yes</td> </tr> </tbody> </table> </body> </html> ``` And here is the Javascript i did with the help of the previous mentioned question: ``` <script> $('input[type="radio"]').change(function () { var firstRow = 'name'; var auto = $('input[name="auto"]:checked').prop('value') || ''; var manually = $('input[name="manually"]:checked').prop('value') || ''; var downgrade = $('input[name="downgrade"]:checked').prop('value') || ''; $('tr').hide(); $('tr:contains(' + firstRow + ')').show(); $('tr:contains(' + auto + ')').show(); $('tr').not(':contains(' + manually + ')').hide(); $('tr').not(':contains(' + downgrade + ')').hide(); }); </script> ``` Here is also an image for better understanding: [![project_image](https://i.stack.imgur.com/l9uAx.jpg)](https://i.stack.imgur.com/l9uAx.jpg) Since i usually don't use JS and JQuery I couldn't quite figure out the problem and the time is short. I would be very grateful for a push in the right direction, thanks in advance.
2018/03/30
[ "https://Stackoverflow.com/questions/49572567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8641691/" ]
Try this, I think this is what you want: ```js $(document).ready(function(){ $('input[type="radio"]').change(function () { var firstRow = 'name'; var auto = $('input[name="auto"]:checked').prop('value') || ''; var manually = $('input[name="manually"]:checked').prop('value') || ''; var downgrade = $('input[name="downgrade"]:checked').prop('value') || ''; var trs = $('tr:not(:first)'); $(trs).hide(); if(auto == 'inactive' || manually == 'inactive' || downgrade == 'inactive'){ // Do nothing as any of three condition says show all // And currently we all rows selected in trs } else { if(auto != '' && auto != 'inactive'){ var chkdName = $('input[name="auto"]:checked').prop('name'); trs = $(trs).find("."+chkdName+':contains('+auto+')').parent(); } if(manually != '' && manually != 'inactive'){ var chkdName = $('input[name="manually"]:checked').prop('name'); trs = $(trs).find("."+chkdName+':contains('+manually+')').parent(); } if(downgrade != '' && downgrade != 'inactive'){ var chkdName = $('input[name="downgrade"]:checked').prop('name'); trs = $(trs).find("."+chkdName+':contains('+downgrade+')').parent(); } } $(trs).show(); }); $("#reset").on('click', function(){ $(':radio').prop('checked', false); $('tr').show(); }); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form name="FilterForm" id="FilterForm" action="" method=""> <label>Auto:</label> <input type="radio" name="auto" value="yes" /> <label>Yes</label> <input type="radio" name="auto" value="no" /> <label>No</label> <input type="radio" name="auto" value="inactive" /> <label>All</label> <br> <label>Manually:</label> <input type="radio" name="manually" value="yes" /> <label>Yes</label> <input type="radio" name="manually" value="no" /> <label>No</label> <input type="radio" name="manually" value="inactive" /> <label>All</label> <br> <label>Downgrade:</label> <input type="radio" name="downgrade" value="yes" /> <label>Yes</label> <input type="radio" name="downgrade" value="no" /> <label>No</label> <input type="radio" name="downgrade" value="inactive" /> <label>All</label> <br> </form> <br><button id="reset">Reset</button><br><br><br><br> <table border="1" id="ExampleTable"> <thead> <tr> <th>Name</th> <th>Auto</th> <th>Manually</th> <th>Downgrade</th> </tr> </thead> <tbody> <tr> <td class="name">Name1</td> <td class="auto">no</td> <td class="manually">no</td> <td class="downgrade">no</td> </tr> <tr> <td class="name">Name2</td> <td class="auto">no</td> <td class="manually">no</td> <td class="downgrade">yes</td> </tr> <tr> <td class="name">Name3</td> <td class="auto">no</td> <td class="manually">yes</td> <td class="downgrade">no</td> </tr> <tr> <td class="name">Name4</td> <td class="auto">yes</td> <td class="manually">no</td> <td class="downgrade">no</td> </tr> <tr> <td class="name">Name5</td> <td class="auto">yes</td> <td class="manually">no</td> <td class="downgrade">yes</td> </tr> <tr> <td class="name">Name6</td> <td class="auto">yes</td> <td class="manually">yes</td> <td class="downgrade">no</td> </tr> <tr> <td class="name">Name7</td> <td class="auto">no</td> <td class="manually">yes</td> <td class="downgrade">yes</td> </tr> <tr> <td class="name">Name8</td> <td class="auto">yes</td> <td class="manually">yes</td> <td class="downgrade">yes</td> </tr> </tbody> </table> ``` Here is the working copy: [fiddle url](https://plnkr.co/edit/PyaHur2a1wquT6t79ixX?p=preview)
**HTML** ``` ... <tr class="header"> // added class here <th>name</th> <th>auto</th> <th>manually</th> <th>downgrade</th> </tr> ... ``` **Script** ``` $('input[type="radio"]').change(function () { var auto = $('input[name="auto"]:checked').prop('value') || ''; var manually = $('input[name="manually"]:checked').prop('value') || ''; var downgrade = $('input[name="downgrade"]:checked').prop('value') || ''; $('tr:not("[class=header]")').each(function(){ var hide = true; if(auto) { hide = $(this).find('td.auto').html() != auto; } if(manually && !hide) { hide = $(this).find('td.manually').html() != manually; } if(downgrade && !hide) { hide = hide && $(this).find('td.downgrade').html() != downgrade; } if(hide) { $(this).hide(); } else { $(this).show(); } }); }); ```
49,572,567
I'm trying to filter a simple `HTML` table with the filter being determined by multiple radio buttons. The goal is to show/hide any rows that contain/don't contain the words in the filter. For example if I select "**yes**" on the "`auto`" filter and "**no**" on the "manually" filter it should look in the column named "auto" for the "yes" value and on the "manually" column for the "no" value. I tried it with [this question](https://stackoverflow.com/questions/19420792/filter-table-with-multiple-radio-inputs) but it filters with the logical OR and not the logical AND. Also i don't quite know how to set the filter inactive when the user wants to deactivate the according filter. Here is my HTML code: ``` <html> <head> <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script> </head> <body> <form name="FilterForm" id="FilterForm" action="" method=""> <label>Auto:</label> <input type="radio" name="auto" value="yes" /> <label>yes</label> <input type="radio" name="auto" value="no" /> <label>no</label> <input type="radio" name="auto" value="inactive" /> <label>inactive</label> <br> <label>Manually:</label> <input type="radio" name="manually" value="yes" /> <label>yes</label> <input type="radio" name="manually" value="no" /> <label>no</label> <input type="radio" name="manually" value="inactive" /> <label>inactive</label> <br> <label>Downgrade:</label> <input type="radio" name="downgrade" value="yes" /> <label>yes</label> <input type="radio" name="downgrade" value="no" /> <label>no</label> <input type="radio" name="downgrade" value="inactive" /> <label>inactive</label> <br> </form> <table border="1" id="ExampleTable"> <thead> <tr> <th>name</th> <th>auto</th> <th>manually</th> <th>downgrade</th> </tr> </thead> <tbody> <tr> <td class="name">Name1</td> <td class="auto">yes</td> <td class="manually">yes</td> <td class="downgrade">yes</td> </tr> <tr> <td class="name">Name2</td> <td class="auto">no</td> <td class="manually">no</td> <td class="downgrade">yes</td> </tr> <tr> <td class="name">Name3</td> <td class="auto">no</td> <td class="manually">yes</td> <td class="downgrade">no</td> </tr> <tr> <td class="name">Name4</td> <td class="auto">yes</td> <td class="manually">no</td> <td class="downgrade">yes</td> </tr> </tbody> </table> </body> </html> ``` And here is the Javascript i did with the help of the previous mentioned question: ``` <script> $('input[type="radio"]').change(function () { var firstRow = 'name'; var auto = $('input[name="auto"]:checked').prop('value') || ''; var manually = $('input[name="manually"]:checked').prop('value') || ''; var downgrade = $('input[name="downgrade"]:checked').prop('value') || ''; $('tr').hide(); $('tr:contains(' + firstRow + ')').show(); $('tr:contains(' + auto + ')').show(); $('tr').not(':contains(' + manually + ')').hide(); $('tr').not(':contains(' + downgrade + ')').hide(); }); </script> ``` Here is also an image for better understanding: [![project_image](https://i.stack.imgur.com/l9uAx.jpg)](https://i.stack.imgur.com/l9uAx.jpg) Since i usually don't use JS and JQuery I couldn't quite figure out the problem and the time is short. I would be very grateful for a push in the right direction, thanks in advance.
2018/03/30
[ "https://Stackoverflow.com/questions/49572567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8641691/" ]
Try this, I think this is what you want: ```js $(document).ready(function(){ $('input[type="radio"]').change(function () { var firstRow = 'name'; var auto = $('input[name="auto"]:checked').prop('value') || ''; var manually = $('input[name="manually"]:checked').prop('value') || ''; var downgrade = $('input[name="downgrade"]:checked').prop('value') || ''; var trs = $('tr:not(:first)'); $(trs).hide(); if(auto == 'inactive' || manually == 'inactive' || downgrade == 'inactive'){ // Do nothing as any of three condition says show all // And currently we all rows selected in trs } else { if(auto != '' && auto != 'inactive'){ var chkdName = $('input[name="auto"]:checked').prop('name'); trs = $(trs).find("."+chkdName+':contains('+auto+')').parent(); } if(manually != '' && manually != 'inactive'){ var chkdName = $('input[name="manually"]:checked').prop('name'); trs = $(trs).find("."+chkdName+':contains('+manually+')').parent(); } if(downgrade != '' && downgrade != 'inactive'){ var chkdName = $('input[name="downgrade"]:checked').prop('name'); trs = $(trs).find("."+chkdName+':contains('+downgrade+')').parent(); } } $(trs).show(); }); $("#reset").on('click', function(){ $(':radio').prop('checked', false); $('tr').show(); }); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form name="FilterForm" id="FilterForm" action="" method=""> <label>Auto:</label> <input type="radio" name="auto" value="yes" /> <label>Yes</label> <input type="radio" name="auto" value="no" /> <label>No</label> <input type="radio" name="auto" value="inactive" /> <label>All</label> <br> <label>Manually:</label> <input type="radio" name="manually" value="yes" /> <label>Yes</label> <input type="radio" name="manually" value="no" /> <label>No</label> <input type="radio" name="manually" value="inactive" /> <label>All</label> <br> <label>Downgrade:</label> <input type="radio" name="downgrade" value="yes" /> <label>Yes</label> <input type="radio" name="downgrade" value="no" /> <label>No</label> <input type="radio" name="downgrade" value="inactive" /> <label>All</label> <br> </form> <br><button id="reset">Reset</button><br><br><br><br> <table border="1" id="ExampleTable"> <thead> <tr> <th>Name</th> <th>Auto</th> <th>Manually</th> <th>Downgrade</th> </tr> </thead> <tbody> <tr> <td class="name">Name1</td> <td class="auto">no</td> <td class="manually">no</td> <td class="downgrade">no</td> </tr> <tr> <td class="name">Name2</td> <td class="auto">no</td> <td class="manually">no</td> <td class="downgrade">yes</td> </tr> <tr> <td class="name">Name3</td> <td class="auto">no</td> <td class="manually">yes</td> <td class="downgrade">no</td> </tr> <tr> <td class="name">Name4</td> <td class="auto">yes</td> <td class="manually">no</td> <td class="downgrade">no</td> </tr> <tr> <td class="name">Name5</td> <td class="auto">yes</td> <td class="manually">no</td> <td class="downgrade">yes</td> </tr> <tr> <td class="name">Name6</td> <td class="auto">yes</td> <td class="manually">yes</td> <td class="downgrade">no</td> </tr> <tr> <td class="name">Name7</td> <td class="auto">no</td> <td class="manually">yes</td> <td class="downgrade">yes</td> </tr> <tr> <td class="name">Name8</td> <td class="auto">yes</td> <td class="manually">yes</td> <td class="downgrade">yes</td> </tr> </tbody> </table> ``` Here is the working copy: [fiddle url](https://plnkr.co/edit/PyaHur2a1wquT6t79ixX?p=preview)
I am not sure what do you want to do with Inactive Radio button, Without inactive following code will solve your problem. ``` $(document).ready(function(){ $('input[type="radio"]').change(function () { var firstRow = 'name'; var auto = $('input[name="auto"]:checked').prop('value') || ''; var manually = $('input[name="manually"]:checked').prop('value') || ''; var downgrade = $('input[name="downgrade"]:checked').prop('value') || ''; $('tr').hide(); $('tr:contains(' + firstRow + ')').show(); var chks = $('input[type="radio"]:checked'); var trs ; if(auto!= '' && auto != 'inactive'){ var chkName = $('input[name="auto"]:checked').prop('name'); trs = $("tr").find("."+chkName+':contains('+auto+')').parent(); } if(manually!= '' && manually != 'inactive'){ var chkName = $('input[name="manually"]:checked').prop('name'); trs = $(trs).find("."+chkName+':contains('+manually+')').parent(); } if(downgrade!= '' && downgrade!= 'inactive'){ var chkName = $('input[name="downgrade"]:checked').prop('name'); trs = $(trs).find("."+chkName+':contains('+downgrade+')').parent(); } $(trs).show(); }); }); ```
13,726,429
I am trying to do a basic string replace using a regex expression, but the answers I have found do not seem to help - they are directly answering each persons unique requirement with little or no explanation. I am using `str = str.replace(/[^a-z0-9+]/g, '');` at the moment. But what I would like to do is allow all alphanumeric characters (a-z and 0-9) and also the '-' character. Could you please answer this and explain how you concatenate expressions.
2012/12/05
[ "https://Stackoverflow.com/questions/13726429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1359306/" ]
Just change `+` to `-`: ``` str = str.replace(/[^a-z0-9-]/g, ""); ``` You can read it as: 1. `[^ ]`: match NOT from the set 2. `[^a-z0-9-]`: match if not `a-z`, `0-9` or `-` 3. `/ /g`: do global match **More information:** * <https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions>
Your character class (the part in the square brackets) is saying that you want to match anything except 0-9 and a-z and +. You aren't explicit about how many a-z or 0-9 you want to match, but I assume the + means you want to replace strings of at least one alphanumeric character. It should read instead: ``` str = str.replace(/[^-a-z0-9]+/g, ""); ``` Also, if you need to match upper-case letters along with lower case, you should use: ``` str = str.replace(/[^-a-zA-Z0-9]+/g, ""); ```
13,726,429
I am trying to do a basic string replace using a regex expression, but the answers I have found do not seem to help - they are directly answering each persons unique requirement with little or no explanation. I am using `str = str.replace(/[^a-z0-9+]/g, '');` at the moment. But what I would like to do is allow all alphanumeric characters (a-z and 0-9) and also the '-' character. Could you please answer this and explain how you concatenate expressions.
2012/12/05
[ "https://Stackoverflow.com/questions/13726429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1359306/" ]
This should work : ``` str = str.replace(/[^a-z0-9-]/g, ''); ``` Everything between the indicates what your are looking for 1. `/` is here to delimit your pattern so you have one to start and one to end 2. `[]` indicates the pattern your are looking for on one specific character 3. `^` indicates that you want every character NOT corresponding to what follows 4. `a-z` matches any character between 'a' and 'z' included 5. `0-9` matches any digit between '0' and '9' included (meaning any digit) 6. `-` the '-' character 7. `g` at the end is a special parameter saying that you do not want you regex to stop on the first character matching your pattern but to continue on the whole string Then your expression is delimited by `/` before and after. So here you say "every character not being a letter, a digit or a '-' will be removed from the string".
Just change `+` to `-`: ``` str = str.replace(/[^a-z0-9-]/g, ""); ``` You can read it as: 1. `[^ ]`: match NOT from the set 2. `[^a-z0-9-]`: match if not `a-z`, `0-9` or `-` 3. `/ /g`: do global match **More information:** * <https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions>
13,726,429
I am trying to do a basic string replace using a regex expression, but the answers I have found do not seem to help - they are directly answering each persons unique requirement with little or no explanation. I am using `str = str.replace(/[^a-z0-9+]/g, '');` at the moment. But what I would like to do is allow all alphanumeric characters (a-z and 0-9) and also the '-' character. Could you please answer this and explain how you concatenate expressions.
2012/12/05
[ "https://Stackoverflow.com/questions/13726429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1359306/" ]
Just change `+` to `-`: ``` str = str.replace(/[^a-z0-9-]/g, ""); ``` You can read it as: 1. `[^ ]`: match NOT from the set 2. `[^a-z0-9-]`: match if not `a-z`, `0-9` or `-` 3. `/ /g`: do global match **More information:** * <https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions>
``` str = str.replace(/\W/g, ""); ``` This will be a shorter form
13,726,429
I am trying to do a basic string replace using a regex expression, but the answers I have found do not seem to help - they are directly answering each persons unique requirement with little or no explanation. I am using `str = str.replace(/[^a-z0-9+]/g, '');` at the moment. But what I would like to do is allow all alphanumeric characters (a-z and 0-9) and also the '-' character. Could you please answer this and explain how you concatenate expressions.
2012/12/05
[ "https://Stackoverflow.com/questions/13726429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1359306/" ]
Just change `+` to `-`: ``` str = str.replace(/[^a-z0-9-]/g, ""); ``` You can read it as: 1. `[^ ]`: match NOT from the set 2. `[^a-z0-9-]`: match if not `a-z`, `0-9` or `-` 3. `/ /g`: do global match **More information:** * <https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions>
We can use `/[a-zA-Z]/g` to select small letter and caps letter sting in the word or sentence and replace. ```js var str = 'MM-DD-yyyy' var modifiedStr = str.replace(/[a-zA-Z]/g, '_') console.log(modifiedStr) ```
13,726,429
I am trying to do a basic string replace using a regex expression, but the answers I have found do not seem to help - they are directly answering each persons unique requirement with little or no explanation. I am using `str = str.replace(/[^a-z0-9+]/g, '');` at the moment. But what I would like to do is allow all alphanumeric characters (a-z and 0-9) and also the '-' character. Could you please answer this and explain how you concatenate expressions.
2012/12/05
[ "https://Stackoverflow.com/questions/13726429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1359306/" ]
This should work : ``` str = str.replace(/[^a-z0-9-]/g, ''); ``` Everything between the indicates what your are looking for 1. `/` is here to delimit your pattern so you have one to start and one to end 2. `[]` indicates the pattern your are looking for on one specific character 3. `^` indicates that you want every character NOT corresponding to what follows 4. `a-z` matches any character between 'a' and 'z' included 5. `0-9` matches any digit between '0' and '9' included (meaning any digit) 6. `-` the '-' character 7. `g` at the end is a special parameter saying that you do not want you regex to stop on the first character matching your pattern but to continue on the whole string Then your expression is delimited by `/` before and after. So here you say "every character not being a letter, a digit or a '-' will be removed from the string".
Your character class (the part in the square brackets) is saying that you want to match anything except 0-9 and a-z and +. You aren't explicit about how many a-z or 0-9 you want to match, but I assume the + means you want to replace strings of at least one alphanumeric character. It should read instead: ``` str = str.replace(/[^-a-z0-9]+/g, ""); ``` Also, if you need to match upper-case letters along with lower case, you should use: ``` str = str.replace(/[^-a-zA-Z0-9]+/g, ""); ```
13,726,429
I am trying to do a basic string replace using a regex expression, but the answers I have found do not seem to help - they are directly answering each persons unique requirement with little or no explanation. I am using `str = str.replace(/[^a-z0-9+]/g, '');` at the moment. But what I would like to do is allow all alphanumeric characters (a-z and 0-9) and also the '-' character. Could you please answer this and explain how you concatenate expressions.
2012/12/05
[ "https://Stackoverflow.com/questions/13726429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1359306/" ]
Your character class (the part in the square brackets) is saying that you want to match anything except 0-9 and a-z and +. You aren't explicit about how many a-z or 0-9 you want to match, but I assume the + means you want to replace strings of at least one alphanumeric character. It should read instead: ``` str = str.replace(/[^-a-z0-9]+/g, ""); ``` Also, if you need to match upper-case letters along with lower case, you should use: ``` str = str.replace(/[^-a-zA-Z0-9]+/g, ""); ```
``` str = str.replace(/\W/g, ""); ``` This will be a shorter form
13,726,429
I am trying to do a basic string replace using a regex expression, but the answers I have found do not seem to help - they are directly answering each persons unique requirement with little or no explanation. I am using `str = str.replace(/[^a-z0-9+]/g, '');` at the moment. But what I would like to do is allow all alphanumeric characters (a-z and 0-9) and also the '-' character. Could you please answer this and explain how you concatenate expressions.
2012/12/05
[ "https://Stackoverflow.com/questions/13726429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1359306/" ]
Your character class (the part in the square brackets) is saying that you want to match anything except 0-9 and a-z and +. You aren't explicit about how many a-z or 0-9 you want to match, but I assume the + means you want to replace strings of at least one alphanumeric character. It should read instead: ``` str = str.replace(/[^-a-z0-9]+/g, ""); ``` Also, if you need to match upper-case letters along with lower case, you should use: ``` str = str.replace(/[^-a-zA-Z0-9]+/g, ""); ```
We can use `/[a-zA-Z]/g` to select small letter and caps letter sting in the word or sentence and replace. ```js var str = 'MM-DD-yyyy' var modifiedStr = str.replace(/[a-zA-Z]/g, '_') console.log(modifiedStr) ```
13,726,429
I am trying to do a basic string replace using a regex expression, but the answers I have found do not seem to help - they are directly answering each persons unique requirement with little or no explanation. I am using `str = str.replace(/[^a-z0-9+]/g, '');` at the moment. But what I would like to do is allow all alphanumeric characters (a-z and 0-9) and also the '-' character. Could you please answer this and explain how you concatenate expressions.
2012/12/05
[ "https://Stackoverflow.com/questions/13726429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1359306/" ]
This should work : ``` str = str.replace(/[^a-z0-9-]/g, ''); ``` Everything between the indicates what your are looking for 1. `/` is here to delimit your pattern so you have one to start and one to end 2. `[]` indicates the pattern your are looking for on one specific character 3. `^` indicates that you want every character NOT corresponding to what follows 4. `a-z` matches any character between 'a' and 'z' included 5. `0-9` matches any digit between '0' and '9' included (meaning any digit) 6. `-` the '-' character 7. `g` at the end is a special parameter saying that you do not want you regex to stop on the first character matching your pattern but to continue on the whole string Then your expression is delimited by `/` before and after. So here you say "every character not being a letter, a digit or a '-' will be removed from the string".
``` str = str.replace(/\W/g, ""); ``` This will be a shorter form
13,726,429
I am trying to do a basic string replace using a regex expression, but the answers I have found do not seem to help - they are directly answering each persons unique requirement with little or no explanation. I am using `str = str.replace(/[^a-z0-9+]/g, '');` at the moment. But what I would like to do is allow all alphanumeric characters (a-z and 0-9) and also the '-' character. Could you please answer this and explain how you concatenate expressions.
2012/12/05
[ "https://Stackoverflow.com/questions/13726429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1359306/" ]
This should work : ``` str = str.replace(/[^a-z0-9-]/g, ''); ``` Everything between the indicates what your are looking for 1. `/` is here to delimit your pattern so you have one to start and one to end 2. `[]` indicates the pattern your are looking for on one specific character 3. `^` indicates that you want every character NOT corresponding to what follows 4. `a-z` matches any character between 'a' and 'z' included 5. `0-9` matches any digit between '0' and '9' included (meaning any digit) 6. `-` the '-' character 7. `g` at the end is a special parameter saying that you do not want you regex to stop on the first character matching your pattern but to continue on the whole string Then your expression is delimited by `/` before and after. So here you say "every character not being a letter, a digit or a '-' will be removed from the string".
We can use `/[a-zA-Z]/g` to select small letter and caps letter sting in the word or sentence and replace. ```js var str = 'MM-DD-yyyy' var modifiedStr = str.replace(/[a-zA-Z]/g, '_') console.log(modifiedStr) ```
5,223,716
I am trying to insensitive replace string, so I'm using str\_ireplace() but it does something I dont want and I have no clue how to overcome this problem. so this is my code: ``` $q = "pArty"; $str = "PARty all day long"; echo str_ireplace($q,'<b>' . $q . '</b>',$str); ``` The output will be like that: `"<b>pArty</b> all day long"`. The output looks like that because I replace insenitive variable `$q` with its sensitive. How can I overcome this so the output will be `"<b>PARty</b> all day long"`?
2011/03/07
[ "https://Stackoverflow.com/questions/5223716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/519002/" ]
You could do this with `preg_replace`, e.g.: ``` $q = preg_quote($q, '/'); // in case it has characters of significance to PCRE echo preg_replace('/' . $q . '/i', '<b>$0</b>', $str); ```
Its because you are asking to replace " P A R t y" with "p A r t y". As commanded, php obeyed. However, why do you even want to replace anything? The original is the word you require.
34,160
I'm making a malware software in my final thesis at the university. I won't use it ever, and it was made by educational and scientific purposes only. But my university will publish it, giving the opportunity for everyone to use it. If someone commit a crime with my software, can I get in trouble?
2018/12/07
[ "https://law.stackexchange.com/questions/34160", "https://law.stackexchange.com", "https://law.stackexchange.com/users/-1/" ]
> > my university will publish it, giving the opportunity for everyone to > use it. If someone commit a crime with my software, can I get in > trouble? > > > I would say "No" for three reasons. I will assume that you are in a jurisdiction of the U.S. or reasonably similar thereto. First, the malware code is part of your thesis, which in turn is a prerequisite (already [approved by the university](https://law.stackexchange.com/questions/34160/can-i-get-in-trouble-for-making-a-malware/34197#comment62964_34160)) for graduation. If anything, the entity that would be knowingly broadcasting the material is the university, not you. Any liability in the vein of [MCL 750.540f](http://www.legislature.mi.gov/(S(2ubfmtd5hibnrarwrhdecvcs))/mileg.aspx?page=getobject&objectname=mcl-750-540f) would fall on the university, as it knows better than you about the presumed "risks" as to whether third-parties might abuse your research. In the context of a *public* university with its typical status of "arm of the state", it would be untenable if one arm of the state (the university) authorizes you to proceed, and subsequently another governmental agency prosecutes *you* once your thesis reaches completion. Second, your thesis with all the source code therein expresses ideas which are protected by the First Amendment. A serious discussion of malware necessarily requires that these ideas be expressed in assembly code (often intertwined with excerpts in machine code) of the architecture for which it is devised. Anything short of that makes a discussion of malware meaningless because this topic depends so heavily on the particulars of the targeted family of processors. Furthermore, the academic context evidences your pursuit of educational & scientific advancement rather than a direct or indirect intent to encourage criminal activity. A person whose ultimate purpose is to promote computer crimes has many alternatives which are quicker and more effective than enrolling in a university, pay tuition, and undergo years of academic study. Third, (without minimizing your merits) it is doubtful that no solution could ever exist for the malware you devise, or that no one else from a "clandestine" setting would ever come up independently with an akin variant of that malware. Thus, publications of malware made with the openness and formalities of a university thesis are likelier to be viewed as a heads up to IT security companies about enhancements they might need to make on products & services they offer.
There's not much I can say without knowing where you're operating, but I would suspect the charges would fall on the party who used it, not the developer. Especially if you could prove your university sanctioned the project's creation and lack of ill intent. I know this isn't the place for opinions, but I could find no legal precedent here in the US, and I can't assume the cyber crime laws for any other country.
2,009,437
How can I get the @@IDENTITY for a specific table? I have been doing ``` select * from myTable ``` as I assume this sets the scope, from the same window SQL query window in SSMS I then run ``` select @@IDENTITY as identt ``` It returns identt as null which is not expected since myTable has many entrie in it already.. I expect it to return the next available ID integer. myTable has a ID column set to Primary key and auto increment.
2010/01/05
[ "https://Stackoverflow.com/questions/2009437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/127257/" ]
You can only truly use `SELECT @@IDENTITY` after an insert - the last insert into a table that has an IDENTITY column is the value you'll get back. You cannot "limit" it to a table - the value in @@IDENTITY - and by the way, I'd **strongly recommend** using SCOPE\_IDENTITY() instead!! - is the last value on any IDENTITY column that was set. The problem with @@IDENTITY is that it will report back the last IDENTITY value inserted into any table - if your INSERT into your data table will cause e.g. a trigger to write an entry into an Audit table and that Audit table has an IDENTITY field, you'll get back that IDENTITY value - not the one inserted into your table. SCOPE\_IDENTITY() solves that.
I've never known @@IDENTITY to be used this way, i've only ever used it to access the ID of a newly inserted record.
2,009,437
How can I get the @@IDENTITY for a specific table? I have been doing ``` select * from myTable ``` as I assume this sets the scope, from the same window SQL query window in SSMS I then run ``` select @@IDENTITY as identt ``` It returns identt as null which is not expected since myTable has many entrie in it already.. I expect it to return the next available ID integer. myTable has a ID column set to Primary key and auto increment.
2010/01/05
[ "https://Stackoverflow.com/questions/2009437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/127257/" ]
You can use [IDENT\_CURRENT](http://msdn.microsoft.com/en-us/library/ms175098.aspx) ``` IDENT_CURRENT( 'table_name' ) ``` Note that IDENT\_CURRENT returns the last identity value for the table **in any session and any scope**. This means, that if another identity value was inserted after your identity value then you will not retrieve the identity value that you inserted.
You can only truly use `SELECT @@IDENTITY` after an insert - the last insert into a table that has an IDENTITY column is the value you'll get back. You cannot "limit" it to a table - the value in @@IDENTITY - and by the way, I'd **strongly recommend** using SCOPE\_IDENTITY() instead!! - is the last value on any IDENTITY column that was set. The problem with @@IDENTITY is that it will report back the last IDENTITY value inserted into any table - if your INSERT into your data table will cause e.g. a trigger to write an entry into an Audit table and that Audit table has an IDENTITY field, you'll get back that IDENTITY value - not the one inserted into your table. SCOPE\_IDENTITY() solves that.
2,009,437
How can I get the @@IDENTITY for a specific table? I have been doing ``` select * from myTable ``` as I assume this sets the scope, from the same window SQL query window in SSMS I then run ``` select @@IDENTITY as identt ``` It returns identt as null which is not expected since myTable has many entrie in it already.. I expect it to return the next available ID integer. myTable has a ID column set to Primary key and auto increment.
2010/01/05
[ "https://Stackoverflow.com/questions/2009437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/127257/" ]
You can only truly use `SELECT @@IDENTITY` after an insert - the last insert into a table that has an IDENTITY column is the value you'll get back. You cannot "limit" it to a table - the value in @@IDENTITY - and by the way, I'd **strongly recommend** using SCOPE\_IDENTITY() instead!! - is the last value on any IDENTITY column that was set. The problem with @@IDENTITY is that it will report back the last IDENTITY value inserted into any table - if your INSERT into your data table will cause e.g. a trigger to write an entry into an Audit table and that Audit table has an IDENTITY field, you'll get back that IDENTITY value - not the one inserted into your table. SCOPE\_IDENTITY() solves that.
[IDENT\_CURRENT](http://msdn.microsoft.com/en-us/library/ms175098.aspx) does what you want. But don't. This is in addition to marc\_s' answer
2,009,437
How can I get the @@IDENTITY for a specific table? I have been doing ``` select * from myTable ``` as I assume this sets the scope, from the same window SQL query window in SSMS I then run ``` select @@IDENTITY as identt ``` It returns identt as null which is not expected since myTable has many entrie in it already.. I expect it to return the next available ID integer. myTable has a ID column set to Primary key and auto increment.
2010/01/05
[ "https://Stackoverflow.com/questions/2009437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/127257/" ]
You can only truly use `SELECT @@IDENTITY` after an insert - the last insert into a table that has an IDENTITY column is the value you'll get back. You cannot "limit" it to a table - the value in @@IDENTITY - and by the way, I'd **strongly recommend** using SCOPE\_IDENTITY() instead!! - is the last value on any IDENTITY column that was set. The problem with @@IDENTITY is that it will report back the last IDENTITY value inserted into any table - if your INSERT into your data table will cause e.g. a trigger to write an entry into an Audit table and that Audit table has an IDENTITY field, you'll get back that IDENTITY value - not the one inserted into your table. SCOPE\_IDENTITY() solves that.
That's correct. @@IDENTITY cannot be used the way you think it can be. It can only be used after an INSERT into a table. Let's consider this for a scenario: You have two tables: Order (Primary Key: OrderID), OrderDetails (Foreign Key: OrderID) You perform INSERT INTO Order VALUES('Pillows') -- Note that OrderId is not mentioned in Values since it is auto number (primary key) Now you want to perform insert into OrderDetail. But you don't always remember how many records there were in Order table prior to you having inserted the record for 'Pillows' and hence you don't remember what was the last PrimaryKey inserted into Order table. You could but even then you wouldn't want to specifically mention to insert (let's say OrderID of 1) when you insert into OrderDetail table. Hence, your OderDetail insert would work kinda like so: INSERT INTO OrderDetail VALUES (@@IDENTITY,'Soft Pillows') Hope this explains the user of @@IDENTITY.
2,009,437
How can I get the @@IDENTITY for a specific table? I have been doing ``` select * from myTable ``` as I assume this sets the scope, from the same window SQL query window in SSMS I then run ``` select @@IDENTITY as identt ``` It returns identt as null which is not expected since myTable has many entrie in it already.. I expect it to return the next available ID integer. myTable has a ID column set to Primary key and auto increment.
2010/01/05
[ "https://Stackoverflow.com/questions/2009437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/127257/" ]
You can use [IDENT\_CURRENT](http://msdn.microsoft.com/en-us/library/ms175098.aspx) ``` IDENT_CURRENT( 'table_name' ) ``` Note that IDENT\_CURRENT returns the last identity value for the table **in any session and any scope**. This means, that if another identity value was inserted after your identity value then you will not retrieve the identity value that you inserted.
I've never known @@IDENTITY to be used this way, i've only ever used it to access the ID of a newly inserted record.
2,009,437
How can I get the @@IDENTITY for a specific table? I have been doing ``` select * from myTable ``` as I assume this sets the scope, from the same window SQL query window in SSMS I then run ``` select @@IDENTITY as identt ``` It returns identt as null which is not expected since myTable has many entrie in it already.. I expect it to return the next available ID integer. myTable has a ID column set to Primary key and auto increment.
2010/01/05
[ "https://Stackoverflow.com/questions/2009437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/127257/" ]
[IDENT\_CURRENT](http://msdn.microsoft.com/en-us/library/ms175098.aspx) does what you want. But don't. This is in addition to marc\_s' answer
I've never known @@IDENTITY to be used this way, i've only ever used it to access the ID of a newly inserted record.
2,009,437
How can I get the @@IDENTITY for a specific table? I have been doing ``` select * from myTable ``` as I assume this sets the scope, from the same window SQL query window in SSMS I then run ``` select @@IDENTITY as identt ``` It returns identt as null which is not expected since myTable has many entrie in it already.. I expect it to return the next available ID integer. myTable has a ID column set to Primary key and auto increment.
2010/01/05
[ "https://Stackoverflow.com/questions/2009437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/127257/" ]
I've never known @@IDENTITY to be used this way, i've only ever used it to access the ID of a newly inserted record.
That's correct. @@IDENTITY cannot be used the way you think it can be. It can only be used after an INSERT into a table. Let's consider this for a scenario: You have two tables: Order (Primary Key: OrderID), OrderDetails (Foreign Key: OrderID) You perform INSERT INTO Order VALUES('Pillows') -- Note that OrderId is not mentioned in Values since it is auto number (primary key) Now you want to perform insert into OrderDetail. But you don't always remember how many records there were in Order table prior to you having inserted the record for 'Pillows' and hence you don't remember what was the last PrimaryKey inserted into Order table. You could but even then you wouldn't want to specifically mention to insert (let's say OrderID of 1) when you insert into OrderDetail table. Hence, your OderDetail insert would work kinda like so: INSERT INTO OrderDetail VALUES (@@IDENTITY,'Soft Pillows') Hope this explains the user of @@IDENTITY.
2,009,437
How can I get the @@IDENTITY for a specific table? I have been doing ``` select * from myTable ``` as I assume this sets the scope, from the same window SQL query window in SSMS I then run ``` select @@IDENTITY as identt ``` It returns identt as null which is not expected since myTable has many entrie in it already.. I expect it to return the next available ID integer. myTable has a ID column set to Primary key and auto increment.
2010/01/05
[ "https://Stackoverflow.com/questions/2009437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/127257/" ]
You can use [IDENT\_CURRENT](http://msdn.microsoft.com/en-us/library/ms175098.aspx) ``` IDENT_CURRENT( 'table_name' ) ``` Note that IDENT\_CURRENT returns the last identity value for the table **in any session and any scope**. This means, that if another identity value was inserted after your identity value then you will not retrieve the identity value that you inserted.
[IDENT\_CURRENT](http://msdn.microsoft.com/en-us/library/ms175098.aspx) does what you want. But don't. This is in addition to marc\_s' answer
2,009,437
How can I get the @@IDENTITY for a specific table? I have been doing ``` select * from myTable ``` as I assume this sets the scope, from the same window SQL query window in SSMS I then run ``` select @@IDENTITY as identt ``` It returns identt as null which is not expected since myTable has many entrie in it already.. I expect it to return the next available ID integer. myTable has a ID column set to Primary key and auto increment.
2010/01/05
[ "https://Stackoverflow.com/questions/2009437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/127257/" ]
You can use [IDENT\_CURRENT](http://msdn.microsoft.com/en-us/library/ms175098.aspx) ``` IDENT_CURRENT( 'table_name' ) ``` Note that IDENT\_CURRENT returns the last identity value for the table **in any session and any scope**. This means, that if another identity value was inserted after your identity value then you will not retrieve the identity value that you inserted.
That's correct. @@IDENTITY cannot be used the way you think it can be. It can only be used after an INSERT into a table. Let's consider this for a scenario: You have two tables: Order (Primary Key: OrderID), OrderDetails (Foreign Key: OrderID) You perform INSERT INTO Order VALUES('Pillows') -- Note that OrderId is not mentioned in Values since it is auto number (primary key) Now you want to perform insert into OrderDetail. But you don't always remember how many records there were in Order table prior to you having inserted the record for 'Pillows' and hence you don't remember what was the last PrimaryKey inserted into Order table. You could but even then you wouldn't want to specifically mention to insert (let's say OrderID of 1) when you insert into OrderDetail table. Hence, your OderDetail insert would work kinda like so: INSERT INTO OrderDetail VALUES (@@IDENTITY,'Soft Pillows') Hope this explains the user of @@IDENTITY.
2,009,437
How can I get the @@IDENTITY for a specific table? I have been doing ``` select * from myTable ``` as I assume this sets the scope, from the same window SQL query window in SSMS I then run ``` select @@IDENTITY as identt ``` It returns identt as null which is not expected since myTable has many entrie in it already.. I expect it to return the next available ID integer. myTable has a ID column set to Primary key and auto increment.
2010/01/05
[ "https://Stackoverflow.com/questions/2009437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/127257/" ]
[IDENT\_CURRENT](http://msdn.microsoft.com/en-us/library/ms175098.aspx) does what you want. But don't. This is in addition to marc\_s' answer
That's correct. @@IDENTITY cannot be used the way you think it can be. It can only be used after an INSERT into a table. Let's consider this for a scenario: You have two tables: Order (Primary Key: OrderID), OrderDetails (Foreign Key: OrderID) You perform INSERT INTO Order VALUES('Pillows') -- Note that OrderId is not mentioned in Values since it is auto number (primary key) Now you want to perform insert into OrderDetail. But you don't always remember how many records there were in Order table prior to you having inserted the record for 'Pillows' and hence you don't remember what was the last PrimaryKey inserted into Order table. You could but even then you wouldn't want to specifically mention to insert (let's say OrderID of 1) when you insert into OrderDetail table. Hence, your OderDetail insert would work kinda like so: INSERT INTO OrderDetail VALUES (@@IDENTITY,'Soft Pillows') Hope this explains the user of @@IDENTITY.
14,225,659
I have found that one of the Microsoft Reporting controls (the Chart) is inadequate for my needs. Since these controls aren't extensible, I've extended the functionality of a WPF control and am saving the control as a graphic. Unfortunately, ReportViewer's image control doesn't support vector graphics, either. Therefore my goal is to generate the PDF from ReportViewer with certain "placeholders" (e.g. a rectangle item), and then come behind with iTextSharp and add the vector graphic on top of these placeholders. Since the report length flows based on the input data, I can't know the coordinates of these placeholders before getting them. I can't think of a way to include a PDF field in the RDLC, which would be nice since iText has the GetFieldPosition() method. Furthermore I know there is iText's PDFWriter.GetVerticalPosition() method, but this is really only useful if you've moved the cursor to that location in the PDFWriter. Truth is, I'm still trying to get my head around iText and PDF. It is *vast*. So my two questions that refer to each other: 1. What kind of placeholder should I use in the RDLC designer that can be systematically identified afterwards and have its position queried? 2. How would I go about getting this position? Thanks in advance! -Brandon
2013/01/08
[ "https://Stackoverflow.com/questions/14225659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1435756/" ]
My imperfect, but working solution is to use text item placeholders that match the background to mark the positions in the .RDLC report. After generating the PDF, these are identified by way of inheriting iTextSharp's LocationTextExtractionStrategy (as per [this entry by greenhat](https://stackoverflow.com/questions/4577789/extract-text-and-text-rectangle-coordinates-from-a-pdf-file-using-itextsharp/8825884#8825884)). In my current test environment the above is copy-pasted verbatim and only deviates in the RenderText() override, which does not add the TextChunk to the list unless `info.GetText()` is an appropriate placeholder string. Snippet of placeholder extraction: ``` PdfReader reader = new PdfReader(fileName); LocationTextExtractionStrategyEx strat = new LocationTextExtractionStrategyEx(); for (int i = 1; i <= reader.NumberOfPages; i++) PdfTextExtractor.GetTextFromPage(reader, i, strat); ``` The native vector image type is WMF, and can be inserted at the absolute location of the placeholder text. To do so for the first placeholder in the list, then: ``` using (FileStream fs = new FileStream("output.pdf", FileMode.Create, FileAccess.Write, FileShare.None)) { using (PdfStamper stamper = new PdfStamper(reader, fs)) { using (Stream wmfStream = new FileStream(@"C:\Paint.wmf", FileMode.Open, FileAccess.Read, FileShare.Read)) { Image replacementVectorImage = Image.GetInstance(wmfStream); replacementVectorImage.SetAbsolutePosition(strat.TextLocationInfo[0].TopLeft[0], strat.TextLocationInfo[0].BottomRight[1]); PdfContentByte cb = stamper.GetOverContent(1); cb.AddImage(replacementVectorImage); } } } ``` Thanks to mkl and VahidN for your valuable input!
* add default images as place holders. * export your xaml files as images. * now it's possible to replace these default images with new images. more info here: <https://stackoverflow.com/a/8751517/298573>
25,428,870
I'm trying to figure out how to write a decorator to check if the function was called with specific optional argument. This may not be the pythonic way of checking for arguments, but I'd like to know the solution using decorators regardless. Here is an example of what I'm looking for: ``` @require_arguments("N", "p") # Question here def g(x,*args,**kwargs): if "N" not in kwargs: raise SyntaxError("missing N") if "p" not in kwargs: raise SyntaxError("missing p") print x g(3,N=2) # Raise "missing p" ``` How do I write the decorator `@require_arguments(*args)` that will raise the appropriate error?
2014/08/21
[ "https://Stackoverflow.com/questions/25428870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/249341/" ]
Here you go: ``` def require_arguments(*reqargs): def decorator(func): def wrapper(*args, **kwargs): for arg in reqargs: if not arg in kwargs: raise TypeError("Missing %s" % arg) return func(*args, **kwargs) return wrapper return decorator @require_arguments("N", "p") # Question here def g(x,*args,**kwargs): print x g(3,N=2) # Raise "missing p" ``` Output: ``` Traceback (most recent call last): File "arg.py", line 19, in <module> g(3,N=2) # Raise "missing p" File "arg.py", line 7, in wrapper raise ValueError("Missing %s" % arg) ValueError: Missing p ```
[dano](https://stackoverflow.com/users/2073595/dano)'s answer is correct, the only suggestions I can add are: * Use [`functools.wraps`](https://docs.python.org/2/library/functools.html#functools.wraps) to create your decorators, this way the name of the function and its *docstring* will be preserved. * Generate a list of all the missing arguments instead of a single one. I personally hate when the compiler just says: '*you forgot a*', and then when I add it it still complains: '*you forgot b*' and so on. The decorator becomes: ``` from functools import wraps def require_arguments(*reqs): def decorator(func): @wraps(func) def decorated(*args, **kwargs): missing = [req for req in reqs if req not in kwargs] if missing: raise TypeError('missing ' + ', '.join(missing)) return func(*args, **kwargs) return decorated return decorator ``` Example ------- ``` @require_arguments('N', 'p') def g(x, *args, **kargs): """just return x""" print x print g.__name__ print g.__doc__ try: print g(3) except TypeError as e: print e ``` *Output* ``` g just return x missing N, p ``` A better approach ----------------- If you need required arguments, just put ask for them explicitly like: def `g(x, N, p)`. You will still be able to invoke the function like `g(x=2, N=5, p=3)` for make your code more expressive, even in a different order if you specify the argument. But you will have a fixed api (which is normally good) and you will be able either to specify the arguments or to use the fixed api order. ``` def f(a, b, c): print a, b, c f(1, 2, 3) # 1 2 3 f(c=1, b=2, a=3) # 3 2 1 ```
71,165,098
What is an appropriate way to solve the following example with swift? I know because of type erasure that you cannot assign `StructB` to `item2` in the constructor. In other languages like *Java* I would solve the problem by not having a generic class parameter `T` in the `Container` struct but let vars `item` and `item2` just be the type of `ProtocolA` (like `var item2: ProtocolA`). This is not allowed by swift: *Protocol 'ProtocolA' can only be used as a generic constraint because it has Self or associated type requirements* I worked through [this](https://docs.swift.org/swift-book/LanguageGuide/Generics.html) section of swifts documentation about generics but so far I was not able to adapt a solution for my simple problem: ```swift protocol ProtocolA { associatedtype B func foo() -> B } struct StructA: ProtocolA { typealias B = String func foo() -> String { "Hello" } } struct StructB: ProtocolA { typealias B = Double func foo() -> Double { 0.0 } } struct Container<T: ProtocolA> { var item: T var item2: T init(item: T) { self.item = item self.item2 = StructB() // err: Cannot assign value of type 'StructB' to type 'T' } } ``` I also want to know how a solution could look if I do not want to specify a generic type parameter at all for the container struct. So that I could write the following: ```swift func test() { let container = Container(StructA()) // no type given } ```
2022/02/17
[ "https://Stackoverflow.com/questions/71165098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3477946/" ]
For the problem as described, the answer is very straightforward: ``` struct Container<T: ProtocolA> { var item: T var item2: StructB // This isn't T; you hard-coded it to StructB in init init(item: T) { self.item = item self.item2 = StructB() } } let container = Container(item: StructA()) // works as described ``` I get the feeling that there's something deeper to this question, which is why Alexander was asking for more context. As written, the question's answer seems too simple, so some of us assume that there's more that you didn't explain, and we want to avoid a round of "here's the answer" followed by "that's not what I meant." As you wrote it, you try to force `item` and `item2` to have the same type. That's obviously not what you mean because `T` is given by the caller, and `item2` is always StructB (which does not have to equal `T`, as the error explains). Is there another way you intend to call this code? It's unclear what code that calls `foo()` would look like. Do you have some other way you intend to initialize Container that you didn't explain in your question? Maybe you want two different types, and you just want StructB to be the default? In that case, it would look like (based on Ptit Xav's answer): ``` struct Container<T: ProtocolA, U: ProtocolA> { var item: T var item2: U // Regular init where the caller decides T and U init(item: T, item2: U) { self.item = item self.item2 = item2 } // Convenience where the caller just decides T and U is default init(item: T) where U == StructB { self.init(item: item, item2: StructB()) } } ``` The `where U == StructB` allows you to make a default type for U.
The only way to do something like you want is : ``` struct Container<T: ProtocolA,U: ProtocolA> { var item: T var item2: U init(item: T, item2: U) { self.item = item self.item2 = item2 } } ```
44,386,174
``` class Node: def __init__(self, data = None, next = None): self.data = data self.next = next class LinkedList(Node): def __init__(self, l_size = 0, head = None, tail = None): Node.__init__(self) self.l_size = 0 self.head = head self.tail = tail def add(self, data): n = Node(data, None) if(self.l_size == 0): self.head.next = n self.head.data = n.data else: self.tail.next = n self.tail.data = n.data n = n.next print(n) self.tail = n self.l_size += 1 return True l = LinkedList() l.add(7) l.add(8) l.add(2) ``` I'm just trying to achieve `(h)-> 7 -> 8 -> 2 <- (l)` Where (h) and (l) are the head and tail pointers respectively. The way I'm implementing this the LL is basically the head and the tail pointers, the Nodes chain together on their own, that's why I made Node a super class.
2017/06/06
[ "https://Stackoverflow.com/questions/44386174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4982544/" ]
Simply aggregate your table per `user_id` and use `HAVING` to ensure both conditions are met for the user. ``` select user_id from settings group by user_id having count(case when token = 'language' and value = 'en' then 1 end) > 0 and count(case when token = 'newsletter' AND value = 1 then 1 end) > 0 ``` You can add a `WHERE` clause to speed this up, if you like: ``` where (token = 'language' and value = 'en') or (token = 'newsletter' AND value = 1) ```
Please try This query : ``` SELECT user_id FROM settings WHERE (token = 'language' AND value = 'en') OR (token = 'newsletter' AND value = '1') ``` There is no use of Group By clause
69,984,598
I tried using a lambda expression and `count_if()` to find the same string value in a `vector`, but it didn't work. The error message is: > > variable 'str' cannot be implicitly captured in a lambda with no capture-default specified > > > ```cpp std::vector<std::string> hello{"Mon","Tue", "Wes", "perfect","Sun"}; for (unsigned int i = 0; i < hello.size(); i++) { int n=0; std::string str=hello[i]; n=std::count_if(hello.begin(),hello.end(),[](std::string s){return s==str;}); std::cout<<n; } ```
2021/11/16
[ "https://Stackoverflow.com/questions/69984598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16188928/" ]
@Steven The brackets `[]` of lambda functions, are called a *capture list*. They define the scope of variables that the lambda function uses. See [this reference](https://en.cppreference.com/w/cpp/language/lambda). When you use this formatting `[&]`, it means you can see all the variables (by reference) of the current scope in your lambda function. So the type of variables doesn't matter. For your example, when you write: ``` s == str ``` The lambda function only knows about the variable `s`, which is passed as an argument. To see the `str`, you can use either of these: 1. `[&]`, pass everything by reference 2. `[&str]`, pass only the variable `str` as reference Note, there are also ways to pass by value.
This function has the same mechanism, only it uses `<hash>` and `<unordered_map>` to store the values and the number of times each is repeated (if it is greater than `1` *occurrence*). ``` template <typename T> void elements(vector<T>& e) { auto h = [](const T* v) { return std::hash<T>()(*v); }; auto eq = [](const T* v1, const T* v2) { return v1->compare(*v2) == 0; }; std::unordered_map<const T*, size_t, decltype(h), decltype(eq)> m(e.size(), h, eq); // Count occurances. for (auto v_i = e.cbegin(); v_i != e.cend(); ++v_i) ++m[&(*v_i)]; // Print value that occur more than once: for (auto m_i = m.begin(); m_i != m.end(); ++m_i) if (m_i->second > 1) std::cout << *m_i->first << ": " << m_i->second << std::endl; } ```   [Example](https://godbolt.org/z/334bexK8s)
11,573,562
In my current project, I am making a sticky-note type application in which the user can have multiple instances open of the same form. However, I was wondering if there was a way in C# where I can create a new instance of form1 however have the new form's title/text/heading to be form2. If this is achievable, I would like a nudge into the correct direction of how to code that part of my app. Thanks everyone. --EDIT-- I realized I forgot to add something important: I need to be able to calculate how many instances are currently open. From there I will add +1 to the form text.
2012/07/20
[ "https://Stackoverflow.com/questions/11573562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1539802/" ]
Try accessing the forms properties from the class: ``` MyForm newForm = new MyForm(); newForm.Show(); newForm.Text = "Form2"; ``` Or call a method from the current form to set the text: ``` // In MyForm public void SetTitle(string text) { this.Text = text; } // Call the Method MyForm newForm = new MyForm(); newForm.Show(); newForm.SetTitle("Form2"); ``` Hope this helps! To check the amount of forms open you could try something like this: ``` // In MyForm private int counter = 1; public void Counter(int count) { counter = count; } // Example MyForm newForm = new MyForm(); counter++; newForm.Counter(counter); ``` It may be confusing to use, but lets say you have a button that opens a new instance of the same form. Since you have one form open at the start `counter = 1`. Every time you click on the button, it will send `counter++` or `2` to the form. If you open another form, it will send `counter = 3` and so on. There might be a better way to do this but I am not sure.
Use a static field to keep a count of how many instances have been opened, and use it to set the form's caption. Here's a sketch; if you want different behavior you could skip the OnFormClosed override: ``` public class TheFormClass : Form { private static int _openCount = 0; protected override void OnLoad(EventArgs e) { _openCount++; base.OnLoad(e); this.Text = "Form" + _openCount; } protected override void OnFormClosed(FormClosedEventArgs e) { _openCount--; base.OnFormClosed(e); } } ```
29,709,291
Chromecast session status returns undefined on Chrome mobile ios. The session exists and has other properties defined, like sessionID. On the desktop, the session status returns "connected", "disconnected", or "stopped" as expected. Is this a bug with Chrome ios? Is there another way to detect the session status?
2015/04/17
[ "https://Stackoverflow.com/questions/29709291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4634213/" ]
Here's one alternative using `ifelse` ``` > transform(df, NewSize=ifelse(Month==1, Size*Month1, ifelse(Month==2, Size*Month2, Size*Month3))) Orig Dest Month Size Month1 Month2 Month3 NewSize 1 A B 1 30 1.0 0.6 0.0 30 2 B A 1 20 0.2 1.0 1.0 4 3 A C 1 10 0.0 0.0 0.6 0 4 A B 2 10 1.0 0.6 0.0 6 5 B A 2 20 0.2 1.0 1.0 20 6 A C 2 20 0.0 0.0 0.6 0 7 A B 3 30 1.0 0.6 0.0 0 8 B A 3 50 0.2 1.0 1.0 50 9 A C 3 20 0.0 0.0 0.6 12 ```
Here's how I'd handle this using `data.table`. ``` require(data.table) setkey(setDT(df), Month)[.(mon = 1:3), ## i NewSize := Size * get(paste0("Month", mon)), ## j by=.EACHI] ## by ``` * `setDT` converts `df` from *data.frame* to *data.table* by reference. * `setkey` reorders that *data.table* by the column specified, `Month`, in increasing order, and marks that column as *key* column, on which we'll perform a join. * We perform a join on the key column set in the previous set with the values `1:3`. This can also be interpreted as a *subset* operation that extracts all rows matching `1,2 and 3` from the key column `Month`. * So, for each value of `1:3`, we calculate the matching rows in `i`. And on those matching rows, we compute `NewSize` by extracting `Size` and `MonthX` for those matching rows, and multiplying them. We use `get()` to achieve extracting the right `MonthX` column. * `by=.EACHI` as the name implies, executes the expression in `j` for each `i`. As an example, `i=1` matches (or joins) to rows 1:3 of `df`. For those rows, the j-expression extracts `Size = 30,20,10` and `Month1 = 1.0, 0.2, 0.0`, and it gets evaluated to return `30, 4, 0`. And then for `i=2` and so on.. Hope this helps a bit even if you're looking for a `dplyr` only answer.
29,709,291
Chromecast session status returns undefined on Chrome mobile ios. The session exists and has other properties defined, like sessionID. On the desktop, the session status returns "connected", "disconnected", or "stopped" as expected. Is this a bug with Chrome ios? Is there another way to detect the session status?
2015/04/17
[ "https://Stackoverflow.com/questions/29709291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4634213/" ]
Here's one alternative using `ifelse` ``` > transform(df, NewSize=ifelse(Month==1, Size*Month1, ifelse(Month==2, Size*Month2, Size*Month3))) Orig Dest Month Size Month1 Month2 Month3 NewSize 1 A B 1 30 1.0 0.6 0.0 30 2 B A 1 20 0.2 1.0 1.0 4 3 A C 1 10 0.0 0.0 0.6 0 4 A B 2 10 1.0 0.6 0.0 6 5 B A 2 20 0.2 1.0 1.0 20 6 A C 2 20 0.0 0.0 0.6 0 7 A B 3 30 1.0 0.6 0.0 0 8 B A 3 50 0.2 1.0 1.0 50 9 A C 3 20 0.0 0.0 0.6 12 ```
You can use `apply`: ``` apply(df, 1, function(u) as.numeric(u[paste0('Month', u['Month'])])*as.numeric(u['Size'])) #[1] 30 4 0 6 20 0 0 50 12 ``` Or a vectorized solution: ``` bool = matrix(rep(df$Month, each=3)==rep(1:3, nrow(df)), byrow=T, ncol=3) df[c('Month1', 'Month2', 'Month3')][bool] * df$Size #[1] 30 4 0 6 20 0 0 50 12 ```
29,709,291
Chromecast session status returns undefined on Chrome mobile ios. The session exists and has other properties defined, like sessionID. On the desktop, the session status returns "connected", "disconnected", or "stopped" as expected. Is this a bug with Chrome ios? Is there another way to detect the session status?
2015/04/17
[ "https://Stackoverflow.com/questions/29709291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4634213/" ]
Here's one alternative using `ifelse` ``` > transform(df, NewSize=ifelse(Month==1, Size*Month1, ifelse(Month==2, Size*Month2, Size*Month3))) Orig Dest Month Size Month1 Month2 Month3 NewSize 1 A B 1 30 1.0 0.6 0.0 30 2 B A 1 20 0.2 1.0 1.0 4 3 A C 1 10 0.0 0.0 0.6 0 4 A B 2 10 1.0 0.6 0.0 6 5 B A 2 20 0.2 1.0 1.0 20 6 A C 2 20 0.0 0.0 0.6 0 7 A B 3 30 1.0 0.6 0.0 0 8 B A 3 50 0.2 1.0 1.0 50 9 A C 3 20 0.0 0.0 0.6 12 ```
In base R, fully vectorized: ``` df$Size*df[,5:7][cbind(1:nrow(df),df$Month)] ```
29,709,291
Chromecast session status returns undefined on Chrome mobile ios. The session exists and has other properties defined, like sessionID. On the desktop, the session status returns "connected", "disconnected", or "stopped" as expected. Is this a bug with Chrome ios? Is there another way to detect the session status?
2015/04/17
[ "https://Stackoverflow.com/questions/29709291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4634213/" ]
Here's how I'd handle this using `data.table`. ``` require(data.table) setkey(setDT(df), Month)[.(mon = 1:3), ## i NewSize := Size * get(paste0("Month", mon)), ## j by=.EACHI] ## by ``` * `setDT` converts `df` from *data.frame* to *data.table* by reference. * `setkey` reorders that *data.table* by the column specified, `Month`, in increasing order, and marks that column as *key* column, on which we'll perform a join. * We perform a join on the key column set in the previous set with the values `1:3`. This can also be interpreted as a *subset* operation that extracts all rows matching `1,2 and 3` from the key column `Month`. * So, for each value of `1:3`, we calculate the matching rows in `i`. And on those matching rows, we compute `NewSize` by extracting `Size` and `MonthX` for those matching rows, and multiplying them. We use `get()` to achieve extracting the right `MonthX` column. * `by=.EACHI` as the name implies, executes the expression in `j` for each `i`. As an example, `i=1` matches (or joins) to rows 1:3 of `df`. For those rows, the j-expression extracts `Size = 30,20,10` and `Month1 = 1.0, 0.2, 0.0`, and it gets evaluated to return `30, 4, 0`. And then for `i=2` and so on.. Hope this helps a bit even if you're looking for a `dplyr` only answer.
You can use `apply`: ``` apply(df, 1, function(u) as.numeric(u[paste0('Month', u['Month'])])*as.numeric(u['Size'])) #[1] 30 4 0 6 20 0 0 50 12 ``` Or a vectorized solution: ``` bool = matrix(rep(df$Month, each=3)==rep(1:3, nrow(df)), byrow=T, ncol=3) df[c('Month1', 'Month2', 'Month3')][bool] * df$Size #[1] 30 4 0 6 20 0 0 50 12 ```
29,709,291
Chromecast session status returns undefined on Chrome mobile ios. The session exists and has other properties defined, like sessionID. On the desktop, the session status returns "connected", "disconnected", or "stopped" as expected. Is this a bug with Chrome ios? Is there another way to detect the session status?
2015/04/17
[ "https://Stackoverflow.com/questions/29709291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4634213/" ]
In base R, fully vectorized: ``` df$Size*df[,5:7][cbind(1:nrow(df),df$Month)] ```
You can use `apply`: ``` apply(df, 1, function(u) as.numeric(u[paste0('Month', u['Month'])])*as.numeric(u['Size'])) #[1] 30 4 0 6 20 0 0 50 12 ``` Or a vectorized solution: ``` bool = matrix(rep(df$Month, each=3)==rep(1:3, nrow(df)), byrow=T, ncol=3) df[c('Month1', 'Month2', 'Month3')][bool] * df$Size #[1] 30 4 0 6 20 0 0 50 12 ```
1,148,807
How would I solve this differential eqn $$xdy - ydx = (x^2 + y^2)^{1/2} dx$$ I tried bringing the sq root term to the left and it looked like a trigonometric substitution might do the trick, but apparently no. Any help would be appreciated.
2015/02/15
[ "https://math.stackexchange.com/questions/1148807", "https://math.stackexchange.com", "https://math.stackexchange.com/users/117251/" ]
$$x\frac{dy}{dx} - y = (x^2 + y^2)^{1/2} $$ is an ODE of the homogeneous kind. The usual method to solve it is to let $y(x)=x\:f(x)$ This leads to an ODE of the separable kind easy to solve. The final result is $y=c\:x^2-\frac{1}{4\:c}$
The substitution $y = u x$ makes this into a separable differential equation.
21,772,974
I am coding a PHP script, but I can't really seem to get it to work. I am testing out the basics, but I don't really understand what GET and POST means, what's the difference? All the definitions I've seen on the web make not much sense to me, what I've coded so far (but since I don't understand POST and GET, I don't know how to get it to work: ``` <form name="mail_sub" method="get"> Name: <input type="text" name="theirname"> <br /> Email:&nbsp; <input type="text" name="theirpass"> <br /> <input type="submit" value="Join!" style="width:200px"> </form> <?php if (isset($_POST['mail_sub'])) { echo $_POST['theirname']; } ?> ```
2014/02/14
[ "https://Stackoverflow.com/questions/21772974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3077765/" ]
To answer the question: GET and POST are one of the many `request types` in the standards of internet. The difference is that GET can't post data, parameters will be appended to the url (url-parameters) which has it's limitations. POST does post parameters/data. The standard is: * GET for getting data. * POST for creating data. * PUT for updating data. * DELETE for removing data.
replace ``` isset($_POST['mail_sub']) ``` by ``` isset($_POST['theirname']) ``` The main difference between GET and POST requests is that in GET requests all parameter are part of the url and the user sees the parameters. In POST requests the url is not modified and all form parameter are hidden from the user. If you have no file uploads or very long field parameter use GET. Use POST when going in production.
21,772,974
I am coding a PHP script, but I can't really seem to get it to work. I am testing out the basics, but I don't really understand what GET and POST means, what's the difference? All the definitions I've seen on the web make not much sense to me, what I've coded so far (but since I don't understand POST and GET, I don't know how to get it to work: ``` <form name="mail_sub" method="get"> Name: <input type="text" name="theirname"> <br /> Email:&nbsp; <input type="text" name="theirpass"> <br /> <input type="submit" value="Join!" style="width:200px"> </form> <?php if (isset($_POST['mail_sub'])) { echo $_POST['theirname']; } ?> ```
2014/02/14
[ "https://Stackoverflow.com/questions/21772974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3077765/" ]
To answer the question: GET and POST are one of the many `request types` in the standards of internet. The difference is that GET can't post data, parameters will be appended to the url (url-parameters) which has it's limitations. POST does post parameters/data. The standard is: * GET for getting data. * POST for creating data. * PUT for updating data. * DELETE for removing data.
GET - If form method is GET then on submitting the form, Form will be submitted to ``` xyz.com/submit.php?theirname=john&theirpass=password // CHECK HERE - form elements are in URL so not so secure ``` and can be checked by PHP as ``` if(isset($_GET['their'])) { $name=$_GET['their']; //name will return John } ``` POST - If form method is POST then on submitting the form, Form will be submitted to ``` xyz.com/submit.php // CHECK HERE form elements are not in URL ``` and can be checked by PHP as ``` if(isset($_POST['their'])) { $name=$_POST['their']; //name will return John } ```
21,772,974
I am coding a PHP script, but I can't really seem to get it to work. I am testing out the basics, but I don't really understand what GET and POST means, what's the difference? All the definitions I've seen on the web make not much sense to me, what I've coded so far (but since I don't understand POST and GET, I don't know how to get it to work: ``` <form name="mail_sub" method="get"> Name: <input type="text" name="theirname"> <br /> Email:&nbsp; <input type="text" name="theirpass"> <br /> <input type="submit" value="Join!" style="width:200px"> </form> <?php if (isset($_POST['mail_sub'])) { echo $_POST['theirname']; } ?> ```
2014/02/14
[ "https://Stackoverflow.com/questions/21772974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3077765/" ]
Post is like "sending" the data to the page without giving the user having any interaction with it, when Get shows the parameters in the URL and making it public for the user. Get is more often used on "unsecure" type of datatransactions like for example a searchform and POST is used when you want to make more secure things like a login form. Using a Get will give you like index.php?parameter=hello&parameter2=world In your example you should use either POST in the method attribute in the formtag or $\_GET in the php section So either ``` <form name="mail_sub" method="post"> Name: <input type="text" name="theirname"> <br /> Email:&nbsp; <input type="text" name="theirpass"> <br /> <input type="submit" value="Join!" style="width:200px"> </form> <?php if (isset($_POST['theirname'])) { echo $_POST['theirname']; } ?> ``` or ``` <form name="mail_sub" method="get"> Name: <input type="text" name="theirname"> <br /> Email:&nbsp; <input type="text" name="theirpass"> <br /> <input type="submit" value="Join!" style="width:200px"> </form> <?php if (isset($_GET['theirname'])) { echo $_GET['theirname']; } ?> ```
GET - If form method is GET then on submitting the form, Form will be submitted to ``` xyz.com/submit.php?theirname=john&theirpass=password // CHECK HERE - form elements are in URL so not so secure ``` and can be checked by PHP as ``` if(isset($_GET['their'])) { $name=$_GET['their']; //name will return John } ``` POST - If form method is POST then on submitting the form, Form will be submitted to ``` xyz.com/submit.php // CHECK HERE form elements are not in URL ``` and can be checked by PHP as ``` if(isset($_POST['their'])) { $name=$_POST['their']; //name will return John } ```
21,772,974
I am coding a PHP script, but I can't really seem to get it to work. I am testing out the basics, but I don't really understand what GET and POST means, what's the difference? All the definitions I've seen on the web make not much sense to me, what I've coded so far (but since I don't understand POST and GET, I don't know how to get it to work: ``` <form name="mail_sub" method="get"> Name: <input type="text" name="theirname"> <br /> Email:&nbsp; <input type="text" name="theirpass"> <br /> <input type="submit" value="Join!" style="width:200px"> </form> <?php if (isset($_POST['mail_sub'])) { echo $_POST['theirname']; } ?> ```
2014/02/14
[ "https://Stackoverflow.com/questions/21772974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3077765/" ]
To answer the question: GET and POST are one of the many `request types` in the standards of internet. The difference is that GET can't post data, parameters will be appended to the url (url-parameters) which has it's limitations. POST does post parameters/data. The standard is: * GET for getting data. * POST for creating data. * PUT for updating data. * DELETE for removing data.
Replace Your Code: ``` <form name="mail_sub" method="post"> Name: <input type="text" name="theirname"> <br /> Email:&nbsp; <input type="text" name="theirpass"> <br /> <input type="submit" name="submit" value="Join!" style="width:200px"> </form> <?php if (isset($_POST['submit'])) { echo $_POST['theirname']; } ?> ```
21,772,974
I am coding a PHP script, but I can't really seem to get it to work. I am testing out the basics, but I don't really understand what GET and POST means, what's the difference? All the definitions I've seen on the web make not much sense to me, what I've coded so far (but since I don't understand POST and GET, I don't know how to get it to work: ``` <form name="mail_sub" method="get"> Name: <input type="text" name="theirname"> <br /> Email:&nbsp; <input type="text" name="theirpass"> <br /> <input type="submit" value="Join!" style="width:200px"> </form> <?php if (isset($_POST['mail_sub'])) { echo $_POST['theirname']; } ?> ```
2014/02/14
[ "https://Stackoverflow.com/questions/21772974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3077765/" ]
$\_POST isn't working for you because you have the form method set to get. ``` <form name="mail_sub" method="post"> ``` There's plenty of better info online as to the difference between post and get so I won't go into that but this will fix the issue for you. Change your PHP as well. ``` if ( isset( $_POST['theirname'] ) ) { echo $_POST['theirname']; } ```
GET - If form method is GET then on submitting the form, Form will be submitted to ``` xyz.com/submit.php?theirname=john&theirpass=password // CHECK HERE - form elements are in URL so not so secure ``` and can be checked by PHP as ``` if(isset($_GET['their'])) { $name=$_GET['their']; //name will return John } ``` POST - If form method is POST then on submitting the form, Form will be submitted to ``` xyz.com/submit.php // CHECK HERE form elements are not in URL ``` and can be checked by PHP as ``` if(isset($_POST['their'])) { $name=$_POST['their']; //name will return John } ```
21,772,974
I am coding a PHP script, but I can't really seem to get it to work. I am testing out the basics, but I don't really understand what GET and POST means, what's the difference? All the definitions I've seen on the web make not much sense to me, what I've coded so far (but since I don't understand POST and GET, I don't know how to get it to work: ``` <form name="mail_sub" method="get"> Name: <input type="text" name="theirname"> <br /> Email:&nbsp; <input type="text" name="theirpass"> <br /> <input type="submit" value="Join!" style="width:200px"> </form> <?php if (isset($_POST['mail_sub'])) { echo $_POST['theirname']; } ?> ```
2014/02/14
[ "https://Stackoverflow.com/questions/21772974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3077765/" ]
To answer the question: GET and POST are one of the many `request types` in the standards of internet. The difference is that GET can't post data, parameters will be appended to the url (url-parameters) which has it's limitations. POST does post parameters/data. The standard is: * GET for getting data. * POST for creating data. * PUT for updating data. * DELETE for removing data.
you used method as GET in form,so your code should be like this ``` <?php echo $_SERVER['PHP_SELF'];?>//the form and action will be same page <form name="mail_sub" method="get" action="<?php echo $_SERVER['PHP_SELF'];?>"> Name: <input type="text" name="theirname"> <br /> Email:&nbsp; <input type="text" name="theirpass"> <br /> <input type="submit" value="Join!" style="width:200px"> </form> <?php echo $_GET['theirname']; ?> ```
21,772,974
I am coding a PHP script, but I can't really seem to get it to work. I am testing out the basics, but I don't really understand what GET and POST means, what's the difference? All the definitions I've seen on the web make not much sense to me, what I've coded so far (but since I don't understand POST and GET, I don't know how to get it to work: ``` <form name="mail_sub" method="get"> Name: <input type="text" name="theirname"> <br /> Email:&nbsp; <input type="text" name="theirpass"> <br /> <input type="submit" value="Join!" style="width:200px"> </form> <?php if (isset($_POST['mail_sub'])) { echo $_POST['theirname']; } ?> ```
2014/02/14
[ "https://Stackoverflow.com/questions/21772974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3077765/" ]
replace ``` isset($_POST['mail_sub']) ``` by ``` isset($_POST['theirname']) ``` The main difference between GET and POST requests is that in GET requests all parameter are part of the url and the user sees the parameters. In POST requests the url is not modified and all form parameter are hidden from the user. If you have no file uploads or very long field parameter use GET. Use POST when going in production.
you used method as GET in form,so your code should be like this ``` <?php echo $_SERVER['PHP_SELF'];?>//the form and action will be same page <form name="mail_sub" method="get" action="<?php echo $_SERVER['PHP_SELF'];?>"> Name: <input type="text" name="theirname"> <br /> Email:&nbsp; <input type="text" name="theirpass"> <br /> <input type="submit" value="Join!" style="width:200px"> </form> <?php echo $_GET['theirname']; ?> ```
21,772,974
I am coding a PHP script, but I can't really seem to get it to work. I am testing out the basics, but I don't really understand what GET and POST means, what's the difference? All the definitions I've seen on the web make not much sense to me, what I've coded so far (but since I don't understand POST and GET, I don't know how to get it to work: ``` <form name="mail_sub" method="get"> Name: <input type="text" name="theirname"> <br /> Email:&nbsp; <input type="text" name="theirpass"> <br /> <input type="submit" value="Join!" style="width:200px"> </form> <?php if (isset($_POST['mail_sub'])) { echo $_POST['theirname']; } ?> ```
2014/02/14
[ "https://Stackoverflow.com/questions/21772974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3077765/" ]
$\_POST isn't working for you because you have the form method set to get. ``` <form name="mail_sub" method="post"> ``` There's plenty of better info online as to the difference between post and get so I won't go into that but this will fix the issue for you. Change your PHP as well. ``` if ( isset( $_POST['theirname'] ) ) { echo $_POST['theirname']; } ```
replace ``` isset($_POST['mail_sub']) ``` by ``` isset($_POST['theirname']) ``` The main difference between GET and POST requests is that in GET requests all parameter are part of the url and the user sees the parameters. In POST requests the url is not modified and all form parameter are hidden from the user. If you have no file uploads or very long field parameter use GET. Use POST when going in production.
21,772,974
I am coding a PHP script, but I can't really seem to get it to work. I am testing out the basics, but I don't really understand what GET and POST means, what's the difference? All the definitions I've seen on the web make not much sense to me, what I've coded so far (but since I don't understand POST and GET, I don't know how to get it to work: ``` <form name="mail_sub" method="get"> Name: <input type="text" name="theirname"> <br /> Email:&nbsp; <input type="text" name="theirpass"> <br /> <input type="submit" value="Join!" style="width:200px"> </form> <?php if (isset($_POST['mail_sub'])) { echo $_POST['theirname']; } ?> ```
2014/02/14
[ "https://Stackoverflow.com/questions/21772974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3077765/" ]
$\_POST isn't working for you because you have the form method set to get. ``` <form name="mail_sub" method="post"> ``` There's plenty of better info online as to the difference between post and get so I won't go into that but this will fix the issue for you. Change your PHP as well. ``` if ( isset( $_POST['theirname'] ) ) { echo $_POST['theirname']; } ```
Post is like "sending" the data to the page without giving the user having any interaction with it, when Get shows the parameters in the URL and making it public for the user. Get is more often used on "unsecure" type of datatransactions like for example a searchform and POST is used when you want to make more secure things like a login form. Using a Get will give you like index.php?parameter=hello&parameter2=world In your example you should use either POST in the method attribute in the formtag or $\_GET in the php section So either ``` <form name="mail_sub" method="post"> Name: <input type="text" name="theirname"> <br /> Email:&nbsp; <input type="text" name="theirpass"> <br /> <input type="submit" value="Join!" style="width:200px"> </form> <?php if (isset($_POST['theirname'])) { echo $_POST['theirname']; } ?> ``` or ``` <form name="mail_sub" method="get"> Name: <input type="text" name="theirname"> <br /> Email:&nbsp; <input type="text" name="theirpass"> <br /> <input type="submit" value="Join!" style="width:200px"> </form> <?php if (isset($_GET['theirname'])) { echo $_GET['theirname']; } ?> ```
21,772,974
I am coding a PHP script, but I can't really seem to get it to work. I am testing out the basics, but I don't really understand what GET and POST means, what's the difference? All the definitions I've seen on the web make not much sense to me, what I've coded so far (but since I don't understand POST and GET, I don't know how to get it to work: ``` <form name="mail_sub" method="get"> Name: <input type="text" name="theirname"> <br /> Email:&nbsp; <input type="text" name="theirpass"> <br /> <input type="submit" value="Join!" style="width:200px"> </form> <?php if (isset($_POST['mail_sub'])) { echo $_POST['theirname']; } ?> ```
2014/02/14
[ "https://Stackoverflow.com/questions/21772974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3077765/" ]
replace ``` isset($_POST['mail_sub']) ``` by ``` isset($_POST['theirname']) ``` The main difference between GET and POST requests is that in GET requests all parameter are part of the url and the user sees the parameters. In POST requests the url is not modified and all form parameter are hidden from the user. If you have no file uploads or very long field parameter use GET. Use POST when going in production.
Replace Your Code: ``` <form name="mail_sub" method="post"> Name: <input type="text" name="theirname"> <br /> Email:&nbsp; <input type="text" name="theirpass"> <br /> <input type="submit" name="submit" value="Join!" style="width:200px"> </form> <?php if (isset($_POST['submit'])) { echo $_POST['theirname']; } ?> ```
39,350,744
I created a custom Lucene index in a Sitecore 8.1 environment like this: ```xml <?xml version="1.0"?> <configuration xmlns:x="http://www.sitecore.net/xmlconfig/"> <sitecore> <contentSearch> <configuration type="Sitecore.ContentSearch.ContentSearchConfiguration, Sitecore.ContentSearch"> <indexes hint="list:AddIndex"> <index id="Products_index" type="Sitecore.ContentSearch.LuceneProvider.LuceneIndex, Sitecore.ContentSearch.LuceneProvider"> <param desc="name">$(id)</param> <param desc="folder">$(id)</param> <param desc="propertyStore" ref="contentSearch/indexConfigurations/databasePropertyStore" param1="$(id)" /> <configuration ref="contentSearch/indexConfigurations/ProductIndexConfiguration" /> <strategies hint="list:AddStrategy"> <strategy ref="contentSearch/indexConfigurations/indexUpdateStrategies/onPublishEndAsync" /> </strategies> <commitPolicyExecutor type="Sitecore.ContentSearch.CommitPolicyExecutor, Sitecore.ContentSearch"> <policies hint="list:AddCommitPolicy"> <policy type="Sitecore.ContentSearch.TimeIntervalCommitPolicy, Sitecore.ContentSearch" /> </policies> </commitPolicyExecutor> <locations hint="list:AddCrawler"> <crawler type="Sitecore.ContentSearch.SitecoreItemCrawler, Sitecore.ContentSearch"> <Database>master</Database> <Root>/sitecore/content/General/Product Repository</Root> </crawler> </locations> <enableItemLanguageFallback>false</enableItemLanguageFallback> <enableFieldLanguageFallback>false</enableFieldLanguageFallback> </index> </indexes> </configuration> <indexConfigurations> <ProductIndexConfiguration type="Sitecore.ContentSearch.LuceneProvider.LuceneIndexConfiguration, Sitecore.ContentSearch.LuceneProvider"> <initializeOnAdd>true</initializeOnAdd> <analyzer ref="contentSearch/indexConfigurations/defaultLuceneIndexConfiguration/analyzer" /> <documentBuilderType>Sitecore.ContentSearch.LuceneProvider.LuceneDocumentBuilder, Sitecore.ContentSearch.LuceneProvider</documentBuilderType> <fieldMap type="Sitecore.ContentSearch.FieldMap, Sitecore.ContentSearch"> <fieldNames hint="raw:AddFieldByFieldName"> <field fieldName="_uniqueid" storageType="YES" indexType="TOKENIZED" vectorType="NO" boost="1f" type="System.String" settingType="Sitecore.ContentSearch.LuceneProvider.LuceneSearchFieldConfiguration, Sitecore.ContentSearch.LuceneProvider"> <analyzer type="Sitecore.ContentSearch.LuceneProvider.Analyzers.LowerCaseKeywordAnalyzer, Sitecore.ContentSearch.LuceneProvider" /> </field> <field fieldName="key" storageType="YES" indexType="UNTOKENIZED" vectorType="NO" boost="1f" type="System.String" settingType="Sitecore.ContentSearch.LuceneProvider.LuceneSearchFieldConfiguration, Sitecore.ContentSearch.LuceneProvider"/> </fieldNames> </fieldMap> <documentOptions type="Sitecore.ContentSearch.LuceneProvider.LuceneDocumentBuilderOptions, Sitecore.ContentSearch.LuceneProvider"> <indexAllFields>true</indexAllFields> <include hint="list:AddIncludedTemplate"> <Product>{843B9598-318D-4AFA-B8C8-07E3DF5C6738}</Product> </include> </documentOptions> <fieldReaders ref="contentSearch/indexConfigurations/defaultLuceneIndexConfiguration/fieldReaders"/> <indexFieldStorageValueFormatter ref="contentSearch/indexConfigurations/defaultLuceneIndexConfiguration/indexFieldStorageValueFormatter"/> <indexDocumentPropertyMapper ref="contentSearch/indexConfigurations/defaultLuceneIndexConfiguration/indexDocumentPropertyMapper"/> </ProductIndexConfiguration> </indexConfigurations> </contentSearch> </sitecore> </configuration> ``` Actually a quite straightforward index that points to a root, includes a template and stores a field. It all works. But I need something extra: * Limit the entries in the index to the latest version * Limit the entries in the index to one language (English) I know this can be easily triggered in the query as well, but I want to get my indexes smaller so they will (re)build faster. The first one could be solved by indexing web instead of master, but I actually also want the unpublished ones in this case. I'm quite sure I will need a custom crawler for this. The second one (limit the languages) is actually more important as I will also need this in other indexes. The easy answer is probably also to use a custom crawler but I was hoping there would be a way to configure this without custom code. Is it possible to configure an custom index to only include a defined set of languages (one or more) instead of all?
2016/09/06
[ "https://Stackoverflow.com/questions/39350744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6144330/" ]
After some research I came to the conclusion that to match all the requirements a custom crawler was the only solution. Blogged the code: <http://ggullentops.blogspot.be/2016/10/custom-sitecore-index-crawler.html> The main reason was that we really had to be able to set this per index - which is not possible with the filter approach. Also, when we added a new version the previous version had to be deleted from the index - also not possible without the crawler... There is quite some code so I won't copy it all here but we had to override the DoAdd and DoUpdate methods of the SitecoreItemCrawler, and for the languages we also had to make a small override of the Update method.
You can easily create a custom processor that will let you filter what you want: ```cs namespace Sitecore.Custom { public class CustomInboundIndexFilter : InboundIndexFilterProcessor { public override void Process(InboundIndexFilterArgs args) { var item = args.IndexableToIndex as SitecoreIndexableItem; var language = Sitecore.Data.Managers.LanguageManager.GetLanguage("en"); if (item != null && (!item.Item.Versions.IsLatestVersion() || item.Item.Language == language)) { args.IsExcluded = true; } } } } ``` And add this processor into the config: ```xml <pipelines> <indexing.filterIndex.inbound> <processor type="Sitecore.Custom.CustomInboundIndexFilter, Sitecore.Custom"></processor> </indexing.filterIndex.inbound> </pipelines> ```
39,386,415
I wrote a piece of code to learn more about `Comparator` function of java collection. I have two sets having 3 elements in each. and i want to compare. I post my code below and output of counter variable. Can anyone explain why variable `i` gives this weird output ?? I could not understand flow. ``` public class TestProductBundle { public static void main(String args[]) { TestProductBundle productBundle = new TestProductBundle(); Set<ClassA> hashSetA = new HashSet<ClassA>() { { add(new ClassA("name", 1, "desc")); add(new ClassA("name", 2, "desc")); add(new ClassA("name", 3, "desc")); } }; Set<ClassA> hashSetB = new HashSet<ClassA>() { { add(new ClassA("name1", 2, "desc1")); //"name" & "desc" are different than previous add(new ClassA("name2", 1, "desc2")); add(new ClassA("name3", 3, "desc3")); } }; if (productBundle.compareCollection(hashSetA, hashSetB)) { System.out.println("Equal set of tree"); } else { System.out.println("Unequal set of tree"); } } @SuppressWarnings("serial") public boolean compareCollection(Set<ClassA> collection1, Set<ClassA> collection2) { TreeSet<ClassA> treeSetA = new TreeSet<ClassA>(new CompareID()) { { addAll(collection1); } }; TreeSet<ClassA> treeSetB = new TreeSet<ClassA>(new CompareID()) { { addAll(collection2); } }; if (treeSetA.containsAll(treeSetB) && treeSetB.containsAll(treeSetA)) return true; else return false; } } ``` code for ClassA and class that implements Comparator. ``` class ClassA { String name; int id; String desc; public ClassA(String name, int id, String desc) { this.name = name; this.id = id; this.desc = desc; } int getId() { return id; } } ``` & ``` class CompareID implements Comparator<ClassA> { int i = 0; @Override public int compare(ClassA o1, ClassA o2) { System.out.println(i++); // Counter variable if (o1.getId() > o2.getId()) return 1; else if (o1.getId() < o2.getId()) return -1; else return 0; } } ``` output is (cross verified in debugger also) ``` 0 1 2 3 0 // why started from 0 again ? 1 2 3 4 5 6 7 8 4 // What the hell !!! 5 6 7 8 Equal set of tree // is that correct output ? ```
2016/09/08
[ "https://Stackoverflow.com/questions/39386415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3042916/" ]
I'm not sure what you are finding strange. You have **two** TreeSet instances, each having its own `CompareID` instance serving as `Comparator`, and each `CompareID` instance maintains it's own counter. Therefore it's not a surprise to see each counter values (0,1,2,etc...) appearing twice. As for the order of appearance of the counter values, that depends on the internal implementation of `TreeSet`. As for > > Equal set of tree // is that correct output ? > > > Yes, both sets contain the same elements. The order doesn't matter. To clarify - the methods `contains` and `containsAll` of `TreeSet` consider an element `x` to be contained in the `TreeSet` if `compare(x,y)==0` for some element `y` of the `TreeSet`, where `compare` is the `compare` method of the supplied `Comparator`. Therefore, in your example, only the `id` property determines if two elements are equal. The following scenario explains the output : ``` 0 // compare method of 1st CompareID object executed 1 // compare method of 1st CompareID object executed 2 // compare method of 1st CompareID object executed 3 // compare method of 1st CompareID object executed 0 // compare method of 2nd CompareID object executed 1 // compare method of 2nd CompareID object executed 2 // compare method of 2nd CompareID object executed 3 // compare method of 2nd CompareID object executed 4 // compare method of 1st CompareID object executed 5 // compare method of 1st CompareID object executed 6 // compare method of 1st CompareID object executed 7 // compare method of 1st CompareID object executed 8 // compare method of 1st CompareID object executed 4 // compare method of 2nd CompareID object executed 5 // compare method of 2nd CompareID object executed 6 // compare method of 2nd CompareID object executed 7 // compare method of 2nd CompareID object executed 8 // compare method of 2nd CompareID object executed ``` EDIT : First you are adding elements to the first `TreeSet` (hence `compare` of the first `Comparator` is called several times in a row), then you are adding elements to the second `TreeSet` (hence `compare` of the second `Comparator` is called several times in a row), then you call `treeSetA.containsAll(treeSetB)` which causes `compare` of the first `Comparator` to be called several times in a row, and finally you call `treeSetB.containsAll(treeSetA)` which causes `compare` of the second `Comparator` to be called several times in a row.
Here Variable i will be initialize for two comparator object , your are initializing i=0, as per your point here compare method will be executed for both sets not necessary to be in sequence, so whats happen is you are expecting sequence output but actually its not ``` 0// for set1(collection1) 1 2 3 // remember this value for set 1 0 // for set2(collection2) 1 2 3 4 5 6 7 8 4 for set1(collection1 which was 3 and now increment to 1 ) 5 6 7 8 ```
39,386,415
I wrote a piece of code to learn more about `Comparator` function of java collection. I have two sets having 3 elements in each. and i want to compare. I post my code below and output of counter variable. Can anyone explain why variable `i` gives this weird output ?? I could not understand flow. ``` public class TestProductBundle { public static void main(String args[]) { TestProductBundle productBundle = new TestProductBundle(); Set<ClassA> hashSetA = new HashSet<ClassA>() { { add(new ClassA("name", 1, "desc")); add(new ClassA("name", 2, "desc")); add(new ClassA("name", 3, "desc")); } }; Set<ClassA> hashSetB = new HashSet<ClassA>() { { add(new ClassA("name1", 2, "desc1")); //"name" & "desc" are different than previous add(new ClassA("name2", 1, "desc2")); add(new ClassA("name3", 3, "desc3")); } }; if (productBundle.compareCollection(hashSetA, hashSetB)) { System.out.println("Equal set of tree"); } else { System.out.println("Unequal set of tree"); } } @SuppressWarnings("serial") public boolean compareCollection(Set<ClassA> collection1, Set<ClassA> collection2) { TreeSet<ClassA> treeSetA = new TreeSet<ClassA>(new CompareID()) { { addAll(collection1); } }; TreeSet<ClassA> treeSetB = new TreeSet<ClassA>(new CompareID()) { { addAll(collection2); } }; if (treeSetA.containsAll(treeSetB) && treeSetB.containsAll(treeSetA)) return true; else return false; } } ``` code for ClassA and class that implements Comparator. ``` class ClassA { String name; int id; String desc; public ClassA(String name, int id, String desc) { this.name = name; this.id = id; this.desc = desc; } int getId() { return id; } } ``` & ``` class CompareID implements Comparator<ClassA> { int i = 0; @Override public int compare(ClassA o1, ClassA o2) { System.out.println(i++); // Counter variable if (o1.getId() > o2.getId()) return 1; else if (o1.getId() < o2.getId()) return -1; else return 0; } } ``` output is (cross verified in debugger also) ``` 0 1 2 3 0 // why started from 0 again ? 1 2 3 4 5 6 7 8 4 // What the hell !!! 5 6 7 8 Equal set of tree // is that correct output ? ```
2016/09/08
[ "https://Stackoverflow.com/questions/39386415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3042916/" ]
I'm not sure what you are finding strange. You have **two** TreeSet instances, each having its own `CompareID` instance serving as `Comparator`, and each `CompareID` instance maintains it's own counter. Therefore it's not a surprise to see each counter values (0,1,2,etc...) appearing twice. As for the order of appearance of the counter values, that depends on the internal implementation of `TreeSet`. As for > > Equal set of tree // is that correct output ? > > > Yes, both sets contain the same elements. The order doesn't matter. To clarify - the methods `contains` and `containsAll` of `TreeSet` consider an element `x` to be contained in the `TreeSet` if `compare(x,y)==0` for some element `y` of the `TreeSet`, where `compare` is the `compare` method of the supplied `Comparator`. Therefore, in your example, only the `id` property determines if two elements are equal. The following scenario explains the output : ``` 0 // compare method of 1st CompareID object executed 1 // compare method of 1st CompareID object executed 2 // compare method of 1st CompareID object executed 3 // compare method of 1st CompareID object executed 0 // compare method of 2nd CompareID object executed 1 // compare method of 2nd CompareID object executed 2 // compare method of 2nd CompareID object executed 3 // compare method of 2nd CompareID object executed 4 // compare method of 1st CompareID object executed 5 // compare method of 1st CompareID object executed 6 // compare method of 1st CompareID object executed 7 // compare method of 1st CompareID object executed 8 // compare method of 1st CompareID object executed 4 // compare method of 2nd CompareID object executed 5 // compare method of 2nd CompareID object executed 6 // compare method of 2nd CompareID object executed 7 // compare method of 2nd CompareID object executed 8 // compare method of 2nd CompareID object executed ``` EDIT : First you are adding elements to the first `TreeSet` (hence `compare` of the first `Comparator` is called several times in a row), then you are adding elements to the second `TreeSet` (hence `compare` of the second `Comparator` is called several times in a row), then you call `treeSetA.containsAll(treeSetB)` which causes `compare` of the first `Comparator` to be called several times in a row, and finally you call `treeSetB.containsAll(treeSetA)` which causes `compare` of the second `Comparator` to be called several times in a row.
Adding to @Erans answer. Change the code to the following and you´ll see which comperator does output when ``` class CompareID implements Comparator<ClassA> { int i = 0; String a; public CompareID(String input) { a = input; } @Override public int compare(ClassA o1, ClassA o2) { // Output comperator "id" System.out.println(a+ " " + i++); // Counter variable if (o1.getId() > o2.getId()) return 1; else if (o1.getId() < o2.getId()) return -1; else return 0; } } ... TreeSet<ClassA> treeSetA = new TreeSet<ClassA>(new CompareID("A")) { { addAll(collection1); } }; TreeSet<ClassA> treeSetB = new TreeSet<ClassA>(new CompareID("B")) { { addAll(collection2); } }; ``` The output will change to the following. The comments include what did produce the output: ``` // This is addALL treeSetA A 0 A 1 A 2 A 3 // this is addAll treeSetB B 0 B 1 B 2 B 3 // this is treeSetA.containsAll(treeSetB) A 4 A 5 A 6 A 7 A 8 // this is treeSetB.containsAll(treeSetA) B 4 B 5 B 6 B 7 B 8 ``` basicly both comperators just output ``` 0-8 0-8 ```
26,504,553
I have 5 imageviews and I am updating them based on value but the problem is for updating all of them I have redundant code for eacg image updation expect the specific imageView object. Here is example, I have such 5 methods to update each imageview which I guess is not optimal solution. ``` public void imageThird(int value){ third.setVisibility(View.VISIBLE); if(value >= 1000 && value <= 800) { third.setImageResource(R.drawable.sa); } else if(value >= 800 && value <= 500) { third.setImageResource(R.drawable.sb); } else if(value >= 500 && value <= 300) { third.setImageResource(R.drawable.sc); } else if(value >= 300 && value <= 150) { third.setImageResource(R.drawable.sd); } else if(value >= 150 && value <= 50) { third.setImageResource(R.drawable.se); } else { third.setImageResource(R.drawable.sa); } } ``` So I have 5 like this method, which is not good I guess, the only difference is the imageview object for each image. May be it is silly question I am not much aware about how images works in Andorid.
2014/10/22
[ "https://Stackoverflow.com/questions/26504553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4132634/" ]
I just tested it with a sample project. It works fine. There must be something wrong with your wiring up the cell. Here is my code. Only indicating changes from plain vanilla tab bar project template. ![enter image description here](https://i.stack.imgur.com/fAKkQ.png) ``` // FirstViewController.swift func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell cell.textLabel?.text = "Cell \(indexPath.row + 1)" return cell } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let detail = segue.destinationViewController as DetailController let cell = sender as UITableViewCell let indexPath = self.tableView.indexPathForCell(cell) detail.detailItem = "Cell \(indexPath!.row + 1)" } //DetailController.swift class DetailController: UIViewController { var detailItem : String! @IBOutlet var label : UILabel! override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) label.text = detailItem } } ```
for calling the method prepareForSegue you must have to add a segue to connect the prototype cell and the destination Controller! method doesn't called if you navigate to destination controller programmatically!
26,504,553
I have 5 imageviews and I am updating them based on value but the problem is for updating all of them I have redundant code for eacg image updation expect the specific imageView object. Here is example, I have such 5 methods to update each imageview which I guess is not optimal solution. ``` public void imageThird(int value){ third.setVisibility(View.VISIBLE); if(value >= 1000 && value <= 800) { third.setImageResource(R.drawable.sa); } else if(value >= 800 && value <= 500) { third.setImageResource(R.drawable.sb); } else if(value >= 500 && value <= 300) { third.setImageResource(R.drawable.sc); } else if(value >= 300 && value <= 150) { third.setImageResource(R.drawable.sd); } else if(value >= 150 && value <= 50) { third.setImageResource(R.drawable.se); } else { third.setImageResource(R.drawable.sa); } } ``` So I have 5 like this method, which is not good I guess, the only difference is the imageview object for each image. May be it is silly question I am not much aware about how images works in Andorid.
2014/10/22
[ "https://Stackoverflow.com/questions/26504553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4132634/" ]
This happened with me when I was registering cell in ViewDidLoad method using `tableView.register(AnyClass?, forCellReuseIdentifier: String)` When i commented this line and added the cell class and cell identifier in storyboard, it started working. Again if I uncomment that code in viewdidload, it stops working.
for calling the method prepareForSegue you must have to add a segue to connect the prototype cell and the destination Controller! method doesn't called if you navigate to destination controller programmatically!
1,787,006
I am working to integrate data from an external web service in the client side of my appliction. Someone asked me to test the condition when the service is unavailable or down. Anyone have any tips on how to block this site temporarily while we run the test to see how the service degrades? For those curious we are testing against Virtual Earth, but Google Maps but this would apply to any equally complicated external service. any thoughts and suggestions are welcome
2009/11/24
[ "https://Stackoverflow.com/questions/1787006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10676/" ]
Create some Mock-Webservice class or interface (and [inject](http://martinfowler.com/articles/injection.html) [it](http://www.youtube.com/watch?v=hBVJbzAagfs)). In there, you could test the response of your system to webservice failures and also what happens, if a web-service request take longer than expected or actually time-out. DeveloperWorks article on mock testing: <http://www.ibm.com/developerworks/library/j-mocktest.html>
How about blocking the domain name(s) in question by putting a nonsense entry into the `hosts` file?
1,787,006
I am working to integrate data from an external web service in the client side of my appliction. Someone asked me to test the condition when the service is unavailable or down. Anyone have any tips on how to block this site temporarily while we run the test to see how the service degrades? For those curious we are testing against Virtual Earth, but Google Maps but this would apply to any equally complicated external service. any thoughts and suggestions are welcome
2009/11/24
[ "https://Stackoverflow.com/questions/1787006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10676/" ]
You need to be sure to test the most common failure modes for this: 1. DNS lookup fails 2. IP connection fails (once DNS lookup succeeds) 3. HTTP response other than 200 4. HTTP response incomplete or timeout 5. HTTP response 200 but RPC or document returned is invalid Those are just a few common failure modes I could think of that will all manifest themselves with different behaviors that you may wish to have your application handle explicitly. If you set up a computer between the caller and service that routes between them, you can simulate each of these failure modes distinctly and modify your application to handle them.
How about blocking the domain name(s) in question by putting a nonsense entry into the `hosts` file?
56,761,464
I need to pick a random number from 31 to 359. ``` rand(31, 359); ``` I need the number is not part from this array of numbers: ``` $badNumbers = array(30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330, 360); ``` How can I do this please? Thanks.
2019/06/25
[ "https://Stackoverflow.com/questions/56761464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10296344/" ]
I would probably do this as it completes when one is found: ``` while(in_array($rand = rand(31, 359), $badNumbers)); echo $rand; ``` Here is another way using an array: ``` $good = array_diff(range(31, 359), $badNumbers); echo $good[array_rand($good)]; ``` Or randomize and choose one: ``` shuffle($good); echo array_pop($good); ``` The array approaches are useful if you need to pick more than one random number. Think `array_rand` again or `array_slice` for the second one.
What you need is a *recursive function* (which is a function that keeps calling itself with a condition to break out once the requirement is met) or an infinite loop that breaks when it finds a number that isn't in the array. What this means is that you try to generate a number, but if that number is in the list, you try again - and keep doing that until satisfied. Here's an example, ```php $badNumbers = array(30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330, 360); function rand_unique(array $array, int $new) { if (in_array($new, $array)) { return rand_unique($array, $new); } return $new; } $newRand = rand_unique($badNumbers, rand(31, 359)); echo $newRand; ``` * Live demo at <https://3v4l.org/mhTFc>
56,761,464
I need to pick a random number from 31 to 359. ``` rand(31, 359); ``` I need the number is not part from this array of numbers: ``` $badNumbers = array(30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330, 360); ``` How can I do this please? Thanks.
2019/06/25
[ "https://Stackoverflow.com/questions/56761464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10296344/" ]
What you need is a *recursive function* (which is a function that keeps calling itself with a condition to break out once the requirement is met) or an infinite loop that breaks when it finds a number that isn't in the array. What this means is that you try to generate a number, but if that number is in the list, you try again - and keep doing that until satisfied. Here's an example, ```php $badNumbers = array(30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330, 360); function rand_unique(array $array, int $new) { if (in_array($new, $array)) { return rand_unique($array, $new); } return $new; } $newRand = rand_unique($badNumbers, rand(31, 359)); echo $newRand; ``` * Live demo at <https://3v4l.org/mhTFc>
This creates an array containing only the good numbers and returns a random value. ``` $goodNumbers = array_diff(range(31,359),[$badNumbers]); $randIndex = array_rand($goodNumbers); $randomGoodNumber = $goodNumbers[$randIndex]; ```
56,761,464
I need to pick a random number from 31 to 359. ``` rand(31, 359); ``` I need the number is not part from this array of numbers: ``` $badNumbers = array(30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330, 360); ``` How can I do this please? Thanks.
2019/06/25
[ "https://Stackoverflow.com/questions/56761464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10296344/" ]
I would probably do this as it completes when one is found: ``` while(in_array($rand = rand(31, 359), $badNumbers)); echo $rand; ``` Here is another way using an array: ``` $good = array_diff(range(31, 359), $badNumbers); echo $good[array_rand($good)]; ``` Or randomize and choose one: ``` shuffle($good); echo array_pop($good); ``` The array approaches are useful if you need to pick more than one random number. Think `array_rand` again or `array_slice` for the second one.
This creates an array containing only the good numbers and returns a random value. ``` $goodNumbers = array_diff(range(31,359),[$badNumbers]); $randIndex = array_rand($goodNumbers); $randomGoodNumber = $goodNumbers[$randIndex]; ```
35,349
I'm making a game with target (orbit camera). I want to limit camera movements when in room. So that camera don't go through walls when moving around target and along the ground. What are common approaches? Any good links with tutorials? I use Unity3D, nevertheless I'm good with a general solution to the problem
2012/08/31
[ "https://gamedev.stackexchange.com/questions/35349", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/19462/" ]
Make a snake game with it. Make a shooter game with it. Make some simple well known games to start off. Once you've done this, you should be more confident with your engine, and making these games will give you ideas on where to keep going.
This is one of the classic problems of game engine development - your engine most probably is too generic. Pick your favorite genre, perhaps even your favorite game - and look at how things work there. Try to copy a thing or two. Make something good, make something bad. Create experiments and problems. Experiments are useful for finding a good direction to take, an unexplored path. Problems have a tendency to keep developers interested for a long time. Pick something you've never done before to make space for both.
35,349
I'm making a game with target (orbit camera). I want to limit camera movements when in room. So that camera don't go through walls when moving around target and along the ground. What are common approaches? Any good links with tutorials? I use Unity3D, nevertheless I'm good with a general solution to the problem
2012/08/31
[ "https://gamedev.stackexchange.com/questions/35349", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/19462/" ]
Make a snake game with it. Make a shooter game with it. Make some simple well known games to start off. Once you've done this, you should be more confident with your engine, and making these games will give you ideas on where to keep going.
Proceeding with levels seems like a good next step, it can teach you how to create data structures to fit your game, and file input/output. Also, I would just have tried to build the engine with a set target game in mind. You don't have to be very specific, but say just make the engine for a specific genre that you like. When you know what to make with your engine, you have a better idea of what actually works in your engine and what doesn't. A good engine would have been "battle-tested" already, and usable in real-world cases. I have been making a game around sample framework code- as I added more features to it that the game would definitely use, it became clearer which parts can be re-used for future games.
35,349
I'm making a game with target (orbit camera). I want to limit camera movements when in room. So that camera don't go through walls when moving around target and along the ground. What are common approaches? Any good links with tutorials? I use Unity3D, nevertheless I'm good with a general solution to the problem
2012/08/31
[ "https://gamedev.stackexchange.com/questions/35349", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/19462/" ]
Make a snake game with it. Make a shooter game with it. Make some simple well known games to start off. Once you've done this, you should be more confident with your engine, and making these games will give you ideas on where to keep going.
I disagree with @William 'MindWorX' Mariager regarding the nature of the question. It's game design and game programming related and belong here. @Tomas, you created the egg before the chicken. You want your coding to have a purpose first. This is how project and business works. Most game development team will create the game design (most of it)(like a Game Design Document) before starting the programming of the game. My studio has the inverse problem. We got a large amount of viable ideas, largely documented, and no game engine, modules or programmers to run/code it. I am even considering learning coding myself instead of waiting for the arrival of a miraculous coder. I remember my first game idea. I was playing a Zynga game on Facebook and I thought: "The game is okay, but it could be more fun" and then: "I could easily create a better game than this". Shortly after, I started creating it. I suggest you think about what game you could improve (without copying or breaching copyrights) and start focusing on this with your game engine. Also, try using brainstorm technics to stimulate and generate ideas and innovation.
35,349
I'm making a game with target (orbit camera). I want to limit camera movements when in room. So that camera don't go through walls when moving around target and along the ground. What are common approaches? Any good links with tutorials? I use Unity3D, nevertheless I'm good with a general solution to the problem
2012/08/31
[ "https://gamedev.stackexchange.com/questions/35349", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/19462/" ]
Go to LudumDare and see games that got a lot of positive attention in previous competitions. Play them and see which ones you like and simply develop on those ideas. Taking ideas from one game is stealing, taking from two or more is research.
This is one of the classic problems of game engine development - your engine most probably is too generic. Pick your favorite genre, perhaps even your favorite game - and look at how things work there. Try to copy a thing or two. Make something good, make something bad. Create experiments and problems. Experiments are useful for finding a good direction to take, an unexplored path. Problems have a tendency to keep developers interested for a long time. Pick something you've never done before to make space for both.
35,349
I'm making a game with target (orbit camera). I want to limit camera movements when in room. So that camera don't go through walls when moving around target and along the ground. What are common approaches? Any good links with tutorials? I use Unity3D, nevertheless I'm good with a general solution to the problem
2012/08/31
[ "https://gamedev.stackexchange.com/questions/35349", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/19462/" ]
This is one of the classic problems of game engine development - your engine most probably is too generic. Pick your favorite genre, perhaps even your favorite game - and look at how things work there. Try to copy a thing or two. Make something good, make something bad. Create experiments and problems. Experiments are useful for finding a good direction to take, an unexplored path. Problems have a tendency to keep developers interested for a long time. Pick something you've never done before to make space for both.
Proceeding with levels seems like a good next step, it can teach you how to create data structures to fit your game, and file input/output. Also, I would just have tried to build the engine with a set target game in mind. You don't have to be very specific, but say just make the engine for a specific genre that you like. When you know what to make with your engine, you have a better idea of what actually works in your engine and what doesn't. A good engine would have been "battle-tested" already, and usable in real-world cases. I have been making a game around sample framework code- as I added more features to it that the game would definitely use, it became clearer which parts can be re-used for future games.
35,349
I'm making a game with target (orbit camera). I want to limit camera movements when in room. So that camera don't go through walls when moving around target and along the ground. What are common approaches? Any good links with tutorials? I use Unity3D, nevertheless I'm good with a general solution to the problem
2012/08/31
[ "https://gamedev.stackexchange.com/questions/35349", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/19462/" ]
This is one of the classic problems of game engine development - your engine most probably is too generic. Pick your favorite genre, perhaps even your favorite game - and look at how things work there. Try to copy a thing or two. Make something good, make something bad. Create experiments and problems. Experiments are useful for finding a good direction to take, an unexplored path. Problems have a tendency to keep developers interested for a long time. Pick something you've never done before to make space for both.
I disagree with @William 'MindWorX' Mariager regarding the nature of the question. It's game design and game programming related and belong here. @Tomas, you created the egg before the chicken. You want your coding to have a purpose first. This is how project and business works. Most game development team will create the game design (most of it)(like a Game Design Document) before starting the programming of the game. My studio has the inverse problem. We got a large amount of viable ideas, largely documented, and no game engine, modules or programmers to run/code it. I am even considering learning coding myself instead of waiting for the arrival of a miraculous coder. I remember my first game idea. I was playing a Zynga game on Facebook and I thought: "The game is okay, but it could be more fun" and then: "I could easily create a better game than this". Shortly after, I started creating it. I suggest you think about what game you could improve (without copying or breaching copyrights) and start focusing on this with your game engine. Also, try using brainstorm technics to stimulate and generate ideas and innovation.
35,349
I'm making a game with target (orbit camera). I want to limit camera movements when in room. So that camera don't go through walls when moving around target and along the ground. What are common approaches? Any good links with tutorials? I use Unity3D, nevertheless I'm good with a general solution to the problem
2012/08/31
[ "https://gamedev.stackexchange.com/questions/35349", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/19462/" ]
Go to LudumDare and see games that got a lot of positive attention in previous competitions. Play them and see which ones you like and simply develop on those ideas. Taking ideas from one game is stealing, taking from two or more is research.
Proceeding with levels seems like a good next step, it can teach you how to create data structures to fit your game, and file input/output. Also, I would just have tried to build the engine with a set target game in mind. You don't have to be very specific, but say just make the engine for a specific genre that you like. When you know what to make with your engine, you have a better idea of what actually works in your engine and what doesn't. A good engine would have been "battle-tested" already, and usable in real-world cases. I have been making a game around sample framework code- as I added more features to it that the game would definitely use, it became clearer which parts can be re-used for future games.
35,349
I'm making a game with target (orbit camera). I want to limit camera movements when in room. So that camera don't go through walls when moving around target and along the ground. What are common approaches? Any good links with tutorials? I use Unity3D, nevertheless I'm good with a general solution to the problem
2012/08/31
[ "https://gamedev.stackexchange.com/questions/35349", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/19462/" ]
Go to LudumDare and see games that got a lot of positive attention in previous competitions. Play them and see which ones you like and simply develop on those ideas. Taking ideas from one game is stealing, taking from two or more is research.
I disagree with @William 'MindWorX' Mariager regarding the nature of the question. It's game design and game programming related and belong here. @Tomas, you created the egg before the chicken. You want your coding to have a purpose first. This is how project and business works. Most game development team will create the game design (most of it)(like a Game Design Document) before starting the programming of the game. My studio has the inverse problem. We got a large amount of viable ideas, largely documented, and no game engine, modules or programmers to run/code it. I am even considering learning coding myself instead of waiting for the arrival of a miraculous coder. I remember my first game idea. I was playing a Zynga game on Facebook and I thought: "The game is okay, but it could be more fun" and then: "I could easily create a better game than this". Shortly after, I started creating it. I suggest you think about what game you could improve (without copying or breaching copyrights) and start focusing on this with your game engine. Also, try using brainstorm technics to stimulate and generate ideas and innovation.
40,655,245
I'm trying to remove gray color outline of images. I saw that that outline means error because image tags don't have source properties. but if i add `src="image.jpg"`, hovering doesn't work. how to fix it? so confused.... this is my code ```css #item1 { background-image: url('cushion01.jpg'); height: 300px; width: 300px; background-repeat: no-repeat; background-size: cover; } #item1:hover { background-image: url('cushion-01.jpeg'); height: 300px; width: 300px; } ``` ```html <div class="secondary__item" style="width: 100%; height : 850px;"> <ul class="item-images"> <li class="item-image"> <img class="item" id="item1" src="image.jpg" /> </li> <li class="item-image"> <img class="item" id="item2" /> </li> </ul> <ul class="item-images"> <li class="item-image"> <img class="item" id="item3" /> </li> <li class="item-image"> <img class="item" id="item4" /> </li> </ul> </div> ```
2016/11/17
[ "https://Stackoverflow.com/questions/40655245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6650139/" ]
Strange thing is that you are trying to set background to `<img>` tag. If I were you I'd use `<div>` instead. Then It would be very simple: HTML: ``` <div class= "secondary__item" style="width: 100%; height : 850px;"> <ul class="item-images"> <li class="item-image"><div class="item" id="item1" ></div></li> <li class="item-image"><div class="item" id="item2" ></div></li> </ul> <ul class="item-images"> <li class="item-image"><div class="item" id="item3" ></div></li> <li class="item-image"><div class="item" id="item4" ></div></li> </ul> </div> ``` CSS: ``` .item { height:300px; width :300px; background-repeat: no-repeat; background-size : cover; /*you can remove it*/ border: 1px solid; } .item:hover { background-image: url('http://shushi168.com/data/out/114/36276270-image.png'); height:300px; width :300px; } ``` Here is a Fiddle: <https://jsfiddle.net/7kzu5qcy/2/>
Have you tried instead of using IDs to use the main identifier? like... ``` .item-image IMG { border:none; } ```
40,655,245
I'm trying to remove gray color outline of images. I saw that that outline means error because image tags don't have source properties. but if i add `src="image.jpg"`, hovering doesn't work. how to fix it? so confused.... this is my code ```css #item1 { background-image: url('cushion01.jpg'); height: 300px; width: 300px; background-repeat: no-repeat; background-size: cover; } #item1:hover { background-image: url('cushion-01.jpeg'); height: 300px; width: 300px; } ``` ```html <div class="secondary__item" style="width: 100%; height : 850px;"> <ul class="item-images"> <li class="item-image"> <img class="item" id="item1" src="image.jpg" /> </li> <li class="item-image"> <img class="item" id="item2" /> </li> </ul> <ul class="item-images"> <li class="item-image"> <img class="item" id="item3" /> </li> <li class="item-image"> <img class="item" id="item4" /> </li> </ul> </div> ```
2016/11/17
[ "https://Stackoverflow.com/questions/40655245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6650139/" ]
Strange thing is that you are trying to set background to `<img>` tag. If I were you I'd use `<div>` instead. Then It would be very simple: HTML: ``` <div class= "secondary__item" style="width: 100%; height : 850px;"> <ul class="item-images"> <li class="item-image"><div class="item" id="item1" ></div></li> <li class="item-image"><div class="item" id="item2" ></div></li> </ul> <ul class="item-images"> <li class="item-image"><div class="item" id="item3" ></div></li> <li class="item-image"><div class="item" id="item4" ></div></li> </ul> </div> ``` CSS: ``` .item { height:300px; width :300px; background-repeat: no-repeat; background-size : cover; /*you can remove it*/ border: 1px solid; } .item:hover { background-image: url('http://shushi168.com/data/out/114/36276270-image.png'); height:300px; width :300px; } ``` Here is a Fiddle: <https://jsfiddle.net/7kzu5qcy/2/>
Place this in your image tag ``` alt="" ```
40,655,245
I'm trying to remove gray color outline of images. I saw that that outline means error because image tags don't have source properties. but if i add `src="image.jpg"`, hovering doesn't work. how to fix it? so confused.... this is my code ```css #item1 { background-image: url('cushion01.jpg'); height: 300px; width: 300px; background-repeat: no-repeat; background-size: cover; } #item1:hover { background-image: url('cushion-01.jpeg'); height: 300px; width: 300px; } ``` ```html <div class="secondary__item" style="width: 100%; height : 850px;"> <ul class="item-images"> <li class="item-image"> <img class="item" id="item1" src="image.jpg" /> </li> <li class="item-image"> <img class="item" id="item2" /> </li> </ul> <ul class="item-images"> <li class="item-image"> <img class="item" id="item3" /> </li> <li class="item-image"> <img class="item" id="item4" /> </li> </ul> </div> ```
2016/11/17
[ "https://Stackoverflow.com/questions/40655245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6650139/" ]
Strange thing is that you are trying to set background to `<img>` tag. If I were you I'd use `<div>` instead. Then It would be very simple: HTML: ``` <div class= "secondary__item" style="width: 100%; height : 850px;"> <ul class="item-images"> <li class="item-image"><div class="item" id="item1" ></div></li> <li class="item-image"><div class="item" id="item2" ></div></li> </ul> <ul class="item-images"> <li class="item-image"><div class="item" id="item3" ></div></li> <li class="item-image"><div class="item" id="item4" ></div></li> </ul> </div> ``` CSS: ``` .item { height:300px; width :300px; background-repeat: no-repeat; background-size : cover; /*you can remove it*/ border: 1px solid; } .item:hover { background-image: url('http://shushi168.com/data/out/114/36276270-image.png'); height:300px; width :300px; } ``` Here is a Fiddle: <https://jsfiddle.net/7kzu5qcy/2/>
Try this: ```css item1:hover { border: none !important; display: block; } ```
40,655,245
I'm trying to remove gray color outline of images. I saw that that outline means error because image tags don't have source properties. but if i add `src="image.jpg"`, hovering doesn't work. how to fix it? so confused.... this is my code ```css #item1 { background-image: url('cushion01.jpg'); height: 300px; width: 300px; background-repeat: no-repeat; background-size: cover; } #item1:hover { background-image: url('cushion-01.jpeg'); height: 300px; width: 300px; } ``` ```html <div class="secondary__item" style="width: 100%; height : 850px;"> <ul class="item-images"> <li class="item-image"> <img class="item" id="item1" src="image.jpg" /> </li> <li class="item-image"> <img class="item" id="item2" /> </li> </ul> <ul class="item-images"> <li class="item-image"> <img class="item" id="item3" /> </li> <li class="item-image"> <img class="item" id="item4" /> </li> </ul> </div> ```
2016/11/17
[ "https://Stackoverflow.com/questions/40655245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6650139/" ]
Strange thing is that you are trying to set background to `<img>` tag. If I were you I'd use `<div>` instead. Then It would be very simple: HTML: ``` <div class= "secondary__item" style="width: 100%; height : 850px;"> <ul class="item-images"> <li class="item-image"><div class="item" id="item1" ></div></li> <li class="item-image"><div class="item" id="item2" ></div></li> </ul> <ul class="item-images"> <li class="item-image"><div class="item" id="item3" ></div></li> <li class="item-image"><div class="item" id="item4" ></div></li> </ul> </div> ``` CSS: ``` .item { height:300px; width :300px; background-repeat: no-repeat; background-size : cover; /*you can remove it*/ border: 1px solid; } .item:hover { background-image: url('http://shushi168.com/data/out/114/36276270-image.png'); height:300px; width :300px; } ``` Here is a Fiddle: <https://jsfiddle.net/7kzu5qcy/2/>
You can apply a simple hack using `margin` & `overflow` property of CSS. Something like this: ``` /* Image Container (Parent) */ .item-image { width: 298px; height: 298px; overflow: hidden; } /* Image (Child) */ .item-image img { margin: -1px; background: #eee; /* To show the area covered by image */ } ``` Have a look at the snippet below (*I've applied background color to image to show the image area*): ```css #item1 { background-image: url('cushion01.jpg'); height: 300px; width: 300px; background-repeat: no-repeat; background-size: cover; } #item1:hover { background-image: url('cushion-01.jpeg'); height: 300px; width: 300px; } .item-image { width: 298px; height: 298px; overflow: hidden; } .item-image img { margin: -1px; background: #eee; } ``` ```html <div class="secondary__item" style="width: 100%; height : 850px;"> <ul class="item-images"> <li class="item-image"> <img class="item" id="item1" src="image.jpg" /> </li> <li class="item-image"> <img class="item" id="item2" /> </li> </ul> <ul class="item-images"> <li class="item-image"> <img class="item" id="item3" /> </li> <li class="item-image"> <img class="item" id="item4" /> </li> </ul> </div> ``` Hope this helps!
40,655,245
I'm trying to remove gray color outline of images. I saw that that outline means error because image tags don't have source properties. but if i add `src="image.jpg"`, hovering doesn't work. how to fix it? so confused.... this is my code ```css #item1 { background-image: url('cushion01.jpg'); height: 300px; width: 300px; background-repeat: no-repeat; background-size: cover; } #item1:hover { background-image: url('cushion-01.jpeg'); height: 300px; width: 300px; } ``` ```html <div class="secondary__item" style="width: 100%; height : 850px;"> <ul class="item-images"> <li class="item-image"> <img class="item" id="item1" src="image.jpg" /> </li> <li class="item-image"> <img class="item" id="item2" /> </li> </ul> <ul class="item-images"> <li class="item-image"> <img class="item" id="item3" /> </li> <li class="item-image"> <img class="item" id="item4" /> </li> </ul> </div> ```
2016/11/17
[ "https://Stackoverflow.com/questions/40655245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6650139/" ]
Strange thing is that you are trying to set background to `<img>` tag. If I were you I'd use `<div>` instead. Then It would be very simple: HTML: ``` <div class= "secondary__item" style="width: 100%; height : 850px;"> <ul class="item-images"> <li class="item-image"><div class="item" id="item1" ></div></li> <li class="item-image"><div class="item" id="item2" ></div></li> </ul> <ul class="item-images"> <li class="item-image"><div class="item" id="item3" ></div></li> <li class="item-image"><div class="item" id="item4" ></div></li> </ul> </div> ``` CSS: ``` .item { height:300px; width :300px; background-repeat: no-repeat; background-size : cover; /*you can remove it*/ border: 1px solid; } .item:hover { background-image: url('http://shushi168.com/data/out/114/36276270-image.png'); height:300px; width :300px; } ``` Here is a Fiddle: <https://jsfiddle.net/7kzu5qcy/2/>
I see the answer to this is given in [chrome/safari display border around image](https://stackoverflow.com/questions/4743127/chrome-safari-display-border-around-image). ``` The reason cited is <img> tag does not have proper value in src attribute. ```
37,546,012
I trying to build a Simon game but I'm messing with CSS. [![simon game](https://i.stack.imgur.com/xWinG.jpg)](https://i.stack.imgur.com/xWinG.jpg) (source: [walmartimages.com](http://i5.walmartimages.com/dfw/dce07b8c-837a/k2-_c8eba155-7ff4-45e8-86ab-704862d4a446.v1.jpg)) I don't know my mistakes but inline-block isn't working as expected: ```css body { text-align: center; } #box { width: 500px; height: 500px; border-radius: 100%; position: relative; margin: auto; background-color: #333; top: 10vh; box-shadow: 0px 0px 12px #222; } #box .pad { width: 240px; height: 240px; float: left; left: 0px; border: 5px solid #333; box-shadow: 0px 0px 2px #222; display: inline-block; position: absolute; } #topLeft { background-color: green; border-top-left-radius: 100%; } #topRight { background-color: red; border-top-right-radius: 100%; /*right: 0;*/ } #bottomLeft { background-color: yellow; border-bottom-left-radius: 100%; } #bottomRight { background-color: blue; border-bottom-right-radius: 100%; } ``` ```html <body> <h1 id="header">freeCodeCamp JS Simon Game</h1> <div id="box"> <div class="pad" id="topLeft"></div> <div class="pad" id="topRight"></div> <div class="pad" id="bottomLeft"></div> <div class="pad" id="bottomRight"></div> </div> </body> ``` <https://jsfiddle.net/gbs4320m/> I tried to mix things up with different settings and consulted online resources but i couldn't figure out the problem. Please help!! Thanks in advance.
2016/05/31
[ "https://Stackoverflow.com/questions/37546012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3531612/" ]
Remove the position absolute: ```css body { text-align: center; } #box { width: 500px; height: 500px; border-radius: 100%; position: relative; margin: auto; background-color: #333; top: 10vh; box-shadow: 0px 0px 12px #222; } #box .pad { width: 240px; height: 240px; float: left; left: 0px; border: 5px solid #333; box-shadow: 0px 0px 2px #222; display: inline-block; } #topLeft { background-color: green; border-top-left-radius: 100%; } #topRight { background-color: red; border-top-right-radius: 100%; /*right: 0;*/ } #bottomLeft { background-color: yellow; border-bottom-left-radius: 100%; } #bottomRight { background-color: blue; border-bottom-right-radius: 100%; } ``` ```html <h1 id="header">freeCodeCamp JS Simon Game</h1> <div id="box"> <div class="pad" id="topLeft"></div> <div class="pad" id="topRight"></div> <div class="pad" id="bottomLeft"></div> <div class="pad" id="bottomRight"></div> </div> ```
Simply remove `position absolute:`and it works just fine.
37,546,012
I trying to build a Simon game but I'm messing with CSS. [![simon game](https://i.stack.imgur.com/xWinG.jpg)](https://i.stack.imgur.com/xWinG.jpg) (source: [walmartimages.com](http://i5.walmartimages.com/dfw/dce07b8c-837a/k2-_c8eba155-7ff4-45e8-86ab-704862d4a446.v1.jpg)) I don't know my mistakes but inline-block isn't working as expected: ```css body { text-align: center; } #box { width: 500px; height: 500px; border-radius: 100%; position: relative; margin: auto; background-color: #333; top: 10vh; box-shadow: 0px 0px 12px #222; } #box .pad { width: 240px; height: 240px; float: left; left: 0px; border: 5px solid #333; box-shadow: 0px 0px 2px #222; display: inline-block; position: absolute; } #topLeft { background-color: green; border-top-left-radius: 100%; } #topRight { background-color: red; border-top-right-radius: 100%; /*right: 0;*/ } #bottomLeft { background-color: yellow; border-bottom-left-radius: 100%; } #bottomRight { background-color: blue; border-bottom-right-radius: 100%; } ``` ```html <body> <h1 id="header">freeCodeCamp JS Simon Game</h1> <div id="box"> <div class="pad" id="topLeft"></div> <div class="pad" id="topRight"></div> <div class="pad" id="bottomLeft"></div> <div class="pad" id="bottomRight"></div> </div> </body> ``` <https://jsfiddle.net/gbs4320m/> I tried to mix things up with different settings and consulted online resources but i couldn't figure out the problem. Please help!! Thanks in advance.
2016/05/31
[ "https://Stackoverflow.com/questions/37546012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3531612/" ]
Remove the position absolute: ```css body { text-align: center; } #box { width: 500px; height: 500px; border-radius: 100%; position: relative; margin: auto; background-color: #333; top: 10vh; box-shadow: 0px 0px 12px #222; } #box .pad { width: 240px; height: 240px; float: left; left: 0px; border: 5px solid #333; box-shadow: 0px 0px 2px #222; display: inline-block; } #topLeft { background-color: green; border-top-left-radius: 100%; } #topRight { background-color: red; border-top-right-radius: 100%; /*right: 0;*/ } #bottomLeft { background-color: yellow; border-bottom-left-radius: 100%; } #bottomRight { background-color: blue; border-bottom-right-radius: 100%; } ``` ```html <h1 id="header">freeCodeCamp JS Simon Game</h1> <div id="box"> <div class="pad" id="topLeft"></div> <div class="pad" id="topRight"></div> <div class="pad" id="bottomLeft"></div> <div class="pad" id="bottomRight"></div> </div> ```
Firstly, you are setting various unnecessary `float:left`, `position:absolute`, `left:0px;` which conflicts with `inline-block` or just don't do anything in this scenario. So let's remove those and get the `#box .pad` definition much simpler: ``` #box .pad { width: 240px; height: 240px; border: 5px solid #333; box-shadow: 0px 0px 2px #222; display: inline-block; } ``` ```css body { text-align: center; } #box { width: 500px; height: 500px; border-radius: 100%; position: relative; margin: auto; background-color: #333; top: 10vh; box-shadow: 0px 0px 12px #222; } #box .pad { width: 240px; height: 240px; border: 5px solid #333; box-shadow: 0px 0px 2px #222; display: inline-block; } #topLeft { background-color: green; border-top-left-radius: 100%; } #topRight { background-color: red; border-top-right-radius: 100%; /*right: 0;*/ } #bottomLeft { background-color: yellow; border-bottom-left-radius: 100%; } #bottomRight { background-color: blue; border-bottom-right-radius: 100%; } ``` ```html <body> <h1 id="header">freeCodeCamp JS Simon Game</h1> <div id="box"> <div class="pad" id="topLeft"></div> <div class="pad" id="topRight"></div> <div class="pad" id="bottomLeft"></div> <div class="pad" id="bottomRight"></div> </div> </body> ``` That gets things in the right order but the segments are showing underneath each other. Why? Because of the way that spaces between `inline-block` elements is handled - see [this question](https://stackoverflow.com/questions/5078239/how-to-remove-the-space-between-inline-block-elements). There are various ways around this as described in the answers to that question but the simplest solution in your case is probably just to `float:left` instead of `display:inline-block`. This will show the elements next to each other and overflow them onto the next "line" in a similar way to `display:inline-block`, but without the spacing issue: ``` #box .pad { width: 240px; height: 240px; border: 5px solid #333; box-shadow: 0px 0px 2px #222; float:left; } ``` ```css body { text-align: center; } #box { width: 500px; height: 500px; border-radius: 100%; position: relative; margin: auto; background-color: #333; top: 10vh; box-shadow: 0px 0px 12px #222; } #box .pad { width: 240px; height: 240px; border: 5px solid #333; box-shadow: 0px 0px 2px #222; float:left; } #topLeft { background-color: green; border-top-left-radius: 100%; } #topRight { background-color: red; border-top-right-radius: 100%; /*right: 0;*/ } #bottomLeft { background-color: yellow; border-bottom-left-radius: 100%; } #bottomRight { background-color: blue; border-bottom-right-radius: 100%; } ``` ```html <body> <h1 id="header">freeCodeCamp JS Simon Game</h1> <div id="box"> <div class="pad" id="topLeft"></div> <div class="pad" id="topRight"></div> <div class="pad" id="bottomLeft"></div> <div class="pad" id="bottomRight"></div> </div> </body> ```
37,546,012
I trying to build a Simon game but I'm messing with CSS. [![simon game](https://i.stack.imgur.com/xWinG.jpg)](https://i.stack.imgur.com/xWinG.jpg) (source: [walmartimages.com](http://i5.walmartimages.com/dfw/dce07b8c-837a/k2-_c8eba155-7ff4-45e8-86ab-704862d4a446.v1.jpg)) I don't know my mistakes but inline-block isn't working as expected: ```css body { text-align: center; } #box { width: 500px; height: 500px; border-radius: 100%; position: relative; margin: auto; background-color: #333; top: 10vh; box-shadow: 0px 0px 12px #222; } #box .pad { width: 240px; height: 240px; float: left; left: 0px; border: 5px solid #333; box-shadow: 0px 0px 2px #222; display: inline-block; position: absolute; } #topLeft { background-color: green; border-top-left-radius: 100%; } #topRight { background-color: red; border-top-right-radius: 100%; /*right: 0;*/ } #bottomLeft { background-color: yellow; border-bottom-left-radius: 100%; } #bottomRight { background-color: blue; border-bottom-right-radius: 100%; } ``` ```html <body> <h1 id="header">freeCodeCamp JS Simon Game</h1> <div id="box"> <div class="pad" id="topLeft"></div> <div class="pad" id="topRight"></div> <div class="pad" id="bottomLeft"></div> <div class="pad" id="bottomRight"></div> </div> </body> ``` <https://jsfiddle.net/gbs4320m/> I tried to mix things up with different settings and consulted online resources but i couldn't figure out the problem. Please help!! Thanks in advance.
2016/05/31
[ "https://Stackoverflow.com/questions/37546012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3531612/" ]
Remove the position absolute: ```css body { text-align: center; } #box { width: 500px; height: 500px; border-radius: 100%; position: relative; margin: auto; background-color: #333; top: 10vh; box-shadow: 0px 0px 12px #222; } #box .pad { width: 240px; height: 240px; float: left; left: 0px; border: 5px solid #333; box-shadow: 0px 0px 2px #222; display: inline-block; } #topLeft { background-color: green; border-top-left-radius: 100%; } #topRight { background-color: red; border-top-right-radius: 100%; /*right: 0;*/ } #bottomLeft { background-color: yellow; border-bottom-left-radius: 100%; } #bottomRight { background-color: blue; border-bottom-right-radius: 100%; } ``` ```html <h1 id="header">freeCodeCamp JS Simon Game</h1> <div id="box"> <div class="pad" id="topLeft"></div> <div class="pad" id="topRight"></div> <div class="pad" id="bottomLeft"></div> <div class="pad" id="bottomRight"></div> </div> ```
You should use `position:relative` for your `#box pad` in CSS. Here is the updated link <https://jsfiddle.net/gbs4320m/2/>
37,546,012
I trying to build a Simon game but I'm messing with CSS. [![simon game](https://i.stack.imgur.com/xWinG.jpg)](https://i.stack.imgur.com/xWinG.jpg) (source: [walmartimages.com](http://i5.walmartimages.com/dfw/dce07b8c-837a/k2-_c8eba155-7ff4-45e8-86ab-704862d4a446.v1.jpg)) I don't know my mistakes but inline-block isn't working as expected: ```css body { text-align: center; } #box { width: 500px; height: 500px; border-radius: 100%; position: relative; margin: auto; background-color: #333; top: 10vh; box-shadow: 0px 0px 12px #222; } #box .pad { width: 240px; height: 240px; float: left; left: 0px; border: 5px solid #333; box-shadow: 0px 0px 2px #222; display: inline-block; position: absolute; } #topLeft { background-color: green; border-top-left-radius: 100%; } #topRight { background-color: red; border-top-right-radius: 100%; /*right: 0;*/ } #bottomLeft { background-color: yellow; border-bottom-left-radius: 100%; } #bottomRight { background-color: blue; border-bottom-right-radius: 100%; } ``` ```html <body> <h1 id="header">freeCodeCamp JS Simon Game</h1> <div id="box"> <div class="pad" id="topLeft"></div> <div class="pad" id="topRight"></div> <div class="pad" id="bottomLeft"></div> <div class="pad" id="bottomRight"></div> </div> </body> ``` <https://jsfiddle.net/gbs4320m/> I tried to mix things up with different settings and consulted online resources but i couldn't figure out the problem. Please help!! Thanks in advance.
2016/05/31
[ "https://Stackoverflow.com/questions/37546012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3531612/" ]
Firstly, you are setting various unnecessary `float:left`, `position:absolute`, `left:0px;` which conflicts with `inline-block` or just don't do anything in this scenario. So let's remove those and get the `#box .pad` definition much simpler: ``` #box .pad { width: 240px; height: 240px; border: 5px solid #333; box-shadow: 0px 0px 2px #222; display: inline-block; } ``` ```css body { text-align: center; } #box { width: 500px; height: 500px; border-radius: 100%; position: relative; margin: auto; background-color: #333; top: 10vh; box-shadow: 0px 0px 12px #222; } #box .pad { width: 240px; height: 240px; border: 5px solid #333; box-shadow: 0px 0px 2px #222; display: inline-block; } #topLeft { background-color: green; border-top-left-radius: 100%; } #topRight { background-color: red; border-top-right-radius: 100%; /*right: 0;*/ } #bottomLeft { background-color: yellow; border-bottom-left-radius: 100%; } #bottomRight { background-color: blue; border-bottom-right-radius: 100%; } ``` ```html <body> <h1 id="header">freeCodeCamp JS Simon Game</h1> <div id="box"> <div class="pad" id="topLeft"></div> <div class="pad" id="topRight"></div> <div class="pad" id="bottomLeft"></div> <div class="pad" id="bottomRight"></div> </div> </body> ``` That gets things in the right order but the segments are showing underneath each other. Why? Because of the way that spaces between `inline-block` elements is handled - see [this question](https://stackoverflow.com/questions/5078239/how-to-remove-the-space-between-inline-block-elements). There are various ways around this as described in the answers to that question but the simplest solution in your case is probably just to `float:left` instead of `display:inline-block`. This will show the elements next to each other and overflow them onto the next "line" in a similar way to `display:inline-block`, but without the spacing issue: ``` #box .pad { width: 240px; height: 240px; border: 5px solid #333; box-shadow: 0px 0px 2px #222; float:left; } ``` ```css body { text-align: center; } #box { width: 500px; height: 500px; border-radius: 100%; position: relative; margin: auto; background-color: #333; top: 10vh; box-shadow: 0px 0px 12px #222; } #box .pad { width: 240px; height: 240px; border: 5px solid #333; box-shadow: 0px 0px 2px #222; float:left; } #topLeft { background-color: green; border-top-left-radius: 100%; } #topRight { background-color: red; border-top-right-radius: 100%; /*right: 0;*/ } #bottomLeft { background-color: yellow; border-bottom-left-radius: 100%; } #bottomRight { background-color: blue; border-bottom-right-radius: 100%; } ``` ```html <body> <h1 id="header">freeCodeCamp JS Simon Game</h1> <div id="box"> <div class="pad" id="topLeft"></div> <div class="pad" id="topRight"></div> <div class="pad" id="bottomLeft"></div> <div class="pad" id="bottomRight"></div> </div> </body> ```
Simply remove `position absolute:`and it works just fine.
37,546,012
I trying to build a Simon game but I'm messing with CSS. [![simon game](https://i.stack.imgur.com/xWinG.jpg)](https://i.stack.imgur.com/xWinG.jpg) (source: [walmartimages.com](http://i5.walmartimages.com/dfw/dce07b8c-837a/k2-_c8eba155-7ff4-45e8-86ab-704862d4a446.v1.jpg)) I don't know my mistakes but inline-block isn't working as expected: ```css body { text-align: center; } #box { width: 500px; height: 500px; border-radius: 100%; position: relative; margin: auto; background-color: #333; top: 10vh; box-shadow: 0px 0px 12px #222; } #box .pad { width: 240px; height: 240px; float: left; left: 0px; border: 5px solid #333; box-shadow: 0px 0px 2px #222; display: inline-block; position: absolute; } #topLeft { background-color: green; border-top-left-radius: 100%; } #topRight { background-color: red; border-top-right-radius: 100%; /*right: 0;*/ } #bottomLeft { background-color: yellow; border-bottom-left-radius: 100%; } #bottomRight { background-color: blue; border-bottom-right-radius: 100%; } ``` ```html <body> <h1 id="header">freeCodeCamp JS Simon Game</h1> <div id="box"> <div class="pad" id="topLeft"></div> <div class="pad" id="topRight"></div> <div class="pad" id="bottomLeft"></div> <div class="pad" id="bottomRight"></div> </div> </body> ``` <https://jsfiddle.net/gbs4320m/> I tried to mix things up with different settings and consulted online resources but i couldn't figure out the problem. Please help!! Thanks in advance.
2016/05/31
[ "https://Stackoverflow.com/questions/37546012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3531612/" ]
You should use `position:relative` for your `#box pad` in CSS. Here is the updated link <https://jsfiddle.net/gbs4320m/2/>
Simply remove `position absolute:`and it works just fine.
16,035,976
I create a loop in Wordpress with the condition like this: 1. Display a specific post format (example: video) 2. Limiting the post number. In this case, I only want to display 2 posts. Here my code: ``` <?php $i = 1; if (have_posts()) : while (have_posts() && $i < 3) : the_post(); ?> <?php get_template_part( 'content-video', get_post_format() ); ?> <?php $i++; endwhile; ?> <?php else : ?> <?php get_template_part( 'content', 'none' ); ?> <?php endif; ?> ``` I already have file name content-video.php. Unfortunately, the loop does not work. Only displayed the first post, not a specific post (video post format) with template from content-video.php. Appreciate for any help, or alternative code. Thanks in advance.
2013/04/16
[ "https://Stackoverflow.com/questions/16035976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2098167/" ]
You can [use `Assume`](http://junit.sourceforge.net/javadoc/org/junit/Assume.html) to turn tests on/off conditionally: > > A set of methods useful for stating assumptions about the conditions in which a test is meaningful. A failed assumption does not mean the code is broken, but that the test provides no useful information. > > >
You can do this with JUnit Rules. There's a whole blog post dedicated to exactly your question [here](http://www.mikereedell.com/2011/12/15/JUnit-Conditional-Ignore-Using-Rules.html), but in short, you do the following: 1. Create a class that implements the `org.junit.rules.TestRule` interface. This interface contains the following method: `Statement apply(Statement base, Description description);` The `base` argument is actually your test, which you run by calling `base.execute()` -- well, the `apply()` method actually returns a `Statement` anonymous instance that will do that. In your anonymous `Statement` instance, you'll add the logic to determine whether or not the test should be run. See below for an example of a `TestRule` implementation that doesn't do anything except execute your test -- and yes, it's not particularly straighforward. 2. Once you've created your `TestRule` implementation, then you need to add the following lines to to your JUnit Test Class: `@Rule public MyTestRuleImpl conditionalTests;` Remember, the field *must* be public. And that's it. Good luck -- as I said, you may have to hack a little, but I believe there's a fair amount explained in the blog post. Otherwise, there should be other information on the internets (or in the JUnit sourc code). Here's a quick example of a TestRule implementation that doesn't do anything. ``` public abstract class SimpleRule implements TestRule { public Statement apply(final Statement base, final Description description) { return new Statement() { public void evaluate() throws Throwable { try { base.evaluate(); } catch (Throwable t) { t.printStackTrace(); } } }; } } ```
13,456,834
I need to execute the following function in a specific context. ``` setTimeout(function () { myFunction(); }, 1000 * 60); var changeDateFormat = function () { console.log(this); // this should be $('.myClass') // but I need to set it from setTimeout // any hints }; ``` P.S.: I am using Underscore.js and jQuery.
2012/11/19
[ "https://Stackoverflow.com/questions/13456834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1113216/" ]
You can use [jQuery.proxy](http://api.jquery.com/jQuery.proxy/). ``` setTimeout($.proxy(myFunction, $(".myClass")), 1000 * 60); ``` Here's an example: <http://jsfiddle.net/UwUQD/1/> As James said you can also use `apply` as jQuery does internally: ``` proxy = function() { return fn.apply( context, args.concat( core_slice.call( arguments ) ) ); }; ``` The first `apply` argument is the execution context (what you'll be able to access using `this`) and the second argument are other arguments you want to pass to myFunction. The `call` function is the same, but accepts additional arguments a bit differently. --- **Or use [bind](http://underscorejs.org/#bind) in Underscore.js** ``` setTimeout(_.bind(myFunction, $(".myClass")), 100); ``` <http://jsfiddle.net/UwUQD/3/>
You can set the scope of a function using the JavaScript call or apply functions. Maybe see this [tutorial](http://odetocode.com/blogs/scott/archive/2007/07/05/function-apply-and-function-call-in-javascript.aspx) for details on how they work. By setting the scope, you can set "this" to be whatever you want.
13,456,834
I need to execute the following function in a specific context. ``` setTimeout(function () { myFunction(); }, 1000 * 60); var changeDateFormat = function () { console.log(this); // this should be $('.myClass') // but I need to set it from setTimeout // any hints }; ``` P.S.: I am using Underscore.js and jQuery.
2012/11/19
[ "https://Stackoverflow.com/questions/13456834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1113216/" ]
You can use [jQuery.proxy](http://api.jquery.com/jQuery.proxy/). ``` setTimeout($.proxy(myFunction, $(".myClass")), 1000 * 60); ``` Here's an example: <http://jsfiddle.net/UwUQD/1/> As James said you can also use `apply` as jQuery does internally: ``` proxy = function() { return fn.apply( context, args.concat( core_slice.call( arguments ) ) ); }; ``` The first `apply` argument is the execution context (what you'll be able to access using `this`) and the second argument are other arguments you want to pass to myFunction. The `call` function is the same, but accepts additional arguments a bit differently. --- **Or use [bind](http://underscorejs.org/#bind) in Underscore.js** ``` setTimeout(_.bind(myFunction, $(".myClass")), 100); ``` <http://jsfiddle.net/UwUQD/3/>
Maybe something like this would help: ``` var changeDateFormat = function () { console.log(this); // this should be $('.myClass') // but I need to set it from setTimeout // any hints }; function callWithContext() { changeDateFormat.call($(".class")); } setTimeout(callWithContext, 1000 * 60); ```
13,456,834
I need to execute the following function in a specific context. ``` setTimeout(function () { myFunction(); }, 1000 * 60); var changeDateFormat = function () { console.log(this); // this should be $('.myClass') // but I need to set it from setTimeout // any hints }; ``` P.S.: I am using Underscore.js and jQuery.
2012/11/19
[ "https://Stackoverflow.com/questions/13456834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1113216/" ]
You can use [jQuery.proxy](http://api.jquery.com/jQuery.proxy/). ``` setTimeout($.proxy(myFunction, $(".myClass")), 1000 * 60); ``` Here's an example: <http://jsfiddle.net/UwUQD/1/> As James said you can also use `apply` as jQuery does internally: ``` proxy = function() { return fn.apply( context, args.concat( core_slice.call( arguments ) ) ); }; ``` The first `apply` argument is the execution context (what you'll be able to access using `this`) and the second argument are other arguments you want to pass to myFunction. The `call` function is the same, but accepts additional arguments a bit differently. --- **Or use [bind](http://underscorejs.org/#bind) in Underscore.js** ``` setTimeout(_.bind(myFunction, $(".myClass")), 100); ``` <http://jsfiddle.net/UwUQD/3/>
Call [`call`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/call) on the function you want invoked, passing your desired `this` object as the first parameter: ``` setTimeout(function () { myFunction.call($('.myClass')); }, 1000 * 60); ```
13,456,834
I need to execute the following function in a specific context. ``` setTimeout(function () { myFunction(); }, 1000 * 60); var changeDateFormat = function () { console.log(this); // this should be $('.myClass') // but I need to set it from setTimeout // any hints }; ``` P.S.: I am using Underscore.js and jQuery.
2012/11/19
[ "https://Stackoverflow.com/questions/13456834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1113216/" ]
You can use [jQuery.proxy](http://api.jquery.com/jQuery.proxy/). ``` setTimeout($.proxy(myFunction, $(".myClass")), 1000 * 60); ``` Here's an example: <http://jsfiddle.net/UwUQD/1/> As James said you can also use `apply` as jQuery does internally: ``` proxy = function() { return fn.apply( context, args.concat( core_slice.call( arguments ) ) ); }; ``` The first `apply` argument is the execution context (what you'll be able to access using `this`) and the second argument are other arguments you want to pass to myFunction. The `call` function is the same, but accepts additional arguments a bit differently. --- **Or use [bind](http://underscorejs.org/#bind) in Underscore.js** ``` setTimeout(_.bind(myFunction, $(".myClass")), 100); ``` <http://jsfiddle.net/UwUQD/3/>
You could use [bind](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind) to bind the callback to the desired context. The downside to this being that some browsers might not support this. But sticking to the basic principles of JS, a *closure* will serve you just perfectly, too: ``` var callBack = (function(that) {//<-- use "that" instead of "this" return function() { console.log(that); }; }($('.myClass')));//<-- pass value for that here setTimeout(callBack,60000); ```
38,753,092
Say I have two dataframes like the following: ``` n = c(2, 3, 5, 5, 6, 7) s = c("aa", "bb", "cc", "dd", "ee", "ff") b = c(2, 4, 5, 4, 3, 2) df = data.frame(n, s, b) # n s b #1 2 aa 2 #2 3 bb 4 #3 5 cc 5 #4 5 dd 4 #5 6 ee 3 #6 7 ff 2 n2 = c(5, 6, 7, 6) s2 = c("aa", "bb", "cc", "ll") b2 = c("hh", "nn", "ff", "dd") df2 = data.frame(n2, s2, b2) # n2 s2 b2 #1 5 aa hh #2 6 bb nn #3 7 cc ff #4 6 ll dd ``` I want to merge them to achieve the following result: ``` #n s b n2 s2 b2 #2 aa 2 5 aa hh #3 bb 4 6 bb nn #5 cc 5 7 cc ff #5 dd 4 6 ll dd ``` Basically, what I want to achieve is to merge the two dataframes whenever the values in s of the first data is found in either the s2 or the b2 columns of data2. I know that merge can work when I specify the two columns from each dataframe but I am not sure how to ADD the OR condition in the merge function. Or how to achieve this goal using other commands from packages such as dpylr. Also, to clarify, there will be a situation where s2 and b2 have matches with s column in the same row. If this is the case, then just merge them once.
2016/08/03
[ "https://Stackoverflow.com/questions/38753092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4962535/" ]
A coupld of problems: 1) you have built a couple of dataframes with factors which has a tendency to screw up matching and indexing, so I used stringsAsFactors =FALSE in hte dataframe calls. 2) you have an ambiguous situation with no stated resolution when both s2 and b2 have matches in the s column (as does occur in your example): ``` > df2[c("s")] <- list( c( df$s[pmax( match( df2$s2 , df$s), match(df2$b2, df$s),na.rm=TRUE)])) > df2 n2 s2 b2 s 1 5 aa hh aa 2 6 bb nn bb 3 7 cc ff ff 4 6 ll dd dd > df2[c("s")] <- list( c( df$s[pmin( match( df2$s2 , df$s), match(df2$b2, df$s),na.rm=TRUE)])) > df2 n2 s2 b2 s 1 5 aa hh aa 2 6 bb nn bb 3 7 cc ff cc 4 6 ll dd dd ``` Once you resolve the ambiguity to your satiusfaction just use the same method to extract and match the "b"s: ``` > df2[c("b")] <- list( c( df$b[pmin( match( df2$s2 , df$s), match(df2$b2, df$s),na.rm=TRUE)])) > df2 n2 s2 b2 s b 1 5 aa hh aa 2 2 6 bb nn bb 4 3 7 cc ff cc 5 4 6 ll dd dd 4 ``` Modified df's: ``` > dput(df) structure(list(n = c(2, 3, 5, 5, 6, 7), s = c("aa", "bb", "cc", "dd", "ee", "ff"), b = c(2, 4, 5, 4, 3, 2)), .Names = c("n", "s", "b"), row.names = c(NA, -6L), class = "data.frame") > dput(df2) structure(list(n2 = c(5, 6, 7, 6), s2 = c("aa", "bb", "cc", "ll" ), b2 = c("hh", "nn", "ff", "dd"), s = c("aa", "bb", "cc", "dd" ), b = c(2, 4, 5, 4)), row.names = c(NA, -4L), .Names = c("n2", "s2", "b2", "s", "b"), class = "data.frame") ``` One step solution: ``` > df2[c("s", "c")] <- df[pmin( match( df2$s2 , df$s), match(df2$b2, df$s),na.rm=TRUE), c("s", "b")] > df2 n2 s2 b2 s c 1 5 aa hh aa 2 2 6 bb nn bb 4 3 7 cc ff cc 5 4 6 ll dd dd 4 ```
If you are familiar with SQL you could use that: ``` library(sqldf) res <- sqldf("SELECT l.*, r.* FROM df as l INNER JOIN df2 as r on l.s = r.s2 OR l.s = r.b2") res n s b n2 s2 b2 1 2 aa 2 5 aa hh 2 3 bb 4 6 bb nn 3 5 cc 5 7 cc ff 4 5 dd 4 6 ll dd 5 7 ff 2 7 cc ff ``` **Data**: ``` df<-structure(list(n = c(2, 3, 5, 5, 6, 7), s = structure(1:6, .Label = c("aa", "bb", "cc", "dd", "ee", "ff"), class = "factor"), b = c(2, 4, 5, 4, 3, 2)), .Names = c("n", "s", "b"), row.names = c(NA, -6L ), class = "data.frame") df2<-structure(list(n2 = c(5, 6, 7, 6), s2 = structure(1:4, .Label = c("aa", "bb", "cc", "ll"), class = "factor"), b2 = structure(c(3L, 4L, 2L, 1L), .Label = c("dd", "ff", "hh", "nn"), class = "factor")), .Names = c("n2", "s2", "b2"), row.names = c(NA, -4L), class = "data.frame") ```
38,753,092
Say I have two dataframes like the following: ``` n = c(2, 3, 5, 5, 6, 7) s = c("aa", "bb", "cc", "dd", "ee", "ff") b = c(2, 4, 5, 4, 3, 2) df = data.frame(n, s, b) # n s b #1 2 aa 2 #2 3 bb 4 #3 5 cc 5 #4 5 dd 4 #5 6 ee 3 #6 7 ff 2 n2 = c(5, 6, 7, 6) s2 = c("aa", "bb", "cc", "ll") b2 = c("hh", "nn", "ff", "dd") df2 = data.frame(n2, s2, b2) # n2 s2 b2 #1 5 aa hh #2 6 bb nn #3 7 cc ff #4 6 ll dd ``` I want to merge them to achieve the following result: ``` #n s b n2 s2 b2 #2 aa 2 5 aa hh #3 bb 4 6 bb nn #5 cc 5 7 cc ff #5 dd 4 6 ll dd ``` Basically, what I want to achieve is to merge the two dataframes whenever the values in s of the first data is found in either the s2 or the b2 columns of data2. I know that merge can work when I specify the two columns from each dataframe but I am not sure how to ADD the OR condition in the merge function. Or how to achieve this goal using other commands from packages such as dpylr. Also, to clarify, there will be a situation where s2 and b2 have matches with s column in the same row. If this is the case, then just merge them once.
2016/08/03
[ "https://Stackoverflow.com/questions/38753092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4962535/" ]
If you are familiar with SQL you could use that: ``` library(sqldf) res <- sqldf("SELECT l.*, r.* FROM df as l INNER JOIN df2 as r on l.s = r.s2 OR l.s = r.b2") res n s b n2 s2 b2 1 2 aa 2 5 aa hh 2 3 bb 4 6 bb nn 3 5 cc 5 7 cc ff 4 5 dd 4 6 ll dd 5 7 ff 2 7 cc ff ``` **Data**: ``` df<-structure(list(n = c(2, 3, 5, 5, 6, 7), s = structure(1:6, .Label = c("aa", "bb", "cc", "dd", "ee", "ff"), class = "factor"), b = c(2, 4, 5, 4, 3, 2)), .Names = c("n", "s", "b"), row.names = c(NA, -6L ), class = "data.frame") df2<-structure(list(n2 = c(5, 6, 7, 6), s2 = structure(1:4, .Label = c("aa", "bb", "cc", "ll"), class = "factor"), b2 = structure(c(3L, 4L, 2L, 1L), .Label = c("dd", "ff", "hh", "nn"), class = "factor")), .Names = c("n2", "s2", "b2"), row.names = c(NA, -4L), class = "data.frame") ```
One base approach is rbinding two merges. You need to re-create the corresponding join keys in `df2` to effectively concatenate the frames. Also, #5 row does not emerge in desired results: ``` t1 <- merge(df, df2, by.x=c("s"), by.y=c("s2")) t1$s2 <- t1$s t2 <- merge(df, df2, by.x=c("s"), by.y=c("b2")) t2$b2 <- t2$s finaldf <- rbind(t1, t2) # s n b n2 b2 s2 # 1 aa 2 2 5 hh aa # 2 bb 3 4 6 nn bb # 3 cc 5 5 7 ff cc # 4 dd 5 4 6 dd ll # 5 ff 7 2 7 ff cc ```
38,753,092
Say I have two dataframes like the following: ``` n = c(2, 3, 5, 5, 6, 7) s = c("aa", "bb", "cc", "dd", "ee", "ff") b = c(2, 4, 5, 4, 3, 2) df = data.frame(n, s, b) # n s b #1 2 aa 2 #2 3 bb 4 #3 5 cc 5 #4 5 dd 4 #5 6 ee 3 #6 7 ff 2 n2 = c(5, 6, 7, 6) s2 = c("aa", "bb", "cc", "ll") b2 = c("hh", "nn", "ff", "dd") df2 = data.frame(n2, s2, b2) # n2 s2 b2 #1 5 aa hh #2 6 bb nn #3 7 cc ff #4 6 ll dd ``` I want to merge them to achieve the following result: ``` #n s b n2 s2 b2 #2 aa 2 5 aa hh #3 bb 4 6 bb nn #5 cc 5 7 cc ff #5 dd 4 6 ll dd ``` Basically, what I want to achieve is to merge the two dataframes whenever the values in s of the first data is found in either the s2 or the b2 columns of data2. I know that merge can work when I specify the two columns from each dataframe but I am not sure how to ADD the OR condition in the merge function. Or how to achieve this goal using other commands from packages such as dpylr. Also, to clarify, there will be a situation where s2 and b2 have matches with s column in the same row. If this is the case, then just merge them once.
2016/08/03
[ "https://Stackoverflow.com/questions/38753092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4962535/" ]
A coupld of problems: 1) you have built a couple of dataframes with factors which has a tendency to screw up matching and indexing, so I used stringsAsFactors =FALSE in hte dataframe calls. 2) you have an ambiguous situation with no stated resolution when both s2 and b2 have matches in the s column (as does occur in your example): ``` > df2[c("s")] <- list( c( df$s[pmax( match( df2$s2 , df$s), match(df2$b2, df$s),na.rm=TRUE)])) > df2 n2 s2 b2 s 1 5 aa hh aa 2 6 bb nn bb 3 7 cc ff ff 4 6 ll dd dd > df2[c("s")] <- list( c( df$s[pmin( match( df2$s2 , df$s), match(df2$b2, df$s),na.rm=TRUE)])) > df2 n2 s2 b2 s 1 5 aa hh aa 2 6 bb nn bb 3 7 cc ff cc 4 6 ll dd dd ``` Once you resolve the ambiguity to your satiusfaction just use the same method to extract and match the "b"s: ``` > df2[c("b")] <- list( c( df$b[pmin( match( df2$s2 , df$s), match(df2$b2, df$s),na.rm=TRUE)])) > df2 n2 s2 b2 s b 1 5 aa hh aa 2 2 6 bb nn bb 4 3 7 cc ff cc 5 4 6 ll dd dd 4 ``` Modified df's: ``` > dput(df) structure(list(n = c(2, 3, 5, 5, 6, 7), s = c("aa", "bb", "cc", "dd", "ee", "ff"), b = c(2, 4, 5, 4, 3, 2)), .Names = c("n", "s", "b"), row.names = c(NA, -6L), class = "data.frame") > dput(df2) structure(list(n2 = c(5, 6, 7, 6), s2 = c("aa", "bb", "cc", "ll" ), b2 = c("hh", "nn", "ff", "dd"), s = c("aa", "bb", "cc", "dd" ), b = c(2, 4, 5, 4)), row.names = c(NA, -4L), .Names = c("n2", "s2", "b2", "s", "b"), class = "data.frame") ``` One step solution: ``` > df2[c("s", "c")] <- df[pmin( match( df2$s2 , df$s), match(df2$b2, df$s),na.rm=TRUE), c("s", "b")] > df2 n2 s2 b2 s c 1 5 aa hh aa 2 2 6 bb nn bb 4 3 7 cc ff cc 5 4 6 ll dd dd 4 ```
One base approach is rbinding two merges. You need to re-create the corresponding join keys in `df2` to effectively concatenate the frames. Also, #5 row does not emerge in desired results: ``` t1 <- merge(df, df2, by.x=c("s"), by.y=c("s2")) t1$s2 <- t1$s t2 <- merge(df, df2, by.x=c("s"), by.y=c("b2")) t2$b2 <- t2$s finaldf <- rbind(t1, t2) # s n b n2 b2 s2 # 1 aa 2 2 5 hh aa # 2 bb 3 4 6 nn bb # 3 cc 5 5 7 ff cc # 4 dd 5 4 6 dd ll # 5 ff 7 2 7 ff cc ```
38,753,092
Say I have two dataframes like the following: ``` n = c(2, 3, 5, 5, 6, 7) s = c("aa", "bb", "cc", "dd", "ee", "ff") b = c(2, 4, 5, 4, 3, 2) df = data.frame(n, s, b) # n s b #1 2 aa 2 #2 3 bb 4 #3 5 cc 5 #4 5 dd 4 #5 6 ee 3 #6 7 ff 2 n2 = c(5, 6, 7, 6) s2 = c("aa", "bb", "cc", "ll") b2 = c("hh", "nn", "ff", "dd") df2 = data.frame(n2, s2, b2) # n2 s2 b2 #1 5 aa hh #2 6 bb nn #3 7 cc ff #4 6 ll dd ``` I want to merge them to achieve the following result: ``` #n s b n2 s2 b2 #2 aa 2 5 aa hh #3 bb 4 6 bb nn #5 cc 5 7 cc ff #5 dd 4 6 ll dd ``` Basically, what I want to achieve is to merge the two dataframes whenever the values in s of the first data is found in either the s2 or the b2 columns of data2. I know that merge can work when I specify the two columns from each dataframe but I am not sure how to ADD the OR condition in the merge function. Or how to achieve this goal using other commands from packages such as dpylr. Also, to clarify, there will be a situation where s2 and b2 have matches with s column in the same row. If this is the case, then just merge them once.
2016/08/03
[ "https://Stackoverflow.com/questions/38753092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4962535/" ]
A coupld of problems: 1) you have built a couple of dataframes with factors which has a tendency to screw up matching and indexing, so I used stringsAsFactors =FALSE in hte dataframe calls. 2) you have an ambiguous situation with no stated resolution when both s2 and b2 have matches in the s column (as does occur in your example): ``` > df2[c("s")] <- list( c( df$s[pmax( match( df2$s2 , df$s), match(df2$b2, df$s),na.rm=TRUE)])) > df2 n2 s2 b2 s 1 5 aa hh aa 2 6 bb nn bb 3 7 cc ff ff 4 6 ll dd dd > df2[c("s")] <- list( c( df$s[pmin( match( df2$s2 , df$s), match(df2$b2, df$s),na.rm=TRUE)])) > df2 n2 s2 b2 s 1 5 aa hh aa 2 6 bb nn bb 3 7 cc ff cc 4 6 ll dd dd ``` Once you resolve the ambiguity to your satiusfaction just use the same method to extract and match the "b"s: ``` > df2[c("b")] <- list( c( df$b[pmin( match( df2$s2 , df$s), match(df2$b2, df$s),na.rm=TRUE)])) > df2 n2 s2 b2 s b 1 5 aa hh aa 2 2 6 bb nn bb 4 3 7 cc ff cc 5 4 6 ll dd dd 4 ``` Modified df's: ``` > dput(df) structure(list(n = c(2, 3, 5, 5, 6, 7), s = c("aa", "bb", "cc", "dd", "ee", "ff"), b = c(2, 4, 5, 4, 3, 2)), .Names = c("n", "s", "b"), row.names = c(NA, -6L), class = "data.frame") > dput(df2) structure(list(n2 = c(5, 6, 7, 6), s2 = c("aa", "bb", "cc", "ll" ), b2 = c("hh", "nn", "ff", "dd"), s = c("aa", "bb", "cc", "dd" ), b = c(2, 4, 5, 4)), row.names = c(NA, -4L), .Names = c("n2", "s2", "b2", "s", "b"), class = "data.frame") ``` One step solution: ``` > df2[c("s", "c")] <- df[pmin( match( df2$s2 , df$s), match(df2$b2, df$s),na.rm=TRUE), c("s", "b")] > df2 n2 s2 b2 s c 1 5 aa hh aa 2 2 6 bb nn bb 4 3 7 cc ff cc 5 4 6 ll dd dd 4 ```
We could use a fuzzy join, it might not be very efficient in this case if you have big data but it's certainly readable. Using my package [*safejoin*](https://github.com/moodymudskipper/safejoin) which wraps (in this case) around *fuzzyjoin* : ``` # devtools::install_github("moodymudskipper/safejoin") library(safejoin) safe_inner_join(df, df2, ~ X("s") == Y("s2") | X("s") == Y("b2")) # n s b n2 s2 b2 # 1 2 aa 2 5 aa hh # 2 3 bb 4 6 bb nn # 3 5 cc 5 7 cc ff # 4 5 dd 4 6 ll dd # 5 7 ff 2 7 cc ff ``` The *fuzzyjoin* syntax would be: ``` library(fuzzyjoin) fuzzy_inner_join(df, df2, match_fun = NULL, multi_by = list(x = "s", y= c("s2","b2")), multi_match_fun = function(x,y) x == y[,"s2"] | x == y[,"b2"]) # n s b n2 s2 b2 # 1 2 aa 2 5 aa hh # 2 3 bb 4 6 bb nn # 3 5 cc 5 7 cc ff # 4 5 dd 4 6 ll dd # 5 7 ff 2 7 cc ff ```
38,753,092
Say I have two dataframes like the following: ``` n = c(2, 3, 5, 5, 6, 7) s = c("aa", "bb", "cc", "dd", "ee", "ff") b = c(2, 4, 5, 4, 3, 2) df = data.frame(n, s, b) # n s b #1 2 aa 2 #2 3 bb 4 #3 5 cc 5 #4 5 dd 4 #5 6 ee 3 #6 7 ff 2 n2 = c(5, 6, 7, 6) s2 = c("aa", "bb", "cc", "ll") b2 = c("hh", "nn", "ff", "dd") df2 = data.frame(n2, s2, b2) # n2 s2 b2 #1 5 aa hh #2 6 bb nn #3 7 cc ff #4 6 ll dd ``` I want to merge them to achieve the following result: ``` #n s b n2 s2 b2 #2 aa 2 5 aa hh #3 bb 4 6 bb nn #5 cc 5 7 cc ff #5 dd 4 6 ll dd ``` Basically, what I want to achieve is to merge the two dataframes whenever the values in s of the first data is found in either the s2 or the b2 columns of data2. I know that merge can work when I specify the two columns from each dataframe but I am not sure how to ADD the OR condition in the merge function. Or how to achieve this goal using other commands from packages such as dpylr. Also, to clarify, there will be a situation where s2 and b2 have matches with s column in the same row. If this is the case, then just merge them once.
2016/08/03
[ "https://Stackoverflow.com/questions/38753092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4962535/" ]
We could use a fuzzy join, it might not be very efficient in this case if you have big data but it's certainly readable. Using my package [*safejoin*](https://github.com/moodymudskipper/safejoin) which wraps (in this case) around *fuzzyjoin* : ``` # devtools::install_github("moodymudskipper/safejoin") library(safejoin) safe_inner_join(df, df2, ~ X("s") == Y("s2") | X("s") == Y("b2")) # n s b n2 s2 b2 # 1 2 aa 2 5 aa hh # 2 3 bb 4 6 bb nn # 3 5 cc 5 7 cc ff # 4 5 dd 4 6 ll dd # 5 7 ff 2 7 cc ff ``` The *fuzzyjoin* syntax would be: ``` library(fuzzyjoin) fuzzy_inner_join(df, df2, match_fun = NULL, multi_by = list(x = "s", y= c("s2","b2")), multi_match_fun = function(x,y) x == y[,"s2"] | x == y[,"b2"]) # n s b n2 s2 b2 # 1 2 aa 2 5 aa hh # 2 3 bb 4 6 bb nn # 3 5 cc 5 7 cc ff # 4 5 dd 4 6 ll dd # 5 7 ff 2 7 cc ff ```
One base approach is rbinding two merges. You need to re-create the corresponding join keys in `df2` to effectively concatenate the frames. Also, #5 row does not emerge in desired results: ``` t1 <- merge(df, df2, by.x=c("s"), by.y=c("s2")) t1$s2 <- t1$s t2 <- merge(df, df2, by.x=c("s"), by.y=c("b2")) t2$b2 <- t2$s finaldf <- rbind(t1, t2) # s n b n2 b2 s2 # 1 aa 2 2 5 hh aa # 2 bb 3 4 6 nn bb # 3 cc 5 5 7 ff cc # 4 dd 5 4 6 dd ll # 5 ff 7 2 7 ff cc ```