qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
list
response
stringlengths
0
115k
229,759
I've tried to use solution from [Can I prepopulate an exposed filter text field?](https://drupal.stackexchange.com/questions/35504/can-i-prepopulate-an-exposed-filter-text-field) but failed. Cache clearing does not help. ``` function mymodule_form_alter(&$form, &$form_state, $form_id) { if ($form_id == "views_exposed_form" && $form['#id'] == "views-exposed-form-test-populate-page" ) { $form['title']['#default_value'] = 'test title'; dpm($form); } } ``` [![enter image description here](https://i.stack.imgur.com/GH8m3.png)](https://i.stack.imgur.com/GH8m3.png)
2017/02/27
[ "https://drupal.stackexchange.com/questions/229759", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/20459/" ]
I think I've figured this out. You need to define the 'content\_translation\_source' property on the translated node, so that Drupal knows what language it's coming from. Eg: **migrate\_plus.migration.articles\_fr.yml** ``` process: #... content_translation_source: plugin: default_value default_value: en #... ``` (Be sure to substitute the value `en` for whatever language you've first imported content -- the example in the OP uses English, but this might be anything). --- I was asked how I figured this out: I'm the guy who got multilingual migrations into D8 core, so I do know a bit about the matter :) In this case, I used xdebug and put a breakpoint where the exception was thrown (ContentEntityBase.php line 745). It looked weird that it was using 'und' as the langcode, rather than 'en'—so I looked up the call stack to see where that was coming from. It turns out to be from content\_translation\_entity\_presave(), which runs: $source\_langcode = !$entity->original->hasTranslation($langcode) ? $manager->getTranslationMetadata($entity)->getSource() : NULL; In this case `$manager->getTranslationMetadata($entity)->getSource()` is basically equivalent to `$entity->content_translation_source->value`. I wondered, why would that yield 'und'? I checked what happens when I translate an entity in the browser, and in that case it gives me 'en'. Something must be setting the source language! Indeed, ContentTranslationHandler::entityFormEntityBuild() calls setSource() when we're translating in-browser. So, I figured I would just replicate that behaviour in the migration, by setting content\_translation\_source in the process. This also explains why D6 -> D8 migration of translations work, since d6\_node\_translation.yml has content\_translation\_source in the process.
17,021,284
I'm trying to convert a c# project to c++. I'm trying the following: ``` class IDocInterface { public: // implemented in CSpecificDoc virtual bool CreateDoc() = 0; // implemented in COperations virtual void AddOperation() = 0; // implemented in CDoc virtual void Save() = 0; }; class COperations { public: void AddOperation() {}; // implementation for CDoc and derivates }; class CDoc : public IDocInterface, public COperations { public: void Save() {}; // implemented here }; class CSpecificDoc : public CDoc { public: bool CreateDoc() {}; // implemented here }; ``` When I try to do: ``` IDoc * pDoc = new CSpecificDoc(); ``` I get error c2259 cannot intantiate abstract class due to folloing members: void IDocInterface::AddOperations() is abstract. Don't know what I'm missing. My inheritance structure works fine like this in c# where i use "interface IDocInterface" and "abstract class CDoc". **Solution:** Added: ``` class IOperations { public: virtual void AddOperation() = 0; } ``` Then change above to: ``` class IDocInterface : public virtual IOperations { public: // implemented in CSpecificDoc virtual bool CreateDoc() = 0; // implemented in CDoc virtual void Save() = 0; }; ``` and ``` class COperations : public virtual IOperations ``` Still, I think its a bit strange that the whole thing worked so nicely in C# without the IOperations class...
2013/06/10
[ "https://Stackoverflow.com/questions/17021284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/268541/" ]
Unless `COperations` inherits `IDocInterface`, its `AddOperations()` member function is not considered related in any way to the virtual function with the same signature defined inside `IDocInterface`. In this case, C++ compiler will complain about a missing implementation. However, inheriting `IDocInterface` in `COperations` would create multiple paths of inheriting the same member function. This may be a problem, because functions, even the pure virtual ones, which are inherited through different paths are considered different (this is in sharp contrast to Java and C#'s implementations of interfaces). You fix this problem by marking your inheritance `virtual`, like this: ``` class IWithOperations { public: // implemented in COperations virtual void AddOperation() = 0; }; class IDocInterface : public virtual IWithOperations { public: // implemented in CSpecificDoc virtual bool CreateDoc() = 0; // implemented in CDoc virtual void Save() = 0; }; class COperations : public virtual IWithOperations { public: void AddOperation() {}; // implementation for CDoc and derivates }; class CDoc : public virtual IDocInterface, public virtual COperations { public: void Save() {} // implemented here virtual bool CreateDoc() = 0; // must be overridden }; class CSpecificDoc : public virtual CDoc { public: bool CreateDoc() {} // implemented here }; ``` Here is a [demo on ideone](http://ideone.com/BO5bkg).
9,023,880
I want to have an array list in vba, hence I have a variant declared in excel vba like: ``` Dim Students(10) as variant ``` Now I want to store numbers in Students list. the numbers are not continuous. Sometime like: ``` Students(2,7,14,54,33,45,55,59,62,66,69) ``` How can I do this in vba? also how can I access the list items?
2012/01/26
[ "https://Stackoverflow.com/questions/9023880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/793468/" ]
Students must be declared as a dynamic array. That is, an array whose bounds can be changed. `Dim Students(10)` gives an array whose bounds cannot be changed and cannot be loaded from an array. ``` Dim Students() As Variant ``` To load Students: ``` Students = Array(2,7,14,54,33,45,55,59,62,66,69) ``` To access the elements: ``` Dim Inx As Long For Inx = LBound(Students) to UBound(Students) Debug.Print Students(Inx) Next ``` LBound (Lower bound) and UBound mean that the for loop adjusts to the actual number of elements in Students.
1,180,541
Let $X$ and $Y$ be compact metric spaces. Let $f:X \to Y$ be a Borel measurable map and suppose that $T:X \to X$ is a homeomorphism. Can one change the topology on $X$ such that 1. $X$ is still a compact metrizable space, with the same Borel sets. 2. The map $T$ remains continuous. 3. The map $f:X \to Y$ is continuous. ? **Note:** If $Y$ is not compact, we can find counterexamples by taking $f$ to be an unbounded function. The answer is YES if we just want complete metrizability of the new topology on $X$, instead of compactness.
2015/03/08
[ "https://math.stackexchange.com/questions/1180541", "https://math.stackexchange.com", "https://math.stackexchange.com/users/84256/" ]
No - This follows from: If $\tau$ properly extends the usual topology on $[0, 1]$, then $\tau$ is not compact. The same is true of any compact Hausdorff space.
35,419,601
I'm using by nested grid. In the main grid I have two radio buttons, while on the second I have two additional radio buttons, and other controls.. I want the total grid will be with 3 rows and 3 columns. Relevant Code is: ``` <xctk:WizardPage Name="Page3" PageType="Interior" Title="Stages" Background="#FF27E0E0"> <xctk:WizardPage.CanSelectNextPage> <MultiBinding Converter="{StaticResource NextFromPage3}"> <Binding ElementName="HR" Path="IsChecked" Mode="OneWay"/> <Binding ElementName="LR" Path="IsChecked" Mode="OneWay"/> <Binding ElementName="yes" Path="IsChecked" Mode="OneWay"/> <Binding ElementName="no" Path="IsChecked" Mode="OneWay"/> </MultiBinding> </xctk:WizardPage.CanSelectNextPage> <Grid ShowGridLines="True" Margin="-5 -10"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="*"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Label x:Name="qual" Content="Select Quality:" FontSize="13.333" Margin="5 10" VerticalAlignment="Top" HorizontalAlignment="Left"/> <RadioButton x:Name="HR" Content="High-Resolution" FontSize="13.333" Grid.Column="1" Margin="5 10" VerticalAlignment="Top"/> <RadioButton x:Name="LR" FontSize="13.333" Content="Low-Resolution" Grid.Column="2" Margin="5 10" VerticalAlignment="Top"/> <Grid Grid.Row="1"> <Grid.Visibility> <MultiBinding Converter="{StaticResource FilterConverter}"> <Binding ElementName ="HR" Path="IsChecked" Mode="OneWay"/> <Binding ElementName ="LR" Path="IsChecked" Mode="OneWay"/> </MultiBinding> </Grid.Visibility> <Label x:Name="symbol" Content="Select Symbol:" Grid.Row ="1" Grid.Column="0" FontSize="13.333" Margin="5 10" VerticalAlignment="Top" HorizontalAlignment="Left"/> <ComboBox x:Name="symbolsCmbBox" FontSize="13.333" Grid.Row="1" Grid.Column="1" Margin="5 10" VerticalAlignment="Top" HorizontalAlignment="Left" ItemTemplate="{StaticResource cmbTemplate}" IsSynchronizedWithCurrentItem="True" SelectedIndex="0"> <ComboBox.ItemsSource> <MultiBinding Converter="{StaticResource SymbolComboboxItemsFilter}"> <Binding ElementName ="HR" Path="IsChecked" Mode="OneWay"/> <Binding ElementName ="LR" Path="IsChecked" Mode="OneWay"/> </MultiBinding> </ComboBox.ItemsSource> </ComboBox> <Label x:Name="isExists" Content="Select Yes if process will perform:" Grid.Row ="2" FontSize="13.333" Margin="5 10" VerticalAlignment="Top" HorizontalAlignment="Left"/> <RadioButton x:Name="yes" Content="Yes" FontSize="13.333" Grid.Row="2" Grid.Column="1" Margin="5 10" VerticalAlignment="Top"/> <RadioButton x:Name="no" Content="No" FontSize="13.333" Grid.Row="2" Grid.Column="2" Margin="5 10" VerticalAlignment="Top"/> </Grid> </Grid> ``` The code above is part of wizard exists on WPF toolkit package. My issue with nested grid above that controls are not located as expected. While I used only one main grid, this issue wasn't happened, but I need the nested grid from other reasons.. EDIT-for the first answer: I want that the main grid will be the first line (3 columns) and the inner grid will start from the second line and will contains two lines in total (3 columns) so how to specify it? EDIT-for the second answer: The first row(main grid) isn't straight with the second and third row(inner grid)- it seems like both radio buttons of the main grid are locate only on column=2 even it doesn't seems from the xaml code. My code now is like appeared on the second answer below. Thanks for your advice!
2016/02/15
[ "https://Stackoverflow.com/questions/35419601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5568730/" ]
I would probably do something like this. Note that this assumes that the file always looks like your example and does no error checking: ``` using (StreamReader reader = new StreamReader(inputFile)) using (StreamWriter writer = new StreamWriter(outputFile)) { bool delete = false; while (!reader.EndOfStream) { string line = reader.ReadLine(); string[] lineItems = line.Split(','); if (lineItems[0].Trim() == "A") delete = lineItems[1].Trim() == "2"; if (!delete) writer.WriteLine(line); } } ```
35,907,750
I have created a Model Admin called 'Clients'. Under the "Security" tab I created a new group called 'clients'. This Model Admin is managing just the clients and not other members. When creating a new member in the CMS using a model admin, I want to automatically generate a password for them (instead of them having to create their own one) one for them and then email it to them. **What I want to happen:** After the staff member clicks `"Add member"` the password and password confirmation textboxs are automatically populated with the generated password. - **This is the most ideal way I believe.** - Then once the staff member clicks save it will send the client and email with the username and newly generated password. [![enter image description here](https://i.stack.imgur.com/MtG6k.jpg)](https://i.stack.imgur.com/MtG6k.jpg) Question is how do you do this? **ClientAdmin.php** ``` <?php class ClientAdmin extends ModelAdmin { private static $menu_icon = 'themes/cadence/images/icons/person.png'; public $showImportForm = false; private static $managed_models = array( 'Member' ); private static $url_segment = 'clients'; private static $menu_title = 'Clients'; public function getList() { $list = parent::getList(); $clientGroup = Group::get()->filter('code', 'clients')->first(); $list = $list->filter('Groups.ID', $clientGroup->ID); return $list; } } ``` **MemberClientExtension.php** ``` <?php class MemberClientExtension extends DataExtension implements PermissionProvider { private static $db = array( ); public function providePermissions() { return array( 'CLIENTS' => 'Can access the site as a client', ); } public function updateCMSFields(FieldList $fields) { } public function generatePasswordForClient(){ $plainPassword = $this->owner->create_new_password(); $encryptedPassword = $this->owner->encryptWithUserSettings($plainPassword); // Need to set password in database here? return $plainPassword; } public function sendClientWelcomeEmail() { $email = new Email('[email protected]', '[email protected]', 'New member sign up'); $email->setTemplate('NewClientSignUp'); $email->populateTemplate(array( 'Email' => $this->owner->Email, 'Password' => $this->generatePasswordForClient() )); return $email->send(); } public function onBeforeWrite() { parent::onBeforeWrite(); } public function onAfterWrite() { parent::onAfterWrite(); // Seems to send 2x emails.. Only want to send one $this->sendClientWelcomeEmail(); } } ```
2016/03/10
[ "https://Stackoverflow.com/questions/35907750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3871401/" ]
You should set temporary plain text password in SetPassword field, and manage the context when onBeforeWrite and onAfterWrite hooks are called. ``` class MemberClientExtension extends DataExtension { protected $sendWelcomeEmail = false; ... // onBeforeWrite on extension is called after password is encrypted and set public function validate(ValidationResult $validationResult) { if (!$this->owner->isInDB()) { $this->sendWelcomeEmail = true; } } public function onAfterWrite() { if ($this->sendWelcomeEmail) { // reset for password change $this->sendWelcomeEmail = false; $password = $this->generatePasswordForClient(); $this->owner->changePassword($password); $this->sendClientWelcomeEmail(array( 'Email' => $this->owner->Email, 'Password' => $password; )); } } } ```
261,443
In user setting.JSON I am using ``` { "salesforcedx-vscode-apex.java.home":"C:\\Program Files\\Java\\jdk1.8.0_131", "salesforcedx-vscode-core.show-cli-success-msg": true, "salesforcedx-vscode-core.retrieve-test-code-coverage": true } ``` in workspace setting I am using ``` { "salesforcedx-vscode-core.push-or-deploy-on-save.enabled": true, "search.exclude": { "**/node_modules": true, "**/bower_components": true, "**/.sfdx": true }, "eslint.nodePath": "c:\\Users\\e3027618\\.vscode\\extensions\\salesforce.salesforcedx-vscode-lwc-45.13.0\\node_modules", "salesforcedx-vscode-core.show-cli-success-msg": true, "salesforcedx-vscode-core.retrieve-test-code-coverage": true } ``` But Still I am getting the below error message: > > No code coverage information was found for test run 7070U00000r8Ny3. > Set "salesforcedx-vscode-core.retrieve-test-code-coverage": true in > your user or workspace settings, then run Apex tests from the Apex > Tests sidebar or using the Run Tests or Run All Tests code lens within > a test class file. > > >
2019/05/07
[ "https://salesforce.stackexchange.com/questions/261443", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/56870/" ]
I was having a similar issue. I'd added `"salesforcedx-vscode-core.retrieve-test-code-coverage": true` into the user "settings.json" as instructed. Yet the error message about "No code coverage information" was still appearing. When I checked the Apex tests side bar there weren't any tests displayed to run. [![enter image description here](https://i.stack.imgur.com/8Mlt3.png)](https://i.stack.imgur.com/8Mlt3.png) Attempting to use the green *Run Tests* button there gave an error about configuring the Apex Language Server. Something had gone wrong with my "salesforcedx-vscode-apex.java.home" setting. After correcting that (See [Activate the Apex Language Server](https://forcedotcom.github.io/salesforcedx-vscode/articles/troubleshooting#activate-the-apex-language-server)) and restarting vscode the Apex Language Server started. And accessing the Apex tests side bar showed all the existing test cases. When I ran them the coverage was now available. [![enter image description here](https://i.stack.imgur.com/LvTOE.png)](https://i.stack.imgur.com/LvTOE.png)
21,549,913
I'm having a rather odd problem with flash messenger in ZF2. I'm using it in quite a simple scenario, save a 'registration complete' message after registering and redirect to the login page and display the message however the messages are never returned by the flash messenger. In controller register action: ``` $this->flashMessenger()->addMessage('Registration complete'); return $this->redirect()->toRoute('default', array('controller' => 'user', 'action' => 'login')); ``` In controller login action: ``` $flashMessenger = $this->flashMessenger(); $mes = $flashMessenger->hasMessages(); $cur = $flashMessenger->hasCurrentMessages(); ``` Both $mes and $cur are false (I tried both just to be sure). Can anyone shed any light on this? I'm using ZF 2.2.2 and PHP 5.3.14. Session save handler is using the dbtable adapter and I have tried disabling this as well as setting the flashmessenger session manager to the use the same dbtable save handler with no result.
2014/02/04
[ "https://Stackoverflow.com/questions/21549913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1141802/" ]
To use the `FlashMessenger` controller plugin, you need to add the following in your controller: ``` <?php class IndexController extends AbstractActionController { public function indexAction() { $this->flashMessenger()->addMessage('Your message'); return $this->redirect()->toRoute('admin/default', array('controller'=>'index', 'action'=>'thankyou')); } public function thankyouAction() { return new ViewModel(); } } ``` Add the following to the `thankyou.phtml` view template: ``` <?php if ($this->flashMessenger()->hasMessages()) { echo '<div class="alert alert-info">'; $messages = $this->flashMessenger()->getMessages(); foreach($messages as $message) { echo $message; } echo '</div>'; } ?> ```
16,621,136
My MainActivity extends activity and I use `getContext()` in another class that has a instance of MainActivity passed in and it works fine there, my code: ``` convertView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.nowview, parent, false); ``` Class constructor: ``` public PictureCard(String url, String title, int index, int pos, MainActivity parent) { this.parent = parent; // ... } ``` How I call the class ``` Card newCard = new PictureCard(links.get(index) , titles.get(index), index, position, parent); ``` (Parent is passed in as this from the MainActivity class)
2013/05/18
[ "https://Stackoverflow.com/questions/16621136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/860869/" ]
Have you tried using `getApplicationContext()` instead of `getContext()`? These links might help: <http://developer.android.com/reference/android/app/Activity.html> [getApplication() vs. getApplicationContext()](https://stackoverflow.com/questions/5018545/getapplication-vs-getapplicationcontext) [Difference between getContext() , getApplicationContext() , getBaseContext() and "this"](https://stackoverflow.com/questions/10641144/difference-between-getcontext-getapplicationcontext-getbasecontext-g)
15,327,794
I am trying to access a parent of the clicked item in the DOM tree, and for some reason it's not having any of it. Here's my jQuery: ``` $('.video-icon').click(function() { alert($(this).closest('.video-space').html()) }); ``` And my html: ``` <div class="video"> <div class="video-space"> <img src="img/video-1.jpg" alt="" class="video-img"> </div> <div class="video-info"> <div class="video-icon"> <img src="img/video.svg" alt="" class="video-icon-img"> </div> <h3 class="video-text">Watch video</h3> <h3 class="video-title" data-video="http://www.youtube.com/watch?v=xxxxxxxxx">Toy Story Trailer</h3> </div> </div> ``` Any advice on to get it working is great!
2013/03/10
[ "https://Stackoverflow.com/questions/15327794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
`.video-space` is *not* an ancestor of `.video-icon`. [`closest`](http://api.jquery.com/closest) looks for the first ancestor element matching the selector, which is why it isn't working. You'll need something like: ``` $('.video-icon').click(function() { alert($(this).closest('.video').find('.video-space').html()) }); ``` **Example:** <http://jsfiddle.net/6zAN7/14/>
22,685,994
This is my mysql query! ``` SELECT projects.projects_id, projects.projects_title, projects.projects_cost FROM projects LEFT JOIN invoice ON invoice.projects_id = projects.projects_id LEFT JOIN project_assign ON project_assign.projects_id=projects.projects_id WHERE project_assign.assigned_user_id=3 AND (SUM( invoice.invoice_amount) < projects.projects_cost OR invoice.projects_id is null ) AND project_assign.project_completed_date IS NOT NULL ``` In this query i want select all row that: > > 1. Is not present in other table e.g. (in my case other table is > "invoice") > 2. Or if persent then this condition must hold `sum(invoice.invoice_amount) < projects.projects_cost` > > > Thanks.
2014/03/27
[ "https://Stackoverflow.com/questions/22685994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3318657/" ]
here's a couple of options. jsfiddle: **<http://jsfiddle.net/a7Rc6/>** html: ``` <a id="one-way">Edit</a> <a id="another-way" href="#">Edit</a> ``` javascript: ``` var value = sel.options[sel.selectedIndex].value; // one way: document.getElementById('one-way').href = 'edittoc.php?key=' + value; // another way: document.getElementById('another-way').onclick = function () { window.location = 'edittoc.php?key=' + value; }; ```
168,502
I have a Dell Latitude E6530. The keyboard has a `SysRq` key (`Fn`+`Home`). However the magic keys (especially the famous `R``E``I``S``U``B`) doesn't work. SysRq is enabled in /proc/sys/kernel/sysrq (I get 1 if I cat this file). It works from external USB keybord. How can I have the `Alt`+`SysRq`+`R``E``I``S``U``B` (in fact, `Alt`+`Fn`+`Home`+`R``E``I``S``U``B`) reboot my system?
2012/07/26
[ "https://askubuntu.com/questions/168502", "https://askubuntu.com", "https://askubuntu.com/users/75177/" ]
The Dell E6420 works as follows * Press/hold both `Fn` and `Alt` * Press/hold `Home/Sysrq` * Release `Fn` * Press key (tested with `T`)
88,560
I'm trying to implement replace by fee functionality with bictoind (v18) and bumpfee rpc call described [here](https://bitcoin.org/en/developer-reference#bumpfee) It works by mean that new transaction is created with higher fee, but result should be: ``` { "txid": "value", (string) The id of the new transaction "origfee": n, (numeric) Fee of the replaced transaction "fee": n, (numeric) Fee of the new transaction "errors": [ str... ] (json array of strings) Errors encountered during processing (may be empty) } ``` but I'm getting basically all null response ``` { "id": "BumpFeeRequest 1561247020661", "error": null, "txid": null, "origfee": null, "fee": null, "errors": null } ``` Which makes it hard to identify the new transaction in down-steam system. How can I get the txid, except querying for last tx
2019/06/22
[ "https://bitcoin.stackexchange.com/questions/88560", "https://bitcoin.stackexchange.com", "https://bitcoin.stackexchange.com/users/29353/" ]
As of June 19 2019, using the following query: ``` bitcoin-indexer=> select reverse_bytes(output_tx.hash_id || output_tx.hash_rest), output.tx_idx, output_tx.current_height, input_tx.current_height, input_tx.current_height - output_tx.current_height from output inner join input on input.output_tx_hash_id = output.tx_hash_id AND input.output_tx_idx = output.tx_idx join tx as output_tx on output.tx_hash_id = output_tx.hash_id join tx as input_tx on input.tx_hash_id = input_tx.hash_id order by (input_tx.current_height - output_tx.current_height) desc limit 40; ``` against fully indexed blockchain (using [rust-bitcoin-indexer](https://github.com/dpc/rust-bitcoin-indexer)), I was able to identify the coinbase of [`d5a045c9d8a5bf7619c52968945c494d49333b80d51f1d0e2747b9e8bb2c6709`](https://blockchair.com/bitcoin/transaction/d5a045c9d8a5bf7619c52968945c494d49333b80d51f1d0e2747b9e8bb2c6709) as the longest held UTXO ever spent (so far). It was created in block 45697 and spent in block 559367, which lasted 8 years 10 months and 3 days. The full set of results: ``` reverse_bytes | tx_idx | current_height | current_height | ?column? --------------------------------------------------------------------+--------+----------------+----------------+---------- \xd5a045c9d8a5bf7619c52968945c494d49333b80d51f1d0e2747b9e8bb2c6709 | 0 | 45697 | 559367 | 513670 \x67e8d773078b75fb5680089b8d2d380be93943a1dcf9c37e309d517a98e5d40c | 0 | 66188 | 570705 | 504517 \x9c90d07be3d18c7a3612cd971934ed89c0d07fa302d4922481d1114dfaedc93d | 0 | 73303 | 577470 | 504167 \x7a8a36f68d265ff49e4df5215a2a6dd922dbfbb6cc695399d2b10efd4a75c47d | 0 | 52632 | 553012 | 500380 \x08ca56db26ad6d171e7fbcb24e592590bf369d70fc5931eb3790278681f35768 | 0 | 52644 | 551281 | 498637 \x5fba526502ee887bc1e6beb0255cfcdfaaf41e0d25e233e447e585458ed37ac5 | 0 | 52652 | 551281 | 498629 \x9596d84e671daea6ee965244ca75e204dfa72a471db3cb51dc406fbfeacc2e92 | 0 | 69951 | 567828 | 497877 \x82b6f02c86fd3afb5ca23b7bf88d509e92516129dc36ceb4864114ed5ec710f5 | 0 | 66446 | 563621 | 497175 \x31a67bf1f3cf01351b76cb16931ceb45c670b50af850181ab586d97040d90a1b | 0 | 82729 | 579816 | 497087 \x463b0f7c96214418af0f50836047ce0e9cbc5940b739d7d67eed1842e2edf768 | 0 | 82944 | 579816 | 496872 \x508d7a4ff36cda617aecd02da86fd5449176b0c75d3e398242253dbce6d54eeb | 1 | 83477 | 579817 | 496340 \x4e0584a90c9dce50ecd9ed1b2d79a3a8af0f690041dccc035fd81f06ac200571 | 0 | 56710 | 551275 | 494565 \xc6c9e4be37ea843fe50df740b5acba5d23c894a4b68191b1c157b281a8a985c5 | 0 | 74897 | 568169 | 493272 \x9296baa58de452d15763079e71861f5580863c462ce855a41e485e92f28f6e98 | 1 | 68586 | 560782 | 492196 \x404116e265c3717b403697ea226f6d839a24f88009b1802b978b692edca95cf4 | 0 | 59137 | 551279 | 492142 \xf6a0cc22d749a299c83c86df3406b9d6d9e6a70215978363ef5e884812112461 | 0 | 60717 | 551279 | 490562 \xa28a27378b3499997d1c990813adddbd25e470e0b44510896435b9a918968a0b | 0 | 61047 | 551272 | 490225 \x36a230b30815e40d238f27f2654ff3681f6c1931076e90c4c05065002b9d91e6 | 0 | 73788 | 562598 | 488810 \xdcc71895e1baf0abb83ff27348211662b517105b18789f4410a55a51dc50a156 | 0 | 66637 | 555282 | 488645 \x899ee05d5c4e91b3ee49958a9d0333ff9b1987c352d946ecdb1fd91588f667ac | 0 | 66336 | 554738 | 488402 \x6284dc97c5c923308675e9b0db88210ad61a42815caaf024b07cc0eb9e262c67 | 0 | 33538 | 521167 | 487629 \x56102337f6f10161a2286fe1ffb91e353b13a17db6a41c6149574d6dae476528 | 0 | 33590 | 521167 | 487577 \xf398b7e93220747aa2f45f36284606b2ae802741160f28f2fd3f2afa40bfd346 | 0 | 66627 | 553372 | 486745 \x708d840ea0041386b4376896b14e510d0cad3cdaeb707fe93ab2d33372723503 | 0 | 68283 | 554738 | 486455 \x452e2d312a18d907f2ef1ec976b1ed18ef2f5a079ee47037a346f260bad339e2 | 0 | 33784 | 519776 | 485992 \x0c1739923133af9f52a5764227f2da487f5f4520b5d0127c0867062a311cfeca | 0 | 65671 | 551393 | 485722 \x6f69ff89b936ac2120cbdc824138022de749977202153680b199bfb1d8afba75 | 1 | 89869 | 575308 | 485439 \xfcc26559921b51b07cf81d858689a4007fc9cf8fad96d4394da89e3e2d1a1299 | 0 | 91948 | 576386 | 484438 \xd1ff751609b5a74f99573d7d7baa1c1dc493c9bebd586f6bf381ee0877282ed2 | 0 | 97810 | 579234 | 481424 \x583b6351a67d96fc42c5294ee4282616c5bd1481e464720cb959fa4c3a5ce192 | 0 | 70534 | 551654 | 481120 \x836f332753244b3eaa6ea80ddcd59d6727de8874abef09f5f5bfa44d05025d05 | 0 | 70541 | 551654 | 481113 \xee2feeca4e02840b7036e28045a5dfd06ab65af5b1068cd9598ec3b87d4f4b32 | 1 | 70542 | 551654 | 481112 \xb0d701da413083e89f00f824a8300387ded7671ca3ca967811c758019cfaf3ba | 0 | 93709 | 574785 | 481076 \x23b140fb832912031596256b184010e52e24cf66da94dabc80770970087d2f82 | 1 | 92499 | 573193 | 480694 \x7712a8c8752090e8fa9527603ed08f72b00ace2b9a495d91e78523ff50844182 | 0 | 77095 | 555959 | 478864 \xed151ae3b0d1cd50df1f97cc4b8747d185b56f54f5aef3754079faa089e3e783 | 0 | 83936 | 561411 | 477475 \x8d432c241971e25172268765b219d6ed82c3868981a85c9189812b57ddd28912 | 0 | 97972 | 574951 | 476979 \xcfc9154235db58abd3f09bfd277b084a95ccbd03ed2161d0ab4ef4ed36166821 | 0 | 84411 | 561076 | 476665 \x5ad52480756416f6288be488f14392799c0ea2d050f96d4306b846d516b02f80 | 1 | 82966 | 558812 | 475846 \x269bbd2cd3dd7f88da4ca7086e75d36f0d2d4a54b1b5f0ed7509f7375cc71715 | 0 | 3607 | 479423 | 475816 (40 rows) ```
223,738
Say the table I'm working with has `firstName` and `date` as the only two column headers, with rows of data. Something like, ``` | firstName | date | -------------------------- + Robert | 2018/01/01 + + Jenny | 2018/01/01 + + George | 2018/01/02 + + Richard | 2018/01/02 + + Michael | 2018/01/03 + + Sean | 2018/01/03 + ``` I can extract the data itself with, ``` set @value = RequestParameter('someSearchKey') set @data = LookupRows('myTable', 'value', @value) ``` And then loop through and print that data with, ``` %%[ for @i = 1 to ROWCOUNT(@data) do SET @ROW = ROW(@data, @i) SET @FIELD = FIELD(@ROW, 'firstName') ]%% <hr> %%=v(@FIELD)=%% <br> %%[ next @i ]%% ``` Is there any way to lookup the headers and loop through them before looping through the data without using SSJS?
2018/07/03
[ "https://salesforce.stackexchange.com/questions/223738", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/58083/" ]
I'm going to add a little more detail here. There's a total of four kinds of note and attachment object you might be seeing on your objects, and they're queried in different ways. Classic Attachments ------------------- ``` SELECT Id FROM Attachment WHERE ParentId = 'SOME_ID' ``` or ``` SELECT Id FROM Attachment WHERE Parent.Type = 'SOME_SOBJECT_TYPE' ``` will get you data on your old-style Attachments. Classic Notes ------------- These work just like Attachments, but with a different sObject: ``` SELECT Id FROM Note WHERE ParentId = 'SOME_ID' ``` or ``` SELECT Id FROM Note WHERE Parent.Type = 'SOME_SOBJECT_TYPE' ``` Content Notes and Content Documents ----------------------------------- Content Notes are the new-style "Enhanced Notes". They're built on the Content architecture under the hood, and have rich-text bodies. Content Documents (with associated Content Versions) represent the new Lightning Files. Unfortunately, both are related to records using the `ContentDocumentLink` object, rather than having a direct lookup, and this comes with some significant query limitations: > > You can't run a query without filters against ContentDocumentLink. > You can't filter on ContentDocument fields if you're filtering by ContentDocumentId. You can only filter on ContentDocument fields if you're filtering by LinkedEntityId. > > > You can't filter on the related object fields. For example, you can't filter on the properties of the account to which a file is linked. You can filter on the properties of the file, such as the title field. > > > A SOQL query must filter on one of Id, ContentDocumentId, or LinkedEntityId. > > > So, to be short, you can't query all `ContentNote` or `ContentDocument` records attached to some specific type of object easily. You'd have to do something like exporting all Ids for a given sObject type and iteratively querying sets of those Ids against the `ContentDocumentLink` table to locate attached files. This is something I've done before (and written about [here](https://salesforce.stackexchange.com/questions/209973/query-to-see-all-files-related-to-specific-object-events/209975#209975)), but it takes some Python or another scripting language to get it done. If you do have a specific Id or Ids of records whose attachments you want to find, you can do it like this: ``` SELECT ContentDocumentId, ContentDocument.Title FROM ContentDocumentLink WHERE LinkedEntityId = 'OBJECT_ID' ``` Note that Content Notes are returned in a Content Document query - they are just a special type of Document.
651
It seems like we have gotten a few vague titles lately: * [What is the best database design for this situation?](https://dba.stackexchange.com/questions/17650/what-is-the-best-database-design-for-this-situation) * [SQL Server memory usage](https://dba.stackexchange.com/questions/17647/sql-memory-usage) * [Select rows where value of second column is not present in first column](https://dba.stackexchange.com/questions/16650/help-with-this-select-in-the-same-table) (maybe) If the community member feels a title is vague, should it be edited to be more specific?
2012/05/09
[ "https://dba.meta.stackexchange.com/questions/651", "https://dba.meta.stackexchange.com", "https://dba.meta.stackexchange.com/users/3928/" ]
Definitely. The title is the most visible part of a question. Having a clear title is very important for both SEO and for clarity and functionality. As long as you are not changing the content/spirit of the title, and not adding meta information (like adding tags to the body of the title) then I think this should be encouraged.
7,353,460
I have a question about Google Fonts. I am using the font "Lato" from [Google Fonts](http://www.google.com/webfonts#QuickUsePlace:quickUse/Family:Lato) and it appears to be working perfect in Firefox, Chrome, IE9 but in IE 7 and 8 the italic version looks real stretched. ![enter image description here](https://i.stack.imgur.com/KU3LK.jpg) I'm not doing anything too crazy just using ``` font-style:italic; font-weight:700; ``` and including the font using: ``` <link href='http://fonts.googleapis.com/css?family=Lato:400,700,700italic,900italic' rel='stylesheet' type='text/css'> ``` Is this a known problem with Google Fonts or is it something I am doing wrong? Thanks!
2011/09/08
[ "https://Stackoverflow.com/questions/7353460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/799653/" ]
For whatever reason (maybe someone can help with the why), Google has decided not to serve any font variants other than the regular one to IE users. This behaviour appears to be controlled by user-agent - if you load the CSS url (in your case <http://fonts.googleapis.com/css?family=Lato:400,700,700italic,900italic>) in Firefox vs IE you'll see that only one `@font-face` block is returned to IE. So, the easiest way to get around it is to load that url in Firefox and copy/paste the CSS into your own css file, rather than serving directly from Google. Now IE will have access to all the font variants as well... but technically you're breaking the link between the CSS file and underlying font files, which *should* never change but that's entirely up to Google's discretion. The unfortunate thing is (probably part of their reasoning), IE doesn't render the font particularly well even then. In my testing, semibold weight shows up bolder than it should and italics seem spaced a little too far apart. It still looks more pleasant than the faux-italic oblique font IE renders without the extra variants, at least. **edit**: After some more research, I've found a great page [on Typekit](http://blog.typekit.com/2011/06/27/new-from-typekit-variation-specific-font-family-names-in-ie-6-8/) which documents the issue exhaustively. Basically, IE is extremely limited when it comes to custom font families - the only way you're going to be able to achieve success with IE is to define your variants as separate font families in IE, and then make use of those different fonts where you would use `font-weight` and `font-style` in other browsers. This should give you universal compatibility. **edit2**: It turns out the urls for IE fonts are different to those for other browsers (IE uses eot format instead of woff). An exhaustive process for how to get this working for your font would be as follows: * Open <http://fonts.googleapis.com/css?family=Lato:400,700,700italic,900italic> in firefox/chrome/etc and copy the css to a new file, or into your ie-only stylesheet. * Go through and take out all the 'local' and 'format' src definitions, leaving you with just the 'url' parts. * For each variant specified in your font stylesheet url (in your example, these would be 400, 700, 700italic and 900italic), load the font stylesheet in IE with *this variant only* and open the resulting CSS in a text editor. For example, load <http://fonts.googleapis.com/css?family=Lato:900italic> to get the superbold italic variant. * Find the matching variant in your new stylesheet (the `font-style` and `font-weight` properties should match) and replace the woff `src` url with the eot one for IE. Also give the font a different family - I recommend suffixing with the style and weight like Typekit do, so that *Open Sans* becomes *Open Sans i9* and so on. * Do this for all remaining variants. * Conditionally include this new stylesheet in place of the one you are already using for other browsers. * Wherever you have used `font-style` or `font-weight` in your css, add a `font-family` as well, referencing the new family name *AND* the correct family name as seen by other browsers. For example: `font-family: 'Open Sans i9', 'Open Sans'; font-weight: 900; font-style: italic;`. This will use the font family name for IE compatibility, and the base family + variants in other browsers.
342,173
I’m trying to create a KitPvP with power-ups and I want it so that when someone with the archer kit throws an egg, it gives the person speed and strength. If there’s an add-on for it, please tell me.
2018/12/09
[ "https://gaming.stackexchange.com/questions/342173", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/222514/" ]
It should be possible to do it with a command like this one: ``` /execute @e[type=egg] ~ ~ ~ effect @a[r=2,tag=archer] speed 10 3 true ``` This will give any player with the tag `archer` who is within a radius of 2 blocks of an egg the effect `speed` for 10 seconds on level 3, while not showing any particles (remove the `true` if you want players to see the particles). This will work for any archer throwing an egg, but it will also give other archers who are close to an egg the same effct. You need to put the command into an active, repeating command block for it to work. You can chain a command block with this command to give the second effects: ``` /execute @e[type=egg] ~ ~ ~ effect @a[r=2,tag=archer] strength 10 3 true ``` And a third command block with this command to remove eggs after they were thrown, to reduce how many players may get the effect (as flying eggs also gives the effects, so throwing an egg at an archer would give both archers the effects). ``` /kill @e[type=egg] ``` There is no way for a command block to know who exactly threw the egg in minecraft pocket edition, so after setting this all up EVERY archer within a small radius of the one throwing the egg will get the effects. This is what it may look like if you set up all 3 command blocks: [![3 command blocks that will repeatingly activate, all set to <code>always active</code>.](https://i.stack.imgur.com/RWZWG.png)](https://i.stack.imgur.com/RWZWG.png)
49,332,571
I want to do something like this: ``` statusReady: boolean = false; jobsReady: boolean = false; ready() { return Promise.all([statusReady, jobsReady]); } ``` ...and the idea is basically so later I can do this: ``` this.ready().then(() => { // Do stuff here when we're all ready }); ``` If everything is already true, I'd expect the promise to resolve immediately, and if anything is false, it waits for the statuses to be true, then resolves. I'd use the ready() function anywhere in which I need to make sure certain pieces are finished loading.
2018/03/17
[ "https://Stackoverflow.com/questions/49332571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6763640/" ]
So if I am correct, you're asking how to create a promise that resolves as soon as a list of booleans are all true? I created a function that does exactly that. It takes an object of booleans as its only arg, and returns a promise that resolves as soon as they are all true. Here is the function: ``` function whenBoolListIsTruePromise (boolList) { return new Promise(function (resolve, reject) { // Check if all values of boolList are already true var initializedAsTrue = true; Object.values(boolList).forEach(function (currentBoolValue) { if (!currentBoolValue) initializedAsTrue = false; }); if (initializedAsTrue) { resolve(); } else { // The following watches changes to any of the bools in the boolList, and resolves the promise when all are true. // 1. Copy boolList data to _actualData. // 2. For each key-value pair in boolList, change it to a :set and :get property that accesses _actualData. // 3. Every time a set is run, check if everything in actual data is now true. If it is, resolve promise. var _actualData = Object.assign({}, boolList); Object.entries(boolList).forEach(function ([boolName, boolValue]) { Object.defineProperty(boolList, boolName, { configurable: true, set: function (newV) { var allTrue = true; _actualData[boolName] = newV; Object.values(_actualData).forEach(function (currentBoolValue) { if (!currentBoolValue) allTrue = false; }); if (allTrue) { // Remove :set and :get, bringing back to a regular simple object Object.entries(_actualData).forEach(function ([boolName2, boolValue2]) { Object.defineProperty(boolList, boolName2, { configurable: true, value: boolValue2, }); }); resolve(); } }, get: function () { return _actualData[boolName]; } }); }); } }); } ``` You use this function by creating an object of booleans and passing it as an argument for this function. This function will return a promise that resolves when all of those booleans are set to true. ``` var myBoolList = {"statusReady": false, "jobsReady": false}; whenBoolListIsTruePromise(myBoolList).then(function () { console.log("All values are now true!"); }, function (error) { console.error(error); }); myBoolList.statusReady = true; myBoolList.jobsReady = true; ``` Here is a working example for you to look at: ```js function whenBoolListIsTruePromise (boolList) { return new Promise(function (resolve, reject) { // Check if all values of boolList are already true var initializedAsTrue = true; Object.values(boolList).forEach(function (currentBoolValue) { if (!currentBoolValue) initializedAsTrue = false; }); if (initializedAsTrue) { resolve(); } else { // The following watches changes to any of the bools in the boolList, and resolves the promise when all are true. // 1. Copy boolList data to _actualData. // 2. For each key-value pair in boolList, change it to a :set and :get property that accesses _actualData. // 3. Every time a set is run, check if everything in actual data is now true. If it is, resolve promise. var _actualData = Object.assign({}, boolList); Object.entries(boolList).forEach(function ([boolName, boolValue]) { Object.defineProperty(boolList, boolName, { configurable: true, set: function (newV) { var allTrue = true; _actualData[boolName] = newV; Object.values(_actualData).forEach(function (currentBoolValue) { if (!currentBoolValue) allTrue = false; }); if (allTrue) { // Remove :set and :get, bringing back to a regular simple object Object.entries(_actualData).forEach(function ([boolName2, boolValue2]) { Object.defineProperty(boolList, boolName2, { configurable: true, value: boolValue2, }); }); resolve(); } }, get: function () { return _actualData[boolName]; } }); }); } }); } var myBoolList = {"statusReady": false, "jobsReady": false}; whenBoolListIsTruePromise(myBoolList).then(function () { console.log("All values are now true!"); }, function (error) { console.error(error); }); myBoolList.statusReady = true; myBoolList.jobsReady = true; ``` This function works by creating :set and :get accessors for each key in the boolList object. The :set function is ran whenever any of the things in the booList object are set (changed). I have made it so the :set function checks if all of the booleans are true, and resolves the promise if they are. Here is a helpful article I found that talks a bit about :get and :set <https://javascriptplayground.com/es5-getters-setters/>
35,587,595
I am creating an app for a pizza restaurant. I have created code (BELOW) that will calculate the subtotal, total and vat when orders are selected and added up. The more you pay the greater the discount you obtain. But unfortunately I don't know what am doing wrong as it comes back as "InvalidCastExpectation was handled". Here is my code: ``` Dim Total As Double Dim TotalProducts As Integer Dim Vat As Decimal = 0 For Each Str As String In ListBox5.Items Total = Total + Str <<<<<< ( this section is the problem) Next TextBox9.Text = FormatCurrency(+Total) For Each Str As String In ListBox1.Items TotalProducts = TotalProducts + CInt(Str) Next Total = Total = CDbl(Total) TextBox6.Text = Format(Total, "0.00") TextBox7.Text = Format(20 / 100 * TextBox7.Text) TextBox6.Text = Format(+Total + TextBox7.Text) Select Total Case Is < 10 TextBox6.Text = Format(Total, "") TextBox8.Text = Format(20 / 100 * TextBox6.Text) TextBox6.Text = Format(+Total + TextBox7.Text) Case Is < 20 MessageBox.Show("10% discount awarded") Total = (Total - (Total * 10 / 100)) TextBox6.Text = Format(+Total) TextBox6.Text = Format(Total, "") TextBox8.Text = Format(20 / 100 * TextBox6.Text) TextBox8.Text = Format(+Total + TextBox7.Text) ```
2016/02/23
[ "https://Stackoverflow.com/questions/35587595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4769326/" ]
You probably could only execute each query only once. 1) The file table is so small that you can load it in a memory map and be done with it 2) The query on the data table, filtered by fileType and ordered by file id, should not take ages (of course you have an index on fileID + lineNum, right ?)
17,985,028
I have this database logic that need to be executed, I want to get all the rows selected by the user and deleted it. My database logic would be getting all the rows and then delete individually. I'm using Fuelphp 1.6 so my code is(as per stated on [fuelphp forum topic in ORM](http://fuelphp.com/forums/discussion/9787/proper-way-to-generate-a-where-in-query#Item_6)): ``` Model_Article::find()->where('id', 'IN', array(1,3))->get(); ``` The problem is I got this error: ``` Call to a member function where() on a non-object ``` Note: Model\_Article extends ORM\Model Can anybody help me? Thank you in advance.
2013/08/01
[ "https://Stackoverflow.com/questions/17985028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2338482/" ]
right... change your "select" to this: ``` Model_Article::find('all', array('where' => array('id', 'IN', array(1,3)))) ``` OR change your select to ``` Model_Article::query()->where('id', 'IN', array(1,3))->get(); ``` After you can do a "delete" in every record.
116,954
The question is from a Master-level Probability Course. It is well known that the underlying assumption for the binomial distribution is that there are *n* independent Bernoulli trials. More specifically, the assumptions are: (1) The number of trials, $n$, is fixed. (2) There are two and only two outcomes, labelled as "success" and "failure". The probability of outcome "success" is the same across the *n* trials. (3) The trials are *independent*. That is, the outcome of one trial doesn't affect that of the others. My question is, are there any counterexamples which just violate one of those three assumptions? Particularly, are there cases where Assumption (2) holds but (3) doesn't, or vice versa?
2014/09/27
[ "https://stats.stackexchange.com/questions/116954", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/56525/" ]
Breaking each one, singly: > > (1) The number of trials, $n$, is fixed. > > > The experiment continues until $k$ successes are observed. Or until $m$ successes in a row. Or until the number of successes exceeds the number of failures by 2. > > (2) There are two and only two outcomes, labelled as "success" and "failure". The probability of outcome "success" is the same across the n trials. > > > P(success) is drawn from a beta distribution with mean $p$. Or P(success) alternates between $p\_\text{A}$ and $p\_\text{B}$. > > (3) The trials are independent. That is, the outcome of one trial doesn't affect that of the others. > > > P(Success|Success at previous trial) = $p\_1$ and P(Success|Failure at previous trial) = $p\_2$ You suggested something like an urn model as a concrete example, and it's quite easy to construct several forms of urn model of this third case (if you use sampling with replacement) - or you could use dice if there's more than one die you could use.
2,372,635
I have a line of code that gets the following error when run through JSLint: ``` Lint at line 604 character 48: Insecure '^'. numExp = parseInt(val[1].replace(/[^\-+\d]/g, ""), 10); ``` This error seems to refer to the following description from JSLint's option page: ``` "true if . and [^...] should not be allowed in RegExp literals. These forms should not be used when validating in secure applications." ``` I don't quite understand how a client-side javascript application can really be considered secure. Even with the most airtight regex, it's still possible to fire up something like firebug and change the variable anyway. The real input validation should be done on the server, and the client browser should probably stick with validation that will handle the abuse of your average user. Is it safe to ignore this error? Am I missing an angle here where my application will be insecure because of client-side input validation?
2010/03/03
[ "https://Stackoverflow.com/questions/2372635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/107728/" ]
"Insecure" means "unspecific" in this context. Both the dot `.` and the exclusive range `[^…]` are not clearly defining what *should* be matched by the regex. For validation purposes, this *can* propose the risk of successfully matching stuff that you did not think of and do not want (think: white-listing vs. black-listing). In any case, dot and exclusive range are valid parts of a regular expression, and if they do what you need (like in this case), I would think of the warning as over-cautious. A malicious user can fiddle with your page logic any time; the warning is more about the regular operation of the page.
52,533,884
I have an app which continually tracks the device location in background. This worked pretty well in ios 11.4 where I could let run the app in background for days while still doing other stuff in foreground. Now with ios 12 the app does stop running after some time when the device is let alone. LocationManager is intialized as follows: ``` locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest; locationManager.requestWhenInUseAuthorization() locationManager.startUpdatingLocation() locationManager.startUpdatingHeading() locationManager.allowsBackgroundLocationUpdates = false locationManager.pausesLocationUpdatesAutomatically = false if #available(iOS 11.0, *) { locationManager.showsBackgroundLocationIndicator = true } locationManager.distanceFilter = prefs.getDoubleFromString(Prefs.PREF_DISTANCE_FILTER, defaultVal: 2.5) ``` When the user decides to start tracking ``` locationManager.allowsBackgroundLocationUpdates = true ``` is set. The app has the "Always" privilege set for location service. Any idea what changed in ios 12 ?
2018/09/27
[ "https://Stackoverflow.com/questions/52533884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5564358/" ]
This seems to be a bug since iOS 12 that apps will get terminated in background for no decent reason. I've filled in a bug report. See for more information and a demo project to demonstrate the problem here: [iOS 12 terminates apps in the background for no reason](https://stackoverflow.com/questions/53005174/ios-12-terminates-apps-in-the-background-for-no-reason) **Bug is fixed in iOS 12.2 beta 2 (16E5191d)**
61,554,530
I have a NodeJS project using Jest and babel. When I run the test I get the following error: `FAIL ./user.test.js ● Test suite failed to run. SyntaxError: C:\Users\...\__test__\mocks\registerUser.json: Unexpected token, expected ";" (2:8)` When i change the registerUser.json to a javascript file I'm able to retrieve the content without any problem, but when I try to use a JSON file won't work. But I can't seem to find the cause of the error when using a json file. My current structure is something like: ``` |-- src |-- __test__ |-- mocks |-- registerUser.json |-- user.test.js |-- tmp .babelrc .eslintignore .eslintrc .gitignore .prettierrc jest.config.js package.json ``` **user.test.js** ``` const userRegisterMock = require('./mocks/registerUser.json'); describe('User', () => { it('[SUCCESS] should be able to register', async () => { // console.log(userRegisterMock) expect(true).toBe(true); }); }); ``` **jest.config.js** ``` module.exports = { bail: 1, testEnvironment: 'node', clearMocks: true, collectCoverage: true, collectCoverageFrom: [ 'src/**', '!src/helpers/**', '!src/app.js', '!src/server.js', '!src/database/**', '!src/config/**' ], coverageDirectory: '__tests__/coverage', coverageReporters: ['text', 'lcov'], coverageThreshold: { global: { branches: 100, functions: 100, lines: 100, statements: 100 } }, moduleFileExtensions: ['js', 'json', 'jsx', 'ts', 'tsx', 'node'], resetModules: false, testMatch: ['**/__tests__/**/*.test.js'], transform: { '.(js|jsx|ts|tsx)': 'babel-jest' } }; ``` **.babelrc** ``` { "presets": [ ["@babel/preset-env", { "useBuiltIns": "usage", // or "entry" "corejs": 3, "targets": { "node": "current" } }] ], "plugins": [ ["@babel/plugin-transform-modules-commonjs"], ["@babel/plugin-transform-runtime", { "regenerator": true }] ] } ``` **registerUser.json** ``` { "name": "Test Case", "country": "Brazil", "birthdate": "25/03/1994", "sex": "Masculino", "nationality": "Brasileiro" } ```
2020/05/02
[ "https://Stackoverflow.com/questions/61554530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12100588/" ]
Your transform regex contains `.js` which matches `.json If you add an `$` in the end, you'll select only files **ending** with `.js`. ``` transform: { '.(js|jsx|ts|tsx)$': 'babel-jest' } ``` An even better regex would be: `'^.+\\.(js|jsx|ts|tsx)$': 'babel-jest'`
191,699
I wrote a program to visualize binary expansions of fractions in the form of a grid. Each row is one fraction; for instance the third row is 1/3 = 0.010101... The digits are color-coded, gray for 1 and blue for 0. ![demo grid](https://i.stack.imgur.com/fi0rA.png) When I made a big version of the grid (below) with many more fractions and one pixel per digit, I was surprised at how many patterns I saw. It's not shocking that there are prominent horizontal stripes around powers of 2, but there are also diagonal "stripes" and near-vertical structures. I can even convince myself there are various thick horizontal bands with different proportions of ones and zeros. This feels like a pretty natural construction, so it must have been done before. Regardless, I'd be interested in any pointers or explanations of the stripes I'm seeing. ![enter image description here](https://i.stack.imgur.com/UMrMt.png)
2012/09/06
[ "https://math.stackexchange.com/questions/191699", "https://math.stackexchange.com", "https://math.stackexchange.com/users/39583/" ]
The dark blue horizontal stripes are caused by termination. They are at $\frac 1{2^n}$ which has all zeros after some point. Just above $\frac 1{2^n}$, you have lots of zeros in the repeat of $\frac 1{2^n-1}$ and still pretty many for numbers a little further away. The blue and gray stripes very near the left edge are the leading $0$ bits and $1$ bit. All the fractions between $\frac 1{2^n+1}$ and $\frac 1{2^{n+1}}$ have the same leading bit. I don't understand the diagonal stripes, maybe they are an artifact of the square pixels. I wonder if the vertical stripes are at positions that have lots of divisors, where you have extra repeats coming, but that is just a guess. Maybe you could look.
43,778,271
In my rails application I am generating a url, whose proper pattern is as follows: `https://example.com/equipment_details/slug` This is the url google is supposed to be indexing. But due to pagination implementation using javascript there is another active url on platform as follows: `http://localhost:3000/equipment_details/slug?page=2`. **controller** method is like below: ``` class EquipmentsController < ApplicationController def equipment_details @equipment = Equipment.friendly.active.includes(:country, :manufacturer, :category, :user).find(params[:id]) if @equipment @products = @equipment.category.equipments.active.where.not("equipment.id = ?", @equipment.id) @countries = Country.active.all @states = State.active.all @cities = City.active.all @services = Service.active.where("category_id = ? AND sub_category_id = ? AND country_id = ? AND state_id = ? AND city_id = ?", @equipment.category_id, @equipment.sub_category_id, @equipment.country_id, @equipment.state_id, @equipment.city_id) respond_to do |format| format.js format.html format.pdf do render :pdf => "vendaxo_#{@equipment.title}", :layout => 'equipment_details_pdf.html.erb', :disposition => 'attachment' end end else flash[:error] = "Equipment not found." redirect_to root_path end end end ``` Basically the main content on both url is same except for the javascript pagination content in the footer. This is causing issues in SEO optimization. How can I send the url with second pattern i.e the uel with `?page=2` to `404` page ? Is there a way to do it from rails routes file?
2017/05/04
[ "https://Stackoverflow.com/questions/43778271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3576036/" ]
If you specifically want to look for a query parameter called `page` and raise an exception to activate the 404 response (if that request isn't an AJAX call from your javascript), you can do that in a before action in your `EquipmentDetailsController` (or whatever it's called). ``` class EquipmentDetailsController < ApplicationController before_action :send_to_404, only: [:name] # or whatever the action is called def send_to_404 if !request.xhr? && !params[:page].nil? raise ActionController::RoutingError.new('Not Found') end end end ```
20,114,242
Successfully using [this SO solution](https://stackoverflow.com/questions/6359972/adwords-api-retrieve-daily-spend-costs) since about a year, my code to get the daily costs of my Google AdWords campaign looks like: ``` sum += campaign.campaignStats.cost.microAmount / 1000000m; ``` I.e. I'm using the [`campaignStats` property](https://developers.google.com/adwords/api/docs/reference/v201306/CampaignService.CampaignStats). Unfortunately in the latest version **v201309** of the API, this property does not exist anymore. I've searched all the examples of [the official .NET wrapper](https://code.google.com/p/google-api-adwords-dotnet/wiki/NoClientLibrary) and also looked through the API documentation just to not find a single clue on how to manage this. **Therefore my question is:** How to retrieve the daily costs of an AdWord campain through the latest Google AdWords API? **Update 1:** I've found [this discussion in the AdWords API forum](https://groups.google.com/forum/#!topic/adwords-api/VIdLuYKwBYo). They suggest to generate a report, fetch and parse this report. There is also [an AdWords blog entry](http://googleadsdeveloper.blogspot.com/2013/10/adwords-api-how-to-migrate-from-stats.html) about it.
2013/11/21
[ "https://Stackoverflow.com/questions/20114242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/107625/" ]
This is the working solution I came up with: ``` private static decimal coreGetAdwordsSumInRange(DateTime start, DateTime end) { var reportDefinition = new ReportDefinition { reportName = string.Format(@"Campaign performance report #{0}", DateTime.Now.Ticks), dateRangeType = ReportDefinitionDateRangeType.CUSTOM_DATE, reportType = ReportDefinitionReportType.CAMPAIGN_PERFORMANCE_REPORT, downloadFormat = DownloadFormat.XML, includeZeroImpressions = false, selector = new Selector { fields = new[] { @"Cost" }, dateRange = new DateRange {min = start.ToString(@"yyyyMMdd"), max = end.ToString(@"yyyyMMdd")} } }; // -- var sum = decimal.Zero; var tempFilePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid() + @".xml"); try { var utils = new ReportUtilities(new AdWordsUser()) { ReportVersion = @"v201309" }; utils.DownloadClientReport(reportDefinition, true, tempFilePath); var doc = new XmlDocument(); doc.Load(tempFilePath); var costNodes = doc.SelectNodes(@"/report/table/row/@cost"); if (costNodes != null) { foreach (XmlNode costNode in costNodes) { var cost = Convert.ToDecimal(costNode.InnerText); sum += cost/1000000m; } } } finally { File.Delete(tempFilePath); } return sum; } ``` [Also available via Pastebin.com](http://pastebin.com/RZM3eS2r).
3,645,198
It is widely known that the variance formula is: $S^{2}=\frac{\sum\_{i=1}^{n}\left ( X\_{i} - \overline{X} \right )^{^{2}}}{n-1}$ and that the standard deviation formula is: $S^{2}=\sqrt[]{\frac{\sum\_{i=1}^{n}\left ( X\_{i} - \overline{X} \right )^{^{2}}}{n-1}}$ But if the purpose of squaring the difference $\left ( X\_{i} - \overline{X} \right )^{^{2}}$ is to eliminate the effect of the sign, would it not be more logical for the standard deviation equation to eliminate only the effect of the square affecting the upper part of the equation and not its entirety? like this: $S^{2}=\frac{\sqrt{\sum\_{i=1}^{n}\left ( X\_{i} - \overline{X} \right )^{^{2}}}}{n-1}$ Does someone understand and can explain to me why it is not like this? Thanks.
2020/04/26
[ "https://math.stackexchange.com/questions/3645198", "https://math.stackexchange.com", "https://math.stackexchange.com/users/779462/" ]
[This is about the "purpose of the variance" part of the question.] The purpose of squaring the error, i.e., $X\_i-\bar X$, is not to eliminate sign effects, any other non-negative function instead of squaring would do the same. Gauss (1821) choosed squaring the error, and he admits that this decision "*is made arbitrarily without a strong necessity*" Laplace proposes the absolute value, but Gauss argued against it. Following Laplace, a doubled error would count as much as the same error done twice. But his main reason was that the absolute value doesn't have a derivative. He states that *"This treatment [that of Laplace] opposes in a higher degree any analytic treatment whereas the results from our principle [squaring the error] distinguish in simplicity and in generality as well."* See <https://archive.org/details/abhandlungenmet00gausrich/page/n17/mode/2up>, p. 5f.
4,411
I'm from a state in the US where all gas is self-service. When traveling to Oregon (where all gas stations are full-service), how does the process work? Do you just pull up to the pump and hand the attendant your credit card? Is tipping required or recommended? And is it true that it is a crime to actually pump your own gas at a station in Oregon?
2011/12/26
[ "https://travel.stackexchange.com/questions/4411", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/396/" ]
Haven't been to Oregon but the way it works in New Jersey where law is the same is as follows: You pull up to the gas station. You wait in the car until an attendant comes. You give him Cash and he pumps the gas. Credit card behavior vary depending on the types of pumps installed. In some gas stations pumps cannot be activated unless an attendant uses his own card to activate the pump. In case the pump can be activated by your own credit card you can pump your own gas and noone will tell you anything about it. One thing to keep in mind though that the register for the gas is usually kept separate from the convenience store so if you decide to pay cash you will need an attendant. Tipping in this case is absolutely your choice. In New Jersey it's not a requirement or recommendation but if you choose to do it. Do it. Technically under the law in both states it is illegal though I have not seen it enforced. [DumbLaws.com has a good explanation for the existence of this law](http://www.dumblaws.com/law/686) but if you are concerned about [legal implications of certain things in various states in the US you can try a different page on the same site](http://www.dumblaws.com/laws/united-states). Makes for an interesting read. :)
82,903
> > **Possible Duplicate:** > > [How would you abbreviate surnames starting with Mc/O/D?](https://english.stackexchange.com/questions/3259/how-would-you-abbreviate-surnames-starting-with-mc-o-d) > > > How would I abbreviate Jane deLuze? If I were listing a numbe of people by initials, like John Doe or John Smith, I could use JD, JS etc.... but how would I do deLuze?
2012/09/17
[ "https://english.stackexchange.com/questions/82903", "https://english.stackexchange.com", "https://english.stackexchange.com/users/26187/" ]
"Every two days" is the same as "every other day." If you wanted to describe a two-day break, it would be "every third day."
150,094
There are some 20 tables in a database of **Sybase instance**, where i need to find the locking schema of tables. Once locking schema is found, i need to compare it in other database which also have same 20 tables. build-ASE16 SP2
2016/09/19
[ "https://dba.stackexchange.com/questions/150094", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/67199/" ]
Use the following to determine the locking schema for each user table in an ASE database: ``` SELECT TableName = CONVERT(VARCHAR(30), so.name) , LockScheme = CONVERT(VARCHAR(30), lockscheme(so.id)) FROM sysobjects so WHERE so.type IN ('S', 'U'); ``` The `CONVERT(VARCHAR(30), xxx)` is simply to make the output easier to see in a console session. If you are using a GUI tool to connect to the ASE instance, they are probably not necessary. Be aware that if you have table names longer than 30 characters, they will be truncated in the output. Run that in both instances and simply compare the output in [BeyondCompare](http://scootersoftware.com/), or some other differencing tool.
16,185,356
I have placed one text area and I want to put restriction on it .. Only special characters | should not be allowed to input in text area because I'm using | character in split function.
2013/04/24
[ "https://Stackoverflow.com/questions/16185356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2300067/" ]
You can achieve this by using the [`.nextAll()`](http://api.jquery.com/nextAll/) functionality. **HTML** ``` <p id="1">1</p> <p id="2">2</p> <p id="3">3</p> <p id="4">4</p> <p id="5">5</p> <p id="6"> 6 <span id="click">Click</span> </p> <p id="7">7</p> <p id="8">8</p> ``` **JavaScript** ``` $("#click").on("click", function() { var $parent = $(this).parent(); $parent.nextAll().remove(); $parent.remove(); }); ``` [JSFiddle](http://jsfiddle.net/s56dS/).
22,264,804
I need to find a way to change the picture when the user clicks on it, I seem to be having problems. heres my code: ``` var canvas = document.getElementById("myCanvas"); var context = canvas.getContext("2d"); var img = new Image(); img.src = 'Birthday.jpg'; img.onload = function() { context.drawImage(img, 47, 90, 200, 300); }; } ``` Ive already tried things like: ``` img.onclick = function() { context.clearRect(47, 90, 200, 300); img2.src = 'BirthdayOUT.jpg'; context.drawImage(img2, 47, 90, 200, 300); }; ```
2014/03/08
[ "https://Stackoverflow.com/questions/22264804", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3395066/" ]
Main Layout main.blade.php ``` @include('includes.header') <body> <!-- main content --> <div id="main_wrapper"> <div class="page_content"> @yield('content') </div> </div> @include('includes.footer') </body> ``` --- header.blade.php ``` <head> <meta charset="UTF-8"> <title>My Page</title> <meta name="viewport" content="initial-scale=1.0,maximum-scale=1.0,user-scalable=no"> <!-- common styles --> <link rel="stylesheet" href="{{ asset('assets/bootstrap.css') }}"> <!-- page specific styles --> @yield('pagespecificstyles') </head> ``` --- footer.blade.php ``` <footer> <!-- common scripts --> <script src="{{ asset('assets/js/jquery.min.js') }}"></script> <!-- page specific scripts --> @yield('pagespecificscripts') ``` mypage.blade.php ``` @extends('layouts.main') @section('pagespecificstyles') <!-- flot charts css--> <link rel="stylesheet" href="{{ asset('assets/lib/owl-carousel/flot.css') }}"> @stop @section('content') <div class="container"> Hello welcome to my page. </div> @endsection @section('pagespecificscripts') <!-- flot charts scripts--> <script src="{{ asset('/assets/lib/flot/jquery.flot.min.js') }}"></script> @stop ```
15,934,851
I'm making a crawler, just trying out the basics. I get stuck at trying to echo the array that I get from the crawler. This is the array: ``` Array ( [0] => Array ( [0] => [email protected] ) [1] => Array ( [0] => [email protected] ) ) ``` And I want to echo this: ``` [email protected] [email protected] ``` So what I did is this: ``` $teller = 1; while ( $teller != 10 ) { foreach ( $email[$teller] as $mail ) { echo $mail; $teller = $teller + 1; } } ``` What am I doing wrong?
2013/04/10
[ "https://Stackoverflow.com/questions/15934851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Does it display an error message? If so, what is it? Also, the while loop is pretty much useless as foreach loop acts as a "while loop" until it has iterated through the entire array.
18,959,325
i'm using jQuery.validationEngine to match Password and Confirm Password fields. ``` <input value="" class="validate[required,custom[password]] text-input" type="password" name="txtpswd" id="txtpswd" /> <input value="" class="validate[required,equals[txtpswd]] text-input" type="password" name="password2" id="password2" /> ``` Above code is working fine. But: First Problem:while i use runat="server" in anyone/both(input tag) of them then it fails matching. Second Problem:while i use server controls(textbox) in lieu of html input tag, then it fails matching. Please tell me where i'm wrong? Please help me to resolve my problem.
2013/09/23
[ "https://Stackoverflow.com/questions/18959325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2791156/" ]
if you want to check **confirm password** validation, then you can use like this. ``` <input type="password" id="password" name="password" class="validate[required]"/> <input type="password" id="confirm_password" name="confirm_password" class="validate[required,equals[password]]"/> ```
30,126,698
So, I have List a: ``` let a = Immutable.List([1]) ``` and List b: ``` let b = Immutable.List([2, 3]) ``` I want to get List `union === List([1, 2, 3])` from them. I try to [merge](http://facebook.github.io/immutable-js/docs/#/List/merge) them fist: ``` let union = a.merge(b); // List([2, 3]) ``` It seems like `merge` method operates with indexes, not with values so overrides first item of `List a` with first item of `List b`. So, my question is what is the most simple way to get union of several lists (ideally without iterating over them and other extra operations).
2015/05/08
[ "https://Stackoverflow.com/questions/30126698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1950327/" ]
You are correct about merge. Merge will update the index with the current value of the merging list. So in your case you had ``` [0] = 1 ``` and merged it with ``` [0] = 2 [1] = 3 ``` which ended up overwriting `[0]=1` with `[0]=2`, and then set `[1]=3` resulting in your observed `[2,3]` array after merging. A very simple approach to solving this would be to use [`concat`](http://facebook.github.io/immutable-js/docs/#/Iterable/concat) ``` var a = Immutable.List([1]); var b = Immutable.List([2,3]); var c = a.concat(b); ``` And it will work for this situation. However, if the situation is more complex, this may be incorrect. For example, ``` var a = Immutable.List([1,4]); var b = Immutable.List([2,3,4]); ``` this would give you two 4's which is not technically a union anymore. Unfortunately there is no union included in Immutable. An easy way to implemented it would be to set each value in each list as the key to an object, and then take those keys as the resulting union. ***[`jsFiddle Demo`](http://jsfiddle.net/ax4t7oof/)*** ``` function union(left,right){ //object to use for holding keys var union = {}; //takes the first array and adds its values as keys to the union object left.forEach(function(x){ union[x] = undefined; }); //takes the second array and adds its values as keys to the union object right.forEach(function(x){ union[x] = undefined; }); //uses the keys of the union object in the constructor of List //to return the same type we started with //parseInt is used in map to ensure the value type is retained //it would be string otherwise return Immutable.List(Object.keys(union).map(function(i){ return parseInt(i,10); })); } ``` This process is `O(2(n+m))`. Any process which uses `contains` or `indexOf` is going to end up being `O(n^2)` so that is why the keys were used here. *late edit* **Hyper-performant** ``` function union(left,right){ var list = [], screen = {}; for(var i = 0; i < left.length; i++){ if(!screen[left[i]])list.push(i); screen[left[i]] = 1; } for(var i = 0; i < right.length; i++){ if(!screen[right[i]])list.push(i); screen[right[i]] = 1; } return Immutable.List(list); } ```
7,727
Briefly ------- My deadlift is great and my squat sucks. I want to continue squatting 3x5 more and more weight while I keep my deadlift where it is. **What's the best way to maintain my deadlift strength with a minimum of training time and recovery resources so I can focus efforts on my squat?** Details ------- I'm male, 5'10'' tall, and weigh approximately 170-175 pounds, though I'm working on moving up to 180 or 185. I keep pretty good food quality but occasionally under-eat at lunch. I recently PR'd my deadlift at 385x2, and can hit a hard set of 5 in the mid-300s. My front squat is primary: I am not currently working on my back squat because of form issues and because I think [it's not necessary](http://www.theironsamurai.com/2011/06/30/are-back-squats-really-necessary-the-legs-hips-and-ass-issue/), but for background I can back squat 225 for reps, probably 240 or so for a max. My front squat has progressed nicely from ~165 to 215 by doing 3 sets of 5, increasing weight every other workout. Once or twice I've been forced to do a 3x3 workout before graduating to 3x5. Those misses were due to poor recovery combined with foolishly adding weight as scheduled. I lift two or three times a week, with two to four days a week of judo, moderate hiking and swimming, sprints, or Ultimate. Lifting sessions currently go as follows: 1. Front squat, starting at 45 or 95 and taking steps of ~50lbs up to 3x5 at the work weight 2. Deadlift, starting at 145 or 215 and taking steps of ~70lbs up to a set of five in the 315-350 range or a double or triple in the 350-380 range 3. One-arm overhead kettlebell presses, 50 pounds, 3x5 or 5x5 4. Other stuff that varies and isn't too strenuous What I'm looking for is a program, preferably with references or an explanation, that describes maintaining the deadlift or other major barbell exercise at a given level while working on other lifts. My goal is the minimum amount of deadlifting in order to still lift in the upper 300s, so that my body can use more recovery resources towards squat strength. However, I'm asking this because I *think* that maintaining my deadlift as-is will make it easier to improve my squat. If I'm wrong on that, tell me, and tell me what to fix instead.
2012/08/17
[ "https://fitness.stackexchange.com/questions/7727", "https://fitness.stackexchange.com", "https://fitness.stackexchange.com/users/1771/" ]
Combination between Robin and my responses: Once a week maintenance on deadlifting, with alternating between a slightly higher rep count and less weight with weeks of higher weight and less reps. So for maintenance, one week do two reps at near max, followed by slightly less weight in the 5 rep range the next week. A few times a year kick it up a bit and try to hit your one rep max that you are maintaining. I would also cycle through some different variations on the deadlift, conventional, sumo, romanian so as not to get stale. I tried to find the references I was looking at originally, but came up dry on my search strings, I'll have to look through my browser history at home.
21,992,842
``` sorted_x = sorted(x.items(), key=lambda x: x[1]) ``` This sorts dictionary x by the first value. I have a dictionary such that: ``` x = {a:(1,2,3)} ``` I want to sort dictionary `x` by the 2nd value of the tuple. How would I accomplish this?
2014/02/24
[ "https://Stackoverflow.com/questions/21992842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2797078/" ]
The same way your first example worked: `sorted(x.items(), key=lambda x: x[1][1])`. Note that this, like your first example, will return a list, not a dict. Dicts, being hash maps, are not ordered and can't be sorted.
2,336
I'm using Blender for Unity3D game asset creation. The Array Modifier does something great (see below) that I would love to be able to do for arbitrary collections of objects. I'm hoping someone might provide instructions / pointers / plugin / ... to help achieve! So... An unapplied Array Modifier creates an entity that behaves like a single mesh during export but can still be modified easily (e.g. change the curve, parameters, etc). I wish to 'group' arbitrary objects to export the same way (possibly sub-including the results of an Array Modifier). A concrete example ------------------ A table comprises legs and top. The legs are identical so array-ed or group instanced (depending upon layout). (Those legs might internally use Curve Modifier which we want to tweak in the future and their spacing might also need tweaking (picture doing this with a long curving fence if you're thinking manual answers!)). On export, the arrayed legs appear as a single mesh (which appears in Unity3D as a single GameObject). Perfect! The table top needs including (otherwise its separation degrades performance due to requiring an extra draw call). * **Group**-ing in Blender does nothing (that I can tell?). * **Parent**-ing them merely produces same parenting in Unity = same performance issue. * **Join**-ing them will make the single object but prevent easy future modification. Potentials ---------- My research found [is-it-possible-to-group-several-objects-and-then-manipulate-them-scale-rotate](https://blender.stackexchange.com/questions/105/is-it-possible-to-group-several-objects-and-then-manipulate-them-scale-rotate) which suggests both parenting and grouping but otherwise nothing. The only potentials I see involves temporarily joining before / during export. This seems annoying overhead. 'Before' requires keeping the blend files outside Unity losing the lovely auto-update. IIUC Unity imports blend files through some magic Blender-invoking that does an FBX export. 'During' might involve some programming hooks that might join things during that export but not modify the original file? All thoughts welcome! Thanks in advance!
2013/08/12
[ "https://blender.stackexchange.com/questions/2336", "https://blender.stackexchange.com", "https://blender.stackexchange.com/users/1087/" ]
It seems that joining (`Ctrl``J`) is exactly what you are looking for. Joining shouldn't prevent future modification. Within the joined mesh, there will still be two disjoint islands (or five, if each leg is disjoint): the table top and the rest of the mesh. If you want to separate it again to work with, you can use `P` → **By Selection**. You can even, immediately after joining, save the table top as a vertex group so you don't have to worry about selecting it again later, although the [**Select Linked**](http://wiki.blender.org/index.php/Doc:2.4/Tutorials/Modeling/Meshes/Selection#Select_Linked) function (`L` or `Ctrl` `L`) should work for that anyway. Are there any other concerns for joining? If so, perhaps there's a workaround.
16,879,520
Here's the deal, I am handling a OCR text document and grabbing UPC information from it with RegEx. That part I've figured out. Then I query a database and if I don't have record of that UPC I need to go back to the text document and get the description of the product. The format on the receipt is: ``` NAME OF ITEM 123456789012 OTHER NAME 987654321098 NAME 567890123456 ``` So, when I go back the second time to find the name of the item I am at a complete loss. I know how to get to the line where the UPC is, but how can I use something like regex to get the name that precedes the UPC? Or some other method. I was thinking of somehow storing the entire line and then parsing it with PHP, but not sure how to get the line either. Using PHP.
2013/06/02
[ "https://Stackoverflow.com/questions/16879520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1229594/" ]
Get all of the names of the items indexed by their UPCs with a regex and [`preg_match_all()`](http://php.net/preg_match_all): ``` $str = 'NAME OF ITEM 123456789012 OTHER NAME 987654321098 NAME 567890123456'; preg_match_all( '/^(.*?)\s+(\d+)/m', $str, $matches); $items = array(); foreach( $matches[2] as $k => $upc) { if( !isset( $items[$upc])) { $items[$upc] = array( 'name' => $matches[1][$k], 'count' => 0); } $items[$upc]['count']++; } ``` This forms `$items` so it looks like: ``` Array ( [123456789012] => NAME OF ITEM [987654321098] => OTHER NAME [567890123456] => NAME ) ``` Now, you can lookup any item name you want in `O(1)` time, as seen in [this demo](http://3v4l.org/AvvN9): ``` echo $items['987654321098']; // OTHER NAME ```
22,190,079
I am looking for a solution to change the font size of the title of every Dialog in my application. I would like to change only the `styles.xml` without changing the code where the dialogs are created. This is what I tried to do: ``` <style name="CustomDialogTheme" parent="@android:style/Theme.Dialog"> <item name="android:windowTitleStyle">@style/MyOwnDialogTitle</item> <item name="android:textSize">40sp</item> </style> <style name="MyOwnDialogTitle"> <item name="android:textSize">70sp</item> </style> <style name="MyTheme"> <item name="android:alertDialogStyle">@style/CustomDialogTheme</item> </style> ``` Thank you :)
2014/03/05
[ "https://Stackoverflow.com/questions/22190079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3382127/" ]
**THIS IS A POSSIBLE WORKAROUND FOR BUGS IN ADT 22.6.0 ONLY, THESE BUGS SUBSEQUENTLY FIXED IN FOLLOWING BUILDS** ---------------------------------------------------------------------------------------------------------------- **Download and install new ADT v22.6.1 from [here (zip)](http://dl.google.com/android/ADT-22.6.1.zip) or use SDK manager to update** Seems like some bug from Google side, this problem found after **"ADT 22.6"** update. Widely reported on **"Android Open Source Project - Issue Tracker"** and nobody properly answered it yet. However I was partially successful to create an AVD by opening **"AVD manager.exe"** from **"Android SDK"** for creating new AVD try to open directly AVD Manager.exe in SDK folder. May be we have to wait for any conformation from **Android community** Worked for me, sort of.. . **(Windows 8.1 Pro 64 Bit, Java JDK 1.7 Update 25, Eclipse Standard Kepler Service Release 1, Android Development Toolkit 22.6.0.v201403010043-1049357)** **Update 1** Further research revealed that launching **AVD Manager** from **SDK Manager (Tools --> Manage AVDs...)** also works without any problems. **Update 2** More bad news is AVD creation not working from **command line tool** too. **Update 3** Assuming some parameter passed during launching **AVD manager** from **Eclipse** causes these problems **Update 4** Updated **Java** to **JDK 1.7 Update 51** and **Eclipse Standard SDK** to **Kepler Service Release 2** their latest and no resolution to the problems. Also tested under **Debian** and same results obtained. **Update 5** At [**https://code.google.com/p/android/issues/detail?id=66661**](https://code.google.com/p/android/issues/detail?id=66661) android project members conforms the problems and promises to fix by upcoming versions of ADT (22.6.1 - 22.6.3). At the mean time I would suggest to roll-back **ADT** to a lower version [**version 22.3.0**](https://dl.google.com/android/ADT-22.3.0.zip) To uninstall current ADT go to **Help --> About Eclipse --> Installation Details --> Android Development Tools --> Uninstall** I may suggest uninstalling whole packages from Android **(DDMS, Hierarchy Viewer, NDT, Traceview, OpenGL ES..etc..)** to avoid any possible compatibility issues and install a fresh new ADT from above link through **archive installation method**. Hope this will solve this problem temporarily. And wait for new release of ADT [here](http://developer.android.com/tools/sdk/eclipse-adt.html). **Update 6** New **ADT**, **version 22.6.1** is out now which will solve these problems
1,890
How to best tune a Linux PC for development purposes?
2009/04/30
[ "https://serverfault.com/questions/1890", "https://serverfault.com", "https://serverfault.com/users/1232/" ]
Spend money on RAM first, disk second, and CPU speed third. Use CVS or some other software version control system even if you're the only programmer. Back up frequently. Actually, spend money on a good monitor and keyboard first.
431,981
show that $5^n + 6^n = 0 \pmod{11}$ for all odd number $n$, but not for any even number $n$. I was not sure about this question. Do I have to pick numbers for $n$? Until I get odd number?
2013/06/28
[ "https://math.stackexchange.com/questions/431981", "https://math.stackexchange.com", "https://math.stackexchange.com/users/84329/" ]
**Hint:** $6\equiv -5\pmod{11}$. ${}{}{}{}$
6,259,764
I am working on my first extension for Google Chrome. I want to be able to hit the "Thumbs Up" button on the Google Music Beta page using my extension. For some reason, the thumbs up button seems to be much more complicated than shuffle, repeat, play, next, and previous. For all of those, the following code works: ``` chrome.tabs.executeScript(tab_id, { code: "location.assign('javascript:SJBpost(\"" + command + "\");void 0');", allFrames: true }); ``` where command="playPause", "nextSong", "prevSong", "toggleShuffle", "togglePlay", etc. I figured a lot of those out using the developer tools to follow the stack trace and see the arguments given to SJBpost. Trying SJBpost with "thumbsUp" returns an error. Obviously this question is going to be restricted to a smaller crowd since not everyone is going to be able to view the source of Google Music, but if you can help me out, I would greatly appreciate it. The div for the thumbs up on the Google Music page looks like this: ``` <div id="thumbsUpPlayer" class="thumbsUp" title="Thumbs up"></div> ``` Now, I've tried doing this using jQuery: ``` $("#thumbsUpPlayer").click() ``` But I get TypeError, undefined\_method message in the javascript console. Any help would be greatly appreciated. I am a huge beginner to javascript and plugins, and all of this stuff, and I'm really excited to get these last pieces of the extension together. Thank you!
2011/06/07
[ "https://Stackoverflow.com/questions/6259764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/345551/" ]
It seems that Google Music Beta doesn't actually listen on the `click()` event per se, rather, it is based on the events which usually precede the actual click event: mouseover, mousedown and mouseup. I'm not a jQuery expert, so I can't exactly figure out why `$("#thumbsUpPlayer").mouseover().mousedown().mouseup()` doesn't work (neither does doing `.trigger`). Anyway, here's some (tested on June 21) working javascript code (no dependencies). ``` function triggerMouseEvent(element, eventname){ var event = document.createEvent('MouseEvents'); event.initMouseEvent(eventname, true, true, document.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, element); element.dispatchEvent(event); } function replicateClick(element){ triggerMouseEvent(element, 'mouseover'); triggerMouseEvent(element, 'mousedown'); triggerMouseEvent(element, 'mouseup'); } function thumbsUp(){ replicateClick(document.getElementById('thumbsUpPlayer')); } function thumbsDown(){ replicateClick(document.getElementById('thumbsDownPlayer')); } ``` It should be probably fairly easy to use, just call `thumbsUp()` if you want a thumbs up or call `thumbsDown()` if you want to thumbs down.
4,856,659
I am working with .NET but I need to communicate with a logging service, unix based, that expects seconds and microseconds since the Unix epoch time. The seconds is easily retrievable doing something like: ``` DateTime UnixEpoch = new DateTime(1970, 1, 1); TimeSpan time = DateTime.UtcNow() - UnixEpoch int seconds = (int) time.TotalSeconds ``` however, I am unsure how to calculate the microseconds. I could use the TotalMilliseconds property and convert it to microseconds but I believe that defeats the purpose of using microseconds as a precise measurement. I have looked into using the StopWatch class but it doesn't seem like I can seed it with a time (Unix Epoch for example). Thanks.
2011/01/31
[ "https://Stackoverflow.com/questions/4856659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/409122/" ]
Use the [`Ticks`](http://msdn.microsoft.com/en-us/library/system.timespan.ticks.aspx) property to get the most fine-grained level of detail. A tick is 100ns, so divide by 10 to get to microseconds. However, that talks about the *representation precision* - it doesn't talk about the *accuracy* at all. Given the coarse granularity of `DateTime.UtcNow` I wouldn't expect it to be particularly useful. See Eric Lippert's [blog post about the difference between precision and accuracy](http://blogs.msdn.com/b/ericlippert/archive/2010/04/08/precision-and-accuracy-of-datetime.aspx) for more information. You may want to start a stopwatch at a known time, and basically add *its* time to the "start point". Note that "ticks" from `Stopwatch` doesn't mean the same as `TimeSpan.Ticks`.
28,096,348
So I'm trying to change the behavior of an `operator+` method for the case where I need less of it implemented within the method of another class. If someone here could give me a hand with one or more of the following I'd be much obliged: 1. Maybe I've been searching wrong? If so, a link to the correct answer or source of info would be great. 2. General way to code something like this? Some code example with the scenario: ```c++ class Rational { public: const Rational Rational::operator+(const Rational &other) const { Rational ans; ans._denominator = other.getDenominator() * getDenominator(); ans._numerator = getNumerator() * other.getDenominator() + other.getNumerator() * getDenominator(); ans.init_rational(); /* <-- This part formats the rational number every time so that it'd look like 1/2 instead of 2/4(f.e). The purpose of the specialized method in the other class is to perform the trace() method where lots of x+x+x is performed, therefore it'd be slow and unnecessary to use "init_rational()" before it's done adding */ return ans; } }; ``` The class where the specialized operator+ is needed: ```c++ template <class T> class Matrix { private: int rows, cols; vector<vector<T>> mat; public: const bool trace(T& ans) const { if (_rows() != _cols()) { ans = T(); return false; } ans = T(); for (int i = 0; i < _rows(); i++) { ans = ans + mat[i][i]; } return true; } } ``` BTW, I suppose what I'm trying to accomplish can be done without the specialization that I asked for with a specialization for the whole `Rational` type instead, is that the actual answer here? Or is what I'm looking for an option too? P.S: If you feel like more info/methods are needed, just ask :p EDIT: From the responses I'm getting here I guess I'm not meant to do it the way I wanted, what about doing something like this though? ```c++ template <Rational> const bool trace(Rational& ans) const{ if (_rows() != _cols()){ ans = Rational(); return false; } ans = Rational(); for (int i = 0; i < _rows(); i++){ //adding method implemented here or in a separate function in the Rational class } return true; } ```
2015/01/22
[ "https://Stackoverflow.com/questions/28096348", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3075303/" ]
What you asked for in the first part of your question indeed didn't seem to make sense like Barry stated, considering your edited info and comments though, is this perhaps what you were looking for? ``` bool trace(Rational& ans) const{return true;} ``` and then ``` template<typename T> bool trace(T& ans) const{return false;} ``` If so, you were really close already, just that you need to place the template declaration on top and as the generic type instead of the other way around where you tended to the specific type :)
3,398
Revelation 21:5 (NIV):: > > He who was seated on the throne said, “I am making everything new!” Then he said, “Write this down, for these words are trustworthy and true.” > > > My pastor included this verse in his sermon today, and after reading it, he added his own emphasis, "And this means **ev-ery-thing!**" But does it really? What "everything" is being made new? My car won't be new again, will it? **What is this verse *really* saying?**
2011/09/26
[ "https://christianity.stackexchange.com/questions/3398", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/20/" ]
The following is taken from a section of the Introduction in the **"Complete Jewish Bible"**, English Version by David Stern, entitled **The Canon** > > Scholars agree that the canon of the Torah achieved its present form before the time of 'Ezra (around 445 B.C.E.), the Prophets later and the Writings last. But the final review of the canon was made by the Council of Yavneh (Jamnia) convened around 90 C.E. by Rabbi Yochanan Ben-Zakkai in the wake of the destruction of the temple by Romans twenty years earlier. Several books now included in the Tanakh were questioned—Daniel and Ezekiel, because of their startling visions and experiences; Esther, because God is not mentioned in it; Song of Songs, because of its overtly sexual character; and Ecclesiastes, because of its depressed world-viewpoint (except for the last two verses, which redeemed it). Ecclesiasticus (not the same as Ecclesiates) was rejected by the rabbis of Yavneh but is found in the Apocrypha, a collection of fifteen ancient Jewish books that include Tobit, Judith, 1-2 Maccabees and the Wisdom of Solomon. Catholic and Anglican Bibles include the Apocrypha. Some sixty other ancient books are collectively called the Pseudepigrapha. English language editions of the Apocrypha and the Pseudipigrapha are available. > > > There are several more pages of history regarding the formation of newer versions, New King James, etc. and the attribution of writings (who wrote which book) for the books of the Tanakh (Old Testament) in the Introduction I've sighted above. However, the passage above seems to best answer the question about the actual "compiling" of the Old Testament.
42,499,764
I am trying to display the product listing on listing page of the product. Each product has category.My table structure ``` categories id name description 1 Cat1 Category 1 2 Cat2 Category 2 ``` This is the category table having `id name and description` ``` products id name description category_id 1 pro1 product 1 1 2 pro2 product 2 2 ``` This is the product table having category\_id. ``` Product Model public function categories() { return $this->belongsTo("App\Category"); } ``` This is the product model where the products are belongs to category ``` Category Model public function products() { return $this->hasMany("App\Product"); } ``` This is the Category model where the Category has many product Now in the product controller on listing function I want the list of product with category name ``` public function index() { $product = Product::with('categories')->get(); print_r($product->categories);die; return view('product.index')->with("list",$product); } ``` I want my Output should be ``` products id name description category name 1 pro1 product 1 cat1 2 pro2 product 2 cat2 ``` I found this error `"Property [categories] does not exist on this collection instance."`
2017/02/28
[ "https://Stackoverflow.com/questions/42499764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5142381/" ]
When you run: ``` $product = Product::with('categories')->get(); ``` you are not getting single products but all products so it should be rather renamed to: ``` $products = Product::with('categories')->get(); ``` Further, looking at your database structure, each product belongs to single category so in `Product` model you should rename ``` public function categories() { return $this->belongsTo("App\Category"); } ``` to ``` public function category() { return $this->belongsTo("App\Category"); } ``` If you do this change, you should then again change ``` $products = Product::with('categories')->get(); ``` to ``` $products = Product::with('category')->get(); ``` Going back to your controller assuming all your products have set category, you can display it like this: ``` foreach ($products as $product) { echo $product->id.' '.$product->name.' '.$product->description.' '.$product->category->name; } ``` You can obviously do the same later in Blade view like so: ``` @foreach ($list as $product) {{ $product->id }} {{$product->name}} {{ $product->description }} {{ $product->category->name }} @endforeach ```
19,945,168
Profiling result of my program says maximum theoretical achieved occupancy is 50% and the limiter are registers. What are general instructions about minimizing number of registers in CUDA code? I see profiling results show number of registers are much more than number of 32 and 16 bit variables I have in my code (per thread)? What can be potentially the reason? Plus, setting "maxregcount" to 32 (32 \* 2048(max threads per SMX) = 65536(max registers per SMX), solves the occupancy limit issue but I don't get much of speed up. Does "maxregcount" try to optimize the code more, so it won't be wasteful in using registers? Or it simply chooses L1 cache or local memory for register spilling?
2013/11/13
[ "https://Stackoverflow.com/questions/19945168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2386951/" ]
You should be able to (depending on your query) directly cast a bit to a bool. There is another thread that talks about this at [DataSets - Class Model - How to get Bool Value from a DataSet](https://stackoverflow.com/questions/3308575/datasets-class-model-how-to-get-bool-value-from-a-dataset).
2,048,807
When I call the `jrxml` file through `.load()`, its throw a exception `FileNotfoundException`. I have tried with absolute path, but it does not work. Please help.
2010/01/12
[ "https://Stackoverflow.com/questions/2048807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/248868/" ]
`FileNotFoundException` generally means the file is not there. Get the path from your code and paste it in you filesystem explorer and see if it exists. If it does, it means it is for some reason inaccessible: > > This exception will be thrown by the FileInputStream, FileOutputStream, and RandomAccessFile constructors when a file with the specified pathname does not exist. It will also be thrown by these constructors if the file does exist but for some reason is inaccessible, for example when an attempt is made to open a read-only file for writing. > > >
105,945
Is there a functionality on StackOverflow as subscribing to rss related to specified tags? So a will receive feeds only that has tags i defined?
2011/09/12
[ "https://meta.stackexchange.com/questions/105945", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/-1/" ]
Create a [filter](https://stackexchange.com/filters), then scroll down and click the RSS link. [Example](https://stackexchange.com/feeds/tagsets/21857/meta-rss?sort=active), linked from [here](https://stackexchange.com/filters/21857/meta-rss).
60,981
I have been adopting [flipped classroom strategies](https://en.wikipedia.org/wiki/Flipped_classroom) (in upper-level chemistry classes ~20-30 students), but I often get feedback from students that they want me to "just go back to regular lectures" and that they perceive the flipped classes as more work. I think the results are positive for student learning in my classes, although I haven't done formal assessments. I also personally appreciate the change of pace and style. Previously students might have felt that I wasn't giving enough concrete examples and this definitely solves the issue, as well as making me more responsive to a particular class's needs. I am wondering about strategies to overcome student apprehension about active learning styles.
2016/01/02
[ "https://academia.stackexchange.com/questions/60981", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/21869/" ]
Here are some ideas from Linda Kober, author of a publication by the National Research Council's Board on Science Education, *Reaching Students: What Research Says About Effective Instruction in Undergraduate Science and Engineering*. This comes from Chapter 6, "Overcoming Challenges", in the section "Helping Students Embrace New Ways of Learning and Teaching": > > * Make clear from the first day why these teaching strategies are effective, and be explicit about how they benefit students, and what > is expected of students. > * Show students evidence of how research-based strategies will help them learn and prepare for their future life. > * Use a variety of interesting learning activities. > * Encourage word-of-mouth among upper-level students who have already taken the course. > * Listen to students’ concerns and make changes to address legitimate ones. > * Make sure that grading and other policies are fair [e.g., group work]. > > > For details you can get a [free PDF download here](http://www.nap.edu/catalog/18687/reaching-students-what-research-says-about-effective-instruction-in-undergraduate) (note blue button in top right).
432,863
Most software creates a directory (usually in `~/Library` or `~/Library/Application Support` in MacOS) to store user preferences, browser history, etc. Most software attempts to create their data directory immediately upon launch and will either crash or refuse to continue if the directory cannot be created. For example, if I create a *file* called `~/Library/Application Support/Google`, then Google Chrome will be unable to access or create a directory there, because the name is already taken by a non directory. This will cause Google Chrome to immediately 'quit unexpectedly'. If I do the equivalent to Firefox, a message will say that an 'unexpected error has prevented changes from being saved' and will have to quit. Why would changes have to be saved in software so importantly that the software will break if it cannot? Do they really need to create a bunch of files to render a webpage at a URL? I do not see any way were *saving data* is critical to the immediate execution of the app. The worst that should happen is all the apps configuration and data should reset as soon as it quits. Why is it common for apps to **break immediately** if no data saving directory is available?
2021/10/20
[ "https://softwareengineering.stackexchange.com/questions/432863", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/-1/" ]
In C programming, we have this notion of *undefined behavior.* It means that, if you write code that creates situations that are not defined by the language standard, anything can happen. The program could crash, it could corrupt memory, it could accidentally call `fireMissiles()`. Or, it could exhibit reasonable behavior. There's no way to be sure, once you enter the "undefined behavior" space. Hence, the simple assumption that a program usually makes that it can access the disk, not an unreasonable assumption in most cases. Most programs will give up if the computer they're running on cannot meet this simple requirement. Continuing to run a program when a machine has been perceived to be compromised in some way can cause all sorts of unforseen problems. Chrome doesn't make the guarantee that it doesn't save any kind of state at all in incognito mode. It only makes certain assertions about your privacy. Remembering the window location when you close the program doesn't have anything to do with your privacy, and I'm sure there are other examples that I haven't thought of.
38,359,938
My view is like: ``` <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <RecyclerView android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" /> <TextView android:layout_width="match_parent" android:layout_height="50dp" /> </LinearLayout> ``` It will give 50dp to `TextView` and rest of area to `RecyclerView`. But if items in `RecyclerView` are less than, say 1 or 2, then it should shrink to the height of it's child views other wise behave like layout specifies. Can any one help??
2016/07/13
[ "https://Stackoverflow.com/questions/38359938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5482691/" ]
I think the best option would be to change `LinearLayout.LayoutParams` of the root view dynamically. When the `RecyclerView`has a low amount of children, then set `LinearLayout` params to: ``` LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT); layout.setParams(params); ``` otherwise, leave as it is. It is very easy to detect if `RecyclerView` should be wrapped. Obtain LinearLayout height: ``` int height = layout.getTop() - layout.getBottom() ``` If this height is lower than the expected maximum height (screen height or other predefined value).
668,550
I am trying to customize chapter title putting the text inside a frame with only the leftframe on. I am thinking at something like that: "1 | chapter". Any suggest will be very appreciate.
2022/12/14
[ "https://tex.stackexchange.com/questions/668550", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/286730/" ]
You can define a command that uses a `\framed` to draw the rule, then use `textcommand` key of `\setuphead` to apply this to all chapters. ```tex \define[1]\leftframed{% \inframed[frame=off, leftframe=on]{#1}% } \setuphead[chapter][ textcommand=\leftframed, ] \starttext \chapter{Section} Hello world! \stoptext ``` [![output sample](https://i.stack.imgur.com/Efpi4.png)](https://i.stack.imgur.com/Efpi4.png)
10,389
I have seen written on almost every music CD and Cassette Tape that I have in my house the line: > > Please do not play on Shabbos and Yom Tov > > > I've always wondered if this is really necessary. Does not having this line make the seller an accomplice to the one who transgresses on Shabbos? More importantly, though, how did this practice originate? Last time I bought a chicken at my local butcher, I don't recall seeing a sign "please do not cook on Shabbos". Actually, I don't remember seeing this *anywhere* else. So why music?
2011/10/02
[ "https://judaism.stackexchange.com/questions/10389", "https://judaism.stackexchange.com", "https://judaism.stackexchange.com/users/128/" ]
Maybe because early Jewish recordings were mostly cantorial style, and there was a serious concern that people would play recordings of Shabbos and Yom Tov liturgy on those days. Also, perhaps it is psychologically more disturbing to think that someone will play a recording that makes **your voice** speak on Shabbos.
21,496,331
In the [reference](http://docs.angularjs.org/guide/dev_guide.services.creating_services)I read: > > Lastly, it is important to realize that all Angular services are > application singletons. This means that there is only one instance of > a given service per injector. > > > but with this simple code seems not to be a singleton ``` 'use strict'; angular.module('animal', []) .factory('Animal',function(){ return function(vocalization){ return { vocalization:vocalization, vocalize : function () { console.log('vocalize: ' + this.vocalization); } } } }); angular.module('app', ['animal']) .factory('Dog', function (Animal) { return Animal('bark bark!'); }) .factory('Cat', function (Animal) { return Animal('meeeooooow'); }) .controller('MainCtrl',function($scope,Cat,Dog){ $scope.cat = Cat; $scope.dog = Dog; console.log($scope.cat); console.log($scope.dog); //$scope.cat = Cat; }); ``` I'm a little confused can you explain me what's the matter ? **UPDATE 1** May be I'm not the sharpest tool in the shed but afer the @Khanh TO reply it would be a better explanation in the reference it's not very clear. **UPDATE 2** ``` 'use strict'; angular.module('animal', []) .factory('Animal',function(){ return { vocalization:'', vocalize : function () { console.log('vocalize: ' + this.vocalization); } } }); angular.module('dog', ['animal']) .factory('Dog', function (Animal) { Animal.vocalization = 'bark bark!'; Animal.color = 'red'; return Animal; }); angular.module('cat', ['animal']) .factory('Cat', function (Animal) { Animal.vocalization = 'meowwww'; Animal.color = 'white'; return Animal; }); angular.module('app', ['dog','cat']) .controller('MainCtrl',function($scope,Cat,Dog){ $scope.cat = Cat; $scope.dog = Dog; console.log($scope.cat); console.log($scope.dog); //$scope.cat = Cat; }); ``` BOOM it's a singleton ! **UPDATE 3** But if you do like ``` 'use strict'; angular.module('animal', []) .factory('Animal',function(){ return function(vocalization){ return { vocalization:vocalization, vocalize : function () { console.log('vocalize: ' + this.vocalization); } } } }); angular.module('app', ['animal']) .factory('Dog', function (Animal) { function ngDog(){ this.prop = 'my prop 1'; this.myMethod = function(){ console.log('test 1'); } } return angular.extend(Animal('bark bark!'), new ngDog()); }) .factory('Cat', function (Animal) { function ngCat(){ this.prop = 'my prop 2'; this.myMethod = function(){ console.log('test 2'); } } return angular.extend(Animal('meooow'), new ngCat()); }) .controller('MainCtrl',function($scope,Cat,Dog){ $scope.cat = Cat; $scope.dog = Dog; console.log($scope.cat); console.log($scope.dog); //$scope.cat = Cat; }); ``` it works
2014/02/01
[ "https://Stackoverflow.com/questions/21496331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/356380/" ]
It's singleton, there is only one object, but is injected into many places. (objects are passed by reference to a method) All your `Animal` are object pointers referring to **the same animal object** which is a **function** in your case. Your `Cat` and `Dog` are objects constructed by this function.
19,172,302
Goal: To Remeasure and then redraw only those signalgraphs that are in view in the virtualizing stack panel of a scrollviewer. Current build: Currently I have a dependency property (UnitsOfTimePerAxisDivision) that affects measure whenever the container in the scrollviewer (signalgraph) is updated. ``` public static readonly DependencyProperty UnitsOfTimePerAxisDivisionProperty = DependencyProperty.Register("UnitsOfTimePerAxisDivision", typeof(int), typeof(SignalGraph), new FrameworkPropertyMetadata(1), FrameworkPropertyMetadataOptions.AffectsMeasure); ``` However, this updates every signalgraph, including those that are not visible. Running measure and then redraw on every single signal is way too time consuming. 1. How can I update only the visible ones? I thought about doing some sort of test like this, [In WPF, how can I determine whether a control is visible to the user?](https://stackoverflow.com/questions/1517743/in-wpf-how-can-i-determine-whether-a-control-is-visible-to-the-user) by basically setting a propertychangedcallback in which I test whether each signal is visible. I will end up testing all the signals still, but at least I won't be drawing all of them. My 2nd question is whether there is some way I can implement this by relying on functions called in measure/arrange. My understanding of virtualizing stack panel is as follows: At the top level we have a treeview that contains a scrollviewer. the scrollviewer's controltemplate contains a grid in which the scrollcontentpresenter places the items within a column and row of set size. ``` ControlTemplate TargetType="{x:Type ScrollViewer}"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="Auto"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="*"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <ScrollContentPresenter Grid.Column="0" Grid.Row="0" /> <ScrollBar Margin="{Binding RelativeSource={RelativeSource AncestorType={x:Type DaedalusGraphViewer:GraphViewer}}, Path=GraphHeight, Converter={StaticResource ScrollBarTopMarginConverter}}" Grid.Row="0" Grid.Column="1" Width="18" Name="PART_VerticalScrollBar" Orientation="Vertical" Value="{TemplateBinding VerticalOffset}" Maximum="{TemplateBinding ScrollableHeight}" ViewportSize="{TemplateBinding ViewportHeight}" Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}"/> <ScrollBar Height="18" Name="PART_HorizontalScrollBar" Orientation="Horizontal" Grid.Row="1" Grid.Column="0" Value="{TemplateBinding HorizontalOffset}" Maximum="{TemplateBinding ScrollableWidth}" ViewportSize="{TemplateBinding ViewportWidth}" Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}"/> </Grid> </ControlTemplate> ``` so let's assume for a second that I tell scrollviewer to remeasure and that the scrollviewer takes up 100x100 on the screen. This results in the scrollviewer measuring the grid by calling the grids.measure(available size) with the available size of 100x100. The grid then deducts the size of the scrollbars (we will just guess ten), and tells scrollviewerpresenter to measure itself with 90x90. The presenter uses the virtualizing stackpanel, which then gives the children infinite size to measure themselves with (both vertically and horizontally I think). However, the virtualizing stack panel only measures children (signalgraphs) until it has filled its size of 90x90, and then the arrange phase proceeds from the scrollviewer down to the virtualizing stack panel. If that's the case, I can place a call at the end of signalgraph's arrange method and only the onscreen signalgraphs should be arranged and redrawn. ``` protected override Size ArrangeOverride(Size finalSize) { visuals.Clear(); DrawSignal(); return base.ArrangeOverride(finalSize); } ``` However, I find when I set a breakpoint in measure override for both the scrollviewer and the signalgraph, the one in the signalgraph is not hit. I can't understand why signalgraphs are not remeasured if the scrollviewer is remeasured. 2. Is it the case that the measure function stores the last size constraint (availableSize) passed to it by its parent and then doesn't perform a new measure unless the constraint changed? The other possibility I considered that might result in no measurement is if the scrollviewer calculates its size independently of the size of its children and then measures them only if the size is new. But maybe the issue is something like this. if someone has reflector and can get me the actual scrollviewer measureoverride code, that would be amazing. If not, I may try to get reflector tomorrow and figure out how to use it. override Measureoverride ( size availableSize) { Size newSize = availableSize. if (availableSize != this.DesiredSize) { Measure chilren(); } } 3. if this is not the case, then what causes signalgraph not to be measured? edit: Yay, I got something to virtualize. i'm not totally crazy. Just mostly crazy. It appears that applying this style breaks virtualization. Removing it makes everything work. Using the built - in virtualization is a lot better than trying to actually test visibility on each signalgraph that exists. I still don't know the answer to #2 above, but i won't need it if i can get this virtualization working. However, I would like to keep my current style and just figure out why the style is breaking virtualization. ``` <!--Style for scrollviewer for signals--> <Style x:Key="SignalScrollViewerStyle" TargetType="{x:Type Components:SignalScrollViewer}"> <Setter Property="OverridesDefaultStyle" Value="True"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type ScrollViewer}"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="Auto"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="*"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <ScrollContentPresenter Grid.Column="0" Grid.Row="0" /> <ScrollBar Margin="{Binding RelativeSource={RelativeSource AncestorType={x:Type DaedalusGraphViewer:GraphViewer}}, Path=GraphHeight, Converter={StaticResource ScrollBarTopMarginConverter}}" Grid.Row="0" Grid.Column="1" Width="18" Name="PART_VerticalScrollBar" Orientation="Vertical" Value="{TemplateBinding VerticalOffset}" Maximum="{TemplateBinding ScrollableHeight}" ViewportSize="{TemplateBinding ViewportHeight}" Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}"/> <ScrollBar Height="18" Name="PART_HorizontalScrollBar" Orientation="Horizontal" Grid.Row="1" Grid.Column="0" Value="{TemplateBinding HorizontalOffset}" Maximum="{TemplateBinding ScrollableWidth}" ViewportSize="{TemplateBinding ViewportWidth}" Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}"/> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style> ``` edit 2: found the solution on this page: I found the solution on this page: "<http://social.msdn.microsoft.com/Forums/vstudio/en-US/deae32d8-d7e2-4737-8c05-bbd860289425/lost-virtualization-on-styled-scrollviewer?forum=wpf> when overriding the default scrollviewer style i didn't bind the attached property to the scrollviewer contentpresenter. uggh, amazing how hard that one line was to find. I was going crazy, thinking that I didn't know what virtualization was actually supposed to do. The only bothersome thing now is that I still don't fully understand how the layout process works. If I have a dependency property with the metadaoption affectsmeasure, and then the dependency property changes, the item will remeasure. Will the parents then remeasure if the size of the element changes? that would be my guess, but it still doesn't explain why I had scrollviewer children that were not remeasuring during the scrollviewer's measure cycle.
2013/10/04
[ "https://Stackoverflow.com/questions/19172302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2324576/" ]
There is no point in using Reflector. VirtualizingStackPanel maintains a list of visible containers. When you start scrolling up or down the VirtualizingStackPanel will remove containers which won't be needed anymore but creates new one. At the end up end up removing 5 old items but adding 5 new so the count of visible containers always stays the same therefore just change the property UnitsOfTimePerAxisDivision and dont worry about which containers are visible. If ScrollViewer passes 90x90 to VirtualizingStackPanel and futhermore the VirtualizingStackPanel passes infinity to the containers, the containers will only get remeasured when in invalid measure state else they return back the "old" size which is their current size. Just let the WPF do the job and don't worry about performance issues. The VirtualizingStackPanel holds visible containers so there wont be any remeasuring or performance hit on all possible containers. Only 20 will be used even though you have 1000 items.
13,801,167
I'm having a problem with timeouts on the third attempt to call a HttpWebRequest.GetRequestStream. This is for debug code to test an intermittent problem with a third party resource, so it is just making the same request over and over. This problem does not manifest itself when using Fidder as a proxy, so this leads me to believe it has something to do with open connections in the connection pool (I remember reading somewhere that two attempts has something to do with the Http 1.1 spec). A number of questions talks about closing the request and [closing the response](https://stackoverflow.com/a/5508926/198048), but I have a using statement around both, so thought this would happen automatically when it goes out of scope. However I've also tried calling close and flush on both the request and response streams. There's also questions that mention [setting the ConnectionLeaseTimeout](https://stackoverflow.com/q/5827030/198048) to 0. But that didn't work either. I'm not sure what else to try, does anyone have any suggestions?
2012/12/10
[ "https://Stackoverflow.com/questions/13801167", "https://Stackoverflow.com", "https://Stackoverflow.com/users/198048/" ]
The problem is in this line: ``` InetAddress address = InetAddress.getByName( "http://localhost:8084/server/index.jsp"); ``` The `InetAddress.getByName(String)` method requires a hostname. You've given it a URL string. The hostname component of that address is `"localhost"`. If you want to "ping" the host associated with a URL, then you need to parse the URL and extract the hostname component something like this: ``` String hostname = new URL(str).getHost(); ``` But you need to deal with the cases where the URL is malformed, or where it doesn't have a host name component. --- I imagine that you are *actually* trying to test some other hostname, because sending an ICMP\_PING request to `"localhost"` (typically `127.0.0.1`) is kind of pointless.
13,003,848
I have a dictionary, of which every key is holding a list as a value. Each list has one or more tuples with 2 items inside, one integer, one string. Example: ``` my_dict = {'dict_key_1': [(100, 'string_x1234'), (95, 'string_rtx3') ..], 'dict_key_2': [(26, 'string_abc3'), (321, 'string_432fd'), ...], 'dict_key_3': [(32, 'string_232df']} ``` I am iterating through this dictionary, and whilst doing that through items in the list. However, in both iterations I must have the dictionary sorted by the highest value of the first item of any tuple in the list. So in that case, since **321** is highest, I would get **dict\_key\_2** first, and its items would be listed starting with the tuple of which first item is **321**, then **26** and so on. I am fine with the second iteration (sorting the list of tuples) with: ``` sorted(data[k], reverse = True) ``` But I currently fail at sorting the main dictionary depending on the highest value of any tuple in the list that that key of dictionary is holding. I currently have: ``` for k in sorted(data, key=lambda k: sorted(data[k])[0][0]): ``` However, it is not working. But when I try to print `sorted(data[k])[0][0])` whilst iterating, it does indeed give the first value [0] of first tuple [0] after having it ordered on the first values of all tuples in that list (`data[k]`) What am I doing wrong? How can I get this dictionary sorted as needed? Thank you.
2012/10/22
[ "https://Stackoverflow.com/questions/13003848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/853934/" ]
If you don't mind sorting the lists in your dict, I would recommend to do this in two passes: ``` for L in my_dict.itervalues(): L.sort(reverse=True) import collections my_sorted_dict = collections.OrderedDict((k, my_dict[k]) for k in sorted(my_dict, key=my_dict.get, reverse=True)) ```
164,777
I have got two existing rasters that have the same cell size (5x5m). The corner of cells from raster A are located exactly at the centres of cells in raster B. I want to place raster B exactly on top of my raster A. I have tried these options: 1. the tool 'resample' on raster B, while maintaining the same cell size and snapping to raster A. 2. the tools 'raster to points' and consequently 'points to raster' on raster B, again, maintaining the grid size and snapping to raster A. 3. the tool 'copy raster', snapping raster B-copy to raster A. All options have the same result: raster B is still exactly where it lay before, with the corners of cells in B at the centre of cells in A. Whenever Google this problem, I end up at 'environment settings' when making the grid for the first time - but I do not have the data on which the grid was based. Do you have any suggestions on how I could solve this, without a need for the original data? I am working in ArcGIS 10.2.1. I've got a basic license, but might be able to do an upgrade to Standard or Advanced if necessary. Edit: the raster files are .asc files.
2015/09/30
[ "https://gis.stackexchange.com/questions/164777", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/12855/" ]
You could for example use a global object for your layers and use the drodown-value to choose the right layer: ``` var dropdownlayers = {}; dropdownlayers["testlayer1"] = { name: "Testlayer1", layer: L.geoJson(), url: "https://gist.githubusercontent.com/anonymous/6622d04d71ed2dd7927a/raw/0eb6c1145cbd60a050d8e46c2a7805504b901d7d/us_states.js" } ; function dropdown_onchange(choice) { load_layer(dropdownlayers[choice.value]); } function load_layer(dropdownchoice) { clean_map(); $.ajax({ dataType: "json", url: dropdownchoice.url, success: function (data) { var layer = dropdownchoice.layer; layer.clearLayers(); layer.addTo(map); $(data.features).each(function (key, data) { layer.addData(data); }); layerControl.addOverlay(layer, dropdownchoice.name); map.fitBounds(layer.getBounds()); } }).error(function () {}); } ``` <http://jsfiddle.net/expedio/kf7zmuny/>
233,830
I dont need wireless. I am expecting very heavy traffic, with possibly thousands of tcp connections open at one time. This would require that the router has good hardware. I also need to limit the different services i will provide. Lets say i need to guarantee 60% of all the bandwidth to HTTP, 10% FTP, and 10% for Mail... So the router software must have flexible QoS options as well. I don't know which one to chooose, because this information is usually not given on the router specs.
2011/02/10
[ "https://serverfault.com/questions/233830", "https://serverfault.com", "https://serverfault.com/users/50382/" ]
For something like 10mbit, 20-30 if you have large packets - look at MIKROTIK (<http://www.mikrotik.com>). The 450G is a nice little piece I Just put into use here. It handles all requirements very nicely for me. Problem is with the pathetic CPU this has.... it will give in with 10mbit voip traffic (Small packets). HTTP, EMAIL etc can go a lot higher. CHeap (100USD), 5 USB ports, very low power usage. And a LOT you can do (MPLS, VLPS etc.).
318,189
I presently have only 180 of 250 available pokemon. According to my son's iPad, he presently has 229 of 1,000 available pokemon. When my eggs hatch, I get the same ones over and over again. When his eggs hatch, he gets a new one every time. How can I increase my available pokemon from 250 to 1,000?
2017/09/14
[ "https://gaming.stackexchange.com/questions/318189", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/196844/" ]
You can upgrade your Pokemon Box capacity in the Shop. You will need 200 coins. Each upgrade expands capacity by 50. [![enter image description here](https://i.stack.imgur.com/ocOTsl.jpg)](https://i.stack.imgur.com/ocOTsl.jpg) As far as the eggs, it's just luck of the draw.
134,297
I own a domain name that is registered at Network Solutions. They offer me two options to enter for DNS records, `A` and `CNAME`. The website provider I'm hosted at, NationBuilder.com gives instructions that instruct me to point the Name Servers to five of their name servers as follows: * `ns10.nationbuilder.com` * `ns11.nationbuilder.com` * `ns12.nationbuilder.com` * `ns13.nationbuilder.com` * `ns14.nationbuilder.com` * `ns15.nationbuilder.com` Anybody know to configure `A` and or `CNAME` records to point to these name servers? I suspect if I PING the name servers and use the IP address in the results and configure "A" records, something will break down the road since I'm not answering their question correctly.
2021/05/08
[ "https://webmasters.stackexchange.com/questions/134297", "https://webmasters.stackexchange.com", "https://webmasters.stackexchange.com/users/119207/" ]
The Schema.org structured data ontology is designed to describe specific objects and their relationships to other specific objects, it's not designed to make broad comparisons to loosely defined collections (of all the other bank accounts in the country) like that. It's arguable that having a way to mark an interest rate as *the highest within a particular service area* may have value, but it's just not the way Schema.org is designed. So the answer to your question is that **it is not possible** to indicate that info.
50,342,509
Below are my two structs, and I want to print values from both structs in UITableViewCell ``` struct MainCell: Decodable { let job_id: String let job_desig: String let job_desc: String let job_location: String let job_emp_gender: String let job_skills: String let company_id: Int } struct Company: Decodable{ let company_id: Int let company_name: String } var mainCellData = [MainCell]() var companyData = [Company]() ``` **- TableView Methods** ``` func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return mainCellData.count + companyData.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell:JobDetails_TableViewCell = tableView.dequeueReusableCell(withIdentifier: "jobCell") as! JobDetails_TableViewCell for jobs in mainCellData { cell.lblDesig.text = jobs.job_desig cell.lblDesc.text = jobs.job_desc cell.lblLocation.text = jobs.job_location cell.comName.text = jobs.name.company_name } return cell } ``` **As I want to print job\_desig, job\_desc and job\_location from my first struct (struct MainCell: Decodable) and company\_name from my second struct (struct Company: Decodable)** Can anybody help me with my issue?
2018/05/15
[ "https://Stackoverflow.com/questions/50342509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7666458/" ]
1. Your `numberOfRowsInSection` doesn't match your requirement. 2. Get rid of the `for` loop in `cellForRowAt`. 3. You don't need to merge anything. You need to look up the company name based on its id. Your code should look like this: ``` func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return mainCellData.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell:JobDetails_TableViewCell = tableView.dequeueReusableCell(withIdentifier: "jobCell") as! JobDetails_TableViewCell let data = mainCellData[indexPath.row] cell.lblDesig.text = data.job_desig cell.lblDesc.text = data.job_desc cell.lblLocation.text = data.job_location cell.comName.text = companyData.first { $0.company_id == data.company_id }?.company_name return cell } ``` The real trick is getting the company name. The idea is that you have `data.company_id` which is of course the company\_id for the row being displayed. You need to iterate through the `companyData` array and find a `Company` that has the same `company_id`. When a match is found, get the `company_name` from that matching company. The code `companyData.first { $0.company_id == data.company_id }?.company_name` means: Iterate through the `companyData` array and find the first entry where the company\_id equals `data.company_id`. If a match is found, return its `company_name`.
6,444,888
I have a C# application with a user interface that contains options for the type of search a user can perform. The options are 'multiple terms' (splits the search term on spaces), 'case sensitive', and 'regular expression'. More options may be added in the future. The options are stored in the properties IsMultipleTerms, IsCaseSensitive, and IsRegularExpression. Each combination of options has a different search predicate, and search predicates are defined like so: ``` private bool SearchCaseInsensitive(string field) { return field.ToLower().Contains(_searchTermLower); } private bool SearchCaseInsensitiveMultiple(string field) { return _searchTermsLower.All(field.ToLower().Contains); } ``` I filter the list like so: ``` var predicate = GetFilterPredicate(); SearchResults.Where(predicate); ``` I currently achieve the lookup by using a class called SearchPredicateOptionSet: ``` public class PredicateOptionSet { public bool IsCaseSensitive { get; set; } public bool IsRegularExpression { get; set; } public bool IsMultipleTerms { get; set; } public Func<SearchResult, bool> Predicate { get; set; } public PredicateOptionSet(bool isCaseSensitive, bool isRegularExpression, bool isMultipleTerms, Func<SearchResult, bool> predicate) { IsCaseSensitive = isCaseSensitive; IsRegularExpression = isRegularExpression; IsMultipleTerms = isMultipleTerms; Predicate = predicate; } } ``` I create a list of them and then query it: ``` private readonly List<PredicateOptionSet> _predicates; public MainWindow() { _predicates = new List<PredicateOptionSet> { new PredicateOptionSet(true, false, false, result => Search(result.Name)), new PredicateOptionSet(false, false, false, result => SearchCaseInsensitive(result.Name)), new PredicateOptionSet(true, false, true, result => SearchMultiple(result.Name)), new PredicateOptionSet(false, false, true, result => SearchCaseInsensitiveMultiple(result.Name)), }; } private Func<SearchResult, bool> GetFilterPredicate() { var predicate = from p in _predicates where p.IsCaseSensitive == IsCaseSensitive && p.IsMultipleTerms == IsMultipleTerms && p.IsRegularExpression == IsRegularExpression select p.Predicate; return predicate.First(); } ``` Is there a cleaner way to achieve this? I feel like I may be missing an important concept.
2011/06/22
[ "https://Stackoverflow.com/questions/6444888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/60371/" ]
At least for the check part you could use an Enum with the `[Flags]` attribute to create bit field. That might be a little more extensible if you add more methods in the future. You could then use a simple lookup table and do away with the `PredicateOptionSet` class. Example: ``` [Flags] public enum PredicateOption { IsCaseSensitive, IsRegularExpression, IsMultipleTerms }; ``` ... ``` public Dictionary<PredicateOption, Func<SearchResult, bool>> _predicates = new Dictionary<PredicateOption, Func<SearchResult, bool>>(); _predicates.Add(PredicateOption.IsCaseSensitive, result => Search(result.Name)); _predicates.Add(PredicateOption.IsCaseSensitive | PredicateOption.IsMultipleTerms, result => SearchCaseInsensitiveMultiple(result.Name)); ``` .... ``` PredicateOption option = PredicateOption.IsCaseSensitive | PredicateOption.IsMultipleTerms; SearchResults.Where(_predicates[option]); ```
12,642,745
I have got a problem with updating entity. Each User can be in one Group only. Schema for user is: * id INT * username STRING * group\_id INT DEFAULT NULL Schema for group is: * id INT * name STRING **Group.php** ``` class Group { /** * @ORM\OneToMany(targetEntity="Saprizo\Entity\User", mappedBy="group", cascade={"all"}) */ protected $users; public function setUsers($users) { foreach ($users as $user) { $user->setGroup($this); } $this->users = $users; } } ``` **User.php** ``` class User { /** * @ORM\ManyToOne(targetEntity="SaprizoStatistics\Entity\Group", inversedBy="users", cascade={"all"}) * @ORM\JoinColumn(name="group_id", referencedColumnName="id", nullable=true) */ protected $group; } ``` When I try to add new users to group like ``` $group->setUsers(array($user1, $user2)); $em->persist($group); $em->flush(); ``` it save all values. But when I try to delete all users from group like ``` $group->setUsers(array()); $em->persist($group); $em->flush(); ``` it do nothing. As I understand after setting an empty array and saving it group\_id column for user1 and user2 should change to `null`. Is it mistake in Doctrine annotations?
2012/09/28
[ "https://Stackoverflow.com/questions/12642745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1353837/" ]
When in doubt over what algorithms you can use for a JCA service, your first port of call should be the JCA [Standard Algorithm Name Documentation](http://docs.oracle.com/javase/6/docs/technotes/guides/security/StandardNames.html). The algorithms **guaranteed** to be supported by the [MessageDigest](http://docs.oracle.com/javase/6/docs/technotes/guides/security/StandardNames.html#MessageDigest) service in a JCA-compliant JVM are: * `MD2` * `MD5` * `SHA-1` * `SHA-256` * `SHA-384` * `SHA-512` It's common for providers to supply aliases for these algorithms, which is why it'd probably work with Bouncy Castle, but you should stick to these if you can to maximise portability. If you change your code to the following, it will work as expected: ``` final MessageDigest digest = MessageDigest.getInstance("SHA-256"); ```
9,979,256
So I have on two of my forms a back and next button, on the first form when you press next it loads the second form, now if you press the back button on the second form it loads the first form, however now there are two intents for the same form. How do I prevent this from occurring? first form start button: ``` final Button start = (Button) findViewById(R.id.start); start.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent i= new Intent(getApplicationContext(), step_1_to_4.class); startActivity(i); } }); ``` Second form back button is the following: ``` final Button back = (Button) findViewById(R.id.step1_back_button); back.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent i= new Intent(getApplicationContext(), HKA_manual_Calibration_v2_no_tabsActivity.class); startActivity(i); } }); ``` so when the user goes back and forth between these two activities it results in multiple activities being created.
2012/04/02
[ "https://Stackoverflow.com/questions/9979256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1308355/" ]
This question is now answered on the Moai forums - sorry for the delay. The long and the short is that the find command syntax differs on Mac and Cygwin, so I have proposed a workaround on the Moai forums. For an upcoming SDK release, we'll tweek the scripts to make sure that they are more Windows-compatible.
14,672
This question is a consequence of : 1. [How to make a film in black and white and add color to some objects?](https://video.stackexchange.com/questions/12664/how-to-make-a-film-in-black-and-white-and-add-color-to-some-objects) 2. [How to show a character in black and white mode with colorful background?](https://video.stackexchange.com/questions/13229/how-to-show-a-character-in-black-and-white-mode-with-colorful-background) This is just for my personal culture. Using gimp + path + transform, I can do it in one 2D image, but I was trying to understand how you guys would make a character in black and white in a colored scene, if the movie is already done. From the previous answers, I understand that the key word is this case is `rotoscoping`. But, I don't understand the principle ! Is it some kind of dynamic path with the time ? What software would you use to do it ? Have you got a link to explain that to a guy without video processing culture like me ? Thanks for reading,
2015/01/25
[ "https://avp.stackexchange.com/questions/14672", "https://avp.stackexchange.com", "https://avp.stackexchange.com/users/9211/" ]
You'd achieve the effect by masking one part of the image and applying a desaturation effect to it. The hard part is masking off one part of the image. In software such as After Effects and Nuke you can mask off an area of the image with bezier splines, and the shape of the masks can be animated. Tracing and animating these masks is what is called rotoscoping (it was invented by animator Max Fleischer in 1915, where he hand traced frames of film projected onto paper). After Effects does come with an automatic rotoscoping tool called "[Roto Brush](https://helpx.adobe.com/after-effects/how-to/aftereffects-roto-brush-cc.html)" that works a bit like the magic wand in Photoshop, except that it changes shape over time. This can take a lot of the work out of rotoscoping, but it is far from infallible.
20,879,357
Edit 4: ------- **This is only an issue if you are using the free version of heroku (with one web dyno) and I made a workaround below. But it is still a valid question so I'm not sure what the reason(s) are for down voting...** This works locally and on another web hotel. Below .htaccess works for index but when a "subdir"/mod\_rewrite dir is accessed like category/Drama all I get is "Application Error" Edit ---- So what I've done is, instead of all rewrites going via .htaccess I send every request like this: <http://example.com/CatX/CatY/CatZ/> to <http://example.com/redirs.php?data=CatXCatYCatZ>. Then in redirs i fetch the page and output it, but this only gives application error on heroku and checking logs is even more confusing because it reports failing to get the request first then goes ahead and fetches it. Problem url example: <http://movie-nights.herokuapp.com/category/Crime/> I only have free addons and base package. I tried curl also but that doesn't output the data should have been fetched via curl - empty result but redirs.php works. "Application Error" ------------------- "An error occurred in the application and your page could not be served. Please try again in a few moments. If you are the application owner, check your logs for details." ``` RewriteEngine on RewriteBase / RewriteRule ^(.*)/css/(.+)$ css/$2 [L] RewriteRule ^(.*)/bilder/(.+)$ %{SCRIPT_URI}bilder/$2 [L] RewriteRule ^(.*)/grafik/(.+)$ grafik/$2 [L] RewriteRule ^(.*)/js/(.+)$ %{SCRIPT_URI}js/$2 [R] RewriteRule ^(.*)/lightbox/(.+)$ %{SCRIPT_URI}lightbox/$2 [L] RewriteRule ^(.*)/bootstrap/(.+)$ bootstrap/$2 [R] RewriteRule ^FAQ(/)*$ %{SCRIPT_URL}faq.php [L] RewriteRule ^MovieDescription/$ %{SCRIPT_URL}xxx/xxx.php [L] RewriteRule ^stream/url\=(.+)$ $1 [R] RewriteRule ^id/([0-9]*)$ id/$0/ [L] RewriteRule ^id/([0-9]*)/(.*)$ id/$0/ [L] RewriteCond %{REQUEST_FILENAME} !-f #<-- here RewriteRule ^(.*)/$ redirs.php?data=$0 [QSA] #<-- here ``` redirs.php ---------- ``` <?php function makeUrl($attr, $url) { if (preg_match('#\?#', $url)) { $attr = '&'. $attr; } else { $attr = '?'. $attr; } return $attr; } function getWebCwd() { $dir = ''; if (!empty($GLOBALS['BaseCat'])) { $dir = $GLOBALS['BaseCat']; } if (!empty($GLOBALS['subUrl'])) { // Can be for example: //$subUrl = 'Streamed-Movies/'; $dir .= $GLOBALS['subUrl']; } return $dir; } $url = '/index.php'; $data = $_GET['data'] . getWebCwd(); if (preg_match('#category\/([a-zA-Z]+)#iu', $data, $matches)) { $url .= makeUrl('category='. $matches[1], $url); } $sid = session_id(); if (!empty($sid)) { $url .= makeUrl(session_name() .'='. $sid, $url); } $url = 'http://'. $_SERVER['SERVER_NAME'] . $url; $opts = array('http' => array( 'method' => "GET", 'header' => "Accept-language: en\r\n" . "Cookie: ".session_name()."=".session_id()."\r\n" ) ); $context = stream_context_create($opts); session_write_close(); // this is the key $html = file_get_contents($url, false, $context); // <-- line 92 echo $html; ``` Error logs from Papertrail addon: (requested url is currect and works if you try to open it) -------------------------------------------------------------------------------------------- ``` Jan 02 00:40:49 movie-nights app/web.1: [Thu Jan 02 08:40:49 2014] [error] [client 10.34.132.2] PHP Warning: file_get_contents(http://movie-nights.herokuapp.com/index.php?category=Crime&PHPSESSID=c54qgv6pgj2mme2is32qljs865): failed to open stream: HTTP request failed! HTTP/1.1 503 Service Unavailable\r\n in /app/www/redirs.php on line 92 Jan 02 00:40:49 movie-nights app/web.1: 10.34.132.2 - - [02/Jan/2014:08:40:19 +0000] "GET /category/Crime/ HTTP/1.1" 200 - Jan 02 00:40:50 movie-nights app/web.1: 10.34.132.2 - - [02/Jan/2014:08:40:49 +0000] "GET /index.php?category=Crime&PHPSESSID=c54qgv6pgj2mme2is32qljs865 HTTP/1.1" 200 16864 ``` So it tries to open <http://movie-nights.herokuapp.com/index.php?category=Crime&PHPSESSID=c54qgv6pgj2mme2is32qljs865> => : failed to open stream: HTTP request failed! HTTP/1.1 503 Service Unavailable => but if you try to open that manually it works. Edit2 ===== I also get this error (below) but from what I've read about it, it shouldn't be a problem? ``` Jan 11 23:05:21 movie-nights app/web.1: [Sun Jan 12 07:01:38 2014] [error] server reached MaxClients setting, consider raising the MaxClients setting ``` Edit3 ===== See solution in my own answer below!
2014/01/02
[ "https://Stackoverflow.com/questions/20879357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/846348/" ]
It looks like your code is taking in a request, then opening a new HTTP request to your server. Unfortunately, you can only handle so many concurrent requests and you're blocking all of your workers (hence MaxClients error). This is causing your call back to your web application from within your web application to fail (with 503, unavailable). If you actually want to redirect the user, you should return an 3XX status code with the new URL you want to redirect to. This will end the current request, return the redirect, and the user's browser will fetch the new URL.
15,049,434
I created the following table, but I got the error below; > > *Incorrect syntax near 'AUTO\_INCREMENT'.* > > > SQL: ``` CREATE TABLE [dbo].[MY_TABLE] ( [ID] INT NOT NULL AUTO_INCREMENT, [NAME] NVARCHAR (100) NULL, [SCHOOL] NVARCHAR (100) NULL, PRIMARY KEY (ID) ); ``` I think I have done everything right. Can someone help me out?
2013/02/24
[ "https://Stackoverflow.com/questions/15049434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1377826/" ]
It is [`IDENTITY`](http://msdn.microsoft.com/en-us/library/ms186775.aspx) not `AUTO_INCREMENT` in SQL Server. Try this instead: ``` CREATE TABLE [dbo].[MY_TABLE] ( [ID] INT NOT NULL IDENTITY(1, 1), [NAME] NVARCHAR (100) NULL, [SCHOOL] NVARCHAR (100) NULL, PRIMARY KEY (ID) ); ```
387,483
I'm trying to send an email to several recipients when a new row is inserted into a table. The list of recipients varies. I would like to be able to set this list using a select statement. I also have installed Navicat which allows me to send email notifications but only to a predetermined set of people. Thanks.
2008/12/22
[ "https://Stackoverflow.com/questions/387483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/48488/" ]
I would be very concerned about putting the load of sending e-mails on my database server (small though it may be). I might suggest one of these alternatives: 1. Have application logic detect the need to send an e-mail and send it. 2. Have a MySQL trigger populate a table that queues up the e-mails to be sent and have a process monitor that table and send the e-mails.
38,414,520
In my game there are Rounds (Round 1, 2 etc...). I want to store them inside of a text file to be saved. To do this I use the following code: ``` global roundNumber roundNumber += 1 file = open('file/roundNumber.txt', 'w') file.write(roundNumber) ``` However, I get an error for `file.write(roundNumber)`: ``` file.write(roundNumber) TypeError: must be string or read-only character buffer, not int ``` I'm not sure what to do - I **need** to store the variable as a number in the text file, but it throws an error. Help Please - Thanks! :D
2016/07/16
[ "https://Stackoverflow.com/questions/38414520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6194302/" ]
i think it should be: ``` ->select('users.*', DB::raw('COUNT(gift_sents.receiver_id) as total_posts')) ``` see doc [here](https://laravel.com/docs/5.2/queries) - 'Raw Expressions' section
3,362,899
Windows Task Manager shows four threads for my simple C# Windows application. What are these for?
2010/07/29
[ "https://Stackoverflow.com/questions/3362899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/336940/" ]
> > 1. Main thread > 2. Debugger thread > 3. Finalizer thread > 4. GDI+ rendering thread > > > [Source](http://bytes.com/topic/c-sharp/answers/588402-do-nothing-winform-app-using-4-threads)
8,202
Relevance logic takes a closer look at the implication operation in first-order logic. It suggests that implications such as: > > p and not p -> q > > > cannot hold; in ordinary English, an example of this is: > > 'Socrates is a man and Socrates is not a man, hence the capital of England is London'. > > > The conclusion although true, appears to be irrelavnt to the premises under discussion. Now, Meyer in the 70s, looked at Peanos Axioms (PA) in Relevance Logic, and showed that contra Godel that it was provably consistent. If the proof of the consistency of PA is important and vital, could not one say that relevant PA is perhaps the correct PA? Or that at least first-order PA is not right PA to look at? Of course, not all of the theorems of traditional PA holds in relevant PA; but is anything essential lost, say to mainstream number theory or physics, rather that the exotic outer reaches of what is possible in traditional PA? (Another way to examine this result in the light of Godel, is to consider his theorem that a theory cannot be both complete and consistent; if one desires completeness, one must embrace inconsistency; and in fact relevant logic is paraconsistent).
2013/09/20
[ "https://philosophy.stackexchange.com/questions/8202", "https://philosophy.stackexchange.com", "https://philosophy.stackexchange.com/users/933/" ]
"Is anything essential lost" or are the shortcomings of Meyer's system in "the exotic outer reaches of what is possible in traditional PA"? PA proves that formula if *p* > 2 is prime, then there is a positive integer *y* which is not a quadratic residue mod *p*; that is, > > ∃y ∀z: ¬(y ≡ z^2 (mod p)). > > > That looks like a pretty unexotic bit of number theory to me. Fails in Meyer's system though. Bad news? See R. Meyer and H. Friedman, Whither Relevant Arithmetic?, JSL 1992, 824–831.
14,867
I've seen some parents blowing on their baby's face when crying. The baby suddenly stops crying but he looked very surprised. I wonder if this could harm the baby in some way.
2014/09/20
[ "https://parenting.stackexchange.com/questions/14867", "https://parenting.stackexchange.com", "https://parenting.stackexchange.com/users/9416/" ]
Blowing on the face is a common trick. It triggers a reflex to hold the breath for a short moment. That stops the crying, and can also be used when washing the child's face etc. I am not aware of any consequences of this, neither positive nor negative.
2,991
I see that the size of alias is 167.7kB, whereas symbolic link is just 4kB. * What's the difference between the two, or what's the purpose of them? * Which one is preferable? For the case that the link/alias is used only in one machine or networked. ADDED ----- <http://prosseek.blogspot.com/2012/12/symbolic-link-and-alias-in-mac.html>
2010/10/07
[ "https://apple.stackexchange.com/questions/2991", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/102/" ]
An alias contains two pieces of information: a unique identifier of the file it links to, and the path and file name of the file it links to. If you rename or move a file, and then create a new file with the path and file name that the file originally had, then any alias that linked to the original file now links to the new file. However, if you rename or move a file without replacing it, and then invoke an alias, the alias is updated to point to the new path and file name, making use of the unique identifier to do so. A symbolic link, on the other hand, does not contain a unique identifier to a file, and would appear as broken if the file is renamed or moved and not replaced with a file of the same path and file name. Your choice should depend on which scenario suits you best.
12,679,571
I have a website (URL: <http://www.fromthepitch.com>). There seems to be a problem with it issuing error codes. For some reason instead of 404 error page it displays the home page. <http://www.fromthepitch.com/asdsad> is meant to show a 404 page but instead displays the home page. Any suggestions on how to solve this problem.
2012/10/01
[ "https://Stackoverflow.com/questions/12679571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1712718/" ]
You have misspelled the `-(void) setAccumulator:(double)value` function of your class simply change your misspelled ``` -(void) setAccuumulator:(double)value { accumulator=value; } ``` to ``` -(void) setAccumulator:(double)value { accumulator=value; } ``` this gives you ``` The result is 50 ```
33,634,909
For someone without any cryptology knowledge - I would like to know if it is possible to take a unencrypted password, and then convert it to an encrypted password that Joomla (3.3.6) will understand after it has been directly inserted into the database via SQL? This link seems to talk about something similar but I don't think it exactly what I need to know ([Joomla 3.2.1 password encryption](https://stackoverflow.com/questions/21304038/joomla-3-2-1-password-encryption)) Is it possible? Is there a ready made encryption script that can do this? Or would I have to find someone that could do it? Thank you
2015/11/10
[ "https://Stackoverflow.com/questions/33634909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5547433/" ]
You can just use MySQL's MD5 function - Joomla understands passwords that are hashed using MD5. No need to create a script. In phpMyAdmin, in the #\_\_users table, just change the password to the one that you want and choose MD5 from the function dropdown.
44,081,433
How would I go about to get this to work? I've searched but I can't get it to work still. Should I just put the a() function in the b function even if I add more variables? ``` counter = 1 def a(): az = 1 bz = 2 cz = 3 def b(): a() if counter > 0 : print az, bz, cz b() ```
2017/05/20
[ "https://Stackoverflow.com/questions/44081433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8039279/" ]
Alright, you need to understand the concept of `scope`. `az`, `bz` and `cz` are known only inside your function `a()`. So you can't print their values inside function `b()`. You could do something like: ``` counter = 1 def a(): az = 1 bz = 2 cz = 3 if counter > 0 : print az, bz, cz def b(): a() b() ``` And as @fileyfood500 said in his comment, you might want to read [this](https://stackoverflow.com/questions/291978/short-description-of-the-scoping-rules).
41,604,160
I am just wondering why a regular list that is passed into a process as an argument (and modified in the process) doesn't remain as a pass by reference as if I had passed it into a function normally? The following is some example code: ``` from multiprocessing import Process def appendThings(x): x.append(1) x.append(2) x.append(3) x = [] p = Process(target=appendThings, args=(x)) p.start() p.join() print(x) ``` I expected to see: ``` [1,2,3] ``` but instead got: ``` [] ``` General insight into multiprocessing is welcome too as I am currently learning :)
2017/01/12
[ "https://Stackoverflow.com/questions/41604160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4515663/" ]
Multiprocessing can not pass python objects directly. The arguments sent to the Process are a copy. You have at least a couple of options to return data: 1. Shared [ctypes](https://docs.python.org/3/library/multiprocessing.html#multiprocessing.Value) 2. [multiprocessing.Manager()](http://docs.python.org/3/library/multiprocessing.html#managers) A working example using the manager: ``` from multiprocessing import Process, Manager def append_things(x): x.append(1) x.append(2) x.append(3) if __name__ == '__main__': x = Manager().list([]) p = Process(target=append_things, args=(x,)) p.start() p.join() print(x) ```
11,080
We have a process that runs within our Magento installation that: 1. Bootstraps Magento 2. Performs some actions which involve writing to a table in mysql 3. Connects to a remote API, which takes a long time to respond (20mins +) 4. Attempts to write more information to a table in mysql The problem is, that due to the long time taken for the remote API to respond, the MySQL server has sometimes 'Gone Away' by the time we attempt to perform step 4. The simplest solution to this is to simply increase the wait\_timeout for MySQL, but this feels like a hacky solution. Is there a way from within Magento to close then reopen the database connection? Or even just force a reconnect after step 3? I tried to dig into it, but the actual instantiation of the connection seems (as with many things in Magento) deeply buried. I'm therefore unsure exactly how I might force a reconnect.
2013/11/22
[ "https://magento.stackexchange.com/questions/11080", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/171/" ]
Yes, you can. Assuming you open the connection with something like this: ``` $db = Mage::getSingleton('core/resource')->getConnection('core_read'); ``` You can close the connection with this: ``` $db->closeConnection(); ``` And then re-open it with this: ``` $db->getConnection(); ``` When I need to make an api call that could take a long time, I close the connection first, then use getConnection to open it again afterwards, which has solved the "mysql server has gone away" problem for me.
26,393,078
I think all i need a little hint for completing this query built with a left outer join. This is a basic example from a my query which list informations from different tables: ``` select t.Transaction_ID, t.Date_Transaction from Transactions t LEFT OUTER JOIN Trans_Payments on Trans_Payments.Transaction_ID = t.Transaction_ID ``` this query returns : ``` trans_id trans_date 1 20/10/2010 1 20/10/2011 2 20/10/2012 3 20/10/2014 4 20/2/2015 5 18/10/2010 ``` That's a good start since this query list all the transactions even the ones with no payment\_mode ( because before i was using a simple join in where for listing transactions and all i get is transactions with a payment mode) Ok, now when i try to add another join: ``` select * from Transactions t LEFT OUTER JOIN Trans_Payments on Trans_Payments.Transaction_ID = t.Transaction_ID LEFT OUTER JOIN Payments on Trans_Payments.Payment_ID = Payments.Payment_ID ``` i get : ![query_result](https://i.stack.imgur.com/dFi8X.jpg) How can I get rid of transaction\_id and duplicated payment\_id in this query result?
2014/10/15
[ "https://Stackoverflow.com/questions/26393078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2233979/" ]
`return x` is ending your for loop after its first iteration.
47,348,836
I have created and started an A/B Test on Firebase Remote Config 2 days ago on my iOS app with this code: ``` [FIRApp configure]; [FIRRemoteConfig.remoteConfig fetchWithCompletionHandler:^(FIRRemoteConfigFetchStatus status, NSError * _Nullable error) { // Do nothing }]; [FIRRemoteConfig.remoteConfig activateFetched]; ``` I have confirmed that the test is live because on some devices I can see the test going on. The problem is that, after two days, the Firebase Console keeps saying that 0 users have participated on the experiment. On the other hand, I've done a another test on Android with the same code and I can see activity after few hours. Is there something I'm missing? Edit - Pods versions: ``` Using Firebase (4.5.0) Using FirebaseABTesting (1.0.0) Using FirebaseAnalytics (4.0.4) Using FirebaseCore (4.0.10) Using FirebaseInstanceID (2.0.5) Using FirebasePerformance (1.0.6) Using FirebaseRemoteConfig (2.1.0) ```
2017/11/17
[ "https://Stackoverflow.com/questions/47348836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/918171/" ]
Finally I reproduced the issue and found a workaround. The key is detaching `activateFetched` from the `application:didFinishLaunchingWithOptions:` method. So, this is the workaround (tested with Firebase 4.7.0): ``` [FIRApp configure]; [FIRRemoteConfig.remoteConfig fetchWithExpirationDuration:60*60 completionHandler:^(FIRRemoteConfigFetchStatus status, NSError * _Nullable error) { // Do nothing }]; dispatch_async(dispatch_get_main_queue(), ^{ [FIRRemoteConfig.remoteConfig activateFetched]; }); ```
30,356,265
I have a batch file that I would like to pick up the newest "manifest" file, so I was hoping to be able to use a for loop for that, but I'm not sure of the correct syntax. This is what I have: ``` for /R %imagePath% %%F in (*.manifest.*) do (set manFile=%%F) ``` Which does the correct thing to return "C:/some/path/to/file.manifest.ext", but not necessarily the newest one. I see other questions like this one that use `dir`, but then I don't get the entire path. My attempt at doing this with `dir` looks like: ``` for /R %imagePath% %%F in ('dir /od *.manifest.*.*') do (set manFile=%%F) ``` This doesn't give me the output I was expecting. What is the best way to accomplish this?
2015/05/20
[ "https://Stackoverflow.com/questions/30356265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/612660/" ]
I think it is working as it is supposed to. In the mentioned case, event is directly attached to the button, hence currentTarget and target will always be the same. > > `$('.container').on('click', '.myButton', function(event) {});` does not mean that the event is attached to the div. It is just delegating the event. Meaning, the event will bubble up only till `.container` and the event is still attached ONLY to `.myButton` > > > **Case 1:** If an event is attached to the div 1. if the button is clicked then the currentTarget would be button and target would be the div. 2. if div is clicked currentTarget would be div and target would also be div **Example** ```js $('.container').on('click', function(event) { console.log(event.currentTarget); console.log(event.target); }); ``` ```css div{ border: 1px solid; width: 150px; height: 150px; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <div class="container"> <button class="myButton">Click Me</button> Click me </div> ``` **Case 2: (Your case)** If event is attached to button then currentTarget and target would be button always ```js $('.container').on('click','.myButton', function(event) { console.log(event.currentTarget); console.log(event.target); }); ``` ```css div{ border: 1px solid; width: 150px; height: 150px; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <div class="container"> <button class="myButton">Click Me</button> Click me </div> ```
1,550,466
I have created dll in C# 3.5 which does some memory intensive matrix calculations where matrices get created and disposed a lot. Everything works fine if dll is called from .Net app but if it is called from C++ created app memory usage just climbs until the function that uses matrices is done. I guess there is a problem with a automatic garbage collection.
2009/10/11
[ "https://Stackoverflow.com/questions/1550466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/103055/" ]
Most probably you are not 'Release'ing the references to the .Net object wrappers from your unmanaged app. The GC cannot collect that memory unless all references (including external ones) are released.
51,154,233
I am testing the Cryptographic hashing functions for Dart.  I can't find any information about DECRYPTION? Can anyone show me how to decryption of the encrypted value? And this is example; ``` import 'dart:convert'; import 'package:crypto/crypto.dart'; void main() async {   var key = utf8.encode('p@ssw0rd');   var bytes = utf8.encode("Dart and Aqueduct makes my life easier. Thank you.");   // TODO: ENCRYPTION   var hmacSha256 = new Hmac(sha256, key); // HMAC-SHA256   var digest = hmacSha256.convert(bytes);   print(“————ENCRYPTION—————“);   print("HMAC digest as bytes: ${digest.bytes}");   print("HMAC digest as hex string: $digest");   print('\r\n');   // TODO: DECRYPTION      ????????????   print(“————DECRYPTION—————“);   print(?????????); } ```
2018/07/03
[ "https://Stackoverflow.com/questions/51154233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The easiest way IMO is to use [encrypt](https://pub.dev/packages/encrypt): ``` import 'package:encrypt/encrypt.dart'; final key = Key.fromUtf8('put32charactershereeeeeeeeeeeee!'); //32 chars final iv = IV.fromUtf8('put16characters!'); //16 chars //encrypt String encryptMyData(String text) { final e = Encrypter(AES(key, mode: AESMode.cbc)); final encrypted_data = e.encrypt(text, iv: iv); return encrypted_data.base64; } //dycrypt String decryptMyData(String text) { final e = Encrypter(AES(key, mode: AESMode.cbc)); final decrypted_data = e.decrypt(Encrypted.fromBase64(text), iv: iv); return decrypted_data; } ```
34,371,433
I have a list like so obtained after some mathematic operations: ``` [[899, 6237], [898, 6237], [897, 6237], [896, 6237], [895, 6237], [899, 6238], [898, 6238], [897, 6238], [896, 6238], [895, 6238], [899, 6239], [898, 6239], [897, 6239], [896, 6239], [895, 6239], [899, 6240], [898, 6240], [897, 6240], [896, 6240], [895, 6240]] ``` I would like the components of each sublist become string of 4 characters size. This is a example of what I want with the first element of the main list: ``` ['0899','6237'] ```
2015/12/19
[ "https://Stackoverflow.com/questions/34371433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5698216/" ]
Using [list comprehension](https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions) and [`format`](https://docs.python.org/2/library/functions.html#format): ``` >>> lst = [ ... [899, 6237], [898, 6237], [897, 6237], [896, 6237], [895, 6237], ... [899, 6238], [898, 6238], [897, 6238], [896, 6238], [895, 6238], ... [899, 6239], [898, 6239], [897, 6239], [896, 6239], [895, 6239], ... [899, 6240], [898, 6240], [897, 6240], [896, 6240], [895, 6240], ... ] >>> [[format(a, '04'), format(b, '04')] for a, b in lst] [['0899', '6237'], ['0898', '6237'], ['0897', '6237'], ['0896', '6237'], ['0895', '6237'], ['0899', '6238'], ['0898', '6238'], ['0897', '6238'], ['0896', '6238'], ['0895', '6238'], ['0899', '6239'], ['0898', '6239'], ['0897', '6239'], ['0896', '6239'], ['0895', '6239'], ['0899', '6240'], ['0898', '6240'], ['0897', '6240'], ['0896', '6240'], ['0895', '6240']] ``` You can also use [`str.format`](https://docs.python.org/2/library/stdtypes.html#str.format): ``` >>> '{:04}'.format(899) '0899' ``` or [`%`-operator (`printf`-style formatting)](https://docs.python.org/2/library/stdtypes.html#string-formatting-operations): ``` >>> '%04d' % 899 '0899' ```
72,301,087
I have three divs in a row. The width of the first (left) div scales depending on it's content (i.e. the length of a text string and the font size). I want the third (right) div to be equally wide as the first, and the second (middle) div to fill up the remaining width. I got this to work with two divs. In the following example, the width of the first div scales depending on the width of its content, and the second div fills the remaining width of the parent: ```css #container{ display:flex; flex-direction:row; } #first{ background:red; } #second{ background:blue; flex-grow:1; } ``` ```html <div id="container"> <div id="first"> alongtextstringthatdoesntwrap<br> shortstring </div> <div id="second"> This div should take up the remaining with. </div> </div> ``` With three divs, all I was able to do was measure the first div (using the developer tools of my browser) and setting the width of the third div to this value. But if the width of the first div changes, because the text string length or the font size varies, then the third is no longer equal to the first: ```css #container{ display:flex; flex-direction:row; } #first{ background:red; } #second{ background:blue; flex-grow:1; } #third{ background:green; width:200px; } ``` ```html <div id="container"> <div id="first"> alongtextstringthatdoesntwrap<br> shortstring </div> <div id="second"> This div should take up the remaining with. </div> <div id="third"> This div should be equally wide as the first div. There are just short words in this div, so the text wraps to (almost) any width. </div> </div> ``` Is it possible, in flexbox, to set the two "framing" divs to equal width, with the width varying dynamically with the content of the divs, and the middle div to fill the remaining space dynamically? I've seen a couple of similar questions on this site, but they were all asked before flexbox became widely compatible with browsers, and I hope that flexbox now offers a solution to this old problem.
2022/05/19
[ "https://Stackoverflow.com/questions/72301087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19050587/" ]
As I understand it is impossible to change the service and the entity. Then in such cases it is better to use `ArgumentMatcher<>` in `Mockito`. **Step 1 :** ``` @AllArgsConstructor public class EntityMatcher implements ArgumentMatcher<Entity> { private Entity left; @Override public boolean matches(Entity right) { return (left.getEventDate().getTime() - right.getEventDate().getTime() <= 1000)); } } ``` Here you ovverride `equals` which will be compare objects. `mathces` can be `ovveride` as you like. I think the difference in one second is enough. **Step 2:** ``` verify(entityRepository).save(argThat(new EntityMatcher(new Entity(new Date(), 1, 2L)))); ``` **Other case :** Most likely, in other tests, such a situation may arise that this `entity` will also need to be checked `when` ``` when(entityRepository.save(any(Entity.class))).thenReturn(new Entity(new Date(), 1, 2L)); ```
37,003
The tag [food](/questions/tagged/food "show questions tagged 'food'") has a description of "Anything that is worthy of being eaten.". Is there a concept in Islam of something being unworthy of being eaten? For some people, there'd be things that are unsafe to eat, or where it'd be disrespectful to eat (eating a species that'd be considered [friends, not food](https://en.wikipedia.org/wiki/Finding_Nemo)), but I haven't considered anything unworthy of being eaten. Related question: [Are there gods unworthy of worship?](https://islam.stackexchange.com/questions/20046/are-there-gods-unworthy-of-worship)
2016/12/26
[ "https://islam.stackexchange.com/questions/37003", "https://islam.stackexchange.com", "https://islam.stackexchange.com/users/301/" ]
Yes there are *halal* foods and *haram* foods. Halal foods are worthy of being eaten while it is forbidden to eat haram foods and so they are unworthy of being eaten. > > وكلوا مما رزقكم الله **حلالا طيبا** > > > And eat of what Allah has provided for you **[which is] lawful and good**. > > > — [Quran 5:88](https://quran.com/5/88) > > > ويحل لهم الطيبات **ويحرم عليهم الخبائث** > > > Makes lawful for them good things, and **makes unlawful for them impure things** > > > — [Quran 7:157](https://quran.com/7/157) > > > There are various things that Muslims are forbidden to eat and drink, such as: > > حرمت عليكم الميتة والدم ولحم الخنزير وما أهل لغير الله به > > > Prohibited to you are dead animals, blood, the flesh of swine, and that which has been dedicated to other than Allah > > > — [Quran 5:3](https://quran.com/5/3) > > > ميتة أو دما مسفوحا أو لحم خنزير فإنه رجس > > > a dead animal or blood spilled out or the flesh of swine - for indeed, it is impure > > > — [Quran 6:145](https://quran.com/6/145?translations=84) Also see [Quran 2:173](https://quran.com/2/173) > > > ولا تأكلوا مما لم يذكر اسم الله عليه > > > And do not eat of that upon which the name of Allah has not been mentioned > > > — [Quran 6:121](https://quran.com/6/121) > > > يا أيها الذين آمنوا إنما الخمر والميسر والأنصاب والأزلام رجس من عمل الشيطان فاجتنبوه لعلكم تفلحون > > > O you who believe! Wine, gambling, altars and divining arrows are filth, made up by Satan. Therefore, refrain from it, so that you may be successful. > > > — [Quran 5:90](https://quran.com/5/90) Also see [Quran 2:219](https://quran.com/2/219) > > > Haram foods have been called خبائث and رجس (impure, evil, filthy, abhorent) and the act of eating haram foods has been called or implied to be فسق , بَاغٍ , إثم , عَادٍ (grave disobedience, transgression and sin).
2,642,651
I have a program in which I need to store a Class object into memory by casting it into String. Is it possible to convert the String back into the original Class so that I can use that class variables? I am doing this in JAVA. Example: test.java ``` class hello{ public String h1; public String h2; } public class test { public static void main(String[] args) { hello h = new hello(); h.h1 = "hello"; h.h2 = "world"; String s = h.toString(); System.out.println("Print s : "+s); // Now I need to convert String s into type hello so that // I can do this: // (hello)s.h1; // (hello)s.h2; } } ``` NOTE: this is not a homework, this is a personal project and I would be grateful if anyone can help! Thanks! Ivar
2010/04/15
[ "https://Stackoverflow.com/questions/2642651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/265107/" ]
I think what you want to do is Serialization. I'm confused by your comment: ``` // Now I need to convert String s into type hello so that // I can do this: // (hello)s.h1; // (hello)s.h2; ``` You can't just cast String objects to arbitrary class types. Maybe you can elaborate on what you're trying to accomplish here. If you want to be able to "save" a class to a file, then read it back in as an object, you want Serialization. Like this: ``` import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; class Hello implements Serializable { public String h1; public String h2; @Override public String toString() { return "{ h1: " + h1 + ", h2: " + h2 + " }"; } public static void main(String[] args) throws Exception { Hello h = new Hello(); h.h1 = "hello"; h.h2 = "world"; ObjectOutputStream outstream = new ObjectOutputStream(new FileOutputStream("hello.ser")); outstream.writeObject(h); System.out.println("1) h: " + h); h = null; System.out.println("2) h: " + h); ObjectInputStream instream = new ObjectInputStream(new FileInputStream("hello.ser")); h = (Hello) instream.readObject(); System.out.println("3) h: " + h); } } ``` It can get more complicated when your fields are more complex classes than String. Implementing Serializable is just a "marker" interface that says that the object can be serialized, it doesn't require any methods to be implemented. Your simple class just needs to be written out using an ObjectOutputStream and can be read back in using an ObjectInputStream.
62,914,095
I have defined several Perl constants like `use constant LVL_FATAL => 1;` (perl 5.18.2). When trying to create a function that needs the name and the value of the constant, I tried: ```perl my $level = eval { 'LVL_' . $_ }; ``` When `$_` is `FATAL`, then `$level` contains `LVL_FATAL`, but not the value of `LVL_FATAL`. I also tried the variants `eval { $level }`, `eval { ($level) }`, `eval { my x = $level }`, and `eval { print $level }`. They all use `LVL_FATAL`. However when I use `eval "$level"`, then I get `1`. Also when i use `eval { LVL_FATAL }` I get `1`, too. Can I use the block variant instead of the string variant for robustness and performance reasons? Remark ------ Remembering that Perl constants are basically functions, I tried `eval ${level}()`, but that did not work; `eval { $level->() }` seemed to do the job in the debugger, but when I used it in my program code, it did not work, however. (When not using `eval`, `LVL_FATAL->()` will give an error ("Undefined subroutine &main::1 ..."), but `LVL_FATAL()` is OK.)
2020/07/15
[ "https://Stackoverflow.com/questions/62914095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6607497/" ]
The following seems to work: ``` my $level = eval { my $name = "LVL_$_"; __PACKAGE__->$name() }; ``` According to [the documentation](https://perldoc.perl.org/constant.html) : > > Constants belong to the package they are defined in. [...] > Constants may be exported by modules, and > may also be called as either class or instance methods, that is, as > `Some::Package->CONSTANT` or as `$obj->CONSTANT` where `$obj` is an instance > of `Some::Package`. Subclasses may define their own constants to > override those in their base class. > > >
4,146
The MacBook Air has the magsafe and a USB port on one side of the chassis and the mini display and another USB port on the other side of the chassis. Does the 3-port cable for the Cinema Display work, seeing as how the magsafe and the mini display are on opposite sides instead of all lined up like on the MacBook Pro? If so, is it graceful or ungainly?
2010/11/19
[ "https://apple.stackexchange.com/questions/4146", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/1616/" ]
Yes, it works, but it's not graceful, it's ungainly: ![alt text](https://i.stack.imgur.com/OTdap.jpg) Source: [Apple Insider](http://www.appleinsider.com/articles/10/10/30/review_apples_new_11_6_inch_and_13_3_inch_macbook_air_late_2010.html&page=3)
38,888,076
in my endeavors to learn C++, I have come accross a lesson I don't understand. It is: creating arrays of structs, or creating arrays of type struct. I can't seem to understand how they work. Could someone please explain it to me, or redirect me to a good tutorial? I have looked myself, but can't find anything that explains well. Thank you.
2016/08/11
[ "https://Stackoverflow.com/questions/38888076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6703282/" ]
I think you need **GROUP BY** ``` SELECT es_id, bl_year, bl_created_by FROM blog WHERE bl_status = 'Approved' GROUP BY es_id, bl_year, bl_created_by ORDER BY bl_year DESC" ``` Simple explanation ,GROUP BY usually cooperates with **aggregate function** like count() : ``` SELECT COUNT(es_id), bl_year FROM blog GROUP BY bl_year ``` this gets count of total blogs in same bl\_year You need to include both **es\_id**, **bl\_created\_by** column in GROUP BY clause because they don't work with aggregate function, if you don't, it can't tell which value to present in these columns, they may be different . Or another present that work with **GROUP\_CONCAT** ``` SELECT GROUP_CONCAT(es_id), bl_year FROM blog WHERE bl_status = 'Approved' GROUP BY es_id, bl_year ORDER BY bl_year DESC" ``` This will gets result like ``` es_ids | bl_year ---------------------------- 24,25,26 | July 2016 ---------------------------- 21,22,23 | June 2016 ```
301,449
* [Who is TeamDAG?](https://meta.stackoverflow.com/questions/351751/meet-team-dag-developer-affinity-growth) * What is the TeamDAG working on? * Why are you working on that and not [insert favorite feature request here]. These are some of the questions that we hear regularly on meta.so and meta.se. In an attempt to answer them, we are kicking off regular updates from the DAG team. These updates will provide a quick overview of the work we have done in the last several weeks and will list some of the notable work that we will/are working on or planning. Over time, they will morph and change being that they are plans, so nothing is guaranteed. That said, we hope you find these updates informative. ### [December 2017 update](https://meta.stackexchange.com/a/304122/354333) ### [November 2017 update](https://meta.stackexchange.com/a/302969/354333) ### [October 2017 update](https://meta.stackexchange.com/a/301450/354333)
2017/09/28
[ "https://meta.stackexchange.com/questions/301449", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/155160/" ]
October 2017 ============ *Note: I updated the title here to match the timing of reports going forward.* Done ---- **Mentorship experiment:** The experiment is over and we learned a ton. More details are coming in a post from the team tomorrow. [For background on the experiment checkout this post](https://meta.stackoverflow.com/questions/353845/stack-overflow-mentorship-research-project). **Review queue updates:** We’ve rolled [the red review dot](https://meta.stackoverflow.com/questions/355233/when-i-look-at-the-review-icon-i-see-red) out to everyone on SO and it will come to the entire network with the topbar. These UX changes have improved the flow of reviews. We will continue to keep our eye on this area, but there are no further changes planned. **“New feature” notification:** This experiment is done and the notification is ready to be used for future new features. You won’t see this notification a lot, but hopefully you’ll be excited to see it when it appears. [See the post for more details.](https://meta.stackoverflow.com/questions/356853/announcement-new-feature-notification) **Inline sign up:** Thanks to our move to https, we implemented inline sign up on our homepage a couple months ago. This change makes signing up for an account easier and it makes it clear you can reuse your Google or Facebook accounts to sign up. We’ve now added [inline sign up to the hero banner on question pages](https://i.stack.imgur.com/W4UG9.jpg). This took a bit longer due to performance concerns since question pages are responsible for almost all of the sites page views. --- In progress ----------- **Rolling out new Top Bar for the network sites:** We turned on a version of the new top bar for meta.stackexchange.com and for all mods on their site. We are [working through a wide array of feedback from the community](https://meta.stackexchange.com/questions/300829/new-top-bar-is-coming-to-the-stack-exchange-network) and plan to release the top bar for all network sites in October. --- Starting in October ------------------- Each of the items below describe some work that is planned for the coming month. As needed, we will directly engage the community to help shape the work. **Automating success measures for question quality:** One of the things we learned from the mentorship experiment is that our current experimentation system doesn’t work for question quality experiments. First step to make progress in this area is to automate what it takes to validate success/failure of any experiment. Not sexy, but critical for us to move quicker. **Ask a question template:** This idea is an oldie, but a goodie. [See this post as an example](https://meta.stackexchange.com/questions/231827/revisiting-question-templates). We think this is a simple place to start on question quality. **Announcement banner:** We are redesigning the announcement banner for system alerts (e.g. site is in read only mode due to fail over) and targeted user messages (e.g “we need you to update your email address”). This is part of the [user messaging system mentioned in the new feature notification post](https://meta.stackoverflow.com/questions/356853/announcement-new-feature-notification). **Community team requests:** Jnat keeps track of our progress on these [via this post](https://meta.stackexchange.com/questions/291031/what-features-did-the-community-team-discuss-have-implemented-or-have-denied-l). Each month we try to take on a few items championed by the community team. --- Investigating ------------- **Ask a question wizard** Several people have proposed breaking down the “ask a question” experience into steps. We are going to start investigations on this in October. **Draft post:** One of the most interesting findings from the mentorship experiment was around the value of being able to create and share draft questions. We think this feature is worth exploring and we will be starting an investigation in October.
26,443,717
I have run the following program on vba excel 2010 32 bit computer : > > Declare Sub sleep Lib "kernel32" (ByVal dwmilliseconds As Long) > > > Sub game() > > > i = 0 > > > Do > > > > ``` > i = i + 1 > > Cells(i, 1).Interior.Color = RGB(100, 0, 0) > sleep 500 > > ``` > > Loop Until i > 10 > > > End Sub > > > But, after running, it shows me the following error : "Can't find dll entry point sleep in kernel32" Can somebody please tell me what I should do next to remove the error? Thanks for the effort.
2014/10/18
[ "https://Stackoverflow.com/questions/26443717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4157397/" ]
Instead of sleep 500 you might want to use: ``` Application.Wait (Now + TimeValue("0:00:05")) ```
30,810
So, I am rereading the **God Machine Rules Update**. An issue I saw the last time I played with it was that there doesn't seem to be a mechanic for removing conditions without resolving them. Lets say a character gains the `Swooning` condition, inflicted upon him by a NPC who got a exceptional success on a first-impressions Socialize roll. If he never meets that person again, he will be stuck with *swooning* forever, and while it will have no negative ongoing effects, it will stay on his character sheet. I'm kinda OK with this; conditions that are never resolved, but never do harm, can become like the scars on a old warrior. However for a more harsh example (that I saw basically happen in play), a character had gained *Obsession*: "Discover supernatural activity in this rural community." Obsession is by default Persistent, but the rules say the storyteller may decide to make it a Temporary (i.e., normal) Condition. We were only briefly stopping though the community to get some information that we expected to send us overseas. (An expert had retired there). This condition was only expected to last that chapter, as the character with it was just going to investigate the usual places, and satisfy his ever-present belief that the supernatural is everywhere. However, another PC kinda screwed up, and we ended up basically driven out of down by a pitchfork wielding mob. (For reference, the *Obsessed* condition gives you 9-again to following with your obsession, but No-10-again on anything else. When it is Persistent, it also gives a beat each time you fail a obligation to follow your obsession.) So this character was stuck with the Obsessed condition for the rest of the game (it was only a short one-story campaign), and by rules AFAICT would never again get 10-again. I might have missed the ruling for escaping conditions without resolution. If not the house rule, I proposed was: > > "With storyteller permission, the character may expend 1 beat to 'let go' of a condition that is unable to be resolved, and does not contribute to the narrative. When ending a condition this way, you do not gain a beat for resolving it." > > >
2013/12/16
[ "https://rpg.stackexchange.com/questions/30810", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/1362/" ]
I'm a longtime member at [RPG.net](http://forum.rpg.net/forum.php), and they have [a board dedicated to discussion of D&D/fantasy d20 games](http://forum.rpg.net/forumdisplay.php?89-RPG-Spotlight-Dungeons-amp-Dragons-Fantasy-D20). The moderation is pretty heavy to keep edition warring out, but the people there are knowledgable and thoughtful. It's my favorite forum. (Someone else will surely tell you about [ENWorld](http://www.enworld.org/).)
31,725,406
I want to print the salary of invoked (any of them) child class in the inherited method of `Detail()`. this cannot be done in this scenario. How would I get the salary with all other details of an employee. Here is the code ``` using System; class Employee { public int ID; public string Name; public string Gender; public string City; public void Detail() { Console.WriteLine("Name: {0} \nGender: {1} \nCity: {2} \nID: {3}", Name, Gender, City, ID); //I want to get Yearly or Hourly Salary with these all } } class PermanatEmp : Employee { public float YearlySalary; } class TempEmp : Employee { public float HourlySalary; } class Class4 { static void Main() { PermanatEmp pe = new PermanatEmp(); pe.ID = 101; pe.Name = "XYZ"; pe.Gender = "Male"; pe.City = "London"; pe.YearlySalary = 20000; pe.Detail(); // how to get Salary with these all } } ```
2015/07/30
[ "https://Stackoverflow.com/questions/31725406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5097662/" ]
You can't and shouldn't - there's no guarantee that an `Employee` will *have* a salary. Instead, any class which *does* have a salary can override `ToString` to include all the properties it wants to. I'd suggest overriding `ToString` instead of having a `Detail` method that just prints the information out, by the way. (As a side note, I would *strongly* advise you not to use public writable fields. [Use properties instead](http://csharpindepth.com/Articles/Chapter8/PropertiesMatter.aspx).)
54,036,434
Ive got an accordion but want to remove the text decoration from a: Hover from the panel headers, but its pretty nested. (about six layers deep) How to do the styling for that particular element? I'm a bit rusty with doing CSS for nested elements... cheers. ``` <div class="row"> <div class="col-md-8 col-offset-2"> <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true"> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="headingOne"> <h4 class="panel-title"> <a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne"> Website </a> </h4> </div> <div id="collapseOne" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne"> <div class="panel-body"> Website Details. </div> </div> </div> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="headingTwo"> <h4 class="panel-title"> <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo"> Author </a> </h4> </div> <div id="collapseTwo" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingTwo"> <div class="panel-body"> Author Details. </div> </div> </div> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="headingThree"> <h4 class="panel-title"> <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseThree" aria-expanded="false" aria-controls="collapseThree"> Credits </a> </h4> </div> <div id="collapseThree" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingThree"> <div class="panel-body"> Thanks to... </div> </div> </div> </div> </div> </div> ```
2019/01/04
[ "https://Stackoverflow.com/questions/54036434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4486022/" ]
```css .panel-title a:hover { text-decoration: none; } ``` ```html <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <div class="row"> <div class="col-md-8 col-offset-2"> <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true"> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="headingOne"> <h4 class="panel-title"> <a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne"> Website </a> </h4> </div> <div id="collapseOne" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne"> <div class="panel-body"> Website Details. </div> </div> </div> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="headingTwo"> <h4 class="panel-title"> <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo"> Author </a> </h4> </div> <div id="collapseTwo" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingTwo"> <div class="panel-body"> Author Details. </div> </div> </div> <div class="panel panel-default"> <div class="panel-heading" role="tab" id="headingThree"> <h4 class="panel-title"> <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseThree" aria-expanded="false" aria-controls="collapseThree"> Credits </a> </h4> </div> <div id="collapseThree" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingThree"> <div class="panel-body"> Thanks to... </div> </div> </div> </div> </div> </div> ```
539,364
I've got three 433MHz receivers (all the same type) and I would like to increase the range on them (by which I mean the physical distance that the receiver can detect the signal from the transmitter). Changing the antenna on the transmitter (the little key fob/dongle thing) isn't an option for practicality reasons. One of these receivers is unfortunately housed in a sheet metal box (which can't be readily changed), so I would like to get the antenna outside the box, but I'm unsure as to how running it out of the enclosure interacts with the total length of wire used in the antenna itself, (i.e. the length exposed outside the enclosure vs total length to get back to where it is soldered to the receiver). The receivers currently have short coiled wire antenna (they look like a spring, but are actually coiled wire). Since the receivers are stationary, I can take some liberty with a larger antenna. Googling suggests that a balanced dipole antenna with a balun is the way to go, with 178mm straight wire on each 'leg' (not sure of the right term) on the antenna. The problem is, I don't know the first thing about RF, so I haven't been able to discern what is a good guide for how to construct such an antenna. Could anyone point me in the direction of a practical guide in this area that is technically sound? **EDIT - Hardware Details:** The transmitter and receivers are Elsema PentaCode series devices: Transmitter: PCK43302 Receivers: PCR43301RE & PCR43302240R * <https://www.elsema.com/pcr43302240r> * <https://www.elsema.com/pcr43301re> Basic details are on page 3 of this document: * <https://www.elsema.com/wp-content/uploads/2019/05/pckmanual.pdf> They're frequency hopping spread spectrum devices, with a freq range of 433.100 to 434.700MHz. Target range is ~200m, not quite line of site (elevation diff of about 10m over 150m due to small hill that rolls off). **EDIT - Directions to Transmitters:** So, the receiver's are stationary, but the transmitters are mobile. In the case of the gates, they're on access roads, meaning the transmitters can be sending a signal from either side of the gate (so, 180 degrees from each other). This is part of the problem, as a high gain antenna in one direction will hurt the radiation pattern 'out the back' (i.e. from the other direction), which isn't great given that the goal is to open it from both sides. Energy radiated 'to the sides' is wasted though. Is there an antenna design that can help achieve this?
2020/12/27
[ "https://electronics.stackexchange.com/questions/539364", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/230227/" ]
Full size antenna options would be a ¼ λ vertical monopole with one radial or a ½ λ horizontal / vertical dipole. [![enter image description here](https://i.stack.imgur.com/BoCTw.jpg)](https://i.stack.imgur.com/BoCTw.jpg) Holes are to be drilled in the enclosures to lead the elements out. The ground point on the PCB is to be connected to the metal enclosure. [![enter image description here](https://i.stack.imgur.com/NUM3T.jpg)](https://i.stack.imgur.com/NUM3T.jpg) The unit may be oriented to have the dipole horizontal or vertical.