qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
sequence
response
stringlengths
0
115k
54,975,362
**React 16.8 (Using classes not hooks)** consider the following `if` statement in a function thats called `onClick` ``` if (this.state.opponentIsDead) { this.setState({ disableAttack: 'disabled', }, () => { this.timer = setTimeout(() => { this.props.postFightData({ train_exp: 100, drop_chance: this.state.monster.drop_chance, gold_rush_chance: this.state.monster.gold_rush_chance, gold_drop: this.state.monster.gold_drop, }); }, 1000); }); } ``` What I am trying to do is wait a second before posting the fight data if you have won the fight, the time out piece works. But as you can see I am updating the state to disable the button. What I was thinking of doing is moving the timeout to the `componentDidUpdate` method, that way the component will re-render and the button will be disabled, how ever I feel thats the wrong way to do it. I understand you can wrap the `setState` in an async function, but I also wonder if thats the best approach. **The goal is to disable the button, then wait 1 second and post the data. Whats the best approach?** Whats wrong with this approach? ------------------------------- For those who might not know, the `setState` will be called to update the state, but instead of re-rendering it will then call the callback function thus the button is not disabled while the timer counts down. it will be disabled after the timer, not before, where as I want it before, not after.
2019/03/04
[ "https://Stackoverflow.com/questions/54975362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1270259/" ]
I suspect something else is causing you issue. This code seems to be working the way you want (or I'm misunderstanding). <https://codesandbox.io/s/8nz508y96j> - button click disables the button and post alert appears 3 seconds later Though using `componentDidUpdate` is the recommended approach.. <https://reactjs.org/docs/react-component.html#setstate> > > The second parameter to setState() is an optional callback function that will be executed once setState is completed and the component is re-rendered. Generally we recommend using componentDidUpdate() for such logic instead. > > >
8,313,043
I am new to App development , I am using XCode 4.2 I am creating an application that reads QR codes . I would like to be able to save the string (NSString format) and possibly the image in a history list so that even if the user close the application the history of scanned QR codes can be retreived, how can I do that ? a sample code will be appreciated Thanks Alot
2011/11/29
[ "https://Stackoverflow.com/questions/8313043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1051935/" ]
`slideToggle` optionally takes 2 parameters `duration` and a `callback` so passing true/false to show/hide will not work. You might have to write your own plugin which will implement this logic. Something like this ``` $.fn.mySllideToggle = function(show){ if(show){ $(this).slideDown(); } else{ $(this).slideUp(); } } ```
16,799,279
I'm not sure if this has been asked before, but I went through a lot of angular 2-way binding posts and frankly couldn't understand what they were talking about. So I'll just state my problem again. Lets say I want to use a tags input plugin such as [this](http://aehlke.github.io/tag-it/examples.html). I define an angular directive called tags and within it, initialize tagsinput on a text input. The text element is bound to a model which is populated in the controller from a service. I have this in Plunker [here.](http://plnkr.co/edit/hIvJjq) The problem is when the directive loads, the model is not populated yet, so the tagsinput plugin is initialized with an empty value. But I want it to be initialized with a server side value. I've come across this problem often and I've been resorting to initializing my plugins in service callbacks within controllers which I know is cardinal sin. I'm unable to get out of thinking that eventually, at some level, the plugin initialization must be delayed until the service returns so the value is available. And am I correct if I say that even in the angular way of doing it, this is somehow achieved? But in any case, I'm not able to figure out how to get this working.
2013/05/28
[ "https://Stackoverflow.com/questions/16799279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/219579/" ]
I think the best way to solve this problem is using a watcher inside your directive. ``` var app = angular.module('app', []); app.controller('Main', function ($scope, $timeout) { //this simulates data being loaded asynchronously after 3 second $timeout(function () { $scope.list = [1, 2, 3, 4]; }, 3000); }); app.directive("mydirective", function() { return { restrict: "A", link: function(scope, element, attrs) { scope.$watch('list', function (newVal, oldVal) { if (newVal) { //initialize the plugns etc scope.result = 'Model has been populated'; } }); } }; }); ``` In my example I am using $timeout inside the controller to simulate an async load of data, once the 'list' model gets populated the watcher inside the directive will realize it (newVal is not empty or undefined) and then the plugin can be initialized. This is a better approach instead of callbacks inside the controller because your code is much more concise. Here is a [jsBin](http://jsbin.com/iwewub/15/edit) EDIT: Just remember that the digest cycle has to be fired when the model is populated. If you are using $resource or $http to fetch the data from the server you don't have to worry, but if you are doing it outside Angular you will have to fire the digest cycle with $scope.$apply() so the watcher can be aware that the model was populated.
46,992
So I have a trigger on Order in a certain condition I need to create another opportunity based on the Order's current opportunity. It was pretty straight forward except for getting the products to copy over. I know this is a high level description, but can anyone help with how I should go about doing this? \*removed code because it had unrelated issues. Will add back when resolved.
2014/08/15
[ "https://salesforce.stackexchange.com/questions/46992", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/4739/" ]
Here is an outline solution that should meet your requirements and be bulkified: 1. Get the Ids of the Opportunity records that meet your criteria from your quotes and store them in a `Set<Id>` 2. Query for those Opportunities with the fields you want to clone and store them in a `List<Opportunity>` 3. Loop through this list and add clones of your Opportunities to a `Map<Id, Opportunity>` which maps the original Opportunity Id to the newly cloned Opportunity 4. `insert` your cloned Opportunity records (you can simple call insert on your Map `values()`) 5. Query for all OpportunityLineItem records with `OpportunityId` equal to the `keySet()` of your map and store them in a `List<OpportunityLineItem>` 6. Loop through these and put them in a `Map<Id, List<OpportunityLineItem>>` which maps the `OpportunityId` to it's OpportunityLineItem records 7. Loop through your `Map<Id, Opportunity>` from step 3, use the key of your map (the original Opportunity Id) to get the OpportunityLineItem records from your `Map<Id, List<OpportunityLineItem>>` in step 6, clone the records, update the Id from the value of your map (the Opportunity record your inserted earlier, which will now have an Id) in your `Map<Id, Opportunity>` and then add them to a `List<OpportunityLineItem>` 8. Finally, `insert` your list of OpportunityLineItem
65,023,560
The following example with ducks, is based on the Head First design patterns book. I have a game with different types of ducks. There is a super class Duck and it has two behaviours: fly and quack, which are stored in fields. The concrete classes decide (in the constructor) which behaviour a concrete breed has (see MalardDuck class). I realised I want my ducks to not only have type Duck but also Quackable (so that I can have methods that accept only quackables - assuming that there are other types that quack - see Lake class). When I implement the interface in MallardDuck, the compiler complains that the class does not have the method quack although it is defined in its superclass - Duck class. Now I could think of two solutions: 1. Overwrite a method quack by just calling the method from the superclass: super.quack() <- but that seems unnecessary (in theory) - a child class has a direct access to superclass's public methods, so why the interface Quackable even complains...? 2. Make Duck implement the Quackable -> this is rather illogical cause some Ducks don't Quack (their quackBehaviour is implemented with SiletnQuack class). However in both solutions the duck: * HAS A quackable behaviour, AND * IS A quackable Isn't that fundamentally wrong? What am I missing? ``` abstract class Duck{ protected Flyiable flyBehaviour; protected Quackable quackBehaviour; public void quack(){ quackBehaviour.quack(); } void performFly(){ flyBehaviour.fly(); } void swim(){ // swimming implementation } abstract void display(); } interface Quackable{ void quack(); } class Quack implements Quackable{ @Override public void quack() { System.out.println("Quack!"); } } class Quack implements Quackable{ @Override public void quack() { System.out.println("Quack!"); } } class SilentQuack implements Quackable{ @Override public void quack() { System.out.println("..."); } } class MallardDuck extends Duck{ public MallardDuck(){ quackBehaviour = new Quack(); flyBehaviour = new FlyWithWings(); } @Override void display() { // it looks like a Mallard duck } } ``` What if I want to accept ducks to this method as quackables (along with other animals): ``` class Lake{ ArrayList<Quackable> quackingAnimals; void addQuackingAnimal(Quackable animal){ quackingAnimals.add(animal); } void displayQuackables(){ //... } } ``` Solution 1: ``` class MallardDuck extends Duck implements Quackable { public MallardDuck(){ quackBehaviour = new Quack(); flyBehaviour = new FlyWithWings(); } @Override void display() { // it looks like a Mallard duck } @Override public void quack() { super.quack(); } } ``` Solution 2: ``` abstract class Duck implements Quackable{ protected Flyiable flyBehaviour; protected Quackable quackBehaviour; public void quack(){ quackBehaviour.quack(); } void performFly(){ flyBehaviour.fly(); } void swim(){ // swimming implementation } abstract void display(); } ```
2020/11/26
[ "https://Stackoverflow.com/questions/65023560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11958281/" ]
This is because `Duck` class DOES NOT implement the `quack` method from the `Quackable` interface. Although it has a `quack` method with the same signature, it is not the same method, that is declared in the interface. I do not understand, why Solution 2 (making the `Duck` class implement `Quackable` interface) would be illogical - it does expose public method for quacking, so all of it's descendants will `quack` anyway (but with different `quack` that is declared in the `Quackable` interface). In my opinion (only opinion), the `Duck` class should implement `Quackable`. If (in your case) not all `Ducks` `quack`, then it is reasonable, that a `Duck` can't be treated as something that has `Quackable` behavior and thus it can't be added to the collection of `Quackable` objects. In this case (in my opinion) you could create another abstract class extending `Duck` and implementing `Quackable` interface (like `QuackingDuck`) and in this case (in my opinion) you should remove `quack` method from `Duck` class - as not all `Ducks` `quack`. I hope that it answers your question. To sum up: * the `quack` method from `Duck` is not the implementation of the `quack` method from `Quackable` interface (as it would be the case in e.g. JavaScript) * in current implementation all `Ducks` `quack`, only their `quacking` behavior (implementation) is different (and in the case of `SilentDuck` - it still `quacks`)
1,518,433
Ofcourse the IL is lanuage independent,can i get the source code back from IL (let the source code be any language C#,VB) ?
2009/10/05
[ "https://Stackoverflow.com/questions/1518433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/160677/" ]
You could use [.NET Reflector](http://www.red-gate.com/products/reflector/) and [Denis Bauer's Reflector.FileDisassembler](http://www.denisbauer.com/NETTools/FileDisassembler.aspx): > > The Reflector.FileDisassembler is a > little add-in for the new version of > Lutz Roeder's .NET Reflector that you > can use to dump the decompiler output > to files of any Reflector supported > language (C#, VB.NET, Delphi). This is > extremely useful if you are searching > for a specific line of code as you can > use VS.NET's "Find in Files" or want > to convert a class from one language > to another. > > >
48,875,492
I have been flabbergasted with this problem since yesterday ``` $('input').click(function(){ var suggid; var state; suggid = $(this).attr("data-notifid"); state = $(this).attr("checked"); $.get('/notifications/toggle_read/', {suggestion_id: suggid, unread: state}); }); ``` I've been trying to send `suggestion_id` and `unread` to my endpoint in a Django app. In a previous iteration, I was also trying `state = $(this).checked;`, since code samples I was finding appeared to do that. The problem is that *I have been testing this code and making minor tweaks maybe about 50 times, and it has only ever sent `unread` once, when I hardcoded it to `"1"`.* Every single other request logged out as something like this: `GET /notifications/toggle_read/?suggestion_id=31` both in my runserver logs and in the console. I always refreshed the page on which the script appeared before testing the code on the widget, and even confirmed it was up-to-date in the browser source. I'm baffled... according to what I've read about `.get()`, this is exactly how you're supposed to send multiple query parameters e.g. `$.get( "test.php", { name: "John", time: "2pm" } );` at [this doc](http://api.jquery.com/jQuery.get/) What am I doing wrong?!
2018/02/19
[ "https://Stackoverflow.com/questions/48875492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1459594/" ]
It seems to me that the below makes no sense, and is always FALSE: ``` if (hist.data %in% rcp.data) ``` So nothing happens with `sim_array` I would start by doing something like this: ``` hist.files.pr <- list.files("/historical", full.names = TRUE, pattern="pr") hist.files.tas <- list.files("/historical", full.names = TRUE, pattern="tas") rcp.files.pr <- list.files("/rcp", full.names = TRUE, pattern="pr") rcp.files.tas <- list.files("/rcp", full.names = TRUE, pattern="tas") ``` At this point you can remove the files from "hist" for models that are not in "rcp" ``` hist.files.tas <- c( "/historical/tas_CNRM-CERFACS-CNRM-CM5_CLMcom-CCLM4-8-17_r1i1p1.nc", "/historical/tas_CNRM-CERFACS-CNRM-CM5_CNRM-ALADIN53_r1i1p1.nc", "/historical/tas_CNRM-CERFACS-CNRM-CM5_RMIB-UGent-ALARO-0_r1i1p1.nc", "/historical/tas_CNRM-CERFACS-CNRM-CM5_SMHI-RCA4_r1i1p1.nc", "/historical/tas_ICHEC-EC-EARTH_CLMcom-CCLM4-8-17_r12i1p1.nc", "/historical/tas_ICHEC-EC-EARTH_DMI-HIRHAM5_r3i1p1.nc", "/historical/tas_ICHEC-EC-EARTH_KNMI-RACMO22E_r12i1p1.nc", "/historical/tas_ICHEC-EC-EARTH_KNMI-RACMO22E_r1i1p1.nc", "/historical/tas_ICHEC-EC-EARTH_SMHI-RCA4_r12i1p1.nc", "/historical/tas_IPSL-IPSL-CM5A-MR_INERIS-WRF331F_r1i1p1.nc", "/historical/tas_IPSL-IPSL-CM5A-MR_SMHI-RCA4_r1i1p1.nc", "/historical/tas_MOHC-HadGEM2-ES_CLMcom-CCLM4-8-17_r1i1p1.nc", "/historical/tas_MOHC-HadGEM2-ES_KNMI-RACMO22E_r1i1p1.nc", "/historical/tas_MOHC-HadGEM2-ES_SMHI-RCA4_r1i1p1.nc") # in this example, fut files is a subset of hist files; that should be OK if their filename structure is the same rcp.files.tas <- hist.files.tas[1:7] getModels <- function(ff) { base <- basename(ff) s <- strsplit(base, "_") sapply(s, function(i) i[[2]]) } getHistModels <- function(hist, fut) { h <- getModels(hist) uh <- unique(h) uf <- unique(getModels(fut)) uhf <- uh[uh %in% uf] hist[h %in% uhf] } hist.files.tas.selected <- getHistModels(hist.files.tas, rcp.files.tas) # hist.files.pr.selected <- getHistModels(hist.files.pr, rcp.files.pr) ``` The double loop (k, r) could probably be avoided by doing something like this: ``` library(raster) his.pr <- values(stack(hist.files.pr.selected, var="pr"))) his.tas <- values(stack(hist.files.tas.selected, var="tas")) rcp.pr <- values(stack(hist.files.pr, var="pr")) rcp.tas <- values(stack(hist.files.tas, var="tas")) ``` And the (i, j) loop over the rows and cols can probably be avoided too. R is vectorized. That is, you can do things like `(1:10) - 2`. Either way, your code is very hard to read with all these nested loops. If you actually need them, it would be better to call functions. For more help, provide some example data instead of files that we do not have, or make a few files available.
614,601
I'm in the process of writing a small web app that would allow me to manage several IIS installations on different servers on our network. We have no domain controller. I have written a small impersonation controller that uses the win32 api and its LogonUser method. I then use System.DirectoryServices and the IIS ADSI provider to create a new site. I have the following routine (exchanged some values with clear-text strings for better readability): ``` if (impersonationSvc.ImpersonateValidUser("Administrator@SRV6", String.Empty, "PASSWORD)) { string metabasePath = "IIS://" + server.ComputerName + "/W3SVC"; DirectoryEntry w3svc = new DirectoryEntry(metabasePath, "Administrator", "PASSWORD"); string serverBindings = ":80:" + site.HostName; string homeDirectory = server.WWWRootNetworkPath + "\\" + site.FolderName; object[] newsite = new object[] { site.Name, new object[] { serverBindings }, homeDirectory }; object websiteId = (object)w3svc.Invoke("CreateNewSite", newsite); int id = (int)websiteId; impersonationSvc.UndoImpersonation(); } ``` This routine works when I use the server the web app is hosted on (SRV6). A new site is created. If I use SRV5 for instance, another Server on our network (with no domain), ImpersonateValidUser works, the DirectoryEntry is created, but w3svc.Invoke fails with the following error: **[COMException (0x80070005): Access denied]** ``` System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail) +377678 System.DirectoryServices.DirectoryEntry.Bind() +36 System.DirectoryServices.DirectoryEntry.get_NativeObject() +31 System.DirectoryServices.DirectoryEntry.Invoke(String methodName, Object[] args) +53 ``` ... Anyone knows how I could solve this?
2009/03/05
[ "https://Stackoverflow.com/questions/614601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13466/" ]
You cannot use impersonation in this situation. The account you are impersonating needs login priveleges on the local machine. If your web servers are not part of a domain, I think Tant102's idea of web services is your only way to go.
16,492,135
``` <div class="carousel colorDissolve"> <img class="item" src="car.jpg" /> <img class="item" src="plane.jpg" /> <img class="item" src="train.jpg"/> <img class="item" src="boat.jpg" /> </div> /* colorDissolve */ .colorDissolve { position: relative; overflow: hidden; width: 287px; height: 430px; background: #000000; } .colorDissolve .item { position: absolute; left: 0; right: 0; opacity: 0; -webkit-animation: colorDissolve 24s linear infinite; -moz-animation: colorDissolve 24s linear infinite; -ms-animation: colorDissolve 24s linear infinite; animation: colorDissolve 24s linear infinite; } .colorDissolve .item:nth-child(2) { -webkit-animation-delay: 6s; -moz-animation-delay: 6s; -ms-animation-delay: 6s; animation-delay: 6s; } .colorDissolve .item:nth-child(3) { -webkit-animation-delay: 12s; -moz-animation-delay: 12s; -ms-animation-delay: 12s; animation-delay: 12s; } .colorDissolve .item:nth-child(4) { -webkit-animation-delay: 18s; -moz-animation-delay: 18s; -ms-animation-delay: 18s; animation-delay: 18s; } @-webkit-keyframes colorDissolve { 0%, 25%, 100% { opacity: 0; } 4.17%, 20.84% { opacity: 1;} } @-moz-keyframes colorDissolve { 0%, 25%, 100% { opacity: 0; } 4.17%, 20.84% { opacity: 1;} } @-ms-keyframes colorDissolve { 0%, 25%, 100% { opacity: 0; } 4.17%, 20.84% { opacity: 1;} } @keyframes colorDissolve { 0%, 25%, 100% { opacity: 0; } 4.17%, 20.84% { opacity: 1;} } ``` I cannot seem to get text OVER images this carousel. If I used a button slider, I can, but I just cannot seem to do it this way. It feels like I am not getting the div structure right. I tried to div each slide, but the text shows on the first slide from every div. Any guidance would be appreciated. I need different text over each slide when it appears, but I cannot get it to structurally work.
2013/05/10
[ "https://Stackoverflow.com/questions/16492135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2371762/" ]
[**JS fiddle DEMO**](http://jsfiddle.net/habo/u5dTp/) modified your markup a little ``` <div class="carousel colorDissolve"> <div class="item"> <img src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcTGNBB_xiix1HdkfCW1OG8NmMqbU23KUIXKE1HuK3RW3UBV_smc" /> <span>Picture Car from Google.com</span> </div> <div class="item"> <img src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcRMj84NfnxY3l_GbZFFUvmBI3Zg_tPjPutlomjfiU0TyPJFG3O1" /> <span>Picture Plane from Google.com</span> </div> <div class="item"> <img src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcS_i3dd7B8UkOKEaI4bVBmpyld_5JkZWbwC8vObZiw6PxUTSl53"/> <span>This is train</span> </div> <div class="item"> <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQZT3h9jLlg7yC3RNr8rg8l2JlurpXkJX1MXRrwh9eYI9BMJD316w" /> <span>This is boatm</span> </div> </div> ``` Added styling to span ``` span{ position:absolute; top:0px; left:0px; color:#c30; font-size:2em; -webkit-text-stroke-width: 1px; -webkit-text-stroke-color: black; } ```
82,886
In my campaign, I am playing a Hybrid Swordmage who is using the Vigilante Character Theme to allow him to apply marks with the Mark of the Vigilante power. This power reads: > > **Effect:** You assume a stance, the mark of the vigilante. Until the stance ends, you gain the following benefits. > > > * Whenever you hit an enemy with a melee or ranged attack, you can mark the enemy until the end of your next turn. > * You gain a +2 power bonus to all defenses against opportunity attacks that you provoke by moving." > > > My question is about the marking. If the target is marked by the mark of the Vigilante power, can I use my Swordmage Aegis of Assault power? The power reads: > > **Effect:** You mark the target. The target remains marked until you use this power against another target. If you mark other creatures using other powers, the target is still marked. A creature can be subject to only one mark at a time. A new mark supersedes a mark that was already in place. > > > If your marked target makes an attack that doesn't include you as a target, it takes a –2 penalty to attack rolls. If that attack hits and the marked target is within 10 squares of you, you can use an immediate reaction to teleport to a square adjacent to the target and make a melee basic attack against it. If no unoccupied space exists adjacent to the target, you can't use this immediate reaction. > > > Note that it refers to the target as a "marked target". Does the effect apply if the target is marked by another power?
2016/06/19
[ "https://rpg.stackexchange.com/questions/82886", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/29712/" ]
It depends on the class ----------------------- Different classes use marks in different ways, some having generic marks, and some having special, named marks. For example, Paladins have not just one, but two named marks, Divine Challenge and Divine Sanction, which have additional features beyond generic marks. **Swordmage Aegis marks are indeed special marks** with extra features you can apply if the mark is ignored, **and thus must be applied with your appropriate Aegis power** or some other power that specifies that it counts as your Aegis **to gain the extra benefits**. This is further supported by the Aegis Blade magic weapon, which has the following power: > > **Power (Daily):** Minor. Mark each enemy within a close burst 3 (save ends). If you have the Swordmage Aegis class feature, treat each mark as if you applied it with your chosen aegis. > > > Generally speaking, any such effects named within a power that adds the mark only apply for marks created with the same power, while other powers that only specify a mark work with any mark. Paladins and Swordmages have these special marks. Cavaliers, Knights, and Berserkers use a Defender Aura instead of marks. Fighters, Wardens, and Battleminds primarily use generic marks.
74,208,833
I have a table called relationships: [![relationships](https://i.stack.imgur.com/ves46.png)](https://i.stack.imgur.com/ves46.png) And another called relationship\_type: [![relationship type](https://i.stack.imgur.com/aZPAK.png)](https://i.stack.imgur.com/aZPAK.png) A person can have a social worker assigned to them on a specified time period (has start and end time), or specified to them with a start time only. I am writing a query to retieve records of a social worker assigned to someone during a filtered time. My query looks like this : ``` SELECT r.person_a AS patient_id, greatest((r.start_date), (r.end_date)) as relationship_date, concat_ws( ' ', pn.family_name, pn.given_name, pn.middle_name ) AS NAME FROM relationship r INNER JOIN relationship_type t ON r.relationship = t.relationship_type_id INNER JOIN person_name pn ON r.person_b = pn.person_id WHERE t.uuid = '9065e3c6-b2f5-4f99-9cbf-f67fd9f82ec5' AND ( r.end_date IS NULL OR r.end_date <= date("2022-10-26")); ``` I only want to retrieve the patient\_id of the user and name of case worker whose relationship is valid during the filtered time. In an instance where a relationship has no end date, i use the start date. Any advice/recommendation on what i am doing wrong will be appreciated. My current output : [![output](https://i.stack.imgur.com/aiU9B.png)](https://i.stack.imgur.com/aiU9B.png)
2022/10/26
[ "https://Stackoverflow.com/questions/74208833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6480460/" ]
There is an Outlook quirk, `.Display` before editing. Appears it applies in this situation too. ```vb Option Explicit Sub CreateTask() Dim itm As Object Dim msg As MailItem Dim olTask As TaskItem Set itm = ActiveExplorer.Selection.Item(1) If itm.Class = olMail Then Set msg = itm Set olTask = CreateItem(olTaskItem) With olTask .subject = msg.subject .RTFBody = msg.RTFBody .Display ' <--- Earlier rather than later .Attachments.Add msg, , 1 End With End If End Sub ```
5,941,313
I am looking for a c# library that is open source but licensed to allow development in closed sourced projects (so something like MIT/BSD style) that allows me to work with compressed files. I am really not that picky about what compression is used, only that it is something common (.zip, .rar, .tar, .tar.gz, etc...). The reason I need this functionality is that I am building a web application platform and right now the best and easiest way to be able to build and distribute modules (or plug-ins) for the platform I think is with a compressed file. The compressed file would hold the .dll files which would include source code and razor views and also any number of supporting files (images, dotlesscss, javascript, etc...). What I want to be able to do is through the web application platform itself, allow an user to be able to just upload one compressed file and have the web application copy the file, extract all the files in it, and the copy the extracted files into the correct locations.
2011/05/09
[ "https://Stackoverflow.com/questions/5941313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/384016/" ]
This is already built into the .net framework :-) just check out the compression namespace: <http://msdn.microsoft.com/en-us/library/system.io.compression.aspx>
2,611,559
My question today is: Is polynomial $1+x+x^2$ irreducible in $\mathbb{Z}\_5[x]?$ Let $[1+x+x^2]$ be the ideal of $\mathbb{Z}\_5[x]$ generated by $1+x+x^2$. Is the quotient ring $\mathbb{Z}\_5[x]/[1+x+x^2]$ a field? How many elements does the quotient ring $\mathbb{Z}\_5[x]/[1+x+x^2]$ have? I've answered most of it but I just have to answer this: How many elements does the quotient ring $\mathbb{Z}\_5[x]/[1+x+x^2]$ have? I know the polynomial is irreducible, and I know it is a field. But how can I answer the last part? I see on the internet that I have to use the division algorithm, but what should I divide? I hope some of you can help me with the last part.
2018/01/19
[ "https://math.stackexchange.com/questions/2611559", "https://math.stackexchange.com", "https://math.stackexchange.com/users/515732/" ]
The correct formula is \begin{align\*} \dfrac{d(f\circ g)(x)}{dx}=\sum\_{i=1}^{n}\dfrac{\partial f}{\partial v\_{i}}(g(x))\dfrac{dg\_{i}(x)}{dx}, \end{align\*} where $g=(g\_{1},...,g\_{n})$.
353,081
Imagine a container filled with highly pressurized air. Now imagine that there is some object, maybe a marble, inside the container. Is it possible to cause the marble to "float" within mid-air, due to the forces of the pressurized air acting on it in all directions? Additionally, why is it that objects tend to spread to the edges of the container, rather than the center? I imagine this would also depend on the shape, size, and pressure of the container, as well as the shape and size of the objects inside. [![OP's MS Paint effort. From http://i.imgur.com/4H5qjI6.png as posted in comments.](https://i.stack.imgur.com/FNVIs.png)](https://i.stack.imgur.com/FNVIs.png)
2017/08/22
[ "https://physics.stackexchange.com/questions/353081", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/64624/" ]
Yes. In practice it probably depends on the temperature, but **let's assume not real air, but an ideal gas**. Then, all you have to do is to increase the pressure enough for it to have the same (or infinitesimally higher) density than the marble: at this point [buoyancy](https://en.wikipedia.org/wiki/Buoyancy) equals the weight of the marble and it can "float". That will not depend on the shape or size of the object inside, only on its density. As for the spread you describe, unless there's some sort of flow in the container, there has to be some effective attraction to the wall. * **Edit**: it's important to note that, if the key concepts are not only *pressure* and *flotation*, but also *air*, than, as many pointed out, air cannot be made as dense as a typical marble without changing phase (and or melting the marble).
34,864,651
Does Ruby cache the result of a method so that it does not need to evaluate it twice if it is called twice? I am working in Rails, so for example, I could do the following where I store the result of a param passed into a Rails controller in a variable like so: ``` def foo_bar_method case param[:foobar] when 'foo' then 'bar' when 'bar' then 'baz' else 'barbaz' end result = foo_bar_method puts result puts result ``` This way I am only evaluating the `foo_bar_method` once. Does Ruby cache the result of this method (or does Rails do this)? Is it faster to use the code shown above, or will the following code result in the same performance? ``` def foo_bar_method case param[:foobar] when 'foo' then 'bar' when 'bar' then 'baz' else 'barbaz' end puts foo_bar_method puts foo_bar_method ```
2016/01/18
[ "https://Stackoverflow.com/questions/34864651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1351770/" ]
Twilio employee here. This is result of TaskRouter being able to hit your AssignmentCallbackUrl with an HTTP POST request. We've noticed that on your Account there's this notification message: > > Cannot POST /assignment > > > Please enable **POST** for your AssignmentCallback endpoint. TaskRouter will actively cancel the reservation if it cannot hit your AssignmentCallbackUrl or there is an error when issuing an Assignment Instruction. The several updates in the console are due to the fact that TaskRouter cancels the reservation due to not hitting the AssignmentCallbackUrl, moving the Worker back to the previous state (Available), and then trying to assign the Task again, and thus generating another Reservation for the Worker for the same Task (repeat 15x until the Max Task Assignment is hit).
16,278
I was taking some photo stacks yesterday, and I also took a plenty of random ones (pointed not at a specific object) too at 200mm. However, I've ended with a shot but I have no idea where I pointed my camera at, and because of the narrow angle of 200mm, I'm lost without any guiding star/object. This happened to me before too, so I was wondering whether there is a software or a website that I can upload a photo, and it will analyze the objects, cross match them with known objects and detect which part of the sky it is? Or is there a method that I can use to figure out by myself (remember that there are no well-known bright stars in the image, at least not that I can identify by myself)?
2016/06/17
[ "https://astronomy.stackexchange.com/questions/16278", "https://astronomy.stackexchange.com", "https://astronomy.stackexchange.com/users/13176/" ]
Have you tried [nova.astrometry.net](http://nova.astrometry.net)? They set up a web service for doing more or less what you're talking about.
176,618
I wanted to delete my lom mod (lots of mobs mod) because it is crashing Minecraft, but I can't because it claims Minecraft is running. However, I do not see Minecraft on my screen. I want to delete my mod without restarting my computer, my restarting doesn't seem to properly work. So I want to close javaw.exe on my task manager but it seems I have alot of javaw.exe and has different type of numbers on it (my first time working with task manager) Which one do I close?
2014/07/12
[ "https://gaming.stackexchange.com/questions/176618", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/82418/" ]
Any program that uses Java will have a process called "javaw.exe". Try closing out of the other programs on your computer and the number of processes will go down. Some sample programs that use Java include web browsers, other games, some music players, et cetera. Your safest bet, unfortunately, is probably to save your work and restart your computer, thus killing all the Java programs at once. Then you should be able to remove the mod. The fact that Minecraft is still considered running despite not being visible on your screen indicates that something has gone wrong in the first place, and you might be seeing computer slowdowns and odd behavior which a restart would clear right up.
53,190,392
How can I add a column from a select query but the value from the new column will be the row count of the select query for example. ``` select quantity from menu; ``` and returns like this ``` +--------+ |quantity| +--------+ | 50 | | 32 | | 23 | +--------+ ``` but I want somthing like this ``` +----------+--------+ |new column|quantity| +----------+--------+ | 1 | 50 | | 2 | 32 | | 3 | 23 | +----------+--------+ ``` the new column should start from 1 and end from row count of the select query statement. Any answer would help Thanks
2018/11/07
[ "https://Stackoverflow.com/questions/53190392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7663474/" ]
Since [you can access the latest version of MySQL](https://stackoverflow.com/questions/53190392/add-a-column-from-a-select-query-with-index/53190422#comment93269574_53190392), we can simply use the [`Row_Number()`](https://dev.mysql.com/doc/refman/8.0/en/window-function-descriptions.html#function_row-number) functionality: ``` SELECT ROW_NUMBER() OVER () AS new_column, quantity FROM menu; ```
50,215,862
I am performing the following `POST` in a `Tower` server: ``` http://<my-tower-url>/api/v2/job_templates/10/launch/ Headers: Content-Type:application/json Authorization:sometokenhere ``` And getting back the error: > > {"detail":"Authentication credentials were not provided."} > > > Have also tried the following: ``` Headers: Content-Type:application/json Authorization:Token sometokenhere ``` as suggested [here](http://docs.ansible.com/ansible-tower/latest/html/towerapi/auth_token.html). Same happens when passing raw username/password in the `POST` body as follows (and skipping the `Authorization` header): ``` { "username": "myusername", "password": "mypass", "inventory": "inventoryname", "verbosity": 0, "extra_vars": { "var1": "somevar1", "var2": "somevar2", "var3": "somevar3", "var4": "somevar4", "var5": "somevar5" } } ``` Any idea why this is not working?
2018/05/07
[ "https://Stackoverflow.com/questions/50215862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2409793/" ]
I ended up using basic auth as follows: **1**.create the user which you want to run your ci jobs with **2**.perform the following post at the respective CI job: ``` curl -o /dev/null -s -w \"%{http_code}\n\" -X POST http://<my-tower-url>/api/v2/job_templates/10/launch/ \ -H \"authorization: Basic $MY_AUTH_TOKEN\" \ -H \"content-type: application/json\" \ -d \"@awx_data.json ``` Where * `awx_data.json` is a file holding the actual `POST` body * `MY_AUTH_TOKEN` is the tyical [`base64`](https://stackoverflow.com/questions/1386112/what-is-base64-clear-text-username-and-password) encoded username+password of the above user You can also assign the above result and check it against `201` which is what `AWX` returns upon successful job creation. Polling the `AWX` server to check if the job was successfully finished is another story of course.
47,313,371
I have widget that inherits from QTreeView, and I want to change the text color, but only for a specific column. Currently I set the stylesheet, so the entire row changes the text color to red when the item is selected. ``` QTreeView::item:selected {color: red} ``` I want to change only the color of the first column when the item is selected. I know how to change the colour for specific columns (using ForegroundRole on the model and checking the index column), but I don't know how to do check if the index is selected in the model.
2017/11/15
[ "https://Stackoverflow.com/questions/47313371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2359027/" ]
You can use a delegate for that: ``` class MyDelegate : public QStyledItemDelegate { public: void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { if (option.state & QStyle::State_Selected) { QStyleOptionViewItem optCopy = option; optCopy.palette.setColor(QPalette::Foreground, Qt::red); } QStyledItemDelegate::paint(painter, optCopy, index); } } myTreeWidget->setItemDelegateForColumn(0, new MyDelegate); ```
382,753
**Question.** What do you recommend to have the arc(-arrow) start outside the node (b) and also stop outside the node (c) in [![enter image description here](https://i.stack.imgur.com/2lLjB.png)](https://i.stack.imgur.com/2lLjB.png) which was created with ``` \documentclass{amsart} \usepackage{tikz} \begin{document} \begin{tikzpicture} \node (a) at (0pt,0pt)[]{$a$}; \node (b) at (0pt,101pt)[]{$b$}; \draw[->] (a)--(b); \draw[->] (b) arc [start angle=0, end angle=74, x radius=25pt, y radius=25pt,line width=4pt] node (c) {$c$}; \end{tikzpicture} \end{document} ``` ? Do you agree that it is somewhat unsystematic of TikZ to not have the straight arrow *also* go from *center to center* by default? **Remarks.** I know more than one way to *somehow* do this, for example with the option "shorten", but none appears the right way to do this. For example, using functionality like (b.north) is not a good solution, since it does not *uniformly* work. One then has to keep track of where one should say "north", where "south", etc, especially when some degree of automation is used in a larger TikZ program.
2017/07/22
[ "https://tex.stackexchange.com/questions/382753", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/133810/" ]
I do not like to use arc, except when necessary, I prefer to use to [out = xx, in = xx]. It is also necessary that the node exists before joining it, otherwise, the coordinate is reached directly. ``` \documentclass{article} \usepackage{tikz} \begin{document} \begin{tikzpicture} \node (a) at (0pt,0pt){$a$}; \node (b) at (0pt,101pt){$b$}; \draw[->] (a)--(b); \path (b) arc (0:90:25pt) node (c) {$c$}; \draw[->] (b) to [out=90,in=0] (c); \end{tikzpicture} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/NT64Q.jpg)](https://i.stack.imgur.com/NT64Q.jpg) another solution in 3 lines! All nodes are defined in a path It remains only to trace the arcs and segments with `[rounded corners]` ``` \documentclass{article} \usepackage{tikz} \begin{document} \begin{tikzpicture} \path node(a) {$a$} --++ (0,101pt)node(b){$b$} |-++ (-1,1) node (c) {$c$}; \draw[rounded corners=0.5cm,->] (a) -- (b) ; \draw[rounded corners=0.5cm,->] (b)|- (c); \end{tikzpicture} \end{document} ```
60,295,589
I have some address data that needs to be corrected. It is intending to show a range of addresses, but this will not work for geocoding. What is an effective way to to remove everything between the hyphen and the first space using regex in excel? Example: ``` 29-45 SICKLES ST 31-39 SHERMAN AV 36-44 ARDEN ST 118-22 NAGLE AV ``` Becomes ``` 29 SICKLES ST 31 SHERMAN AV 36 ARDEN ST 118 NAGLE AV ```
2020/02/19
[ "https://Stackoverflow.com/questions/60295589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12817139/" ]
Since you have tagged `RegEx` you could use it like so within Excel's VBA: ``` Sub Test() Dim arr As Variant: arr = Array("29-45 SICKLES ST", "31-39 SHERMAN AV", "36-44 ARDEN ST", "118-22 NAGLE AV") With CreateObject("VBScript.RegExp") .Pattern = "-\d*\s*" For x = LBound(arr) To UBound(arr) arr(x) = .Replace(arr(x), " ") Next End With End Sub ```
8,971,000
How to request Android download manager to download multiple files at the same time. Also I would like to know each and every file download status.
2012/01/23
[ "https://Stackoverflow.com/questions/8971000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/676625/" ]
Request the first one. Then, request the second one. Then, request the third one. Continue as needed. Whether they download "at the same time" is not your concern, nor do you have control over it. They will download when `DownloadManager` decides to download them, which may be simultaneously or not.
279,991
Please tell me how can save a string with special characters to DB.Special characters may contatin single `quotes/double quotes` etc.. I am using ASP.NET with C#
2008/11/11
[ "https://Stackoverflow.com/questions/279991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Use parameterized queries. <http://aspnet101.com/aspnet101/tutorials.aspx?id=1> When rendering to the client, you should also use Server.HtmlEncode() to convert characters which have special meaning in HTML to numeric character references.
2,767,291
Trying to evaluate the integral $$\int\_0^\infty \frac{\log(x)^2}{(1+x)^2}dx$$ or equivalently $$\int\_{-\infty}^\infty e^x\frac{x^2}{(1+e^x)^2}dx$$ The answer should be $\frac{\pi^2}{3}$ Looks like we can use residue theorem, but the integration path does not seem to be easy to choose
2018/05/05
[ "https://math.stackexchange.com/questions/2767291", "https://math.stackexchange.com", "https://math.stackexchange.com/users/290124/" ]
Since you want to use the residue theorem, I'll provide the contour-analysis based approach using a **keyhole contour** (the coolest way of evaluating this integral). A nice tip you can use when you want to use a residue-based approach and see that your function has a logarithm in the numerator is to consider the same function with the logarithm raised to an extra power of one. In this case, the power is two so we use the function$$g(z)=f(z)\log^3z\qquad\qquad f(z)=\frac 1{(1+z)^2}$$And the contour we integrate, pictured below, is a keyhole contour. [![Keyhole](https://i.stack.imgur.com/BRx6W.jpg)](https://i.stack.imgur.com/BRx6W.jpg) A keyhole contour allows us to derive the integral by exploiting the logarithm's multivalued behavior. In this case, we define the argument above the positive real axis to be zero and below to be $2\pi$. I.e $z=x$ above and $z=xe^{2\pi i}$ below the real axis. To evaluate the contour integral, we first parametrize about each piece of the contour. Let the larger and smaller circle have a radius of $R$ and $\epsilon$ respectively and the arcs $\Gamma\_{R}$ and $\gamma\_{\epsilon}$ respectively. Now define the complex function$$f(z)=\frac 1{(1+z)^2}$$ and integrate it about the contour to get$$\begin{multline}\oint\limits\_{\mathrm C}dz\, f(z)\log^3z=\int\limits\_{\epsilon}^{R}dx\, f(x)\log^3x+\int\limits\_{\Gamma\_{R}}dz\, f(z)\log^3z\\-\int\limits\_{\epsilon}^{R}dx\, f(x)(\log|x|+2\pi i)^3+\int\limits\_{\gamma\_{\epsilon}}dz\, f(z)\log^3z\end{multline}$$ As $R\to\infty$ and $\epsilon\to0$, the second and fourth integrals vanish, leaving us with$$\oint\limits\_{\mathrm C}dz\, f(z)\log^3z=-12\pi^2\int\limits\_0^{\infty}dx\, f(x)\log x-6\pi^2 i\int\limits\_0^{\infty}dx\, f(x)\log^2x+8\pi^2i\int\limits\_0^{\infty}dx\, f(x)$$Where the middle integral is the one we want. The residue at $z=-1$ is$$\operatorname\*{Res}\_{z\, =\, -1}\frac {\log^3z}{(1+z)^2}=\lim\limits\_{z\to -1}\frac {d}{dz}\,\frac {(z+1)^2\log^3z}{(z+1)^2}=3\pi^2$$So the contour integral is simply $2\pi i$ times that. Taking the imaginary part gives$$6\pi^3=-6\pi\int\limits\_0^{\infty}dx\, f(x)\log^2x+8\pi^3\underbrace{\int\limits\_0^{\infty}dx\, f(x)}\_1$$Isolating and dividing both sides by $-6\pi$, it's clear that$$\int\limits\_0^{\infty}dx\,\frac {\log^2x}{(1+x)^2}\color{blue}{=\frac {\pi^2}3}$$
20,630,552
I have a simple c program that consists of `main.c` and `selection_sort.c`. I am compiling with `gcc -Wall -Wextra main.c selection_sort.c` I get no errors of warnings, but when executed it immediately terminates without any `printf` or `system quot`. I am using Linux OS. ``` //main.c #include <stdio.h> #include <stdlib.h> #include <time.h> void selection_sort(); int main(void) { printf("Program started...\n"); selection_sort(); printf("Selection_sort has finished...\n"); return 0; } //selection_sort.c #include <stdio.h> #include <stdlib.h> #define size 10000 void selection_sort() { int i,j, array[size]; for(i = 0; i < size; i++) { int num = rand() % size; array[i] = num; printf("%d ", num); } for(i = 0; i < size; i++){ int max_index = i; for(j = 0; j < size; j++) { if(array[j] > max_index) { max_index = array[j]; } } int tmp = array[i]; array[i] = array[max_index]; array[max_index] = tmp; } printf("\n"); for(i = 0; i < size;i++){ printf("%d", array[i]); } } ```
2013/12/17
[ "https://Stackoverflow.com/questions/20630552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3008098/" ]
For anything below Honeycomb (API Level 11) you'll have to use setLayoutParams(...). you can dynamically set the position of view in Android. for example if you have an ImageView in LinearLayout of your xml file.So you can set its position through LayoutParams.But make sure to take LayoutParams according to the layout taken in your xml file.There are different LayoutParams according to the layout taken. Here is the code to set: ``` FrameLayout.LayoutParams layoutParams=new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); layoutParams.setMargins(int left, int top, int right, int bottom); imageView.setLayoutParams(layoutParams); ```
56,779,996
I need to show all the letters in uppercase while the user is writing. I'm using this: `android:inputType="textCapCharacters"` But, when I push shift it turns to lowercase. I need something permanent.
2019/06/26
[ "https://Stackoverflow.com/questions/56779996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10561060/" ]
Functions will look into the module level scope i.e. global scope automatically when some name does not exist in the local scope. So, rather than checking in the `globals` dict, you can *ask for forgiveness*: ``` def _get_client(): try: return api_client except NameError: return some_api.Client() ```
61,423,714
I'm looping through a array filled with objects, and when i certain condition is met i want to make a copy of the current item and change a value **only** for the duplicated item. Something like: ``` while (j--) { if (value[j].extended.subcategories[0] === "lorem") { value.push(value[j]); value[DUPLICATED_ITEM].extended.subcategories[0] = "ipsum"; } } ``` I was playing around in jsfiddle and i also tried something like: ``` while (j--) { if (value[j].extended.subcategories[0] === "lorem") { value[value.length] = value[j]; value[value.length].extended.subcategories[0] = "ipsum"; } } ``` This does add a duplicate but when trying to change a value in the object it's (still) undefined. --- Small sidenote: while playing with the fiddle, i found another weird interaction that i don't really get. If you do this: <https://jsfiddle.net/luffyyyyy/bs1h0qLz/13/>. Both array[0] and array[3] get a value of 8 while i just specify array[3] = 8;
2020/04/25
[ "https://Stackoverflow.com/questions/61423714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2851791/" ]
Using Javascript / jQuery the following will remove all "hovered" action buttons, for a specific user role, on the subscriptions admin dashboard from the status column: ``` add_action( 'admin_footer', 'admin_dashboard_subscriptions_filter_callback' ); function admin_dashboard_subscriptions_filter_callback() { global $pagenow, $post_type; $targeted_user_role = 'va_support'; // <== Your defined user role slug // Targeting subscriptions admin dashboard for specific user role if( $pagenow === 'edit.php' && $post_type === 'shop_subscription' && current_user_can( $targeted_user_role ) ) : ?> <script> jQuery(function($){ $('td.column-status > div.row-actions').each(function() { $(this).remove(); }); }); </script> <?php endif; } ``` Code goes in functions.php file of your active child theme (or active theme). Tested and works.
14,322
Ma recherche initiale sur l'étymologie de [« désormais » (adv. de temps)](http://www.littre.org/definition/d%C3%A9sormais) m'a dévoilé une définition de **mais** comme « davantage », voir ci-dessous. > > **Dès**,        **or** ou **ore**, heure (voy. OR),      et      **mais** [=] davantage : > > > mot à mot, dès l'heure en avant. > > > Ensuite, je me lance dans [l'étymologie de « mais »](https://fr.wiktionary.org/wiki/mais#.C3.89tymologie) : > > [1.] (Xe siècle) Du latin [magis](https://fr.wiktionary.org/wiki/magis#la) (« plus, plutôt ») [[Plus, davantage.]](https://fr.wiktionary.org/wiki/magis#la) > > > La connotation de « magis », et de **mais** dans « désormais », me semble neutre. 2. Pourtant, en français moderne, « mais » peut servir [« à marquer opposition, restriction, différence » (cf la définition 3)](http://www.littre.org/definition/mais). Donc, le sens de « mais », comment a-t-il évolué de 1 à 2 ? Est-il devenu opposé? J'ai tenté de lire [l'étymologie du TLF sur « mais »](http://www.cnrtl.fr/etymologie/mais/1), dont la longueur et le manque de formatage m'ont rebuté.
2015/07/06
[ "https://french.stackexchange.com/questions/14322", "https://french.stackexchange.com", "https://french.stackexchange.com/users/-1/" ]
Je ne sais pas si ceci répondra à votre question, et je ne suis pas spécialiste de l'étymologie (et le TLF m'est aussi difficile à lire qu'à vous, même reformaté), mais il me semble qu'on peut affirmer en résumé : * Le **sens originel** de *mais* est celui de *magis* en latin : « plus, davantage ». Il me semble que c'est bien ce sens qui est à l'origine de *désormais*. * Pour obtenir un effet d'opposition ou de restriction, il fallait originellement y ajouter la **particule de négation** (*ne*, *non*). On retrouve ces constructions dans les exemples du TLF, ou dans certaines expressions figées, comme « n'en pouvoir mais ». > > « Il les assura même de la bénédiction pourtant hypothétique de sa > mère et de la pensée affectueuse de Dabek Sariéloubal qui **n'en pouvait** > **mais**. » (René Fallet, *Le triporteur*, 1951) > > > * Au cours des siècles, la particule de négation a de plus en plus fréquemment été omise, le sens négatif restant dominant dans l'usage et l'idée d'opposition passant donc au mot *mais* lui-même. (C'est le même phénomène qui explique l'existence simultanée des sens négatif et positif de *plus*.) * Finalement, le sens originel s'est perdu et le sens d'opposition est resté dans l'usage.
138,043
I want to create a new net.tcp://localhost:x/Service endpoint for a WCF service call, with a dynamically assigned new open TCP port. I know that TcpClient will assign a new client side port when I open a connection to a given server. Is there a simple way to find the next open TCP port in .NET? I need the actual number, so that I can build the string above. 0 does not work, since I need to pass that string to another process, so that I can call back on that new channel.
2008/09/26
[ "https://Stackoverflow.com/questions/138043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4829/" ]
Here is what I was looking for: ``` static int FreeTcpPort() { TcpListener l = new TcpListener(IPAddress.Loopback, 0); l.Start(); int port = ((IPEndPoint)l.LocalEndpoint).Port; l.Stop(); return port; } ```
73,394,646
In a webapp implemented as a Jetty container, we have a custom `javax.ws.rs.ext.MessageBodyWriter<T>` annotated with ``` @Singleton @Provider @Produces( "application/rss+xml" ) ``` We also have a resource which works just fine. The `get()` method is annotated with ``` @Produces( "application/vnd.api+json" ) ``` Visiting that endpoint returns the expected json response. Adding `.rss` to the endpoint causes a 406 response to be returned. What could be the reason it is not finding the `MessageBodyWriter` for returning the RSS response? The full stacktrace is: ``` javax.ws.rs.NotAcceptableException: HTTP 406 Not Acceptable at org.glassfish.jersey.server.internal.routing.MethodSelectingRouter.getMethodRouter(MethodSelectingRouter.java:472) at org.glassfish.jersey.server.internal.routing.MethodSelectingRouter.access$000(MethodSelectingRouter.java:73) at org.glassfish.jersey.server.internal.routing.MethodSelectingRouter$4.apply(MethodSelectingRouter.java:674) at org.glassfish.jersey.server.internal.routing.MethodSelectingRouter.apply(MethodSelectingRouter.java:305) at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:86) at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:89) at org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:89) at org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:69) at org.glassfish.jersey.server.internal.routing.RoutingStage.apply(RoutingStage.java:38) at org.glassfish.jersey.process.internal.Stages.process(Stages.java:173) at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:247) at org.glassfish.jersey.internal.Errors$1.call(Errors.java:248) at org.glassfish.jersey.internal.Errors$1.call(Errors.java:244) at org.glassfish.jersey.internal.Errors.process(Errors.java:292) at org.glassfish.jersey.internal.Errors.process(Errors.java:274) at org.glassfish.jersey.internal.Errors.process(Errors.java:244) at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:265) at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:234) at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:684) at <our package>.Jetty94HttpContainer.handle(Jetty94HttpContainer.java:167) // Jetty94HttpContainer extends AbstractHandler implements Container at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:127) at com.codahale.metrics.jetty9.InstrumentedHandler.handle(InstrumentedHandler.java:284) at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:127) at org.eclipse.jetty.server.Server.handle(Server.java:516) at org.eclipse.jetty.server.HttpChannel.lambda$handle$1(HttpChannel.java:487) at org.eclipse.jetty.server.HttpChannel.dispatch(HttpChannel.java:732) at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:479) at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:277) at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:311) at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:105) at org.eclipse.jetty.io.ChannelEndPoint$1.run(ChannelEndPoint.java:104) at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.runTask(EatWhatYouKill.java:338) at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.doProduce(EatWhatYouKill.java:315) at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.tryProduce(EatWhatYouKill.java:173) at org.eclipse.jetty.util.thread.strategy.EatWhatYouKill.run(EatWhatYouKill.java:131) at org.eclipse.jetty.util.thread.ReservedThreadExecutor$ReservedThread.run(ReservedThreadExecutor.java:409) at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:883) at org.eclipse.jetty.util.thread.QueuedThreadPool$Runner.run(QueuedThreadPool.java:1034) at java.base/java.lang.Thread.run(Thread.java:829) ```
2022/08/17
[ "https://Stackoverflow.com/questions/73394646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/167745/" ]
The resource methods annotated with a request method should declare the supported request media types equals to the entity providers that supply mapping services between representations and their associated Java types. Adding: ``` @Produces( "application/vnd.api+json", "application/rss+xml" ) ``` to the `get()` method should do the trick.
5,720,386
I have a small chat implementation, which uses a `Message` model underneath. In the `index` action, I am showing all the messages in a "chat-area" form. The thing is, I would like to start a background task which will poll the server for new messages every X seconds. How can I do that and have my JS unobtrusive? I wouldn't like to have inline JS in my `index.html.erb`, and I wouldn't like to have the polling code getting evaluated on every page I am on.
2011/04/19
[ "https://Stackoverflow.com/questions/5720386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31610/" ]
This would be easiest using a library like mootools or jquery. On `domready`/`document.ready`, you should check for a given class, like "chat-area-container". If it is found, you can build a new `<script>` tag and inject it into DOM in order to include the javascript specific for the chat area. That way, it isn't loaded on every page. The "chat-area-container" can be structured so that it is hidden or shows a loading message, which the script can remove once it is initialized. On the dynamically created `<script>` tag, you add an onLoad event. When the script is finished loading, you can call any initialization functions from within the onLoad event. Using this method, you can progressively enhance your page - users without javascript will either see a non-functioning chat area with a loading message (since it won't work without js anyway), or if you hide it initially, they'll be none-the-wiser that there is a chat area at all. Also, by using a dynamic script tag, the onLoad event "pseudo-threads" the initialization off the main javascript procedural stack.
23,943,895
Is it possible to get an Excel VLOOKUP to pick out the most recent date where it finds multiple lookup values: e.g. this is what I have at the moment: ``` =IFERROR(VLOOKUP(A$1:A$5635,'RSA Report'!A:V,21,FALSE),"") ``` it would currently pick (User1 acting as the value that is being looked up) ``` Col A (1) Col U (21) User1 22/10/2013 ``` from ``` Col A (1) Col U (21) User1 22/10/2013 User1 28/03/2014 User1 22/10/2013 User1 28/03/2014 ``` whereas I want it to pick ``` Col A (1) Col U (21) User1 28/03/2014 ```
2014/05/29
[ "https://Stackoverflow.com/questions/23943895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/436493/" ]
VLookup is designed to look for a single match for a specific value (either using an exact or approximate comparison). It doesn't check for any other matching values. I can think of 2 options which might help: * If you can sort the data, sort Column U in descending order. The most recent date will then be returned as the first match. * If you can't sort the data, you could consider using the [DMax](http://office.microsoft.com/en-us/excel-help/dmax-HP005209061.aspx) function. This allows you to specify criteria and then return the maximum value for a specific field. It does require you to put the criteria in a table format rather than specifying directly within the formula, so it's not ideal in all situations. Here's an example showing DMAX: Formula: `=DMAX(B3:C7,"Date",E3:E4)` This assumes that your table of data is in range B3:B7, you want to find the maximum value in a field called "Date" and your criteria is in range E3:E4 (where E3 contains the field name you are filtering on, and E4 contains the value you are looking for). One of the benefits of DMax is that you can use multiple sets of criteria.
15,250,942
I need to animate a relative-positioned div, where the animation goes from `display:none;` to `display:block;`. I need to "scale" it, starting from the bottom-right corner towards the top-left corner. Are there any ways of doing this? (Preferably in jQuery, but anything that works is good)
2013/03/06
[ "https://Stackoverflow.com/questions/15250942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2140478/" ]
I am not sure that you want to fade in or change the size of the element. It sounds like you want need to bring it out of hiding. Since HTML layout is all done from the top and the left, getting something to animate from the bottom right to the top left is tricky to say the least. By carefully combining `slideUp` and `slideDown` with position fixed or absolute, [you can get an element to show from the bottom up.](http://www.bennadel.com/blog/1827-Using-jQuery-s-SlideUp-and-SlideDown-Methods-With-Bottom-Positioned-Elements.htm) But I have not heard of a way to slide right to left without using some [very advanced jQuery with bleeding edge includes.](https://stackoverflow.com/questions/521291/jquery-slide-left-and-show) So I offer this solution: Since the div you are trying to show is positioned relative you probably have some kind of wrapper, or an easily place one. With a wrapper in place you can set it's `overflow` rules to hidden and then place the 'hiding' div out side of its bounds. [Now with a simple jQuery animate](http://jsfiddle.net/q8w9d/2/) you can bring 'show' it by re-positioning it inside the bounds of the wrapper Here is an example: HTML: ``` <div class='wrapper'> <div class='growIt'>Text for div</div> </div> <input type='button' id='showHide' value='Show / Hide'/> ``` CSS: ``` .wrapper{ background:blue; position:relative; width:200px; height:200px; overflow:hidden; } .growIt{ background: red; position:relative; width:200px; height:200px; top:200px; left:200px; display:block; } ``` jQuery: ``` $(function(){ var hiding = true; $('#showHide').click(function(){ if(hiding == true){ hiding = false; $('.growIt').animate({top:'0px',left:'0px'},2000); }else{ hiding = true; $('.growIt').animate({top:'200px',left:'200px'},2000); } }); }); ``` When you click the button it will either hide or show the red div. If your requirement of animating it from `display:none` to `display:block` is because you need it to push other form elements out of the way when it comes into view, [I would suggest adding another wrapper with `position:relative` and then making the wrapper slide 'down' from the bottom.](http://jsfiddle.net/KftqU/2/)
60,322,576
Hello guys i have json data from firestore and i want to display these data in html table. This is my customer-list.component.html ``` <body> <div class="container"> <div class="title"> <h3>Customer Table</h3> </div> <div class="row"> <div class="col-md-12"> </div> <div class="col-lg-8 col-md-10 ml-auto mr-auto"> <div class="table-responsive"> <table class="table"> <thead> <tr> <th class="text-center">#</th> <th>Name</th> <th>Age</th> <th>Active</th> </tr> </thead> <tbody> <div *ngFor="let customer of customers" style="width: 300px;"> <app-customer-details [customer]='customer'></app-customer-details> </div> <div style="margin-top:20px;"> <button type="button" class="button btn-danger" (click)='deleteCustomers()'>Delete All</button> </div> </tbody> </table> </div> </div> ``` Seems like there is nothing wrong in there. This is my customer-details.component.html ``` <div *ngIf="customer"> <tr> <td> <label>First Name: </label> {{customer.name}} </td> <td> <label>Age: </label> {{customer.age}} </td> <td> <label>Active: </label> {{customer.active}} </td> <span class="button is-small btn-primary" *ngIf='customer.active' (click)='updateActive(false)'>Inactive</span> <span class="button is-small btn-primary" *ngIf='!customer.active' (click)='updateActive(true)'>Active</span> <span class="button is-small btn-danger" (click)='deleteCustomer()'>Delete</span> </tr> </div> ``` But my table output is : [![table](https://i.stack.imgur.com/AlMO4.jpg)](https://i.stack.imgur.com/AlMO4.jpg) Thanks for answers.
2020/02/20
[ "https://Stackoverflow.com/questions/60322576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7244857/" ]
When you look at the DOM tree you will find out that `<tr><app-customer-details>...</app-customer-details</td>` This will not result in the component rendering inside the table as a but will cram the entire component HTML template inside one column. By adding an attribute selector to the component i.e. selector: 'app-customer-details, [app-customer-details]', you can add the selector directly to the element like so and now the elements inside the component HTML template will render correctly inside the table. Look at this [link](https://stackoverflow.com/questions/51972286/child-component-loses-parent-table-formatting); The correct code is as follows: Customer-list.component.html ``` <div class="container"> <div class="title"> <h3>Customer Table</h3> </div> <div class="row"> <div class="col-md-12"> </div> <div class="col-lg-8 col-md-10 ml-auto mr-auto"> <div class="table-responsive"> <table class="table"> <thead> <tr> <!-- <th class="text-center">#</th> --> <th>Name</th> <th>Age</th> <th>Active</th> </tr> </thead> <tbody> <tr *ngFor="let customer of customers" [customerDetails]="customer"> </tr> <div style="margin-top:20px;"> <button type="button" class="button btn-danger" (click)='deleteCustomers()'>Delete All</button> </div> </tbody> </table> </div> </div> </div> </div> ``` Customer-details.component.html ``` <td> {{customerDetails.name}} </td> <td> {{customerDetails.age}} </td> <td> {{customerDetails.active}} </td> ``` Customer-details.component.ts ``` import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'customerDetails, [customerDetails]', templateUrl: './customer-details.component.html', styleUrls: ['./customer-details.component.css'] }) export class CustomerDetailsComponent implements OnInit { @Input() customerDetails: object = {}; constructor() { } ngOnInit() { } } ```
27,266,402
How to get color picker in IE11 I am getting just text box in ie11 when I type ``` <input type="color" name="clr1" value=""/> ``` The above code is working fine in chrome but in IE it is shwoing just textbox.
2014/12/03
[ "https://Stackoverflow.com/questions/27266402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4307008/" ]
Try this: ``` <![if !IE]> <input type="color" name="clr1" value=""/> <![endif]> <!--[if IE]> <input type="text" name="clr1" value="" style="display:none"/> <button onclick="var s = Dlg.ChooseColorDlg(clr1.value); window.event.srcElement.style.color = s; clr1.value = s">&#9608;&#9608;&#9608;&#9608;&#9608;</button> <object id="Dlg" classid="CLSID:3050F819-98B5-11CF-BB82-00AA00BDCE0B" width="0" height="0"></object> <![endif]--> ```
55,687,688
i have table Collection: ``` id orderId productId 1 201 1 2 202 2 3 205 3 4 206 1 5 207 1 6 208 1 7 311 2 ``` OrderId and ProductId is relations to Collection table. And I need to check if exist record where eg. productId = 1 AND orderId[205, 206, 207, 208]. How i should built my query to find what i want? The array of orderId is not static, it's dynamic and depends of situation, can have diffrent number of elements. I tried to make it like this: ``` $ordersCollection = [various id objects of orders ]; $productId = just productId createQueryBuilder('p') ->andWhere('p.product = :productId') ->andWhere('p.order in :ordersCollection') ->setParameters(['productId' => $productId, 'ordersCollection' => $ordersCollection]) ->getQuery() ->getResult(); ``` But it doesn't work
2019/04/15
[ "https://Stackoverflow.com/questions/55687688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10925079/" ]
Couple of things - don't use `forEach()`, and use `map()` in your `myFunction`: ```js myDiv = Array.from(document.getElementsByClassName('myDiv')); function myFunction(){ const number = myDiv.map(d => d.dataset["number"]); console.log(number); } ``` ```html <div class="myDiv" data-name="MrMr" data-number="1"> THIS IS A TEXT </div> <div class="myDiv" data-number="2"> another text. </div> <div class="myDiv" data-number="3"> another text. </div> <div class="myDiv" data-number="4"> another text. </div> <p id="demo"></p> <button onclick="myFunction();">Button</button> ```
44,710,509
In order to configure spring batch admin UI to use db2 database, I referred the Admin UI documentation which says **"launch the application with a system property -DENVIRONMENT=[type]."** I understand that **"-DENVIRONMENT=db2**" should be kept in some file. I tried by keeping in **batch-default.properties** file, but that did not work. Since I am using WLP(liberty server), tried by keeping in server.xml file, no help. Still in the console I see env-context.xml file from batch admin is still loading batch-hsql.properties file(default configuration).
2017/06/22
[ "https://Stackoverflow.com/questions/44710509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5964695/" ]
I finally found a fix. I used 'qs' to stringify 'options' with {arrayFormat : 'brackets'} and then concatinated to url ended with '?' as follows: ``` var request = require('request'); var qs1 = require('qs'); var getLibs = function() { var options = qs1.stringify({ packages: ['example1', 'example2', 'example3'], os: 'linux', pack_type: 'npm' },{ arrayFormat : 'brackets' }); request({url:'http://localhost:3000/package?' + options}, function (error , response, body) { if (! error && response.statusCode == 200) { console.log(body); } else if (error) { console.log(error); } else{ console.log(response.statusCode); } }); }(); ``` Note: I tried to avoid concatenation to url, but all responses had code 400
13,121,242
I wish to bind a texture on a cube (creating cube using GlutSolidCube and not glvertex) but the whole texture is bound. In the image file I have all textures together (for speed and because the teacher requested) and I only want part of the texture to be bound. How can I do that????
2012/10/29
[ "https://Stackoverflow.com/questions/13121242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1766548/" ]
Textures are the unit of texture binding. If you want to "cut out" part of a texture, you do so by adjusting the texture coordinates that you use. Instead of using the full range of 0..1, use smaller values that match the sub-texture's location inside the texture.
26,501,936
To expire a timer in 5 seconds, is there any practical difference between these two? Is any one preferable(performance, resource, etc.) to the other for this case? [Option 1] **`deadline_timer`**: ``` boost::asio::deadline_timer timer(io_service); timer.expires_from_now(boost::posix_time::seconds(5)); ``` [Option 2] **`waitable_timer`**(`system_timer` or `steady_timer`): ``` boost::asio::system_timer timer(io_service); timer.expires_from_now(std::chrono::seconds(5)); ``` *PS: Please concentrate on comparing `deadline_timer` vs. `system_timer`, rather than `system_timer` vs. `steady_timer`.*
2014/10/22
[ "https://Stackoverflow.com/questions/26501936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3687475/" ]
The only difference is between clock types used. As of Boost 1.56, both `basic_deadline_timer` and `basic_waitable_timer` use `detail::deadline_timer_service` inside. There's no difference in how it performs waiting, the only difference is in how it performs time calculation. In its `wait()` method it uses `Time_Traits::now()` to check if it needs to wait more. For `system_timer` it's `std::chrono::system_clock::now()`, and for `deadline_timer` it's `boost::posix_time::microsec_clock::universal_time()` or `boost::posix_time::second_clock::universal_time()` depending on the presence of high precision clock (see [time\_traits.hpp](http://www.boost.org/doc/libs/1_56_0/boost/asio/time_traits.hpp)). `std::chrono::system_clock` implementation is provided by a compiler/standard library vendor, whereas `boost::posix_time::*clock` is implemented by Boost using available system functions. These implementations of course may have different performance and/or precision depending on the platform and the compiler.
28,732,250
I don't want to use smart pointers. Her'es my code. ``` CCOLFile *pCOLFile = CCOLManager::getInstance()->parseFile(strCOLPath); // returns instance of CCOLFile // ... pCOLFile->unload(); // hoping to comment this out, and use destructor instead. delete pCOLFile; struct CCOLFile { std::string m_strFilePath; std::vector<CCOLEntry*> m_vecEntries; }; void CCOLFile::unload(void) { for (auto pCOLEntry : m_vecEntries) { delete pCOLEntry; } m_vecEntries.clear(); } ``` Is it safe in c++ to comment my call to CCOLFile::unload, and then move the code from the CCOLFile::unload method to the CCOLFile destructor?
2015/02/26
[ "https://Stackoverflow.com/questions/28732250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4539315/" ]
Yes - see [C++ Super-FAQ section on Destructors](http://isocpp.org/wiki/faq/dtors). However if you do move that code to the dtor, or have the dtor call unload(), you need to make sure your 'delete pCOLEntry' doesn't throw exceptions. Reason: if it did, and if your CCOLFile dtor got called because of stack-unwinding, you will end up with an exception within an exception; bang; do not do that. Another problem if 'delete pCOLEntry' can throw an exception: your unload() method will end up with gobbledegook in your CCOLFile object. In particular, only some of the pCOLEntry pointers will have been deleted and they will now point to the carcass of what was once a CCOLEntry object but is now just a ghost. I called that a "Ghost Pointer" in the C++ FAQ. It's a bad thing since you will perhaps in the future use that Ghost Pointer, then you'll end up with a "Wild Pointer." Badness ensues. Lots of other issues with your code: since you have avoided using a smart-pointer (why?) you really ought to wrap your usage in a try/catch block, or at least put BIG FAT UGLY COMMENTS in your code to make sure no one ever does anything that might throw an exception. Basically if anything throws an exception before control-flow reaches your unload() or 'delete' call, all the CCOLEntry objects will leak and perhaps more significantly any desirable side effects in their dtor will not happen - closing files, unlocking locks, whatever. Note: I'm not asking you whether your code can CURRENTLY throw an exception in that area - that is only a small part of the concern. The concern is not just the present but the future. Someone else (likely at 3am) will add some code somewhere in there and that code will be able to throw an exception. Smart pointers make that innocuous, or a BIG FAT UGLY COMMENT at least makes it slightly less likely. Another consideration: you need to be concerned with 'ownership' and the copy-constructor and assignment-operator. The [Rule of Three (which I coined in 1991, but which has been more recently been replaced by the Rule of Five or even better the Rule of Zero)](http://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming)) tells you you will need all of them if you explicitly define one of them, in this case the dtor. Here again a smart-pointer would likely help. Another thing: your use of (void), e.g., in the definition of CCOLFile::unload(void)) is considered by at least some as an abomination :-) :-) :-)
31,239,897
How can I get the total number of table elements having ID inside a DIV tag using Selenium Webdriver and C#? Expected Output: I need output as "Number of Table ID = 2 " ``` <form id="form1"> <div class="sec_container_pop"> <div class="sec_header_pop"> Item Details </div> <table class="subheader"> <div class="spacerdiv"/> <div style="width: 900px; height: 400px; overflow-x: auto; position: relative; overflow-y: auto;"> <table class="reportscontent_pop" style="width: 880px"> <table id="tItemDetails0" class="reportscontent_pop" style="width: 880px; display: none;"> <table class="reportscontent_pop" style="width: 880px"> <table id="tItemDetails1" class="reportscontent_pop" style="width: 880px; display: none;"> </div> </form> ```
2015/07/06
[ "https://Stackoverflow.com/questions/31239897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4985758/" ]
Try like this: ``` WebElement webElement = driver.findElement(By.xpath("//form[@id='form1']/div[4]")); //Get list of table elements using tagName List<WebElement> list = webElement.findElements(By.tagName("table")); ```
8,506,986
i am using this ``` SELECT TOP (100) PERCENT CONVERT(char(10), [Reg Date1], 103) AS [Reg Date], Regs FROM (SELECT CAST(SetupDateTime AS datetime) AS [Reg Date1], COUNT(DISTINCT ID) AS Regs FROM dbo.tbl_User WHERE (CAST(SetupDateTime AS datetime) BETWEEN CAST(DATEADD(dd, - 7, GETDATE()) AS datetime) AND CAST(DATEADD(dd, - 1, GETDATE()) AS datetime)) GROUP BY CAST(SetupDateTime AS datetime)) AS a ORDER BY [Reg Date1] ``` which then produces ``` Reg Date Regs 07/12/2011 1 07/12/2011 1 07/12/2011 1 08/12/2011 1 08/12/2011 1 09/12/2011 1 09/12/2011 1 10/12/2011 1 10/12/2011 1 10/12/2011 1 ``` but i want it to do ``` Reg Date Regs 07/12/2011 10 08/12/2011 12 09/12/2011 15 10/12/2011 11 11/12/2011 10 12/12/2011 17 ``` i cant seem to get it to group in this way
2011/12/14
[ "https://Stackoverflow.com/questions/8506986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1097453/" ]
Try this: ``` SELECT TOP (100) PERCENT CONVERT(char(10), [Reg Date1], 103) AS [Reg Date], Sum(Regs) FROM (SELECT CAST(SetupDateTime AS datetime) AS [Reg Date1], COUNT(DISTINCT ID) AS Regs FROM dbo.tbl_User WHERE (CAST(SetupDateTime AS datetime) BETWEEN CAST(DATEADD(dd, - 7, CAST(convert(varchar, GETDATE(), 112) AS datetime)) AS datetime) AND CAST(convert(varchar, GETDATE(), 112) AS datetime)) GROUP BY CAST(SetupDateTime AS datetime)) AS a group by CONVERT(char(10), [Reg Date1], 103) ORDER BY CONVERT(char(10), [Reg Date1], 103) ```
49,856,675
I'm trying to export some data, taken from an sql database, to a txt- or csv-file. The print statement: ``` for x in range(len(data)): print(data[x]) ``` this outputs what I want, every element in a new line ``` (1, 90, Netherlands, male) (2, 50, Germany, Female) ``` etc.. Now, when I try putting this to a text file it just adds everything in 1 long line, all the info pasted behind each other just like a regular `print(data)` command. I posted my code below so you get the context ``` sql = 'SELECT * FROM batch' c.execute(sql) data = c.fetchall() list1 = [] addDataToList = list1.append(data) for x in range(len(data)): print(data[x]) with open('Rapport.txt', mode="w") as output: for x in range(len(data)): output.write("\n" .join(str(data[x]))) ```
2018/04/16
[ "https://Stackoverflow.com/questions/49856675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9519442/" ]
I could have just deleted this question but given that the SQLite JSON1 extension appears to be relatively poorly understood I felt it would be more useful to provide an answer here for the benefit of others. What I have set out to do here is possible but the SQL syntax is rather more convoluted. ``` UPDATE keywords set locs = (select json_set(json(keywords.locs),'$.**N**', ifnull( (select json_extract(keywords.locs,'$.**N**') from keywords where id = '1'), 0) + 1) from keywords where id = '1') where id = '1'; ``` will accomplish both of the updates I have described in my original question above. Given how complicated this looks a few explanations are in order * The `UPDATE keywords` part does the actual updating, but it needs to know what to updatte * The `SELECT json_set` part is where we establish the value to be updated * If the relevant value does not exsit in the first place we do not want to do a `+ 1` on a null value so we do an `IFNULL` TEST * The `WHERE id =` bits ensure that we target the right row --- Having now worked with JSON1 in SQLite for a while I have a tip to share with others going down the same road. It is easy to waste your time writing extremely convoluted and hard to maintain SQL in an effort to perform in-place JSON manipulation. Consider using SQLite in memory tables - `CREATE TEMP TABLE...` to store intermediate results and write a sequence of SQL statements instead. This makes the code a whole lot eaiser to understand and to maintain.
13,244
I know the $|1\rangle$ state can relax spontaneously to the $|0\rangle$ state, but can the opposite also happen?
2020/08/10
[ "https://quantumcomputing.stackexchange.com/questions/13244", "https://quantumcomputing.stackexchange.com", "https://quantumcomputing.stackexchange.com/users/12906/" ]
As a first note: the (uncontrolled) transition of $|1\rangle$ to $|0\rangle$ is generally not referred to as *dephasing* but as *relaxation*. The noise-process that involves (spontaneous) relaxation is also called the *amplitude damping* channel. Now, if you have a system which has a finite temperature, meaning that there is some energy in the system, the reverse might spontaneously happen as well - the $|0\rangle$ state spontaneously transitions to the $|1\rangle$ state, something we call (spontaneous) *excitation*. So yeah, if there is any energy in the system (i.e. de facto **every** conceivable system), the reverse is also possible. If you're familiar with the math, you might want to check out the *generalized amplitude damping* channel, for instance as introduced [here](https://arxiv.org/abs/1902.00967). It formalizes the above idea that, in addition of a small relaxation probability, there is also a (small) probability of a spontaneous excitation.
38,503,229
Learning React & chrome extensions the hard way, so my `this.url` has one of 2 values: `null` or `www.sample.com` I'm getting the url value from an async call using `chrome.storage.local.get(...)` so once I get the response from the storage I set the value to this.url and want to use such value to display a component using a ternary operator like so: ``` export default React.createClass({ url: '', componentDidMount: function(){ this.observeResource(); }, observeResource(){ var self = this function getValue(callback){ chrome.storage.local.get('xxxx', callback); } getValue(function (url) { this.url = url.xxxx; return this.url; }); }, /* RENDER */ render: function(){ return ( <div className="app"> <AppHeader /> {this.url != null ? <VideoFoundOverlay /> : null} {this.url == null ? <VideoNotFoundOverlay /> : null } </div> ) } }); ``` I can not get the value of `this.url` outside of the `observeResource` function. Where am I going wrong?
2016/07/21
[ "https://Stackoverflow.com/questions/38503229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4183602/" ]
You need to use [**this.setState()**](https://facebook.github.io/react/docs/component-api.html#setstate) ``` constructor(props) { super(props) this.state = { url: '' } } componentDidMount() { setTimeout(() => { this.setState({ url: 'www.sample.com' }) }, 1000) } render() { return <div>this.state.url</div> } ``` Look at working example in [JSFiddle](https://jsfiddle.net/SergeyBaranyuk/Lg6m8m6t/3/)
60,125,337
The ANTLR4 lexer pattern [\p{Emoji}]+ is matching numbers. See screenshot. Note that it correctly rejects alpha chars. Is there an issue with the pattern? [![enter image description here](https://i.stack.imgur.com/QkkX2.png)](https://i.stack.imgur.com/QkkX2.png)
2020/02/08
[ "https://Stackoverflow.com/questions/60125337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9668824/" ]
`\p{Emoji}` matches everything that has the Unicode Emoji property. Numbers do have that property, so `\p{Emoji}` is correct in matching them. Why though? The Unicode standard defines any codepoint to have the Emoji property if it can appear as part of an Emoji. Numbers can appear as parts of emojis (for example I think shapes with numbers on them, which for them reason count as emojis, consist of a shape, followed by a join, followed by the number), so they have that property. If you only want to match codepoints that are emojis by themselves, you can just use the `Emoji_Presentation` property instead. This will fail to match combined emojis though. If you want to match any sequence that creates an emoji, I think you'll want to match something like "`Emoji_Presentation`, followed by zero or more of '(`Join_Control` or `Variation_Selector`) followed by `Emoji`'" (here you want `Emoji` instead of `Emoji_Presentation` because that's where numbers are allowed). --- However, for the purpose of allowing emojis in identifiers (as opposed to a lexer rule to match emojis and nothing else), you don't actually have to worry about whether a number is part of an emoji or not, just that it doesn't appear as the first character of the identifier. So you could simply define your fragment for the starting character to only include `Emoji_Presentation` and then the fragment for continuing characters to include `Emoji` as well as `Join_Control` and `Variation_Selector`. So something like this would work: ``` fragment IdStart : [_\p{Alpha}\p{General_Category=Other_Letter}\p{Emoji_Presentation}] ; fragment IdContinue : IdStart // The `\p{Number}` might be redundant, I'm not sure. I don't know // whether there are any (non-ascii) numeric codepoints that don't // also have the `Emoji` property. | [\p{Number}\p{Emoji}\p{Join_Control}\p{Variation_Selector}] ; Identifier: IdStart IdContinue*; ``` Of course that's assuming you actually want to allow characters besides emojis. The definition in your question only included emojis (or was meant to anyway), but since it was called `Identifier`, I'm assuming you just removed the other allowed categories to simplify it.
67,406,088
We have a requirement where our Users can hide/Unhide and move around Excel Columns. Once the user clicks on generate CSV button, we want the columns to be in a particular sequence. For example, Col1, Col2, Col3 are the column headings in the Excel first row A,B,C Columns. User moved the column Col2 to the end and did hide Col2: A,B,C columns are now having headings: Col1, Col3, Col2(hidden) Our CSV file should be generated as: Col1, Col2, Col3. Using below code, we are unable to see Col2 and even if we manage to unhide, how can we know that the user has moved the Col2 at the end? ``` Public Sub ExportWorksheetAndSaveAsCSV() Dim csvFilePath As String Dim fileNo As Integer Dim fileName As String Dim oneLine As String Dim lastRow, lastCol As Long Dim idxRow, idxCol As Long Dim dt As String dt = Format(CStr(Now), "_yyyymmdd_hhmmss") ' --- get this file name (without extension) fileName = Left(ThisWorkbook.Name, InStrRev(ThisWorkbook.Name, ".", -1, vbTextCompare) - 1) ' --- create file name of CSV file (with full path) csvFilePath = ThisWorkbook.Path & "\" & fileName & dt & ".csv" ' --- get last row and last column lastRow = Cells(Rows.Count, 1).End(xlUp).Row lastCol = Cells(1, Columns.Count).End(xlToLeft).Column ' --- open CSC file fileNo = FreeFile Open csvFilePath For Output As #fileNo ' --- row loop For idxRow = 1 To lastRow If idxRow = 2 Then GoTo ContinueForLoop End If oneLine = "" ' --- column loop: concatenate oneLine For idxCol = 1 To lastCol If (idxCol = 1) Then oneLine = Cells(idxRow, idxCol).Value Else oneLine = oneLine & "," & Cells(idxRow, idxCol).Value End If Next ' --- write oneLine > CSV file Print #fileNo, oneLine ' -- Print: no quotation (output oneLine as it is) ContinueForLoop: Next ' --- close file Close #fileNo End Sub ```
2021/05/05
[ "https://Stackoverflow.com/questions/67406088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11772301/" ]
If the header names are fixed (and only the position varies) then you'd loop over the headers looking for the ones you want, and note their positions: then use that information to write the cells' values to the output file. ```vb Public Sub ExportWorksheetAndSaveAsCSV() Dim csvFilePath As String Dim fileNo As Integer Dim fileName As String Dim oneLine As String Dim lastRow As Long Dim idxRow, idxCol As Long Dim dt As String, ws As Worksheet, hdr, arrCols, arrPos, i As Long, f As Range, sep Set ws = ActiveSheet 'or whatever lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row 'find all required columns arrCols = Array("Col1", "Col2", "Col3") ReDim arrPos(LBound(arrCols) To UBound(arrCols)) For i = LBound(arrCols) To UBound(arrCols) 'Note: lookin:=xlFormulas finds hidden cells but lookin:=xlValues does not... Set f = ws.Rows(1).Find(arrCols(i), lookat:=xlWhole, LookIn:=xlFormulas) If Not f Is Nothing Then arrPos(i) = f.Column Else MsgBox "Required column '" & arrCols(i) & "' not found!", _ vbCritical, "Missing column header" Exit Sub End If Next i 'done finding columns fileName = Left(ThisWorkbook.Name, InStrRev(ThisWorkbook.Name, ".", -1, vbTextCompare) - 1) dt = Format(CStr(Now), "_yyyymmdd_hhmmss") csvFilePath = ThisWorkbook.Path & "\" & fileName & dt & ".csv" fileNo = FreeFile Open csvFilePath For Output As #fileNo For idxRow = 1 To lastRow If idxRow <> 2 Then oneLine = "" sep = "" 'loop over the located column positions For idxCol = LBound(arrPos) To UBound(arrPos) oneLine = oneLine & sep & ws.Cells(idxRow, arrPos(idxCol)).Value sep = "," Next Print #fileNo, oneLine End If Next Close #fileNo ' --- close file End Sub ```
43,274,643
I have this code and i want to stop animate between loops for ex 5sec, I was googled and found just rotate (no delay) ```css .line-1{ border-left: 2px solid rgba(255,255,255,.75); white-space: nowrap; overflow: hidden; direction:ltr; } /* Animation */ .anim-typewriter{ animation: typewriter 4s steps(44) 1s infinite normal both, blinkTextCursor 500ms steps(44) infinite normal; } @keyframes typewriter{ from{width: 0;} to{width: 24em;} } @keyframes blinkTextCursor{ from{border-left-color: rgba(255,255,255,.75);} to{border-left-color: transparent;} } ``` ```html <p class="line-1 anim-typewriter" style="margin-left:auto;margin-right:auto;">Good News: You Won :)<a href="Awards/"> Get Award </a></p> ```
2017/04/07
[ "https://Stackoverflow.com/questions/43274643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7613282/" ]
I believe this is what you are looking for? ``` -- Generate a sequence of dates from 2010-01-01 to 2010-12-31 select toDate('2010-01-01') + number as d FROM numbers(365); ``` <https://clickhouse.tech/docs/en/sql-reference/table-functions/numbers/>
4,835,739
Is there a straight forward way to "brut force" the network connection (cellular and WIFI) off and back on on an iphone? I'm working on an application that syncs through dropbox and would like to test & debug my error recovery code from lost connections. UPDATE: I should have been a bit more specific, I want to turn this off in sw. For example after launching a request to dropbox, I want to simulate a failed download by turning off the network.
2011/01/29
[ "https://Stackoverflow.com/questions/4835739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/512447/" ]
Instead of doing a JOIN to retrieve both the article and the user data in a single query, why not do two separate queries, one to retrieve the articles and the second to retrieve the user data who's relevant to the articles? It is surely simpler and is probably more efficient.
98,363
We use `sha1sum` to calculate SHA-1 hash value of our packages. **Clarification about the usage:** We distribute some software packages, and we want users to be able to check that what they downloaded is the correct package, down to the last bit. The SHA-1 cryptographic hash algorithm has been replaced by SHA-2 since SHA-1 is known to be considerably weaker. Can we still use `sha1sum`? Or should we replace it with `sha256sum`, or `sha512sum`?
2015/09/02
[ "https://security.stackexchange.com/questions/98363", "https://security.stackexchange.com", "https://security.stackexchange.com/users/24842/" ]
I suppose you "use `sha1sum`" in the following context: you distribute some software packages, and you want users to be able to check that what they downloaded is the correct package, down to the last bit. This assumes that you have a way to convey the hash value (computed with SHA-1) in an "unalterable" way (e.g. as part of a Web page which is served over HTTPS). I also suppose that we are talking about *attacks* here, i.e. some malicious individual who can somehow alter the package as it is downloaded, and will want to inject some modification that will go undetected. The security property that the used hash function should offer here is **resistance to second-preimages**. Most importantly, this is *not* the same as resistance to collisions. A collision is when the attacker can craft two distinct messages *m* and *m'* that hash to the same value; a second-preimage is when the attacker is given a fixed *m* and challenged with finding a distinct *m'* that hashes to the same value. Second-preimages are a lot harder to obtain than collisions. For a "perfect" hash function with output size *n* bits, the computational effort for finding a collision is about 2*n*/2 invocations of the hash function; for a second-preimage, this is 2*n*. Moreover, structural weaknesses that allow for a faster collision attack do not necessarily apply to a second-preimage attack. This is true, in particular, for the known weaknesses of SHA-1: right now (September 2015), there are some known theoretical weaknesses of SHA-1 that should allow the computation of a collision in less than the ideal 280 effort (this is still a huge effort, about 261, so it has not been actually demonstrated yet); but these weaknesses are differential paths that intrinsically require the attacker to craft both *m* and *m'*, therefore they do not carry over second-preimages. For the time being, there is no known second-preimage attack on SHA-1 that would be even theoretically or academically faster than the generic attack, with a 2160 cost that is way beyond technological feasibility, by a [long shot](https://security.stackexchange.com/questions/6141/amount-of-simple-operations-that-is-safely-out-of-reach-for-all-humanity/6149#6149). **Bottom-line:** within the context of what you are trying to do, SHA-1 is safe, and likely to remain safe for some time (even MD5 would still be appropriate). Another reason for using `sha1sum` is the availability of client-side tools: in particular, the command-line hashing tool provided by Microsoft for Windows (called [FCIV](https://support.microsoft.com/en-us/kb/841290)) knows MD5 and SHA-1, but not SHA-256 (at least so says the documentation)(\*). Windows 7 and later also contain a command-line tool called "certutil" that can compute SHA-256 hashes with the "-hashfile" sub-command. This is not widely known, but it can be convenient at times. --- That being said, a powerful reason *against* using SHA-1 is that of **image**: it is currently highly trendy to boo and mock any use of SHA-1; the crowds clamour for its removal, anathema, arrest and public execution. By using SHA-1 you are telling the world that you are, definitely, not a hipster. From a business point of view, it rarely makes any good not to yield to the fashion *du jour*, so you should use one of the SHA-2 functions, e.g. SHA-256 or SHA-512. There is no strong reason to prefer SHA-256 over SHA-512 or the other way round; some small, 32-bit only architectures are more comfortable with SHA-256, but this rarely matters in practice (even a 32-bit implementation of SHA-512 will still be able to hash several dozens of megabytes of data per second on an anemic laptop, and even in 32-bit mode, a not-too-old x86 CPU has some abilities at 64-bit computations with SSE2, which give a good boost for SHA-512). Any marketing expert would tell you to use SHA-512 on the sole basis that 512 is greater than 256, so "it must be better" in some (magical) way.
34,934,717
I'm writing my own HTTP server. I'm using `Java Socket` for it. I read request from `InputStream` next way ``` val input = BufferedReader(InputStreamReader(socket.inputStream, "UTF-8")) ``` When I receive requests from `curl` or browser all is good. But when I receive request from `Postman` I get something like this: ``` ��g�������#���=��g�������#���, ��9� ��3���5�/�=��9� ��3���5�/�, ``` I tried to use others encodings for `InputStreamReader` such as `UTF-16` and `ASCII`. Which encoding is used for Postman requests and how I can read it on my server? ***UPDATE:*** Sorry, this is my failure. I used HTTPS when making requests.
2016/01/21
[ "https://Stackoverflow.com/questions/34934717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3830108/" ]
If the first two bytes received are ASCII 31 (0x1F) and 139 (0x8B) you are receiving a GZIP stream and for some reason convinced the client that you supported GZIP `Content-Encoding` (not the same thing as the charset encoding). The data looks more binary than character encoding. Gzip, deflate, SSL, or other reason for binary data is what should be looked at. You may not be doing content negotiation correctly and therefore receiving binary gzip or deflate. Or using HTTPS vs. HTTP. Or uploading an image. Something but not text.
34,393,450
One of the rule defined in the PMD rule set is: **"Avoid using Volatile"** which explains that **"Use of modifier volatile is not recommended"**. This rule is mentioned under the **Controversial Rule Set** of PMD. In my team, we have Sonar configured on various modules which indirectly has the rule set from PMD and hence any use of **volatile** pops as a critical warning. **Question is why are we using volatile?** The volatile keyword is used for boolean variables to control the state of the external session. This state is accessed across various threads and hence to know if the state is UP or DOWN, it is maintained as a boolean volatile variable, so that visibility is shared across multiple threads. **My question is how to fix this sonar warning?** One solution is to remove the rule from the rule set, which is not allowed because: firstly it is not recommended as these rules form the basic guidelines defined from PMD rule set and secondly the SONAR server in my organisation is a central server being used by all the teams. Hence is not allowed. Another solution is to ignore the sonar warning by use of some annotation, which is again not recommended on basic rule set. Can anyone suggest how can we fix this sonar warning in code? Thanks in advance.
2015/12/21
[ "https://Stackoverflow.com/questions/34393450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/988206/" ]
First off, this rule does not indicate a general problem in the code - `volatile` is a perfectly fine keyword, and there is nothing wrong with it. That's why it's a [controversial rule](http://pmd.sourceforge.net/pmd-4.3.0/rules/controversial.html#AvoidUsingVolatile). On the other hand, using it is indeed a bit of an advanced technique that requires you to know what you are doing. Situations exist where you would know that, let's say, the people who will maintain your code will not have sufficient Java knowledge. In such cases, the rule *may* make sense. To satisfy the rule in your case, use [AtomicBoolean](https://docs.oracle.com/javase/8/docs/api/index.html?java/util/concurrent/atomic/AtomicBoolean.html).
8,955,967
trying to load a single field into an array and then loading that in a picker. I think its in the creation of the array that I have a problem. This is my code: ``` NSFetchRequest *request = [[NSFetchRequest alloc] init]; [request setEntity:entityDescr]; [request setPropertiesToFetch:[NSArray arrayWithObject:@"name"]]; NSError *error; NSArray *array = [managedObjectContext executeFetchRequest:request error:&error]; self.pickerData = array; ``` The error I get is this: > > Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSManagedObject isEqualToString:]: unrecognized selector sent to instance 0x7bb8100' > > > Any help would be appreciated...
2012/01/21
[ "https://Stackoverflow.com/questions/8955967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1161756/" ]
Please go through the documentation of NSManaged Object- <http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/CoreDataFramework/Classes/NSManagedObject_Class/Reference/NSManagedObject.html> Then fetch the data properly and pass to Picker. Main issue is wrong kind of comparison of objects, due to which app is crashing.
87,904
Is there a formula for the size of Symplectic group defined over a finite ring $Z/p^k Z$?
2012/02/08
[ "https://mathoverflow.net/questions/87904", "https://mathoverflow.net", "https://mathoverflow.net/users/21237/" ]
From Christopher Perez's answer, we have $|Sp\_{2n}(\mathbb{Z}/p\mathbb{Z})| = p^{n^2} \prod\_{i=1}^n (p^{2i}-1)$. Following Johannes Hahn, we wish to determine the size of the kernel of the homomorphism $Sp\_{2n}(\mathbb{Z}/p^k\mathbb{Z}) \to Sp\_{2n}(\mathbb{Z}/p\mathbb{Z})$. To compute this, we may induct on $k$: For $k \geq 1$, elements in the kernel of the homomorphism $Sp\_{2n}(\mathbb{Z}/p^{k+1}\mathbb{Z}) \to Sp\_{2n}(\mathbb{Z}/p^k\mathbb{Z})$ have the form $I + p^k A$ for a matrix $A = \left( \begin{smallmatrix} E & F \\ G & H \end{smallmatrix} \right)$ with values in $\mathbb{Z}/p\mathbb{Z}$. The symplectic condition (given in [Wikipedia](http://en.wikipedia.org/wiki/Symplectic_matrix)) is equivalent to the conditions that $F^t = F$, $G^t = G$, and $E^t + H = 0$. $F$ and $G$ are therefore symmetric matrices, while $H$ and $E$ determine each other, with no further conditions. The kernel of one-step reduction therefore has size $p^{n(n+1)/2} \cdot p^{n(n+1)/2} \cdot p^{n^2}$, or $p^{2n^2 + n}$. The final answer is therefore: $|Sp\_{2n}(\mathbb{Z}/p^k\mathbb{Z})| = p^{(2k-1)n^2 + (k-1)n} \prod\_{i=1}^n (p^{2i}-1)$ **Edit:** To address kassabov's complaint, I'll explain the calculation in a bit more detail. The symplectic condition on $I + p^k A$ is that $(I + p^k A)^t \Omega (I + p^k A) \equiv \Omega \pmod {p^{k+1}}$, where $\Omega = \left( \begin{smallmatrix} 0 & I\_n \\ -I\_n & 0 \end{smallmatrix} \right)$. Because $k \geq 1$, we may eliminate the $p^{2k} A^t \Omega A$ term when expanding, to get $$ \Omega + p^k A^t \Omega + p^k \Omega A \equiv \Omega \pmod {p^{k+1}}$$ By subtracting $\Omega$ from both sides, we get the conditions I mentioned on the blocks in $A$. As you mentioned, this coincides with the symplectic Lie algebra condition. George McNinch gave an elegant explanation in the comments, but a possibly more pedestrian reason is that $(p^k)$ is a square zero ideal in $\mathbb{Z}/p^{k+1}\mathbb{Z}$, so one has a canonical isomorphism between the kernel of reduction and the Lie algebra tensored with the quotient ring.
1,887,374
Let's say we have an arbitrary complex number $z \in \mathbb{C}$ , $z = x+iy$ Then the absolute value (or magnitude/norm of $z$) is defined as follows. $$|z| \stackrel{\text{def}}{=} \sqrt{x^2 + y^2}$$ But to me it seems a bit hand wavy as that is exactly the magnitude of a vector in $\mathbb{R^2}$ e.g $||\vec{a}|| = \sqrt{(a\_1, a\_2) \bullet (a\_1, a\_2)} = \sqrt{a\_{1}^{2} + a\_2^2}$ I asked a question earlier if it was possible to write a complex number as a vector in $\mathbb{R}^2$ : [Writing Complex Numbers as a Vector in $\mathbb{R^2}$](https://math.stackexchange.com/questions/1886864/writing-complex-numbers-as-a-vector-in-mathbbr2), and the answer was yes, as $\mathbb{C}$ is isomorphic to $\mathbb{R^2}$, however one has to be careful with how you choose to write it. Am I correct in saying that you can describe a point in the complex plane as a 2-tuple $(x, iy)$ over $\mathbb{R^2}$ but only as a one tuple, a scalar $x+ iy$ over $\mathbb{C}$. i.e. $\mathbb{C}$ is one-dimensional with respect to itself, but two-dimensional with respect to $\mathbb{R}$. I ask this as there may be a misinterpretation on my part. I've included this image here to illustrate my point. [![enter image description here](https://i.stack.imgur.com/Ypgld.png)](https://i.stack.imgur.com/Ypgld.png) To find the absolute value (the magnitude) of $|z|$, **if** $z = (x, iy)$ (a 2-tuple over $\mathbb{R}$, or a point in $\mathbb{R^2}$), then wouldn't the absolute value be, by the Theorem of Pythagoras (or via the square root of the dot-product with itself) $$|z| \stackrel{\text{def}}{=} \sqrt{x^2 + i^2y^2} \implies |z| \stackrel{\text{def}}{=} \sqrt{x^2 - y^2}$$ Now this can't be right, so my question boils down to: **Why is the $i$ just dropped in the definition of the absolute value of $|z|$?** We certainly can't use the Theorem of Pythagoras over $\mathbb{C}$ as $\mathbb{C}$ is one-dimensional with respect to itself, so we must be using the Theorem of Pythagoras over $\mathbb{R^2}$, and in that case one of the basis vectors must be $(0, i)$, correct? (i.e it must contain the Imaginary Axis for $\mathbb{R^2} = \mathbb{C}$) If I'm totally off the ball here, please tell me as it seems I'm having trouble making the connection between $\mathbb{R^2}$ and $\mathbb{C}$. I've included extra information in my question so that you can see where I'm coming from when I make the arguments I'm trying to make.
2016/08/09
[ "https://math.stackexchange.com/questions/1887374", "https://math.stackexchange.com", "https://math.stackexchange.com/users/266135/" ]
The standard inner product of two complex numbers $z\_1,z\_2 \in \mathbb{C}$ is defined to be $z\_1\bar{z\_2}$, so the norm it induces will be $||z\_1||:=\sqrt{z\_1z\_1}=\sqrt{z\_1\bar{z\_1}}=\sqrt{(a+bi)(a-bi)}=\sqrt{a^2+b^2}$. As a vector space over $\mathbb{R}$ (which it is almost never considered to be in practice), $\mathbb{C}$ has dimension two and thus is isomorphic to $\mathbb{R}^2$, the standard basis might be chosen to be $\{(1,0), (0,i)\}$ where we represent a number $z=a+bi$. The canonical isomorphic then sends $(1,0) \to (1,0)$ and $(0,i) \to (0,1)$, thus if you take a vector in $\mathbb{C}$, say $z=a+bi$, and "transport" it to $\mathbb{R^2}$ to investigate its norm in that inner product space (where the inner product is defined to be $(x\_1,y\_1)(x\_2,y\_2)=x\_1x\_2+y\_1y\_2$), we have $z=a+bi=a(1,0)+b(0,i)$, apply the canonical isomorphism and we get $a+bi$ is transported to $(a,b)$, (and *not* (a,bi)!), so the inner product here is different, there being no conjugation in the second coordinate, but that's fine because we're dropped the $i$ anyways by moving to $\mathbb{R^2}$. Pythagoras is fine. One further comment: viewing $\mathbb{C}$ as a two-dimensional vector space over $\mathbb{R}$ is convenient merely for visualizing the complex plane, not for investigating its properties as a vector space, consider the following excerpt from Rudin's *Functional Analysis*: [![enter image description here](https://i.stack.imgur.com/xh8xf.png)](https://i.stack.imgur.com/xh8xf.png)
32,426,744
We are trying to use Microsoft.Deployment.WindowsInstaller dll (C#) and install the MSI package. I couldn't find much examples regarding this. The installation is successfull. In case of error I want to display the error message in specific language using lcid. so I use the below method passing the error code. The MSI used has language English. ``` // Sample code for installing try { Installer.InstallProduct(@"Sample.msi", "ALLUSERS=1 ADDLOCAL=ALL"); } catch (InstallCanceledException ex) { errorList.Add(ex.ErrorCode + " " + ex.Message); } catch (InstallerException ex) { errorList.Add("Exit Code: " + ex.ErrorCode + ", " + ex.Message); // Translate error message to different language // ex.GetErrorRecord is always null,so the below method doesn't work. string langError = Installer.GetErrorMessage(ex.GetErrorRecord(),System.Globalization.CultureInfo.GetCultureInfo(1031)); } ``` Am I using the method right? Please provide / point me to example where I can get the correct error message in specific language. Thanks an lot in advance.
2015/09/06
[ "https://Stackoverflow.com/questions/32426744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1593585/" ]
You should show more of your code so we can see where you're getting that error from, so some of this may be what you're already doing. If you use Installer.InstallProduct then you get an InstallerException if it fails, and that already contains a Message as well as an ErrorCode. Basically you need the result from (underneath everything) the call to MsiInstallProduct, and this is the list including your 1603: <https://msdn.microsoft.com/en-us/library/aa368542(v=vs.85).aspx> But you are using the error message function that returns errors during the actual install that includes the "file in use" 1603: <https://msdn.microsoft.com/en-us/library/aa372835(v=vs.85).aspx> You may have done all this, if so, then your question may be about how you get the error message from the InstallerException in the appropriate language. So maybe you need to call the GetErrorMessage overload that uses GetErrorRecord from the InstallerException and the culture info as parameters.
23,145,872
having trouble implementing this bxslider slider. first things first, the images are all visible? how do i make this look like an actual slider? you can see the issue live here; <http://danielmdesigns.com/windermere/index.html> otherwise, i've done exactly what the website told me to =/ JS Script ``` <!-- jQuery library (served from Google) --> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <!-- bxSlider Javascript file --> <script src="/js/jquery.bxslider.min.js"></script> <!-- bxSlider CSS file --> <link href="/lib/jquery.bxslider.css" rel="stylesheet" /> <script src="bxslider.js" type="text/javascript"></script> ``` HTML ``` <ul class="bxslider"> <li><img src="images/Couple%20on%20Lounge%20Chair_Towneclub.jpg" /></li> <li><img src="images/Man%20on%20Bench_Towneclub.jpg" /></li> <li><img src="images/Picnic%20Couple_Towneclub.jpg" /></li> <li><img src="images/Small%20Golf_Towneclub.jpg" /></li> </ul> ``` CSS ``` .bxslider{ height:600px; width:auto; background-color:#c41230; /*background-image: url(images/imagescroll_1.png);*/ background-size:cover; position:relative; top:95px; } ``` JS file ``` $(document).ready(function(){ $('.bxslider').bxSlider(); }); ``` I am an amateur, but all help is very appreciated. Thanks in advance.
2014/04/18
[ "https://Stackoverflow.com/questions/23145872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3475867/" ]
The exact complexity of this algorithm is O(⌊sqrt(num)⌋-1) This is number of checks ((num % ArrayOfPrimes[i]) == 0) condition. In case number 19 this algorithm will 3 checks: 2, 3, 4
37,240,904
I changed my php version into `5.6` but when i run `composer update` it still thinks I am using 5.4 version. The version of my server is `5.4` but I changed my project directory php version in to `5.6`. I changed that one via cpanel php configuration. Here's the screenshot: [![enter image description here](https://i.stack.imgur.com/ad3pp.png)](https://i.stack.imgur.com/ad3pp.png) As you can see i changed my project directory php version in to 5.6, but when i run composer update, it still thinks that i am using 5.4 version. I also tried adding this in my composer.json: ``` "platform": { "php": "5.5.9" } ``` And when I run composer update, it installs some dependencies except for the last one..it is giving me this error: ``` Generating autoload files > Illuminate\Foundation\ComposerScripts::postUpdate Parse error: syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in /home3/idmadm/public_html/app/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php on line 146 ``` When I checked line 146 of helpers.php, this is the code: ``` function auth($guard = null) { if (is_null($guard)) { return app(AuthFactory::class); //THIS IS THE CODE!! } else { return app(AuthFactory::class)->guard($guard); } } ``` I researched about that error and some said it's because of my PHP Version. I guess Laravel still think that my PHP Version is 5.4 where in fact, i changed it into 5.6. How can i let Laravel know that I am using PHP Version 5.6. Any help please! Your help will be greatly appreciated and rewarded! Thanks! :) PS: The reason why I am changing PHP version in the directory because some websites that are hosted in my server do not support PHP 5.5+.
2016/05/15
[ "https://Stackoverflow.com/questions/37240904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/822465/" ]
You are declaring a "no match" too soon: you need to walk the whole list before adding a new subject. Your program tries the first subject, and if ut does not match, it adds a subject, and moves on. Unfortunately, it does not break, so it keeps adding the same subject for each existing one that does not match. In order to fix this problem make a boolean variable called "found", set it to false before the loop, and search for matches. Once a match is found, set the variable to true, and break. After the loop check your variable. If it's true, do not add, and say that you found a duplicate. Otherwise, add the new subject.
13,596,449
Good day, I'm currently new in working with databases. I downloaded an application called MySql Worckbench 5.2 CE because I saw that it has an easy way of creating and accessing databases. I'm now in the process of exporting the .sql. Whenever I go to the export tab which looks like this: ![enter image description here](https://i.stack.imgur.com/QmKDS.png) After I click on Start Export, it gives me this error: ![enter image description here](https://i.stack.imgur.com/DToSu.png) I'm not sure what the error is cause I'm not familiar with MySql dump.. is there a way to resolve this? or use an alternative way. I'm also not familiar with using mysql from cmd (Windows) but if there is any suggestion or steps I can follow, it would be a great help.
2012/11/28
[ "https://Stackoverflow.com/questions/13596449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1557464/" ]
A couple of tips to help make routing less confusing. It can be a bit unnerving to get used to. **Routing Rule #1** Always check the output of `rake routes` to be sure how to call your various routing methods. You might *think* you know how your routes will play out by looking at `routes.rb` but you won't *know* until you look at the compiled routes table. In your case you're expecting a route with the format: ``` /projects/:project_id/lists/:list_id/tasks/:id ``` Be sure that's the case. If it is, your call should look like: ``` project_list_task_path(@project, @list, task) ``` Note that the arguments here are `:project_id`, `:list_id` and `:id`, so all three are required in this case. Any in brackets in the path specification can be ignored, like `:format` usually is. **Routing Rule #2** Use the `_path` methods unless you strictly require the full URL. They're shorter and the output is easier to read and debug. They also don't inadvertently flip the URL in the browser and cause session problems if you don't properly differentiate between `www.mysite.com` and `site.com`. **Routing Rule #3** Don't forget there's a *huge* difference between `@project` and `@project.id` when it's supplied to a routing path method. The router will always call the `to_param` method if it's available and this can be over-ridden in your model to produce pretty or friendly URLs. `id` is for your database and your database alone. `to_param` is for routing but you shouldn't be calling it manually unless you're doing something exceptionally irregular.
60,728,260
I know, that using gets() is a very bad idea as it may lead to buffer overflow. But I have some queries. Suppose a c program has the following code- ``` char word[6]; gets(word); puts(word); ``` If I input for example - `HELLO WORLD`, is it correct to assume that `gets()` reads it as `[H] [E] [L] [L] [O] [ ]`, and the rest goes into the input buffer ? If that happens than, how does `puts()` get the data to display the complete string ?
2020/03/17
[ "https://Stackoverflow.com/questions/60728260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11687739/" ]
This is the exact problem with `gets`; it *will not* stop once it reads 6 characters, it will keep reading until it sees a newline character and assign those characters to the memory immediately following the end of the `word` buffer. This is what a buffer overflow *is*. If there isn't anything *important* for several bytes after the `word` buffer (like the return address for the stack frame, or another local variable), then overwriting that memory doesn't cause *obvious* problems, and `puts` will do pretty much the same thing - read from `word` *and the memory following it* until it sees the string terminator.
44,953,922
I am trying to do a search on my MySQL database to get the row that contains the most similar value to the one searched for. Even if the closest result is very different, I'd still like to return it (Later on I do a string comparison and add the 'unknown' into the learning pool) I would like to search my table 'responses' via the 'msg1' column and get one result, the one with the lowest levenshtein score, as in the one that is the most similar out of the whole column. This sort of thing: ``` SELECT * FROM people WHERE levenshtein('$message', 'msg1') ORDER BY ??? LIMIT 1 ``` I don't quite grasp the concept of levenshtein here, as you can see I am searching the whole table, sorting it by ??? (the function's score?) and then limiting it to one result. I'd then like to set $reply to the value in column "reply" from this singular row that I get. Help would be greatly appreciated, I can't find many examples of what I'm looking for. I may be doing this completely wrong, I'm not sure. Thank you!
2017/07/06
[ "https://Stackoverflow.com/questions/44953922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7286275/" ]
You would do: ``` SELECT p.* FROM people p ORDER BY levenshtein('$message', msg1) ASC LIMIT 1; ``` If you want a threshold (to limit the number of rows for sorting, then use a `WHERE` clause. Otherwise, you just need `ORDER BY`.
75,998
Ok, here's the story. I have a server running FTP 'out there' I can connect to it using the admin account, browse files, download files. When I try to upload files, I get 550 Access Denied. I have tried through FileZilla and command line. I have windows firewall turned off (on my machine) I can UPLOAD files from another machine (using the same admin account) on our local network (that means, same public IP) what is the problem? I am running Windows 7, Build 7100 and the other machine on the network is running XP SP3 The thing that gets me though, is that this worked for the last probably 4 months, without a problem, I get back in the office after a weekend today and it won't work...
2009/10/19
[ "https://serverfault.com/questions/75998", "https://serverfault.com", "https://serverfault.com/users/-1/" ]
A common problem I have had with Windows boxes and FTP access, is that the local account I set up to log in via FTP on the target box does not have the "do not expire" checkbox checked. So basically it has expired the FTP account password, and wants it to be changed - but that can only be done manually, not through FTP. That is the default state for new accounts created on the system and it must be changed manually (even the command line option /noexpire does not work on MS Server 2003 and below). That might be your problem. To fix it, someone with admin access on the FTP target server has to login and check the "do not expire" checkbox for your FTP login account. Ron
17,737,104
Hey, it's all about Jquery. I am using two Div and a button, at a time only one div is shown. Suppose these are div: ``` <div id="first"></div> <div id="second"></div> ``` And button is: ``` <input type="button" value="show first" onClick="called a javascript();"/> ``` Only single div is shown i.e. `first` ``` <script> $(document).ready( function() { $("#second").hide(); }); </script> ``` Now on clicking button, I want to hide first div, show second and the `value` of button is changed to show second and if clicked again it revert back to previous state. Thanks in advance
2013/07/19
[ "https://Stackoverflow.com/questions/17737104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2585973/" ]
Heres' the **[FIDDLE](http://jsfiddle.net/vonDy2791/vN88X/)**. Hope it helps. html ``` <div id="first" style="display:none;">first</div> <div id="second">second</div> <input id="btn" type="button" value="show first" /> ``` script ``` $('#btn').on('click', function () { var $this = $(this); if ($this.val() === 'show first') { $('#first').show(); $('#second').hide(); $this.val('show second'); } else { $('#first').hide(); $('#second').show(); $this.val('show first'); } }); ```
32,667,075
Is this correct? ``` var headers = new Headers(); headers.append('Accept', 'application/json, application/pdf') ``` I want to accept both json and pdf files.
2015/09/19
[ "https://Stackoverflow.com/questions/32667075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3949281/" ]
Yes, [it is correct](http://www.w3.org/Protocols/HTTP/HTRQ_Headers.html). Example form w3c: ``` Accept: text/plain, text/html ```
30,459,682
I would like to implement an Amazon SNS topic which first delivers messages to a SQS queue that is a subscriber on the topic, and then executes an AWS Lambda function that is also a subscriber on the same topic. The Lambda function can then read messages from the SQS queue and process several of them in parallel (hundreds). My question is whether there is any way to guarantee that messages sent to the SNS topic would first be delivered to the SQS queue, and only then to the Lambda function? The purpose of this is to scale to a large number of messages without having to execute the Lambda function separately for every single message.
2015/05/26
[ "https://Stackoverflow.com/questions/30459682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/445202/" ]
What you're looking for is currently not possible with one `SNS Topic`. If you subscribe your `Lambda` to a `SNS Topic` that particular `Lambda` gets executed each time that `SNS Topic` receives a message, in parallel. Solution might be to have two `SNS Topics` and publish messages to the first one and have your `SQS` subscribe to it. After successful submission of messages to this first topic you could send a message to the second `SNS Topic` to execute your `Lambda` to process messages the first `SNS Topic` stored to `SQS`. Another possible solution might be the above, you could just send some periodic message to the second topic to run the subscribed `Lambda`. This would allow you to scale your `Lambda SQS Workers`.
6,794,998
Hi I am New to android programming and currently developing an application that uses location manager to get user location and place a marker on a map. i am attempting to use AsyncTask to run the LocationListener and Constantly update the marker when the user location has changed. this is the class i am working on... ``` public class IncidentActivity extends MapActivity{ public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); this.setContentView(R.layout.incidentactivity); mapView = (MapView)findViewById(R.id.mapView); mapView.setBuiltInZoomControls(true); mapView.setTraffic(true); mapController = mapView.getController(); String coordinates[] = {"-26.167004","27.965505"}; double lat = Double.parseDouble(coordinates[0]); double lng = Double.parseDouble(coordinates[1]); geoPoint = new GeoPoint((int)(lat*1E6), (int)(lng*1E6)); mapController.animateTo(geoPoint); mapController.setZoom(16); mapView.invalidate(); new MyLocationAsyncTask().execute(); } private class MyLocationAsyncTask extends AsyncTask<Void, Location, Void> implements LocationListener{ private double latLocation; private Location l; //location management variables to track and maintain user location protected LocationManager locationManager; protected LocationListener locationListener; @Override protected Void doInBackground(Void... arg0) { Looper.prepare(); locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, locationListener); this.publishProgress(l); return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); } @Override protected void onProgressUpdate(Location... values) { super.onProgressUpdate(values); } //this method is never executed i dont know why...? public void onLocationChanged(Location location) { if (location != null){ latLocation = location.getLatitude(); Toast.makeText(getBaseContext(), " Your latLocation :" + latLocation, Toast.LENGTH_LONG).show(); //Log.d("Your Location", ""+latLocation); } } public void onProviderDisabled(String provider) { } public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } } } ```
2011/07/22
[ "https://Stackoverflow.com/questions/6794998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/858528/" ]
I've just implemented such `AsyncTask`: ``` class GetPositionTask extends AsyncTask<Void, Void, Location> implements LocationListener { final long TWO_MINUTES = 2*60*1000; private Location location; private LocationManager lm; protected void onPreExecute() { // Configure location manager - I'm using just the network provider in this example lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this); nearProgress.setVisibility(View.VISIBLE); } protected Location doInBackground(Void... params) { // Try to use the last known position Location lastLocation = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); // If it's too old, get a new one by location manager if (System.currentTimeMillis() - lastLocation.getTime() > TWO_MINUTES) { while (location == null) try { Thread.sleep(100); } catch (Exception ex) {} return location; } return lastLocation; } protected void onPostExecute(Location location) { nearProgress.setVisibility(View.GONE); lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); lm.removeUpdates(this); // HERE USE THE LOCATION } @Override public void onLocationChanged(Location newLocation) { location = newLocation; } public void onProviderDisabled(String provider) {} public void onProviderEnabled(String provider) {} public void onStatusChanged(String provider, int status, Bundle extras) {} } ```
50,919,141
When I go to <https://dojotoolkit.org/>, I get, "Unable to connect". In some browsers I get "You have reached a domain that is pending ICANN verification". I've used a number of dojo libraries in my code. Does anyone know what happened to the owner and whether this is likely to be fixed in the near future? If it isn't fixed, what is my best option for replacing it?
2018/06/19
[ "https://Stackoverflow.com/questions/50919141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9504680/" ]
This seems to be a temporary administrative DNS issue, based on their [Twitter response](https://twitter.com/dojo/status/1008720540838842368): > > We apologize for the issues accessing the Dojo 1 web site. We’re > working on it as fast as possible. In the mean time, you can add the > IP address directly to /etc/hosts. 104.16.205.241 > > > There are also some workarounds on the [dojo gitter.im channel](https://gitter.im/dojo/dojo?at=5b241a151ee2d149ecc5bd01): > > Reference guide content is also at <https://github.com/dojo/docs/> And > tutorials are at > <https://github.com/dojo/dojo-website/tree/master/src/documentation/tutorials> > > > Also, as mentioned in this [related question](https://stackoverflow.com/q/50908711/2039), you can use the [Archive.org Wayback Machine](https://web.archive.org/web/20171215051426/https://dojotoolkit.org/documentation/).
58,956,907
I have Angular 8 app and I have table: ``` <table> <thead> <tr> <th>...</th> ... </tr> </thead> <tbody> <tr *ngFor="let item of items"> <td (click)="toggleDetails(item)">...</td> <td>...</td> ... </tr> </tbody> </table> <span id="details-row" *ngIf="expandedItem"> <a (click)="convertFile(expandedItem.id, 'pdf')" class="pointer ml-3"> <i class="far fa-file-pdf"></i> Download as PDF </a> </span> ``` in my .ts file I have: ``` toggleDetails(item: any) { this.expandedItem = item; //todo if row isn't clicked -> insert document.getElementById("details-row").innerHTML new table row after row I clicked and angular bindings must work (I mean click handler) //todo if this row is already clicked -> remove this new table row } convertFile(id: number, format: string) { console.log(id); console.log(format); } ``` I can't use multiple `tbody`s. How can I implement my todos? Or are there other ways to implement that?
2019/11/20
[ "https://Stackoverflow.com/questions/58956907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5525734/" ]
A `br` to a block label jumps to the *end* of the contained instruction sequence -- it is a behaves like a `break` statement in C. A `br` to a loop label jumps to the *start* of the contained instruction sequence -- it behaves like a `continue` statement in C. The former enables a *forward* jump, the latter a *backwards* jump. Neither can express the other.
35,521,122
Besides the wrong use of DLLs, when I try to use the `theTestValue` inside the `IntPtr` method the IntelliSense marks it as fail. I would like to know why this is happening because I need to use a `bool` from outside inside this method. ``` public partial class Form1 : Form { [DllImport("user32.dll")] private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll")] private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam); private static LowLevelKeyboardProc _proc = HookCallback; private delegate IntPtr LowLevelKeyboardProc( int nCode, IntPtr wParam, IntPtr lParam); public bool theTestValue = false; //This is the value private static IntPtr HookCallback( int nCode, IntPtr wParam, IntPtr lParam) { theTestValue = true; //Red marked } return CallNextHookEx(_hookID, nCode, wParam, lParam); } ```
2016/02/20
[ "https://Stackoverflow.com/questions/35521122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3772108/" ]
You cannot access the field because the method is static and the field has been declared on instance level (not static). If you change the code so that both are either static or not, the error will be gone.
39,961,269
I want to use a thread as an event loop thread. I mean a Java thread with a "QThread like behaviour" (`t2` in the following example). Explanation: I have a thread `t1` (main thread) and a thread `t2` (a worker thread). I want that `method()`, called from `t1`, is executed in `t2` thread. Currently, I made this code (it works, but I don't like it): -Thread **t1** (Main thread, UI thread for example): ``` //... // Here, I want to call "method()" in t2's thread Runnable event = new Runnable() { @Override public void run() { t2.method(param); } }; t2.postEvent(event); //... ``` -Thread **t2**: ``` //... Queue<Runnable> eventLoopQueue = new ConcurrentLinkedQueue<Runnable>(); //... @Override public void run() { //... Runnable currentEvent = null; while (!bMustStop) { while ((currentEvent = eventLoopQueue.poll()) != null) { currentEvent.run(); } } //... } public void method(Param param) { /* code that should be executed in t2's thread */ } public void postEvent(Runnable event) { eventLoopQueue.offer(event); } ``` This solution is ugly. I don't like the "always-working" main loop in `t2`, the new `Runnable` allocation each time in `t1`... My program can call `method` something like 40 times per second, so I need it to be efficient. I'm looking for a solution that should be used on Android too (I know the class [Looper](https://developer.android.com/reference/android/os/Looper.html) for Android, but it's only for Android, so impossible)
2016/10/10
[ "https://Stackoverflow.com/questions/39961269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6523232/" ]
Consider using `BlockingQueue` instead of `Queue` for its method `take()` will block the thread until an element is available on the queue, thus not wasting cycles like `poll()` does.
319,068
I'm attempting an in place upgrade from SQL 2014 to SQL 2017, Standard Edition on Windows 2012 R2 (Yes, I know...) The issue is that the installer never presents me with a screen to select the instance and under Select Features, there are no options, just greyed out entries for Shared Features and Redistributable Features (no checkboxes). Because I already upgraded SQL Browser/Writer, hitting Next> at this point gives me the validation errors dialog and the installer shows "There are no features selected for upgrade". I've run the system configuration check report and migration assistant - all green. The summary.txt file shows that it discovered Database Engine Services, Reporting Services - Native, SSMS, and Adv\_SSMS, all SQL 2014. The installer is fine. If I begin to install a named instance of 2017, it provides me with features to select. I did the same with a 2016 installer and had the same problem. At this point, I'm at a loss for what to do next except uninstall 2014 and install 2017, which is a pain. Note that we were successful uninstalling SSRS 2014 and installing 2017 though we rolled that change back with a snapshot when we hit the engine upgrade roadblock. Grateful for any troubleshooting thoughts.
2022/11/02
[ "https://dba.stackexchange.com/questions/319068", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/44412/" ]
Could it be that your SQL 2014 is 32-bit? SQL 2017 is only available as 64-bit: SQL Server 2017 (14.x) is only available for 64-bit platforms. Cross-platform upgrade is not supported. You cannot upgrade a 32-bit instance of SQL Server to native 64-bit using SQL Server Setup. However, you can back up or detach databases from a 32-bit instance of SQL Server, and then restore or attach them to a new instance of SQL Server (64-bit) if the databases are not published in replication. You must re-create any logins and other user objects in master, msdb, and model system databases.
24,807,638
Is there a way i can split up a large jgraph graphics 2d document into multiple pages in a pdf using itext. I have a large flowchart created using jgraph. I need to write this flowchart into a pdf wit multiple pages. I need to make sure that each pdf page height is limited to 5000.SO if the graphics object height is more than 5000 it spans across multiple pages in the pdf. Is there a way i can read the graphics object in chunk (upto a height of 5000 in each iteration), keep writing it to a new pdf page and iterate till i completely read the object. Any inputs/directions will be helpful. Below is what i have till now - ``` float imageIdealHeight = 5000; float imageIdealWidth = 5000; float imageActualWidth=0; float imageActualHeight=0; mxRectangle imageBounds = ((mxGraph) graph).getGraphBounds(); imageActualWidth= (float) imageBounds.getWidth(); imageActualHeight = (float) imageBounds.getHeight(); System.out.println("Actual Width = "+imageActualWidth); System.out.println("Actual Height = "+imageActualHeight); numPages = (int) Math.ceil(imageActualHeight/imageIdealHeight); Rectangle actualRectangle = new Rectangle(imageActualWidth, imageActualHeight); //Custom Rectangle Rectangle idealRectangle = new Rectangle(imageIdealWidth, imageIdealHeight); Document document = new Document(idealRectangle ); //Create Pdf Writer PdfWriter writer = PdfWriter.getInstance(document, fos); //Open Document document.open(); //Create huge template with actual image dimensions PdfContentByte canvas = writer.getDirectContent(); PdfTemplate template = canvas.createTemplate(imageActualWidth, imageActualHeight); PdfCanvasFactory pdfCanvasFactory = new PdfCanvasFactory(canvas); //Draw graphics to this template Graphics2D g2=template.createGraphics(imageActualWidth, imageActualHeight); mxGraphics2DCanvas mxcanvas = new mxGraphics2DCanvas( g2); mxcanvas = (mxGraphics2DCanvas) mxCellRenderer.drawCells((mxGraph) graph, null, 1, null, pdfCanvasFactory); mxcanvas.getGraphics().dispose(); g2.dispose(); //Add template now... canvas.addTemplate(template,0, -15000); document.newPage(); canvas.addTemplate(template, 0, -10000); document.newPage(); canvas.addTemplate(template,0 , -5000); document.newPage(); canvas.addTemplate(template, 0, 0); document.newPage(); document.close(); ```
2014/07/17
[ "https://Stackoverflow.com/questions/24807638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3829109/" ]
You want a PDF with pages that measure 5000 by 5000 user units. This means that you're going to create a document with a custom rectangle like this: ``` Rectangle rect = new Rectangle(5000, 5000); Document document = new Document(rect); ``` Obviously, you're also going to create a writer like this: ``` PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("my_file.pdf")); ``` And you're going to open the document: ``` document.open(); ``` Let's assume that your Graphics2D "image" is 10000 by 10000 point. This means that you'd need to distribute that image over 4 pages. The trick is to create a `PdfTemplate` object that measures 10000 by 10000. ``` PdfContentByte canvas = writer.getDirectContent(); PdfTemplate template = canvas.createTemplate(10000, 10000); ``` Now we'll draw the graphics to this template: ``` Graphics2D gd2d = new PdfGraphics2D(template, 10000, 10000); // draw stuff to gd2d gd2d.dispose(); ``` You've now created a large Form XObject with content that doesn't fit a page. This content will be present in the PDF file only once as an *external object* (hence the term XObject). All you have to do, is to add the document as many times as needed. For example: ``` canvas.addTemplate(template, 0, 0); document.newPage(); ``` I hope you have a notion of the coordinate system: (0, -5000), (-5000, -5000), (0, 0) and (-5000, 0) are the x, y offsets needed to divide a 10000 by 10000 object over 4 pages that are only 5000 by 5000 in size. The only line of code that remains, is: ``` document.close(); ``` And you're done. For a full example, see [LargeTemplate](http://itextpdf.com/sandbox/graphics2d/LargeTemplate): ``` public void createPdf(String dest) throws IOException, DocumentException { float width = 602; float height = 15872; float maxHeight = 5000; Document document = new Document(new Rectangle(width, maxHeight)); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(DEST)); document.open(); PdfContentByte canvas = writer.getDirectContent(); PdfTemplate template = canvas.createTemplate(width, height); Graphics2D g2d = new PdfGraphics2D(template, width, height); for (int x = 10; x < width; x += 100) { for (int y = 10; y < height; y += 100) { g2d.drawString(String.format("(%s,%s)", x, y), x, y); } } g2d.dispose(); int pages = ((int)height / (int)maxHeight) + 1; for (int p = 0; p < pages; ) { p++; canvas.addTemplate(template, 0, (p * maxHeight) - height); document.newPage(); } document.close(); } ``` As you can see, I used the dimensions you mention in your comment: ``` float width = 602; float height = 15872; ``` I also introduce a maximum height: ``` float maxHeight = 5000; ``` I create a page with dimensions width x maxHeight and a Graphics2D template with dimensions width x height. For testing purposes, I use `drawString()` to draw coordinate information every 100 points. I calulate how many pages I'll need: ``` int pages = ((int)height / (int)maxHeight) + 1; ``` Now I add the template as many times as there are pages, using some elementary math to calculate the offset: ``` for (int p = 0; p < pages; ) { p++; canvas.addTemplate(template, 0, (p * maxHeight) - height); document.newPage(); } ``` I don't know which Math you are using, but the resulting PDF looks exactly the way I expect it: [large\_template.pdf](http://itextpdf.com/sites/default/files/large_template.pdf)
48,984,780
I just started out with node.js and wanted to do something with nodemailer. I've installed the packages (Oauth2, Express, Body-parser, Node, Nodemailer) using `npm install (package name)` The issues I have are when I try and get information from my HTML form by using `req.body.subject` it gives the error that it req is not defined. (Sending a mail by doing `node app.js` in the cmd works fine and doesn't give any errors) ``` C:\Users\Gebruiker\Desktop\nodemailer\app.js:31 subject: req.body.subject, ^ ReferenceError: req is not defined at Object.<anonymous> (C:\Users\Gebruiker\Desktop\nodemailer\app.js:31:14) at Module._compile (module.js:660:30) at Object.Module._extensions..js (module.js:671:10) at Module.load (module.js:573:32) at tryModuleLoad (module.js:513:12) at Function.Module._load (module.js:505:3) at Function.Module.runMain (module.js:701:10) at startup (bootstrap_node.js:190:16) at bootstrap_node.js:662:3 PS C:\Users\Gebruiker\Desktop\nodemailer> ``` I have this error on my pc and on my server. I have been searching for a answer for a while now and couldn't find a answer for my issue. I am sorry if I did something wrong in this post or that it isn't clear enough I am pretty new on here. The code: HTML form. ``` <html> <head> <script src="app.js"></script> </head> <form action="/send-email" method="post"> <ul class="inputs"> <li> <label for="from">From</label> <input type="text" id="from" name="from" /> </li> <li> <label for="to">To</label> <input type="text" id="to" name="to" /> </li> <li> <label for="subject">Subject</label> <input type="subject" id="subject" name="subject" /> </li> <li> <label for="message">Message</label> <input type="message" id="message" name="message" /> </li> <li> <button>Send Request</button> </li> </ul> </form> </body> </html> ``` Nodemailer code. ``` var nodemailer = require('nodemailer'); var path = require('path'); var bodyParser = require('body-parser'); var express = require('express'); var OAuth2 = require('oauth2'); var app = express(); app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json()); app.get('/', function (req, res) { res.render('default'); }); const transporter = nodemailer.createTransport({ service: 'Gmail', auth: { type: 'OAuth2', user: 'xxxx@gmail.com', clientId: 'xxxx', clientSecret: 'xxxx', refreshToken: 'xxxx', accessToken: 'xxxx', }, }); var mailOptions = { from: 'Xander <xxxx@gmail.com>', to: req.body.to, subject: req.body.subject, html: 'Hello Planet! <br />Embedded image: <img src="cid: download.jpg"/>', attachments: [{ filename: 'download.jpg', path: 'download.jpg', cid: 'download.jpg' }] } transporter.sendMail(mailOptions, function(err, res){ if(err){ console.log('Mail not sent'); } else { console.log('Mail sent'); } }); ``` I am sorry if the answer to this question is really simple and easy, this is my first real thing I am trying to do with nodemailer and node.js.
2018/02/26
[ "https://Stackoverflow.com/questions/48984780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9391401/" ]
You don't have to revert your code back to using `$scope` since using controller as syntax is better ([See advantages](https://stackoverflow.com/questions/32755929/what-is-the-advantage-of-controller-as-in-angular)). You have to bind not only your `ng-model` but also your `ng-submit` to your controller instance `subscription`. ```js var app = angular.module('myApp', []) app.controller('SubscriptionCtrl', function() { var subscription = this; subscription.redeem = function() { console.log(subscription.accessCode) } }) ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myApp"> <div ng-controller="SubscriptionCtrl as subscription"> <form ng-submit="subscription.redeem()"> <input class="text-uppercase" type="number" ng-maxlength="6" placeholder="Indtast kode" ng-model="subscription.accessCode" /> <input type="submit" class="btn btn-dark-green" value="Indløs" /> </form> </div> </div> ```
4,341,848
``` var adList = new Array(); adList[0]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg';/* adList[0]["h3"] = 'Product title2'; adList[0]["button"]["link"] = '#link-url'; adList[0]["button"]["text"] = 'Buy now'; adList[0]["h3"] = 'asdfasdfasdf'; adList[1]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg'; adList[1]["h3"] = 'Product title2'; adList[1]["button"]["link"] = '#link-url'; adList[1]["button"]["text"] = 'Buy now'; adList[1]["h3"] = 'asdfasdfasdf'; ``` I'm getting an error `adList[0] is undefined`, can I not define arrays like this? Do I have to specify `adList[0]` as an array before I assign variables to it?
2010/12/03
[ "https://Stackoverflow.com/questions/4341848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/197606/" ]
The problem is that you're trying to refer to `adList[0]` which hasn't had a value assigned to it. So when you try to access the value of `adList[0]['img']`, this happens: ``` adList -> Array adList[0] -> undefined adList[0]["img"] -> Error, attempting to access property of undefined. ``` Try using array and object literal notation to define it instead. ``` adList = [{ img: 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg', h3: 'Product title 1', button: { text: 'Buy now', url: '#link-url' } }, { img: 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg', h3: 'Product title 2', button: { text: 'Buy now', url: '#link-url' } }]; ``` Or you can simply define `adList[0]` and `adList[1]` separately and use your old code: ``` var adList = new Array(); adList[0] = {}; adList[1] = {}; adList[0]["img"] = 'http://www.gamer-source.com/image/media/screenshot/thumbnail/489.jpg'; ... etc etc ```
65,018,327
I am a beginner on React and am working on a project but I could not pass this error, I looked through similar topics, but still couldn't fix the problem, I will be glad if you guys help me! --- > > ERROR Invariant Violation: The navigation prop is missing for this > navigator. In react-navigation v3 and v4 you must set up your app > container directly. More info: > <https://reactnavigation.org/docs/en/app-containers.html> This error is > located at: > in Navigator (at MainComponent.js:81) > in RCTView (at View.js:34) > in View (at MainComponent.js:80) > in Main (at App.js:7) > in App (at renderApplication.js:45) > in RCTView (at View.js:34) > in View (at AppContainer.js:106) > in RCTView (at View.js:34) > in View (at AppContainer.js:132) > in AppContainer (at renderApplication.js:39) > > > --- **MainComponent.js** ```html import React, { Component } from 'react'; import Menu from './MenuComponent'; import Home from './HomeComponent'; import Dishdetail from './DishdetailComponent'; import { View } from 'react-native'; import 'react-native-gesture-handler'; import { createStackNavigator } from 'react-navigation-stack'; import { createDrawerNavigator } from 'react-navigation-drawer'; import { DISHES } from '../shared/dishes'; const MenuNavigator = createStackNavigator({ Menu: { screen: Menu }, Dishdetail: { screen: Dishdetail } }, { initialRouteName: 'Menu', navigationOptions: { headerStyle: { backgroundColor: "#512DA8" }, headerTintColor: '#fff', headerTitleStyle: { color: "#fff" } } } ); const HomeNavigator = createStackNavigator({ Home: { screen: Home } }, { navigationOptions: { headerStyle: { backgroundColor: "#512DA8" }, headerTitleStyle: { color: "#fff" }, headerTintColor: "#fff" } }); const MainNavigator = createDrawerNavigator({ Home: { screen: HomeNavigator, navigationOptions: { title: 'Home', drawerLabel: 'Home' } }, Menu: { screen: MenuNavigator, navigationOptions: { title: 'Menu', drawerLabel: 'Menu' }, } }, { drawerBackgroundColor: '#D1C4E9' }); class Main extends Component { constructor(props) { super(props); this.state = { dishes: DISHES, selectedDish: null }; } onDishSelect(dishId) { this.setState({selectedDish: dishId}) } render() { return ( <View style={{flex:1, paddingTop: 10}}> <MainNavigator /> </View> ); } } export default Main; ``` This is the Error SS: [![enter image description here](https://i.stack.imgur.com/UyUEq.png)](https://i.stack.imgur.com/UyUEq.png)
2020/11/26
[ "https://Stackoverflow.com/questions/65018327", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14374677/" ]
Use dense\_rank instead row\_number ``` SELECT * FROM (SELECT Indicator, ReportedDate, dense_rank() OVER(PARTITION BY (select 1) ORDER BY ReportedDate desc) as periods FROM @t) a where periods <= 2 ```
28,884,115
I'm facing some problems launching my rails app hosted on bluehost. I think that the problem is the passenger version interacting with the rails 4 app but I'm not sure. When I launch my app I get this trace: ``` Ruby (Rack) application could not be started These are the possible causes: There may be a syntax error in the application's code. Please check for such errors and fix them. A required library may not installed. Please install all libraries that this application requires. The application may not be properly configured. Please check whether all configuration files are written correctly, fix any incorrect configurations, and restart this application. A service that the application relies on (such as the database server or the Ferret search engine server) may not have been started. Please start that service. Further information about the error may have been written to the application's log file. Please check it in order to analyse the problem. Error message: Could not initialize MySQL client library Exception class: RuntimeError Application root: /home5/barracam/rails_apps/admin/admin Backtrace: # File Line Location 0 /home5/barracam/ruby/gems/gems/mysql2-0.3.18/lib/mysql2.rb 31 in `require' 1 /home5/barracam/ruby/gems/gems/mysql2-0.3.18/lib/mysql2.rb 31 in `' 2 /usr/lib64/ruby/gems/1.9.3/gems/bundler-1.3.5/lib/bundler/runtime.rb 72 in `require' 3 /usr/lib64/ruby/gems/1.9.3/gems/bundler-1.3.5/lib/bundler/runtime.rb 72 in `block (2 levels) in require' 4 /usr/lib64/ruby/gems/1.9.3/gems/bundler-1.3.5/lib/bundler/runtime.rb 70 in `each' 5 /usr/lib64/ruby/gems/1.9.3/gems/bundler-1.3.5/lib/bundler/runtime.rb 70 in `block in require' 6 /usr/lib64/ruby/gems/1.9.3/gems/bundler-1.3.5/lib/bundler/runtime.rb 59 in `each' 7 /usr/lib64/ruby/gems/1.9.3/gems/bundler-1.3.5/lib/bundler/runtime.rb 59 in `require' 8 /usr/lib64/ruby/gems/1.9.3/gems/bundler-1.3.5/lib/bundler.rb 132 in `require' 9 /home5/barracam/rails_apps/admin/admin/config/application.rb 7 in `' 10 /home5/barracam/rails_apps/admin/admin/config/environment.rb 2 in `require' 11 /home5/barracam/rails_apps/admin/admin/config/environment.rb 2 in `' 12 config.ru 3 in `require' 13 config.ru 3 in `block in' 14 /home5/barracam/ruby/gems/gems/rack-1.5.2/lib/rack/builder.rb 55 in `instance_eval' 15 /home5/barracam/ruby/gems/gems/rack-1.5.2/lib/rack/builder.rb 55 in `initialize' 16 config.ru 1 in `new' 17 config.ru 1 in `' 18 /etc/httpd/modules/passenger/lib/phusion_passenger/rack/application_spawner.rb 225 in `eval' 19 /etc/httpd/modules/passenger/lib/phusion_passenger/rack/application_spawner.rb 225 in `load_rack_app' 20 /etc/httpd/modules/passenger/lib/phusion_passenger/rack/application_spawner.rb 157 in `block in initialize_server' 21 /etc/httpd/modules/passenger/lib/phusion_passenger/utils.rb 563 in `report_app_init_status' 22 /etc/httpd/modules/passenger/lib/phusion_passenger/rack/application_spawner.rb 154 in `initialize_server' 23 /etc/httpd/modules/passenger/lib/phusion_passenger/abstract_server.rb 204 in `start_synchronously' 24 /etc/httpd/modules/passenger/lib/phusion_passenger/abstract_server.rb 180 in `start' 25 /etc/httpd/modules/passenger/lib/phusion_passenger/rack/application_spawner.rb 129 in `start' 26 /etc/httpd/modules/passenger/lib/phusion_passenger/spawn_manager.rb 253 in `block (2 levels) in spawn_rack_application' 27 /etc/httpd/modules/passenger/lib/phusion_passenger/abstract_server_collection.rb 132 in `lookup_or_add' 28 /etc/httpd/modules/passenger/lib/phusion_passenger/spawn_manager.rb 246 in `block in spawn_rack_application' 29 /etc/httpd/modules/passenger/lib/phusion_passenger/abstract_server_collection.rb 82 in `block in synchronize' 30 prelude> 10:in `synchronize' 31 /etc/httpd/modules/passenger/lib/phusion_passenger/abstract_server_collection.rb 79 in `synchronize' 32 /etc/httpd/modules/passenger/lib/phusion_passenger/spawn_manager.rb 244 in `spawn_rack_application' 33 /etc/httpd/modules/passenger/lib/phusion_passenger/spawn_manager.rb 137 in `spawn_application' 34 /etc/httpd/modules/passenger/lib/phusion_passenger/spawn_manager.rb 275 in `handle_spawn_application' 35 /etc/httpd/modules/passenger/lib/phusion_passenger/abstract_server.rb 357 in `server_main_loop' 36 /etc/httpd/modules/passenger/lib/phusion_passenger/abstract_server.rb 206 in `start_synchronously' 37 /etc/httpd/modules/passenger/helper-scripts/passenger-spawn-server 99 in `' Powered by Phusion Passenger, mod_rails / mod_rack for Apache and Nginx. ``` I tried to run a rails 3 app and all works fine. What do you think about the problem? Any help is really appreciated.
2015/03/05
[ "https://Stackoverflow.com/questions/28884115", "https://Stackoverflow.com", "https://Stackoverflow.com/users/677210/" ]
I was getting the same error, so after a lot of research, and trial and error.... I locked my mysql2 gem at version 3.0.16, and set up my database.yml like so: ``` adapter: mysql2 encoding: utf8 database: store username: root password: host: localhost reconnect: true port: 3306 ``` My app is running rails on 4.20, and works fine now. (although it still has sporadic trouble connecting to the mysql db? maybe the bluest server gets overloaded? there is no real pattern, and it doesn't happen all that often.
33,921
Do qualia have an evolutionary function, and if so what is it? Could qualia help us solve problems that Turing machines can't solve? Could qualia help us solve problems faster than normal computers? Our brain often works like a general problem solving machine. Could qualia have evolved to optimize this machine? Could evolution limit it to solving only the problems that our genes are "interested" in? Could qualia have other purposes?
2016/05/01
[ "https://philosophy.stackexchange.com/questions/33921", "https://philosophy.stackexchange.com", "https://philosophy.stackexchange.com/users/20480/" ]
Qualia are supposed to be (by definition) not the causes of any physical events, hence there is no way that they could enter into evolutionary or any other kinds of scientific explanation of a phenomenon. For instance, imagine there were ghosts which simply couldn't cause any events in the physical world--couldn't rattle any chains, nor even appear to anybody to scare them. Such ghosts could not even in principle enter in to any scientific account of a phenomenon. **Edit** I've received several down votes on this answer, which surprises me, since my answer is clearly correct. Let me quote some evidence. I'll start with an excellent introduction to the philosophy of mind. > > "If qualia cannot be physically described or explained, then they are not part of the network of physical causal relations that are responsible for human behavior. If qualia are not part of that causal network, however, then they make no causal contribution to human behavior." Jaworski, "Philosophy of Mind: An Introduction" Blackwell 2011, p. 213 > > > Somebody in the comment thread below says that Jaworski, a professional philosopher of mind who published a peer-reviewed book on the subject with a reputable publisher is just wrong about the definition of "qualia." Ok, so let's look and see what other scholars in standard, peer-reviewed reference works thing. > > "... this response does not apply to those philosophers who take the view that qualia are irreducible, non-physical entities [e.g. Chalmers, Frank Jackson, etc.]. **However, these philosophers have other severe problems of their own. In particular, they face the problem of phenomenal causation. Given the causal closure of the physical, how can qualia make any difference?** For more here, see Tye 1995, Chalmers 1996).'' Michael Tye, in the [SEP article on Qualia.](http://plato.stanford.edu/entries/qualia/#Uses) > > > The implied answer of the question is: "They can't." Nobody who believes in qualia should count as a physicalist, but rejecting physicalism is not the same thing as rejecting the causal closure of the physical world. Rejecting closure isn't just rejecting physicalism, it's opening the door back up to straightforward substance dualism where my mental properties cause physical events by pushing my pineal gland around or something. But, hey, maybe the entire scholarly community has gotten Chalmers and company wrong. Maybe Chalmers has simply been slighted by careless, slapdash slanders by wild eyed physicalists who cannot stand to hear their theories contradicted. So, let's look and see what Chalmers himself says about whether qualia have causal powers. > > "A problem with the view that I have advocated is that if consciousness is merely naturally supervenient upon the physical, then it seems to lack causal efficacy. The physical world is more or less causally closed, in that for any given physical event, it seems that there is a physical explanation of (modulo a small amount of quantum indeterminacy). This implies that there is no room for a nonphysical consciousness to do any independent causal work. It seems to be a mere epiphenomenon, hanging off the engine of physical causation, but making no difference in the physical world." David Chalmers, *The Conscious Mind: In Search of a Fundamental Theory,* Oxford University Press, 1996, p. 150. > > > Chalmers does go on to suggest ways in which he will try to avoid, or at least soften the blow, of having to make qualia epiphenomenal, but whether those responses are successful is a matter of further scholarly controversy. For my money, I don't think any of his proposed fixes, like endorsing causal overdetermination, or extreme humeanism about causation look even remotely plausible. I would love for people who are still down voting to explain in the comments exactly what kind of evidence they think would be necessary to prove the claim at issue here. Remember, the issue at stake is not the *empirical* question, "Do psychological states have causal powers?" but rather "Could qualia, those theoretical posits whose properties are stipulated by their use in the philosophy of mind of David Chalmers, Frank Jackson, et al., have causal powers?"
41,732
My company has corporate offices around the country and I have been hired under contract to work in one office while the rest of my team works in another. We are in the same time zone, but definitely remote. I have not met the team yet, but will be flying up there soon. What is your best advice for integrating and developing with this team? What are the most important priorities? Standard versioning control, e-mail, phone, conference call and IM are all available resources, however Google apps, Skype and the like are not for security reasons.
2011/01/31
[ "https://softwareengineering.stackexchange.com/questions/41732", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/13514/" ]
* **An excellent IM tool**. My team uses MS Office Communicator (and are currently migrating to [Lync](http://lync.microsoft.com/en-us/launch/Pages/launch.aspx). You need something that's faster than email to ask those "QQ"s. * A **video/audio chat tool** (like Lync or the newest Skype) that supports **multiple** users having video/audio chat at the same time. This provides for faster meetings overall as there's less fumbling to switch who is presenter. * A **remote desktop** application. Many times you may be asked to look over someone's code, or vice versa. Having a quick remote desktop application integrated with audio is a must to quickly solve problems. We actually use this when my entire team is in the office because it's quicker and easier than walking to someone's desk. We can invite the whole team and do a quick tutorial.
93,705
St. Thomas Aquinas, [*Summa Theologica* II-II q. 78 a. 1](https://isidore.co/aquinas/summa/SS/SS078.html#SSQ78A1THEP1) co., says that usury is to sell the use of a consumable good separately from the consumable good itself: > > To take usury for money lent is unjust in itself, because this is to sell what does not exist, and this evidently leads to inequality which is contrary to justice. In order to make this evident, we must observe that there are certain **things the use of which consists in their consumption**: thus we consume wine when we use it for drink and we consume wheat when we use it for food. Wherefore in such like things the use of the thing must not be reckoned apart from the thing itself, and whoever is granted the use of the thing, is granted the thing itself and for this reason, to lend things of this kin is to transfer the ownership. Accordingly if a man wanted to sell wine separately from the use of the wine, he would be selling the same thing twice, or he would be selling what does not exist, wherefore he would evidently commit a sin of injustice. On like manner he commits an injustice who lends wine or wheat, and asks for double payment, viz. one, the return of the thing in equal measure, the other, the price of the use, which is called usury. > > > On the other hand, there are **things the use of which does n̲o̲t̲ consist in their consumption**: thus to use a house is to dwell in it, not to destroy it. Wherefore in such things both may be granted: for instance, one man may hand over to another the ownership of his house while reserving to himself the use of it for a time, or vice versa, he may grant the use of the house, while retaining the ownership. For this reason a man may lawfully make a charge for the use of his house, and, besides this, revendicate the house from the person to whom he has granted its use, as happens in renting and letting a house. > > > But that explanation makes no sense to me. Just because the use of wine consists in its destruction, I do not see how this implies that the sale of the use of wine also implies the sale of the property itself. I see no significant difference between using a house as a dwelling and using wine for drinking. If the sale of the use of the house can be separated from the sale of the property itself, then the sale of the use of the wine can also be separated from the sale of the property itself.
2022/12/05
[ "https://christianity.stackexchange.com/questions/93705", "https://christianity.stackexchange.com", "https://christianity.stackexchange.com/users/60033/" ]
St. Thomas Aquinas gets of a lot of things right, but on this matter I believe he is simply incorrect. His argument has two parts. First, it is only okay to charge for the use of something when ownership can be separated from the use, such as with renting a house. If something is consumed (destroyed) by the use, then the ownership cannot be separated, and therefore it's not okay to charge for the use separately from the thing; you'd be double-dipping, and that's not good. I don't necessarily disagree with that idea. I'm not fully convinced of it, either, but I'd love to see the principal applied to certain software licensing regimes, for example. I also want to point out this doesn't strictly eliminate money-lending as a potential business venture. It would be okay under this rule to, say, lend $100 in exchange for receiving $110 when the loan is repaid (the balance plus $10 in reasonable profit). What this principal says is the charge for a monetary loan should be fixed up front, rather than grow the longer the loan (use) lasts. --- But there is still the second part of the argument (money is consumed in the use), and here is where I need to pose a question: *which type of thing is money, really?* Let's say I take small loan to buy food: say I visit a restaurant and pay by credit card. Clearly the money the was consumed by the purchase, and very soon so is the food. It seems like Mr Aquinas is right. But what if I take a larger loan to start a business? The business is still there after I spend the money, and (hopefully) very soon so is the money. Economically, we say money is **fungible**: that is, it is easily converted from one thing to another. There are many things one can purchase with money that are also **durable** and themselves (perhaps somewhat less) fungible. So I can take a loan to purchase (or rent) a thing in order to perform some service, then sell the thing to get the money back, and return the "same" money to lender. That is, money *can* be consumed from the use, but it is not *certain* to be. Now lets go back to restaurant example, and add another wrinkle. Let's say my bank balance is $0; I have no money of my own at this particular moment. However, I do have a steady job and am expecting a paycheck tomorrow, and we'll also say my current broke state is for expected reasons that don't particularly concern me. This helps us look at the nature of this small credit card loan in terms of a *time shift*, as well. Even for this most ephemeral use of the money, I still only need or want it *for a particular moment in time*, and then I return it, perhaps as soon as the next day. Even here, we see the loan was ultimately about use over time, rather than consumption. --- The nature of any loan, then, is the borrower must return to the lender the full the value of what was borrowed, and on top of this the lender may reasonably charge a fee for the **use** of the borrowed money, to make it worth his effort and inconvenience. The longer the duration of the loan, the longer the lender is deprived of the use of the money himself (to make other loans, for example), and therefore it is justifiable this fee can also be time-based. Where we should take exception is with **EXCESSIVE** usuary. --- For fun, let's further look at a basic idea for limiting excessive usury. What if we had legal limits in place to prevent finance charges beyond the value of the initial principal of any loan? The moment interest and fees have reach the value of the original principal, any outstanding balance is still owed, but the lender no longer has the ability to tack on additional charges. This seems like a great baseline protection for borrowers. It might even still allow excessive usury, but as a final backstop it's better than nothing. But now let's think deeper. How does one arrive at this situation? Either you agreed to (and signed for) a loan with excessive usury built in, or you failed at some point to meet your repayment obligations for the original loan, allowing the use fees (interested) to pile up. At this point, the lender could reasonably argue you are extending the loan to use periods, which justify new charges. I think doubling over the original principal is still excessive, but at some point holding onto the balance is depriving the lender of their property, and there needs to be a penalty. Perhaps a better idea is that at this point interest can no longer compound.
58,013,886
I use ngx-cookieconsent module for an angular app, I need to manually set the cookie's status after a specific event but I didn't find a public method to do that in the injectable NgcCookieConsentService. Does anybody know if it is possible or if there is a workaround?
2019/09/19
[ "https://Stackoverflow.com/questions/58013886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5635645/" ]
Yes, by default it takes `HEAD`, but you could feed it any ref : ``` git log --graph --oneline # outputs history backwards from HEAD git log --graph --oneline branch-1 # outputs only branch-1 history git log --graph --oneline --all # outputs all branch histories ``` To address your comment below : for the case of `--all`, it doesn't mean it takes all commits, but all refs. So all the `refs/` dir will be explored (and `HEAD` also) --- Edit after new scope : To find lost (dangling) commits, use `fsck` ``` git fsck --lost-found ``` --- Finally, to link the two, you can nest commands. ``` git log --graph --oneline $(git fsck --lost-found | sed -E 's/dangling (tree|commit|blob|tag) //') ```
35,571,752
I can't get the lower and upper bound of y. ``` library(ggplot2) ggplot(data,aes(x=n,y=value,color=variable)) + geom_line()+ labs(color="Legend")+ scale_x_continuous("x",expand=c(0,0), breaks=c(1,2,5,10,30,60))+ scale_y_continuous("y",expand=c(0,0), breaks=round(seq(0,max(data[,3]),by=0.1),1)) ``` Data (there will be more variables later): ``` n variable value 1 1 0.2339010 2 1 0.2625115 5 1 0.2781600 10 1 0.2776770 30 1 0.3344481 60 1 0.4810225 ``` 1. I want the upper bound of y to be the highest value of y (0.4810225) rounded up to the highest second decimal (0.5). How do I show '0.5' as maximum y-value on the plot? (Much like how 60 is the maximum x-value.) 2. How do I show y=0.0 at the beginning of the axis? [![enter image description here](https://i.stack.imgur.com/M9suy.jpg)](https://i.stack.imgur.com/M9suy.jpg)
2016/02/23
[ "https://Stackoverflow.com/questions/35571752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
`Box* a;` declares a *pointer* to a `Box` object. You don't ever *create* a `Box` object so `a` doesn't point to anything. The behaviour writing `a->data` is therefore *undefined*. Either drop the pointer so you get `Box a;`, or use `Box* a = new Box();`. In the latter case, don't forget to call `delete a;` at some point else you'll leak memory. Finally, writing `a->data = "Hello World";` could be problematic: `a->data` will then be a pointer to a *read-only* string literal; the behaviour on attempting to modify the contents of that buffer is *undefined*. It's far better to use a `std::string` as the type for `a`.
25,330,425
I am trying to set up an onClickListener to my ListView in my AlertDialog, but I keep getting errors. When using this code I get an error under "setOnClickListener" stating `The method setOnClickListener(View.OnClickListener) in the type AdapterView<ListAdapter> is not applicable for the arguments (new DialogInterface.OnClickListener(){})` Here's my code, hopefully someone could help me out, thanks. ``` String names[] ={"A","B","C","D"}; AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity()); LayoutInflater inflater = getActivity().getLayoutInflater(); View convertView = (View) inflater.inflate(R.layout.customdialog, null); alertDialog.setView(convertView); alertDialog.setTitle("List"); ListView lv = (ListView) convertView.findViewById(R.id.listView1); ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,names); lv.setAdapter(adapter); alertDialog.show(); lv.setOnClickListener(new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub switch(which){ case 0: Toast.makeText(getActivity(), "clicked 1", Toast.LENGTH_SHORT).show(); break; } } }); ```
2014/08/15
[ "https://Stackoverflow.com/questions/25330425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2657363/" ]
Use `OnItemClickListener`. There is param (third one) `int position` which gives you the index of list item click. Based on index you can do what you want. ``` lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3) { switch(position){ case 0: Toast.makeText(getActivity(), "clicked 1", Toast.LENGTH_SHORT).show(); break; } } }); ```
70,356,210
I am fetching data from a text file where I need to match the substring to get the matched line. Once, I have that, I need to get the third 8 digit value in the line which comes after the delimiter "|". Basically, all the values have varying lengths and are separated by a delimiter "|". Except the first substring (id) which is of fixed length and has a fix starting and end position. Text file data example: ``` 0123456|BHKAHHHHkk|12345678|JuiKKK121255 9100450|HHkk|12348888|JuiKKK10000000021sdadad255 ``` ``` $file = 'file.txt'; // the following line prevents the browser from parsing this as HTML. header('Content-Type: text/plain'); // get the file contents, assuming the file to be readable (and exist) $contents = file_get_contents($file); // escape special characters in the query $txt = explode("\n",$contents); $counter = 0; foreach($txt as $key => $line){ $subbedString = substr($line,2,6); // $searchfor = '123456'; //echo strpos($subbedString,$searchfor); if(strpos($subbedString,$searchfor) === 0){ $matches[$key] = $searchfor; $matchesLine[$key] = substr($line,2,50); echo "<p>" . $matchesLine[$key] . "</p>"; $counter += 1; if($counter==10) break; } ```
2021/12/14
[ "https://Stackoverflow.com/questions/70356210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15691137/" ]
By default, `array_search` performs the same comparison as the `==` operator, which will attempt to ["type juggle"](https://www.php.net/manual/en/language.types.type-juggling.php) certain values. For instance, `'1' == 1`, `'1.' == 1`, and `'1.' == '1'` are all true. That means that `'1'` and `'1.'` will always match the same element in your lookup table. Luckily, the function takes a third argument, which [the manual describes](https://www.php.net/array_search) as: > > If the third parameter `strict` is set to `true` then the `array_search()` function will search for identical elements in the `haystack`. This means it will also perform a strict type comparison of the `needle` in the `haystack`, and objects must be the same instance. > > > This makes it equivalent to the `===` operator instead. Note that `'1' === 1`, `'1.' === 1`, and `'1.' === '1'` are all false. So you just need to add that argument: ``` echo array_search($char,$dict,true); ```
44,618,935
I've been trying out to solve the [monty hall problem](https://en.wikipedia.org/wiki/Monty_Hall_problem) in Python in order to advance in coding, which is why I tried to randomize everything. The thing is: I've been running into some trouble. As most of you probably know the monty problem is supposed to show that changing the door has a higher winrate (66%) than staying on the chosen door (33%). For some odd reason though my simulation shows a 33% winrate for both cases and I am not really sure why. Here's the code: ``` from random import * def doorPriceRandomizer(): door1 = randint(0,2) #If a door is defined 0, it has a price in it door2 = randint(0,2) #If a door is defined either 1 or 2, it has a goat in it. door3 = randint(0,2) while door2 == door1: door2 = randint(0,2) while door3 == door2 or door3 == door1: door3 = randint(0,2) return door1,door2,door3 #This random placement generator seems to be working fine. while True: loopStart = 0 amountWin = 0 amountLose = 0 try: loopEnd = int(input("How often would you like to run this simulation: ")) if loopEnd < 0: raise ValueError doorChangeUser = int(input("[0] = Do not change door; [1] = Change door: ")) if doorChangeUser not in range(0,2): raise ValueError except ValueError: print("Invalid input. Try again.\n") else: while loopStart != loopEnd: gameDoors = doorPriceRandomizer() inputUser = randint(0,2) if doorChangeUser == 0: if gameDoors[inputUser] == 0: amountWin += 1 loopStart += 1 else: amountLose += 1 loopStart += 1 elif doorChangeUser == 1: ChangeRandom = 0 while gameDoors[ChangeRandom] == gameDoors[inputUser]: ChangeRandom = randint(0,2) if gameDoors[ChangeRandom] == 0: amountWin += 1 loopStart += 1 else: amountLose += 1 loopStart += 1 print("Win amount: ",amountWin,"\tLose amount: ",amountLose) ``` What am I doing wrong? I really appreciate all help! Thanks in advance!
2017/06/18
[ "https://Stackoverflow.com/questions/44618935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8179999/" ]
``` ChangeRandom = 0 while gameDoors[ChangeRandom] == gameDoors[inputUser]: ChangeRandom = randint(0,2) ``` This doesn't do what you think it does. Instead of checking if the `ChangeRandom` door is the same as the `inputUser` door, this checks if the `ChangeRandom` door and the `inputUser` door have the same value -- that is to say they're either both winners or both losers. That said, that's not even what you want to do. What you want to do is to find a door that's not the user's input that IS a loser door, then switch to the OTHER one that isn't the user's input. This could be implemented with minimal change to your code as: ``` other_wrong_door = next(c for c, v in enumerate(gameDoors) if v != 0 and c != inputUser) new_door = next(c for c, _ in enumerate(gameDoors) if c != inputUser and c != other_wrong_door) ``` But honestly this merits a re-examining of your code's structure. Give me a few minutes to work something up, and I'll edit this answer to give you an idea of how I'd implement this. ``` import random DOORS = [1, 0, 0] def runonce(switch=False): user_choice = random.choice(DOORS) if user_choice == 1: # immediate winner if switch: # if you won before and switch doors, you must lose now return False else: new_doors = [0, 0] # remove the user-selected winner new_doors = [0] # remove another loser return bool(random.choice(new_doors)) # of course, this is always `0`, but # sometimes it helps to show it. In production you # wouldn't bother writing the extra lines and just return False else: if switch: new_doors = [1, 0] # remove the user-selected loser new_doors = [1] # remove another loser return bool(random.choice(new_doors)) # as above: this is always True, but.... else: return False # if you lost before and don't switch, well, you lost. num_trials = int(input("How many trials?")) no_switch_raw = [run_once(switch=False) for _ in range(num_trials)] switch_raw = [run_once(switch=True) for _ in range(num_trials)] no_switch_wins = sum(1 for r in no_switch_raw if r) switch_wins = sum(1 for r in switch_raw if r) no_switch_prob = no_switch_wins / num_trials * 100.0 switch_prob = switch_wins / num_trials * 100.0 print( " WINS LOSSES %\n" f"SWITCH: {switch_wins:>4} {num_trials-switch_wins:>6} {switch_prob:.02f}\n" f"NOSWITCH:{no_switch_wins:>4} {num_trials-no_switch_wins:>6} {no_switch_prob:.02f}") ```
43,691,884
We are covering the topic of classes at my school. I am supposed create a class called Student that we can use to hold different test scores in a dynamically allocated array. I'm struggling to figure out why when I print out the array of a specific instance of this class, it gives me completely incorrect values. I know my setter function for the class is setting the correct values but whenever I go to print them out they are completely wrong. Below is my code. The commented out portion in main() was just being used to test my logic for the makeArray() function. ``` #include <iostream> using namespace std; class Student { private: string name; int id; int* testptr; int num; void makeArray() { int array[num]; testptr = &array[num]; for (int i = 0; i < num; i++) { array[i] = 0; } } public: Student() { setName("None"); setID(10); num = 3; makeArray(); } Student(int n) { setName("None"); setID(10); if (n > 0) num = n; else num = 3; makeArray(); } Student(string nm, int i, int n) { setName(nm); setID(i); if (n > 0) num = n; else num = 3; makeArray(); } void setName(string nm) { name = nm; } void setID(int i) { if (i >= 10 && i <= 99){ id = i; } else { cout << "Error: Cannot set id to " << i << " for " << getName(); id = 10; } } void setScore(int i, int s) { if ((i >= 0 && i <= num) && (s >= 0 && s <= 100)) { //Here is where I set the values for the array. They come out correct in the console. testptr[i] = s; cout << testptr[i] << endl; } else { cout << "The test " << i << " cannot be set to " << s << " for " << getName() << endl; } } string getName() const { return name; } int getID() const { return id; } void showScore() { //This is where I print out the values of the array. They come out incorrect here. for (int i = 0; i < num; i++) { cout << "Test " << i << " had a score of " << testptr[i] << endl; } } void display() { cout << "Calling the display function" << endl; cout << "The Name: " << getName() << endl; cout << "The ID: " << getID() << endl; showScore(); } ~Student() { } }; int main() { Student c("Joe", 40, 5); c.setScore(0, 90); c.setScore(1, 91); c.setScore(2, 92); c.setScore(3, 93); c.setScore(4, 94); c.display(); /**int* testpointer; int num = 3; int array[num]; testpointer = &array[0]; for (int i = 0; i < num; i++) { testpointer[i] = i; cout << testpointer[i] << endl; }**/ } ```
2017/04/29
[ "https://Stackoverflow.com/questions/43691884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1730420/" ]
``` find . -type d -exec function.sh "{}" \; ```
50,342,462
I'm looking for help finding Python functions that allow me to take a list of strings, such as `["I like ", " and ", " because "]` and a single target string, such as `"I like lettuce and carrots and onions because I do"`, and finds all the ways the characters in the target string can be grouped such that each of the strings in the list comes in order. For example: ``` solution(["I like ", " and ", " because ", "do"], "I like lettuce and carrots and onions because I do") ``` should return: ``` [("I like ", "lettuce", " and ", "carrots and onions", " because ", "I ", "do"), ("I like ", "lettuce and carrots", " and ", "onions", " because ", "I ", "do")] ``` Notice that in each of the tuples, the strings in the list parameter are there in order, and the function returns each of the possible ways to split up the target string in order to achieve this. Another example, this time with only one possible way of organizing the characters: ``` solution(["take ", " to the park"], "take Alice to the park") ``` should give the result: ``` [("take ", "Alice", " to the park")] ``` Here's an example where there is no way to organize the characters correctly: ``` solution(["I like ", " because ", ""], "I don't like cheese because I'm lactose-intolerant") ``` should give back: ``` [] ``` because there is no way to do it. Notice that the `"I like "` in the first parameter cannot be split up. The target string doesn't have the string `"I like "` in it, so there's no way it could match. Here's a final example, again with multiple options: ``` solution(["I", "want", "or", "done"], "I want my sandwich or I want my pizza or salad done") ``` should return ``` [("I", " ", "want", " my sandwich ", "or", " I want my pizza or salad ", "done"), ("I", " ", "want", " my sandwich or I want my pizza ", "or", " salad ", "done"), ("I", " want my sandwich or I", "want", " my pizza ", "or", " salad ", "done")]` ``` Notice that, again, each of the strings `["I", "want", "or", "done"]` is included in each of the tuples, in order, and that the rest of the characters are reordered around those strings in any way possible. The list of all the possible reorderings is what is returned. Note that it's also assumed that the first string in the list will appear at the start of the target string, and the last string in the list will appear at the end of the target string. (If they don't, the function should return an empty list.) **What Python functions will allow me to do this?** I've tried using regex functions, but it seems to fail in the cases where there's more than one option.
2018/05/15
[ "https://Stackoverflow.com/questions/50342462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5049813/" ]
I have a solution, it needs a fair bit of refactoring but it seems to work, I hope this helps, it was quite an interesting problem. ``` import itertools import re from collections import deque def solution(search_words, search_string): found = deque() for search_word in search_words: found.append([(m.start()) for m in re.compile(search_word).finditer(search_string)]) if len(found) != len(search_words) or len(found) == 0: return [] # no search words or not all words found word_positions_lst = [list(i) for i in itertools.product(*found) if sorted(list(i)) == list(i)] ret_lst = [] for word_positions in word_positions_lst: split_positions = list(itertools.chain.from_iterable( (split_position, split_position + len(search_word)) for split_position, search_word in zip(word_positions, search_words))) last_seach_word = search_string[split_positions[-1]:] ret_strs = [search_string[a:b] for a, b in zip(split_positions, split_positions[1:])] if last_seach_word: ret_strs.append(last_seach_word) if len(search_string) == sum(map(len,ret_strs)): ret_lst.append(tuple(ret_strs)) return ret_lst print(solution(["I like ", " and ", " because ", "do"], "I like lettuce and carrots and onions because I do")) print([("I like ", "lettuce", " and ", "carrots and onions", " because ", "I ", "do"), ("I like ", "lettuce and carrots", " and ", "onions", " because ", "I ", "do")]) print() print(solution(["take ", " to the park"], "take Alice to the park")) print([("take ", "Alice", " to the park")]) print() print(solution(["I like ", " because "], "I don't like cheese because I'm lactose-intolerant")) print([]) print() ``` Outputs: ``` [('I like ', 'lettuce', ' and ', 'carrots and onions', ' because ', 'I ', 'do'), ('I like ', 'lettuce and carrots', ' and ', 'onions', ' because ', 'I ', 'do')] [('I like ', 'lettuce', ' and ', 'carrots and onions', ' because ', 'I ', 'do'), ('I like ', 'lettuce and carrots', ' and ', 'onions', ' because ', 'I ', 'do')] [('take ', 'Alice', ' to the park')] [('take ', 'Alice', ' to the park')] [] [] [('I', ' ', 'want', ' my sandwich ', 'or', ' I want my pizza or salad ', 'done'), ('I', ' ', 'want', ' my sandwich or I want my pizza ', 'or', ' salad ', 'done'), ('I', ' want my sandwich or I ', 'want', ' my pizza ', 'or', ' salad ', 'done')] [('I', ' ', 'want', ' my sandwich ', 'or', ' I want my pizza or salad ', 'done'), ('I', ' ', 'want', ' my sandwich or I want my pizza ', 'or', ' salad ', 'done'), ('I', ' want my sandwich or I', 'want', ' my pizza ', 'or', ' salad ', 'done')] ``` *Edit: refactored code to have meaningful variable names.* *Edit2: added the last case i forgot about.*
13,444,551
I have been staring at this all night now. I am trying to make a simple interactive ball game for Android, but I just can't seem to get the onFling method working. My logs that are in onFling don't appear in LogCat, and there is no response to a fling gesture. I think I'm doing something wrong with the gesturedetector or gesturelistener. Please help me out so I can finally go to sleep :) . This is my code: This is outside of onCreate, but still in the Activity: ``` @Override public boolean onTouchEvent(MotionEvent me) { return gestureDetector.onTouchEvent(me); } SimpleOnGestureListener simpleOnGestureListener = new SimpleOnGestureListener() { @Override public boolean onDown(MotionEvent e) { return true; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { ballSpeed.x = velocityX; ballSpeed.y = velocityY; Log.d("TAG", "----> velocityX: " + velocityX); Log.d("TAG", "----> velocityY: " + velocityY); return true; } }; GestureDetector gestureDetector = new GestureDetector(null, simpleOnGestureListener); ``` **EDIT:** Apparently the above code does work. That means that the mistake is somewhere else. @bobnoble says that I should post my onCreate() method: ``` @Override public void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); // hide title bar getWindow().setFlags(0xFFFFFFFF,LayoutParams.FLAG_FULLSCREEN| LayoutParams.FLAG_KEEP_SCREEN_ON); super.onCreate(savedInstanceState); setContentView(R.layout.main); // create pointer to main screen final FrameLayout mainView = (android.widget.FrameLayout) findViewById(R.id.main_view); // get screen dimensions Display display = getWindowManager().getDefaultDisplay(); try { display.getSize(size); screenWidth = size.x; screenHeight = size.y; } catch (NoSuchMethodError e) { screenWidth = display.getWidth(); screenHeight = display.getHeight(); } ballPosition = new android.graphics.PointF(); ballSpeed = new android.graphics.PointF(); // create variables for ball position and speed ballPosition.x = 4 * screenWidth / 5; ballPosition.y = 2 * screenHeight / 3; ballSpeed.x = 0; ballSpeed.y = 0; // create initial ball ballView = new BallView(this, ballPosition.x, ballPosition.y, 20); mainView.addView(ballView); // add ball to main screen ballView.invalidate(); // call onDraw in BallView //listener for touch event mainView.setOnTouchListener(new android.view.View.OnTouchListener() { public boolean onTouch(android.view.View v, android.view.MotionEvent e) { //set ball position based on screen touch ballPosition.x = e.getX(); ballPosition.y = e.getY(); ballSpeed.y = 0; ballSpeed.x = 0; //timer event will redraw ball return true; }}); } ```
2012/11/18
[ "https://Stackoverflow.com/questions/13444551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1270930/" ]
I put the code you provided into an `Activity`, commenting out the `ballSpeed` lines and added `Log` output. Works as expected. The logcat showing the output is at the end. If this does not work for you, the issue is somewhere else in your `Activity` code. You may want to post your `onCreate` method. ``` @Override public boolean onTouchEvent(MotionEvent me) { Log.i(TAG, "onTouchEvent occurred..."); return gestureDetector.onTouchEvent(me); } SimpleOnGestureListener simpleOnGestureListener = new SimpleOnGestureListener() { @Override public boolean onDown(MotionEvent e) { Log.i(TAG, "onDown event occurred..."); return true; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // ballSpeed.x = velocityX; // ballSpeed.y = velocityY; Log.d("TAG", "----> velocityX: " + velocityX); Log.d("TAG", "----> velocityY: " + velocityY); return true; } }; GestureDetector gestureDetector = new GestureDetector(null, simpleOnGestureListener); ``` Logcat shows multiple `onTouchEvent`s, the `onDown` and the `onFling` ``` 11-18 15:51:25.364: I/SO_MainActivity(13415): onTouchEvent occurred... 11-18 15:51:25.364: I/SO_MainActivity(13415): onDown event occurred... ... 11-18 15:51:25.584: I/SO_MainActivity(13415): onTouchEvent occurred... 11-18 15:51:25.604: I/SO_MainActivity(13415): onTouchEvent occurred... 11-18 15:51:25.664: D/TAG(13415): ----> velocityX: 3198.8127 11-18 15:51:25.664: D/TAG(13415): ----> velocityY: -1447.966 ``` Edit based on looking at the `onCreate` method: The `mainView.setOnTouchListener` `onTouch` method is consuming the touches by returning true. By returning true, the `onTouch` method is indicating it has completely handled the touch event, and not to propagate it further. Change it to `return false;` will cause it to propagate the touch event and you should see the other touch event methods getting called.
3,982,456
> > **Possible Duplicate:** > > [FindBugs for .Net](https://stackoverflow.com/questions/397641/findbugs-for-net) > > > I need something like [FindBugs](http://findbugs.sourceforge.net/) for C#/.NET ... Could you tell me where I can find something like this ? Thanks.
2010/10/20
[ "https://Stackoverflow.com/questions/3982456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/272774/" ]
[FxCop](http://msdn.microsoft.com/en-us/library/bb429476.aspx) is a static analysis tool for .NET that has the ability to detect various possible bugs as well as advise you of good programming practices and Microsoft naming conventions. It seems like Microsoft have stopped development on the standalone FxCop tool now in favour of encouraging you to buy a version of Visual Studio with the static code analysis built in (which I think for VS2010 is the "Premium" edition and above).
11,237,884
When I edit code in the middle of statements, it replaces the current code around it. I cannot find a way to replace this with a normal cursor that only inserts data instead of replacing it. Is that functionality possible in Eclipse? [![Look at the black cursor to the right of the 3rd statement](https://i.stack.imgur.com/Af1Lc.png)](https://i.stack.imgur.com/Af1Lc.png)
2012/06/28
[ "https://Stackoverflow.com/questions/11237884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1193857/" ]
The problem is also identified in your status bar at the bottom: [![overwrite label in status bar](https://i.stack.imgur.com/LeaRC.png)](https://i.stack.imgur.com/LeaRC.png) You are in overwrite mode instead of insert mode. **The “Insert” key toggles between insert and overwrite modes.**
54,588,347
I am encrypting a changeset with a bunch of optional fields, but I am currently using a ton of If statements to see if a changeset contains a field before trying to encrypt it. I have a feeling there is an Enum function (like reduce) that would do this in a way that is idiomatically more Elixir, but none of what I have come up with is more performant than a ton of ugly If statements. ``` def encrypt(changeset) do if changeset.changes["address"] do {:ok, encrypted_address} = EncryptedField.dump(changeset.changes.address, key_id) changeset |> put_change(:address, encrypted_address) end if changeset.changes["dob"] do {:ok, encrypted_dob} = EncryptedField.dump(changeset.changes.dob, key_id) changeset |> put_change(:address, encrypted_dob) end if changeset.changes["email"] do {:ok, encrypted_email} = EncryptedField.dump(changeset.changes.email, key_id) changeset |> put_change(:email, encrypted_email) end ... end ```
2019/02/08
[ "https://Stackoverflow.com/questions/54588347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10350915/" ]
All you need is to iterate through fields, conditionally updating the changeset: ```rb def encrypt(changeset) do Enum.reduce(~w[address dob email]a, changeset, fn field, changeset -> if changeset.changes[field] do {:ok, encrypted} = EncryptedField.dump(changeset.changes[field], key_id) put_change(changeset, field, encrypted) else changeset # unlike your implementation this works end end) end ``` --- Another way would be to [`Enum.filter/2`](https://hexdocs.pm/elixir/Enum.html#filter/2) the fields in the first place: ```rb def encrypt(changeset) do ~w[address dob email]a |> Enum.filter(&changeset.changes[&1]) |> Enum.reduce(changeset, fn field, changeset -> {:ok, encrypted} = EncryptedField.dump(changeset.changes[field], key_id) put_change(changeset, field, encrypted) end) end ``` --- *Sidenote:* according to style guidelines by the core team, pipes are to be used if and only there are many links in the chain. --- *Reply to the second answer:* Idiomatic code using `with` would be: ```rb def encrypt(changeset) do ~w[address dob email] |> Enum.reduce(changeset, fn field -> with %{^field => value} <- changeset.changes, {:ok, encrypted} <- EncryptedField.dump(value, key_id) do put_change(changeset, field, encrypted) else _ -> changeset end end) end ```
3,532,587
> > If $p,q,r,x,y,z$ are non zero real number such that > > > $px+qy+rz+\sqrt{(p^2+q^2+r^2)(x^2+y^2+z^2)}=0$ > > > Then $\displaystyle \frac{py}{qx}+\frac{qz}{ry}+\frac{rx}{pz}$ is > > > what try $(px+qy+rz)^2=(p^2+q^2+r^2)(x^2+y^2+z^2)$ $p^2x^2+q^2y^2+r^2z^2+2pqxy+2qryz+2prxz=p^2x^2+p^2y^2+p^2z^2+q^2x^2+q^2y^2+q^2z^2+r^2x^2+r^2y^2+r^2z^2$ $2pqxy+2qryz+2prxz=p^2y^2+p^2z^2+q^2x^2+q^2z^2+r^2x^2+r^2y^2$ How do i solve it Help me please
2020/02/03
[ "https://math.stackexchange.com/questions/3532587", "https://math.stackexchange.com", "https://math.stackexchange.com/users/14096/" ]
Write $v=(p,q,r)$ and $w=(x,y,z)$. Then the given relation states $$v\cdot w+|v||w|=0$$ But $v\cdot w=|v||w|\cos\theta$ where $\theta$ is the angle between them, so $$|v||w|(\cos\theta+1)=0$$ Since none of the scalars are zero, we get $\cos\theta=-1$, so $v=kw$ for some nonzero $k\in\mathbb R$ and $$\frac{py}{qx}+\frac{qz}{ry}+\frac{rx}{pz}=\frac{kxy}{kyx}+\frac{kyz}{kzy}+\frac{kzx}{kxz}=3$$
69,942,096
I've written a console application (.NET 5.0) in C# in Visual Studio which sorts an array from high to low and then it has to print out the second largest element in that array. Im getting close but ive been trying things for the past 2 hours and I don't get why I always get an out of bounds error at the last 'if'. The program is supposed to detect duplicates so for instance if the input is '1 1 2 2 5 5 9 9" it will print out "5" as it is the second largest. My current code is below I can't get it to work without crashing using System; ``` namespace second_largest { class Program { static void Main(string[] args) { double[] input = Array.ConvertAll(Console.ReadLine().Split(" "), Convert.ToDouble); for (int repeat = 0; repeat < input.Length; repeat++) { for (int j = 0; j < input.Length - 1; j++) { if(input[j] < input[j+1]) { double temp = input[j]; input[j] = input[j + 1]; input[j + 1] = temp; } } } for (int i = 0; i < input.Length; i++) { if(input[i] == input[i + 1]) { } else { Console.WriteLine(input[i]); } Console.WriteLine(input[i]); } } } } ```
2021/11/12
[ "https://Stackoverflow.com/questions/69942096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17057956/" ]
You see the error because you iterate up to `i < input.Length` which means that `i + 1` on the following if statement is out of bounds of the length of the input array. You need to do the same thing you've done on the previous nested for loop: `for(int i = 0; i < input.Length - 1; i++)`
23,140,033
``` { * * AControl: Control handle determined by Spy++ (e.g. 0037064A) * ANewText: Text to assign to control * AWinTitle: Window Title/Caption * } function ControlSetText(const AControl, ANewText, AWinTitle: string): boolean; function EnumChildren(AWindowHandle: HWND; ALParam: lParam): bool; stdcall; begin ShowMessage(AControl); // if commented out - code works fine TStrings(ALParam).Add(IntToStr(GetDlgCtrlID(AWindowHandle))); Result := true; end; var _MainWindowHandle: HWND; _WindowControlList: TStringlist; i: integer; _ControlHandle: integer; begin Result := false; _MainWindowHandle := FindWindow(nil, PWideChar(AWinTitle)); if _MainWindowHandle <> 0 then begin _WindowControlList := TStringlist.Create; try if TryStrToInt('$' + Trim(AControl), _ControlHandle) then try EnumChildWindows(_MainWindowHandle, @EnumChildren, UINT_PTR(_WindowControlList)); for i := 0 to _WindowControlList.Count - 1 do begin if (StrToInt(_WindowControlList[i]) = _ControlHandle) then begin SendMessage(StrToInt(_WindowControlList[i]), WM_SETTEXT, 0, integer(PCHAR(ANewText))); Result := true; end; end; except on E: Exception do MessageDlg(E.Message, TMsgDlgType.mtError, [TMsgDlgBtn.mbOK], 0) end; finally FreeAndNil(_WindowControlList); end; end; end; ``` The debugger raises an exception with the message > > --------------------------- Debugger Exception Notification --------------------------- > > > Project Default\_project.exe raised exception class $C0000005 with message 'access violation at > 0x00406fae: write of address 0x00408dbb'. > > > It breaks at: ``` for i := 0 to _WindowControlList.Count - 1 do ``` I call it like this: ``` ControlSetText('00070828', 'New TEdit text', 'Delphi_test_app'); ``` I am planning an update, so, not only control handle could be passed, but also control type+identifier e.g. 'Edit1'. EDIT: What I am trying is to do is to implement <http://www.autohotkey.com/docs/commands/ControlSetText.htm>
2014/04/17
[ "https://Stackoverflow.com/questions/23140033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2578854/" ]
The problem is that your callback is a local nested function. That is it is nested inside `ControlSetText`. It must be declared at global scope. Any extra state information must be passed in through the `lParam` parameter. I also find it odd that you store integers and pointers in strings. Store them as integers or pointers. In fact it is more than odd. You put control ids in the list, as strings, but then use them as window handles. So once you get past the crash the code won't work. I don't want to get into debugging that in this question.
2,285,472
``` class User < ActiveRecord::Base has_one :location, :dependent => :destroy, :as => :locatable has_one :ideal_location, :dependent => :destroy, :as => :locatable has_one :birthplace, :dependent => :destroy, :as => :locatable end class Location < ActiveRecord::Base belongs_to :locatable, :polymorphic => true end class IdealLocation < ActiveRecord::Base end class Birthplace < ActiveRecord::Base end ``` I can't really see any reason to have subclasses in this situation. The behavior of the location objects are identical, the only point of them is to make the associations easy. I also would prefer to store the data as an int and not a string as it will allow the database indexes to be smaller. I envision something like the following, but I can't complete the thought: ``` class User < ActiveRecord::Base LOCATION_TYPES = { :location => 1, :ideal_location => 2, :birthplace => 3 } has_one :location, :conditions => ["type = ?", LOCATION_TYPES[:location]], :dependent => :destroy, :as => :locatable has_one :ideal_location, :conditions => ["type = ?", LOCATION_TYPES[:ideal_location]], :dependent => :destroy, :as => :locatable has_one :birthplace, :conditions => ["type = ?", LOCATION_TYPES[:birthplace]], :dependent => :destroy, :as => :locatable end class Location < ActiveRecord::Base belongs_to :locatable, :polymorphic => true end ``` With this code the following fails, basically making it useless: ``` user = User.first location = user.build_location location.city = "Cincinnati" location.state = "Ohio" location.save! location.type # => nil ``` This is obvious because there is no way to translate the :conditions options on the has\_one declaration into the type equaling 1. I could embed the id in the view anywhere these fields appear, but this seems wrong too: ``` <%= f.hidden_field :type, LOCATION_TYPES[:location] %> ``` Is there any way to avoid the extra subclasses or make the LOCATION\_TYPES approach work? In our particular case the application is very location aware and objects can have many different types of locations. Am I just being weird not wanting all those subclasses? Any suggestions you have are appreciated, tell me I'm crazy if you want, but would you want to see 10+ different location models floating around app/models?
2010/02/18
[ "https://Stackoverflow.com/questions/2285472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/86820/" ]
Why not use named\_scopes? Something like: ``` class User has_many :locations end class Location named_scope :ideal, :conditions => "type = 'ideal'" named_scope :birthplace, :conditions => "type = 'birthplace" # or whatever end ``` Then in your code: ``` user.locations.ideal => # list of ideal locations user.locations.birthplace => # list of birthplace locations ``` You'd still have to handle setting the type on creation, I think.
15,074,078
I am using GNU Make and would like it to add a prefix to each recipe command as it's echoed. For example, given this makefile: ``` foo: echo bar echo baz ``` Actual behavior: ``` $ make -B foo echo bar bar echo baz baz ``` Desired behavior: ``` $ make -B foo + echo bar bar + echo baz baz ``` (In this case, `+` is the prefix.) It would be nice if I could configure what the prefix is, but that's not essential.
2013/02/25
[ "https://Stackoverflow.com/questions/15074078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/396038/" ]
The easiest way is to change the `SHELL` make variable. In this case, running the shell with the `-x` parameter should do the trick. Something like ``` $ make SHELL:='bash -x' ``` Or even ``` $ make .SHELLFLAGS:='-x -c' ``` in this case. For more sophisticated output a quick shell script fits the bill: ``` $ cat script #!/bin/bash echo "EXECUTING [$*]" $* ``` followed by ``` $ make SHELL:=./script .SHELLFLAGS:= ```
41,612,974
I have a clock written with pure Javascript and CSS. Every time when new minute begins, my const which is responsible for rotating clocks hands is recalculated to first value (90deg). It causes problem because the clock's hand should rotate back to the first position from the end. I would like that my rotate value will not restart and always go on new minute\hour with current rotate value. [Check my demo](http://codepen.io/Zharkov/pen/dNMJZM) What I do? **CSS** ``` .clock { width: 20rem; height: 20rem; border: 1px solid rgba(0, 0, 0, .3); background: #ffafbd; /* Old browsers */ background: -moz-linear-gradient(top, #ffafbd 0%, #ffc3a0 100%); /* FF3.6-15 */ background: -webkit-linear-gradient(top, #ffafbd 0%, #ffc3a0 100%); /* Chrome10-25,Safari5.1-6 */ background: linear-gradient(to bottom, #ffafbd 0%, #ffc3a0 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */ filter: progid: DXImageTransform.Microsoft.gradient( startColorstr='#ffafbd', endColorstr='#ffc3a0', GradientType=0); /* IE6-9 */ border-radius: 50%; margin: 50px auto; position: relative; padding: 2rem; } .clock-face { position: relative; width: 100%; height: 100%; transform: translateY(-3px); /* account for the height of the clock hands */ } .hand { width: 50%; height: 2px; background: #4568dc; /* Old browsers */ background: -moz-linear-gradient(top, #4568dc 0%, #b06ab3 100%); /* FF3.6-15 */ background: -webkit-linear-gradient(top, #4568dc 0%, #b06ab3 100%); /* Chrome10-25,Safari5.1-6 */ background: linear-gradient(to bottom, #4568dc 0%, #b06ab3 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */ filter: progid: DXImageTransform.Microsoft.gradient( startColorstr='#4568dc', endColorstr='#b06ab3', GradientType=0); /* IE6-9 */ position: absolute; top: 50%; transform: rotate(90deg); transform-origin: 100%; transition: transform .2s cubic-bezier(0, 2.48, 0.72, 0.66); } .hour-hand { top: 45%; left: 32.5%; width: 35%; transform-origin: 75%; } ``` **JavaScript** ``` const secondHand = document.querySelector(".second-hand"); const minutesHand = document.querySelector(".min-hand"); const hourHand = document.querySelector(".hour-hand"); function getDate() { const now = new Date(); const seconds = now.getSeconds(); const secondsRotate = ((seconds / 60) * 360) + 90; secondHand.style.transform = `rotate(${secondsRotate}deg)`; const minutes = now.getMinutes(); const minutesRotate = ((minutes / 60) * 360) + 90; minutesHand.style.transform = `rotate(${minutesRotate}deg)`; const hours = now.getHours(); const hoursRotate = ((hours / 12) * 360) + 90; hourHand.style.transform = `rotate(${hoursRotate}deg)`; console.log(hours); } setInterval(getDate, 1000); ```
2017/01/12
[ "https://Stackoverflow.com/questions/41612974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6182081/" ]
Why do you want to use a list of dataframes? You can easily put all data in one dataframe: ``` library(dplyr) df = bind_rows(myList, .id="name") # new Variable threshold df %>% mutate(threshold = ifelse(pos.score >=18, "good", "bad")) ``` now you can filter and select your data within this dataframe (or even split it into a list of dataframes.)
5,174,860
could please anybody provide a sample how to do this ? I'm not talking about form validation, but for instance when a user clicks a button in an auction system and it is too late - a fancy message pops up. Is there anything like this in YUI api, or some widget ?
2011/03/02
[ "https://Stackoverflow.com/questions/5174860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/306488/" ]
Y.Overlay is the widget to use here. <http://developer.yahoo.com/yui/3/overlay/> ``` var overlay = new Y.Overlay({ width:"40em", visible:false, center: true, zIndex:10, headerContent: "Uh oh!" }).render("#somewhere"); ``` This will create the Overlay in the DOM, but it will be hidden. In response to an error, you would then do ``` overlay.set('bodyContent', "The error message"); overlay.show(); ``` Overlay does not come with a default skin, so you'll need to include css to style it like your app. Check out the user guide or just inspect the rendered Overlay in FireBug or Web Inspector to see the DOM and class structure for skinning.
3,957,082
I have a class that takes many arguments to create. It’s a sort of an audio processor that needs a sample rate, sample resolution, number of channels etc. Most of the parameters have sane defaults. And most of them should be only settable in the initializer (constructor), because it makes no sense to change them afterwards. I do not want to create a gargantuan initializer with all the parameters because (1) it would be huge and essentially it would only copy the passed values, doing no real work, and (2) the user would have to specify values for all the parameters. What’s a good way to solve this? I’ve tried writing getters and setters for the params. This means that I could not create the “real” audio processing unit in the constructor, since the parameter values are not known then. I had to introduce a new method (say `prepareForWork`) so that the users can do something like: ``` AudioProcessor *box = [[AudioProcessor alloc] init]; [box setSampleRate:…]; [box setNumberOfChannels:…]; [box prepareForWork]; [box doSomeProcessing]; ``` This is nice because it does not require an unwieldy constructor. Also the defaults are set in the initializer which means that I can take a fresh `AudioProcessor` instance and it could still do some work. The flip side is that (1) there is an extra method that has to be called before the instance can do any real work and (2) the class should refuse to change any of the parameters after `prepareForWork` was called. Guarding both these invariants would take some boilerplate code that I don’t like. I thought I could create a special “preset” class that would look like this: ``` @interface SoundConfig : NSObject { NSUInteger numberOfChannels; NSUInteger sampleResolution; float sampleRate; } ``` And then require an instance of this class in the `AudioProcessor` initializer: ``` @interface AudioProcessor : NSObject {…} - (id) initWithConfig: (SoundConfig*) config; ``` Default values would be set in the `SoundConfig` initializer, the `AudioProcessor` constructor would be simple and there would be no invariants to keep watching by hand. Another approach I thought of was a kind of `AudioProcessorBuilder` class. You would create an instance of that, set the audio params through accessors and then finally it would build an `AudioProcessor` instance for you, setting all the properties through a non-public setters so that you could not change them later (and break the invariant). Now that I write this I favour the `SoundConfig` approach. How do you solve this, is there a better approach?
2010/10/18
[ "https://Stackoverflow.com/questions/3957082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17279/" ]
See how `NSURLConnection` is implemented and [used](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html). It uses an `NSURLRequest` object to parameterise it, similarly to the way your `SoundConfig` object parameterises the `AudioProcessor` object.
7,288,222
I want to inject a DLL into a process. Once this DLL is in there, it should catch & properly handle **all** access violation exceptions which occur in the process. Is there any way to accomplish this?
2011/09/02
[ "https://Stackoverflow.com/questions/7288222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How about SetUnhandledExceptionFilter( **function** )? **function**'s prototype is: ``` LONG __stdcall ExceptionHandler(EXCEPTION_POINTERS *ExceptionInfo); ``` I've used this function to create crash dumps, etc.