qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
list
response
stringlengths
0
115k
311,206
In the below config I want to remove the body field from **content** and add it in **hidden** as **body: true** when I uninstall the layout module. *Basically when I install the layout module the fields in manage display should get disabled/hidden and when I uninstall the module the fields should be displayed.* How can I achieve this programatically? This config code is of `entity_view_display.node.article.default` ``` uuid: eedc35e4-0592-4f1a-bdc6-47dbf60fa929 langcode: en status: true dependencies: config: - field.field.node.article.body - field.field.node.article.comment - field.field.node.article.field_image - field.field.node.article.field_media - field.field.node.article.field_sample_text - field.field.node.article.field_tags - node.type.article module: - layout_builder - text - user third_party_settings: layout_builder: enabled: false allow_custom: false id: node.article.default targetEntityType: node bundle: article mode: default content: body: type: text_default label: above settings: { } third_party_settings: { } weight: 0 region: content hidden: comment: true field_image: true field_media: true field_sample_text: true field_tags: true langcode: true links: true search_api_excerpt: true ```
2022/05/18
[ "https://drupal.stackexchange.com/questions/311206", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/106781/" ]
I have solved the issue. Instead of `\Drupal::entityTypeManager()` I used ``` $articleDefaultLayout = LayoutBuilderEntityViewDisplay::load( 'node.article.default' ); $articleDefaultLayout->setComponent('body'); ```
60,515,444
I am trying to compute average scores for responses to different events. My data is in long format with one row for each event, sample dataset `data` here: ``` Subject Event R1 R2 R3 R4 Average 1 A 1 2 2 N/A 2.5 1 B 1 1 1 1 1 ``` So to get the average for event A, it would be (R1 + R2 + R3)/3 ignoring the N/A, whereas event B has 4 responses. I computed the average for Event A in `dplyr` as: ``` data$average <- data%>%filter(Event == "A") %>% with(data, (R1 + R2 + R3)/4) ``` I ran into problems when I tried to do the same for the next event...Thank you for the help!
2020/03/03
[ "https://Stackoverflow.com/questions/60515444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11510607/" ]
You don't need to filter for each event at a time. `dplyr` is able to process all rows at once, one by one. Also when using `dplyr`, you don't need to assign to a variable outside of its context, such as `data$average <- (something)`. You can use `mutate()`. So the intuitive syntax for `dplyr` would be: ``` data <- data %>% mutate(average = mean(c(R1, R2, R3, R4), na.rm = TRUE)) ```
10,367,957
I have noticed a high memory and CPU usage during mvn-gwt operation especially during compile phase. Memory usage just soars. I just wanna know if this is normal and if anyone else is experiencing this. My current JVM setting is `-Xms64m -Xmx1280m -XX:MaxPermSize=512m` ![Memory usage during GWT Compile](https://i.stack.imgur.com/KGqCy.png)
2012/04/28
[ "https://Stackoverflow.com/questions/10367957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/680915/" ]
I think it's normal. Because the phase of compilation in GWT is really very resource-intensive. GWT provides a larger library (in gwt-user.jar) that must be analyzed during compilation and a number of compiler optimizations that require much memory and processing power. Thus, the GWT compiler use much memory internally.
43,590
I'm planning to travel from Osaka to Tokyo and back, and since the ride will be long, I think it's the perfect time to make friends. However, I'm unsure how the Japanese see this kind of behaviour - a stranger suddenly conversing with them who is a foreigner. Is it considered rude? Is it a case-to-case basis? --- Additional info : I can speak Japanese. I've been studying it for a year. I am at a conversational level but still not as good as locals and I may not know some words they might throw at me.
2015/02/20
[ "https://travel.stackexchange.com/questions/43590", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/18310/" ]
I haven't found Japanese as chatty as Europeans or Americans, but there are some friendly people who would want to chat with a foreigner. You won't know until you try. Old ladies and people with families tend to be the most chattiest -- young women and businessmen tend to be the least. There's a stereotype (that I've found to be true) that folks from Osaka tend to be much friendlier than those from Tokyo. You should be aware that it's only 2 hours on the Shinkansen, which in Japan is not considered a very long train ride (some people have daily 2 hour train ride commutes). But still, you might strike up a conversation. I'd suggest riding in the regular car (not Green Car), maybe taking the Hikari instead of the Nozomi, and asking to get your seat in the non-reserved section so you can deliberately sit near someone who looks friendly.
68,336,320
I'm currently trying to write a simple C#-WPF-Application that functions as a simple universal 'launcher'. For different applications we program. It's purpose is to check the current software version of the 'real' software and if a new one is available it starts to copy the installer from a network share and runs the installer afterwards. Then it starts the 'real' application and thats it. The user Interface mainly consists of a startup window which shows the user the currently executed action (version check, copy, installation, startup, ...). Now I create my view and my viewModel in the overridden StartUp method in App.cs ``` public override OnStartup(string[] args) { var viewModel = new StartViewModel(); var view = new StartView(); view.DataContext = viewModel; view.Show(); // HERE the logic for the Launch starts Task.Run(() => Launch.Run(args)); } ``` The problem is that if I don't go async here the Main Thread is blocked and I cannot update the UI. Therefore I got it working by using the `Task.Run(...)`. This solves my problem of blocking the UI thread, but I have some problems/questions with this: 1. I cannot await the task, because that would block the UI again. Where to await it? 2. Is my concept of starting this workflow here ok in the first place? --- Some update to clarify: After I show the UI to the user my logic starts to do heavy IO stuff. The possible calls I came up with are the following 3 variants: ``` view.Show(); // v1: completely blocks the UI, exceptions are caught DoHeavyIOWork(); // v2: doesn't block the UI, but exceptions aren't caught Task.Run(() => DoHeavyIOWork()); // v3: doesn't block the UI, exceptions are caught await Task.Run(() => DoHeavyIOWork()); ``` Currently I'm not at my work PC so i apologies for not giving you the original code. This is an on the fly created version. I guess v1 and v2 are bad because of exceptions and the UI blocking. I thought v3 didn't work when I tried it in my office. Now it seems to work in my local example. But I'm really not sure about v3. Because I'm using `async void StartUp(...)` there. Is it okay here?
2021/07/11
[ "https://Stackoverflow.com/questions/68336320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12165174/" ]
> > I cannot await the task, because that would block the UI again. Where to await it? > > > `await` doesn't block the UI. Using `await` here is fine. > > Is my concept of starting this workflow here ok in the first place? > > > I usually recommend that *some* UI is shown immediately when doing any asynchronous operation. Then when the async operation is complete, you can update/replace the UI.
36,515,177
So I'm fooling around a bit with Haskell, trying to learn it by myself. I'm trying to solve a certain question where I'm supposed to create a list of random numbers and then sum them up. I have the code to generate them - using `getStdRandom` and `randomR`. Using them both returns a list of `IO Float`: `[IO Float]` Now, when I try to sum up the list using say foldl or foldr, or even trying a simple recursion summation, I get errors and such - to my understanding this is because `IO Float` is a monad, so I need to do some Haskell magic to get it to work. I've been googling around and haven't found something that works. Is there any way to sum up the list? or even convert it into a list of floats so that its easier to work around in other parts of the code?
2016/04/09
[ "https://Stackoverflow.com/questions/36515177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/475680/" ]
Note that a list with type `[IO Float]` is **not** a list of numbers. It is a list of I/O actions that *generate* numbers. The I/O wasn't executed yet, so in your case the random number generator hasn't actually generated the numbers. You can use the [`sequence :: Monad m => [m a] -> m [a]`](http://hackage.haskell.org/package/base-4.8.2.0/docs/Prelude.html#v:sequence) function to combine the list of IO actions into a single IO action that provides a list of results: ``` do the_numbers <- sequence your_list return $ sum the_numbers ``` Alternatively you could use the [`foldM`](http://hackage.haskell.org/package/base-4.8.2.0/docs/Control-Monad.html#v:foldM) function to write a monadic fold: ``` sumIONumbers :: [IO Float] -> IO Float sumIONumbers xs = foldM f 0.0 xs where f acc mVal = do val <- mVal -- extract the Float from the IO return $ acc + val ``` --- As noted in the comments you can also make use of the fact that every `Monad` is also a `Functor` (this is enforced in newer versions) and thus you can use [`fmap :: Functor f => (a -> b) -> f a -> f b`](http://hackage.haskell.org/package/base-4.8.2.0/docs/Prelude.html#v:fmap) to apply a function inside the IO: ``` fmap sum (sequence your_list) ``` Or use the infix synonym [`<$>`](http://hackage.haskell.org/package/base-4.8.2.0/docs/Prelude.html#v:-60--36--62-): ``` sum <$> sequence your_list ```
44,241,464
Data (snippet) in node file: ``` C0243192 C1522005 C1524024 C1524059 C1623416 C1959616....... ``` Header file for Node file: ``` conceptID:ID ``` Relationship(snippet) file date: ``` C0000039,C0001555,AQ_ C0000039,C0001688,AQ_ C0000039,C0002776,AQ_ ..... ``` Header file for relationship file: ``` :START_ID,:END_ID,:TYPE ``` When I try to run bulk import script as ``` neo4j-import --into graph.db --nodes:concept "MRREl-nodes,nheader" --relationships "MRREl-relations,rheader" --deliminiter , --skip-duplicate-node true ``` I get error: ``` Error in input data Caused by:Missing header of type START_ID, among entries [C0000005:string, C0036775:string, RB_:string] ```
2017/05/29
[ "https://Stackoverflow.com/questions/44241464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2717058/" ]
There are two places where this can happen ``` n, r = map(int, input().split()) ``` and ``` n1, n2 = map(int, input().split()) ``` In both cases you are assuming that the input contains only two values. What if there are 3 or 20? Try something like ``` for x in map(int, input().split()): # code here ``` Or wrap the whole thing in try/except so that too many values will be handled cleanly. Your for loop can probably just be ``` for i in range(2 , n): n_list.append(map(int, input().split()) ```
8,031
I am working through Liddle's "An Introduction to Modern Cosmology", and in a newtonian derivation of the Friedman equation he states: > > in a spherically symmetric distribution of matter, a particle feels no force at all from the material at greater radii, and the material at smaller radii gives exactly the force which one would get if all the material was concentrated at the central point. > > > He attributes this result to Newton, Can anyone give a mathematical or physical explanation as to why this is true? Thanks
2014/11/23
[ "https://astronomy.stackexchange.com/questions/8031", "https://astronomy.stackexchange.com", "https://astronomy.stackexchange.com/users/2869/" ]
The original result is Newton's [shell theorem](https://en.wikipedia.org/wiki/Shell_theorem). Since we can break up a spherically symmetric distribution into spherically symmetric concentric shells, it is sufficient to consider the corresponding statement for one such shell: for each shell taken *individually*, there is no force on a particle inside, and a force on a particle outside as if all of the mass was concentrated at the center. This can be derived directly from Newton's law of gravitation through careful integration (one such derivation in the wiki link above), but probably the cleanest method is rather through Gauss's law, which states that the divergence of the gravitational field is proportional to the mass density: $$\nabla\cdot\mathbf{g} = -4\pi G\rho\text{.}$$ It's just the same as the law for the electric field because Coulomb's law and Newton's law of gravitation have the same form (with $\epsilon\_0\mapsto-(4\pi G)^{-1}$). By the [divergence theorem](https://en.wikipedia.org/wiki/Divergence_theorem), the flux through a surface enclosing volume $V$ is proportional to the enclosed mass: $$\int\_{\partial V}\mathbf{g}\cdot\mathrm{d}\mathbf{S} = \int\_V\nabla\cdot\mathbf{g}\,\mathrm{d}V = -4\pi GM\_\text{enc}\text{,}$$ since then we are just integrating the density over the entire volume. But each shell should have a spherically symmetric gravitational field, so $\mathbf{g} = g\hat{\mathbf{r}}$, where $g = g(r)$ is a function of radius only. Since the Gaussian surface has constant $r$, all we get is $g(r)$ times its area: $$-4\pi GM\_\text{enc} = g(r)\int\_{\partial{V}}\mathrm{d}\mathbf{S} = 4\pi r^2 g(r)\text{,}$$ and it follows that $$\mathbf{g} = -\frac{GM\_\text{enc}}{r^2}\text{.}$$ Obviously, if the particle is inside the shell, the Gaussian surface encloses no mass, since again we are considering each shell individually. The total effect of a spherically symmetric distribution would just be the sum of the effects of each individual shell.
8,604,499
I am using AQGridView in my project. we need to create a black colored border around each image. Can anyone help me on this. Thanks in advance. Regards, Jas.
2011/12/22
[ "https://Stackoverflow.com/questions/8604499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/978091/" ]
You can create two user defined functions and use them as per your need. This will offer more generic solution. ``` [jaypal:~/Temp] cat file a 212 b 323 c 23 d 45 e 54 f 102 [jaypal:~/Temp] awk ' function max(x){i=0;for(val in x){if(i<=x[val]){i=x[val];}}return i;} function min(x){i=max(x);for(val in x){if(i>x[val]){i=x[val];}}return i;} {a[$2]=$2;next} END{minimum=min(a);maximum=max(a);print "Maximum = "maximum " and Minimum = "minimum}' file Maximum = 323 and Minimum = 23 ``` In the above solution, there are 2 user defined functions - `max` and `min`. We store the column 2 in an array. You can store each of your columns like this. In the `END` statement you can invoke the function and store the value in a variable and print it. Hope this helps! **Update:** Executed the following as per the latest example - ``` [jaypal:~/Temp] awk ' function max(x){i=0;for(val in x){if(i<=x[val]){i=x[val];}}return i;} function min(x){i=max(x);for(val in x){if(i>x[val]){i=x[val];}}return i;} /^#/{next} {a[$6]=$6;next} END{minimum=min(a);maximum=max(a);print "Maximum = "maximum " and Minimum = "minimum}' sample Maximum = 222 and Minimum = 3.01 ```
3,927
I've been wanting to post on this for some time, but don't want to post something just to have it shut down as a duplicate because it talks about disabilities and someone else has already posted about disabilities. Autism Spectrum has some fairly unique problems specific to the workplace that other disabilities do not, because we seem relatively normal, especially on the high end, but our communication skills and behaviors can cause trouble for us. In short, we can come across as jerks when we don't intend to, and that's something that other disabilities don't have to face. You don't consider someone who is deaf to be rude for not hearing you for example. I would like to pose a question or two asking for advice on how to deal with AS in the workplace, but would like to ensure it's on topic. What is the best way to do so?
2016/09/21
[ "https://workplace.meta.stackexchange.com/questions/3927", "https://workplace.meta.stackexchange.com", "https://workplace.meta.stackexchange.com/users/46894/" ]
I deal with aspbergers as well so please do not think that I am dismissing your needs or concerns. SE is designed around providing answers to questions that will potentially help many people. So when asking any question it is important to make sure that your question is as broadly applicable as possible. If your question is only applicable to your specific situation at a specific point in time then it is better to ask in Chat or elsewhere. But if your situation can be generalized into one that you deal with often or even just a few times chances are that other people deal with that same general situation so your question could be helpful. But make sure when generalizing the question that you do not go so generic that the solutions provided are not useful because they miss important parts. Right now you are probably thinking boy that's a tough ask, and it is. These types of questions can work here but the vast majority of them will either be too broad or too specific. We can save some of them with edits but the more the OP can do to make it a better question in the first place the more helpful the answers are likely to be to them. Second you have to make sure you provide a goal that you want to achieve. "This is my situation, what should I do?" How many hundreds of these have we seen in the last few months. They get closed usually and just as often as not end up with a lot of useless answers. Instead make sure you have a "This is my situation, I want to achieve X, how can I do that given these conditions" question. And make sure that X is in the scope of the workplace. This is not a Q&A about special needs and situations, it is about the workplace. Make sure that the context of the question is clearly in the scope of that. Finally, try to stay out of comment wars. I struggle with this as well. But if an answer is not helpful just down vote it and move on. Questions that generate lots of comments get more attention in a bad way. Questions that are borderline are more likely to get closed if they are controversial than if they just get answers but no comment wars. When the OP of the question gets involved in comment wars I have noticed the questions tend to get closed quickly.
16,443,223
I am working n getting the source code of remote page the url of that remote page it got dynamically from the url the user click according to the arrays `array('event_id', 'tv_id', 'tid', 'channel')` : i use the code below to get the who;e page source and it works great. ``` <?php $keys = array('event_id', 'tv_id', 'tid', 'channel'); // order does matter $newurl = 'http://lsh.streamhunter.eu/static/popups/'; foreach ($keys as $key) $newurl.= empty($_REQUEST[$key])?0:$_REQUEST[$key]; $newurl.='.html'; function get_data($newurl) { $ch = curl_init(); $timeout = 5; //$userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US)AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.X.Y.Z Safari/525.13."; $userAgent = "IE 7 – Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30)"; curl_setopt($ch, CURLOPT_USERAGENT, $userAgent); curl_setopt($ch, CURLOPT_FAILONERROR, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_AUTOREFERER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 10); curl_setopt($ch,CURLOPT_URL,$newurl); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout); $data = curl_exec($ch); curl_close($ch); return $data; } $html = get_data($newurl); echo $html ?> ``` the trick here is that i want to echo only line no 59 of the code how to do so?
2013/05/08
[ "https://Stackoverflow.com/questions/16443223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2362208/" ]
The dump from ncdump -k gives the netcdf file format as netCDF-4. I was able to open the file with the `ncdf4` package since ncdf does not seem to be backwards compatible with version 4 files: > > "However, the ncdf package does not provide an interface for netcdf > version 4 files." > > > from the `ncdf4` documentation. ``` library(ncdf4) mycdf <- nc_open(file.choose(), verbose = TRUE, write = FALSE) timedata <- ncvar_get(mycdf,'time') lat <- ncvar_get(mycdf,'latitude') long <- ncvar_get(mycdf,'longitude') harvestdata <- ncvar_get(mycdf,'harvest') str(harvestdata) ``` gives ``` num [1:79, 1:78, 1:32, 1:199] NA NA NA NA NA NA NA NA NA NA ... ```
33,644,839
I am having an issue in Visual Studio 2015 (VB.Net) where the Navigation Bar is not showing. I have set the settings in Tools > Options > Text Editor > All Languages and set the "Navigation Bar" setting to checked. The bar will show up for a second and then disappear. I have tried it in Safe Mode and still the same. I have tried editing the CurrentSettings.vssettings and it shows when you load but again it then disappears. Any Thoughts?
2015/11/11
[ "https://Stackoverflow.com/questions/33644839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5549372/" ]
Try this: **uncheck** the checkbox in tools\options\text editor\all languages\general\navigation bar and click OK. This is unintuitive, but then--come back to the same checkbox, which should now be Unchecked, check it, and click OK. This has worked for me. Why the navigation bar disappears randomly is a mystery.
30,350,208
My models CAR BRANDS MODEL ``` class CarBrand < ActiveRecord::Base has_many :car_ads end ``` CAR ADVERTISEMENTS MODEL ``` class CarAd < ActiveRecord::Base has_one :car_brand end ``` my controller: ``` def index @car_ads = CarAd.all.order("car_ads.created_at DESC") end ``` car ads migrations: ``` class CreateCarAds < ActiveRecord::Migration def up create_table :car_ads do |t| t.integer "user_id" t.integer "car_brand_id" t.integer "car_model_id" t.integer "state_id", :limit => 2 t.integer "vin_id" t.integer "year_manufac", :precision => 4 t.integer "km_age" t.integer "price_usd", :limit => 7 t.integer "car_tel_number", :precision => 8 t.float "motor_volume", :limit => 10 t.string "transmission" t.integer "horse_power", :limit => 3 t.text "description" t.boolean "visible", :default => true t.boolean "active", :default => true t.string "photo_file_name" t.string "photo_content_type" t.integer "photo_file_size" t.datetime "photo_updated_at" t.timestamps null: false end add_index :car_ads, :user_id add_index :car_ads, :car_brand_id add_index :car_ads, :car_model_id add_index :car_ads, :state_id add_index :car_ads, :vin_id end def down drop_table :car_ads end end ``` Car brands migratiions ``` class CreateCarBrands < ActiveRecord::Migration def up create_table :car_brands do |t| t.string "brand", :limit => 20 t.timestamps null: false end end def down drop_table :car_brands end end ``` so the problem is that i cant get car brand form car ads, please help, i wanted to get that like iterating ``` <% @car_ads.each do |carad|%> <%= carad.car_brand %> <%end%> ```
2015/05/20
[ "https://Stackoverflow.com/questions/30350208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4666863/" ]
Put `ng-cloak` at your controller definition (or wherever you don't want to see the template rendering... specs recommend placing it in small portions of the page): ``` <div ng-controller="MyCtrl" ng-cloak> ``` <https://docs.angularjs.org/api/ng/directive/ngCloak>
58,452,256
I recently update my spring boot app 2.1.9 to 2.2.0 and i'm facing a problem. When i'm calling "configprops" from actuator endpoint, an exception is throw : Scope 'job' is not active for the current thread I reproduce the bug : <https://github.com/guillaumeyan/bugspringbatch> (just launch the test). Original project come from <https://github.com/spring-guides/gs-batch-processing/tree/master/complete> I tried to add : ```java @Bean public StepScope stepScope() { final StepScope stepScope = new StepScope(); stepScope.setAutoProxy(true); return stepScope; } ``` but it does not work (with spring.main.allow-bean-definition-overriding=true) Here is my configuration of the spring batch ``` @Bean @JobScope public RepositoryItemReader<DossierEntity> dossierToDiagnosticReader(PagingAndSortingRepository<DossierEntity, Long> dossierJpaRepository, @Value("#{jobParameters[origin]}") String origin) { RepositoryItemReader<DossierEntity> diagnosticDossierReader = new RepositoryItemReader<>(); diagnosticDossierReader.setRepository(dossierJpaRepository); diagnosticDossierReader.setMethodName("listForBatch"); // doing some stuff with origin return diagnosticDossierReader; } ``` ```java ExceptionHandlerExceptionResolver[199] - Resolved [org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.dossierToDiagnosticReader': Scope 'job' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No context holder available for job scope] ```
2019/10/18
[ "https://Stackoverflow.com/questions/58452256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2178038/" ]
I downloaded your project and was able to reproduce the case. There are two issues with your example: * You are defining a job scoped bean in your app but the `JobScope` is not defined in your context (and you are not using `@EnableBatchProcessing` annotation that adds it automatically to the context). If you want to use the job scope without `@EnableBatchProcessing`, you need to add it manually to the context. * Your test fails because there is no job running during your test. Job scoped beans are lazily instantiated when a job is actually run. Since your test does not start a job, the bean is not able to be proxied correctly. Your test does not seem to test a batch job, I would exclude the job scoped bean from the test's context.
11,378,982
I want to execute a SELECT query but I don't how many columns to select. Like: ``` select name, family from persons; ``` How can I know which columns to select? "I am currently designing a site for the execute query by users. So when the user executes this query, I won't know which columns selected. But when I want to show the results and draw a table for the user I should know which columns selected."
2012/07/07
[ "https://Stackoverflow.com/questions/11378982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1105438/" ]
For unknown query fields, you can just use this code. It gives you every row fields name=>data. You can even change the key to `''` to get ordered array columns by num following the columns' order in the database. ``` $data = array(); while($row = mysql_fetch_assoc($query)) { foreach($row as $key => $value) { $data[$row['id']][$key] = $value; } } print_r($data); ```
10,694,139
I have a question about Maven, the maven-release-plugin, git integration, pom.xml's, and having pom.xml's in subdirectories of the repo's local copy rather than in the root. Here's the setup: * I have a github account with a limited number of private repositories * I want to (am just learning to) use Maven to organize my builds/releases * I might need to create many Maven "projects", several projects per git repository * Each maven project requires a "pom.xml" to define its characteristics * I can't, or at least it's not convenient to, put all project pom.xml files in the root of the git repository * So I end up with this folder layout for projects: + git\_repo\_root\_dir - **project\_A** folder * pom.xml * other\_code - **project\_B** folder * pom.xml * other\_code - **etc.** - ... * I can successfully go to directory git\_repo\_root\_dir/project\_A and do an "mvn release:prepare" * I fail with this step in git\_repo\_root\_dir/project\_A: "mvn release:perform" + The problem seems to be that the git-tagged code is successfully checked out to git\_repo\_root\_dir/project\_A/target/checkout/project\_A in preparation for the release build, but then after the checkout the "maven-release" plugin goes to directory git\_repo\_root\_dir/project\_A/target/checkout/. instead of git\_repo\_root\_dir/project\_A/target/checkout/project\_A/. to do the actual build, and there's no way to tell the "maven-release" plugin to step into a subdirectory of the special tagged copy of the source before trying to mess with the pom.xml * QUESTION: is there a way around this? Is there an option to somehow tell "mvn release:perform" to go to the subdirectory? Here's the actual error I get during this process: ``` [INFO] --- maven-release-plugin:2.0:perform (default-cli) @ standard_parent_project --- [INFO] Checking out the project to perform the release ... [INFO] Executing: /bin/sh -c cd "/Users/___/DEV c8ion 01/maven_based_code/0maven/standard_parent_project/target" && git clone [email protected]:clarafaction/0maven.git '/Users/___/DEV c8ion 01/maven_based_code/0maven/standard_parent_project/target/checkout' ... /* note, the pom.xml the build should go out of at this point is at '/Users/___/DEV c8ion 01/maven_based_code/0maven/standard_parent_project/target/checkout/standard_parent_project/pom.xml' */ ... [INFO] [ERROR] The goal you specified requires a project to execute but there is no POM in this directory (/Users/___/DEV c8ion 01/maven_based_code/0maven/standard_parent_project/target/checkout). Please verify you invoked Maven from the correct directory. -> [Help 1] ``` Thanks.
2012/05/21
[ "https://Stackoverflow.com/questions/10694139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1409003/" ]
This should do the trick: ``` <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-release-plugin</artifactId> <version>2.3.2</version> <executions> <execution> <id>default</id> <goals> <goal>perform</goal> </goals> <configuration> <pomFileName>your_path/your_pom.xml</pomFileName> </configuration> </execution> </executions> </plugin> ```
56,833,298
I have multiple buttons (with the ids 'a', 'b', ...) and if you click them, they should display their corresponding image ('a.JPG', 'b.JPG', ...) at a fixed point on the website. The idea is to listen for when a button is clicked and change the code inside the output to include its id. ``` 'use strict'; var bild = '', i, j, k; function gedrueckt(k) { bild = '<img src="img/' + k + '.JPG" width="1600" hight="900" alt="Vergroessertes Bild"></img>'; document.querySelector('output').innerHTML = bild; } for (i = 1; i < 8; i = i + 1) { j = String.fromCharCode(97 + i); document.getElementById(j).addEventListener('click', gedrueckt(j)); } ``` The problem is that an image already appears before any button is clicked and pressing a different button does not change the displayed image.
2019/07/01
[ "https://Stackoverflow.com/questions/56833298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11723122/" ]
This code should change the src on each button click, changing the picture according the the ID of the button: ```js let img = document.getElementById('img') const change = id => { img.src = `${id}.jpeg` img.alt = `${id}.jpeg` } ``` ```html <img id="img" src=""> <br> <button onclick="change(this.id)" id="a">A</button> <button onclick="change(this.id)" id="b">B</button> <button onclick="change(this.id)" id="c">C</button> ``` > > If there no `src` and no `alt` property provided, the image will not be displayed. > > > I might've misunderstood you, in that you want the image to change on keyboard button press, which this code should do the trick: ```js let img = document.getElementById('img') const change = id => { img.src = `${id}.jpeg` img.alt = `${id}.jpeg` } const list = ['a','b','c'] document.addEventListener('keydown', e => list.includes(e.key) && change(e.key)) ``` ```html <img id="img" src=""> ```
56,584,966
i have a dataframe as below. ``` test = pd.DataFrame({'col1':[0,0,1,0,0,0,1,2,0], 'col2': [0,0,1,2,3,0,0,0,0]}) col1 col2 0 0 0 1 0 0 2 1 1 3 0 2 4 0 3 5 0 0 6 1 0 7 2 0 8 0 0 ``` For each column, i want to find the index of value 1 before the maximum of each column. For example, for the first column, the max is 2, the index of value 1 before 2 is 6. for the second column, the max is 3, the index of value 1 before the value 3 is 2. In summary, I am looking to get [6, 2] as the output for this test DataFrame. Is there a quick way to achieve this?
2019/06/13
[ "https://Stackoverflow.com/questions/56584966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3862109/" ]
Use [**`Series.mask`**](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.mask.html) to hide elements that aren't 1, then apply [**`Series.last_valid_index`**](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.last_valid_index.html) to each column. ``` m = test.eq(test.max()).cumsum().gt(0) | test.ne(1) test.mask(m).apply(pd.Series.last_valid_index) col1 6 col2 2 dtype: int64 ``` --- Using numpy to vectorize, you can use [**`numpy.cumsum`**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.cumsum.html) and [**`argmax`**](https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html): ``` idx = ((test.eq(1) & test.eq(test.max()).cumsum().eq(0)) .values .cumsum(axis=0) .argmax(axis=0)) idx # array([6, 2]) pd.Series(idx, index=[*test]) col1 6 col2 2 dtype: int64 ```
39,897,670
I have a service in an Angular 2 using TypeScript. I want to be able to share an array of values that I get from that service. when one component makes a change to the array I need it to be reflected in another component. This is the basics of my service and the object it uses ``` export class deviceObj { device_Id:number; deviceGroup_Id:number; name:string; favoriteFlag:boolean; visibleFlag:boolean; } export class Favorite { favorite_Id: number; device: deviceObj; constructor(){this.device = new deviceObj()}; } @Injectable() export class FavoriteService { private headers = new Headers({'Content-Type': 'application/json'}); private favoritesURL = 'URL THAT FEETCHES DATA'; favorites: Favorite[]; constructor(private http: Http) { this.getFavorites().then(favorites => this.favorites = favorites); } getFavorites(): Promise<Favorite[]> { return this.http.get(this.favoritesURL).toPromise().then(response => response.json() as Favorite[]).catch(this.handleError); } protected handleError2(error: Response) { console.error(error); return Observable.throw(error.json().error || 'server error'); } private handleError(error: any): Promise<any> { console.error('An error occurred', error); // return Promise.reject(error.message || error); } } ``` And here is one of the components that gets the array of favorites. ``` import {FavoriteService} from'../../services/favorite/favorite.service'; declare var jQuery: any; @Component({ selector: '[sidebar]', directives: [ ROUTER_DIRECTIVES, SlimScroll ], template: require('./sidebar.html') }) export class Sidebar implements OnInit { constructor(config: ConfigService, el: ElementRef, router: Router, location: Location, private favoriteService:FavoriteService) { } getFavorites(): void{ this.favoriteService .getFavorites() .then(favorites => this.favorites = favorites); } ``` In each component that uses the service it has its own favorites array that gets assigned on load. However I want a singleton variable in the service where changes can be reflected in two components. I'm not sure how to do this with promises. I am happy to clarify further if needed. Any help would greatly be apreciated.
2016/10/06
[ "https://Stackoverflow.com/questions/39897670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1710501/" ]
While it can probably be done with Promises, I can answer in the form of Observables at the very least, if you're of a mind to read about them... Given `ComponentA` and `ComponentB` both looking at a `SharedService` for their source of `SomeObject[]` data: The service: ``` import { Injectable } from '@angular/core'; import { Observable, Observer } from 'rxjs/rx'; import 'rxjs/add/operator/share'; import { SomeObject } from './some-object'; @Injectable() export class SomeService{ SharedList$: Observable<SomeObject[]>; private listObserver: Observer<SomeObject[]>; private sharedList: SomeObject[]; constructor(private http: Http){ this.sharedList = []; this.SharedList$ = new Observable<SomeObject[]>(x => this.listObserver = x).share(); } getList(){ // Get the data from somewhere, i.e. http call this.http.get(...) .map(etc) .subscribe(res => { this.sharedList = res; this.listObserver.next(this.sharedList); }); // the important part is after getting the data you want, observer.next it } addItem(item: SomeObject): void { this.sharedList.push(item); this.listObserver.next(this.sharedList); } } ``` Components then have: ``` import { Component, OnInit } from '@angular/core'; import { Observable, Observer } from 'rxjs/rx'; import { SharedService } from './some.service'; import { SomeObject } from './some-object'; @Component({...}) export class CommponentA implements OnInit { private list: SomeObject[]; constructor(private service: SharedService){ this.list = []; } ngOnInit(){ this.service.SharedList$.subscribe(lst => this.list = lst); this.service.getList(); } private onClick(item: SomeItem): void { this.service.addItem(item); } } ``` `ComponentB` would look similar - subscribing to the same `SharedList$` property on the service. When the service's `getList()` method is called, and it pushes a new `SomeObject[]` through the observables (`this.listObserver.next(..)`), the components subscribed to that property will be able to read the value pushed to it. Edit: Exposed an `addItem` method on the service that the components can call to push items to the list. The service then pushes it through the observable, (`this.listObserver.next(...)`) in the same style as when getting the data through x other method (i.e. http).
25,961,140
I have two table and first named **table1**: ``` ID | Name | Type | isActive | isDeleted | ----------------------------------------------- 1 | item 1 | 4 | 1 | 0 | 2 | item 2 | 2 | 1 | 0 | 3 | item 3 | 1 | 1 | 1 | 4 | item 4 | 1 | 1 | 0 | 5 | item 5 | 1 | 1 | 0 | 6 | item 6 | 3 | 1 | 0 | 7 | item 7 | 1 | 1 | 0 | 8 | item 8 | 2 | 1 | 0 | 9 | item 9 | 1 | 1 | 0 | 10 | item 10 | 1 | 1 | 0 | ``` AND second named **table1\_meta**: ``` ID | table1_id | options | value ------------------------------------ 1 | 1 | dont_ask | 1 2 | 2 | dont_ask | 1 3 | 5 | dont_ask | 1 4 | 6 | dont_ask | 1 5 | 8 | alwasys_ask| 1 6 | 9 | alwasys_ask| 1 7 | 1 | is_flagged | 1 8 | 2 | is_flagged | 0 9 | 3 | is_flagged | 0 10 | 4 | is_flagged | 0 11 | 5 | is_flagged | 0 12 | 6 | is_flagged | 1 13 | 7 | is_flagged | 0 14 | 8 | is_flagged | 0 15 | 9 | is_flagged | 0 16 | 10 | is_flagged | 0 ``` I'm trying to count rows in **table1** where certain specific criteria is met, some of these conditionals. The WHERE condition must contain these criteria: ``` table1.type = 1 and table1.isActive = 1 and table1.isDeleted = 0 and table1_meta.options = 'is_flagged' and table1_meta.value = 0 ``` and this: ``` table1_meta.options = 'dont_ask' and table1_meta.value = 1 ``` and this: ``` table1_meta.options = 'always_ask' and table1_meta.value = 1 ``` so, how can I do that? SQLFiddle link: <http://sqlfiddle.com/#!2/2eb27b> Thanks.
2014/09/21
[ "https://Stackoverflow.com/questions/25961140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1720048/" ]
When using `CASE` the syntax is `WHEN "00" =>`, thus no use of `THEN`. The code is therefore: ``` CASE input24 IS WHEN "00" => output0 <= '1' ; output1 <= '0' ; output2 <= '0' ; output3 <= '0' ; ... ``` If `input24` is `std_logic_vector` you must when the case with a `WHEN OTHERS =>` to handle the remaining encodings of `input24`. The code is: ``` WHEN OTHERS => output0 <= 'X' ; output1 <= 'X' ; output2 <= 'X' ; output3 <= 'X' ; ``` For writing the assignment in a single like, still use `;` as statement separator, thus not `,` as shown in the question code, and then just remove the whitespace. The code is: ``` WHEN "01" => output0 <= '0'; output1 <= '1'; ... ``` For assign to multiple signals in one statement, the VHDL-2008 supports aggregate assignment, so if you are using VHDL-2008, you can write: ``` WHEN "10" => (output3, output2, output1, output0) <= std_logic_vector'("0100"); ``` For VHDL-2003, a solution may be to create an intermediate `output` signal as `std_logic_vector`, and then assign to this. Code can then be: ``` ... signal output : std_logic_vector(3 downto 0); begin ... WHEN "11" => output <= "1000"; ... output0 <= output(0); output1 <= output(1); output2 <= output(2); output3 <= output(3); ``` If the `output` is used, then the exact implementation where the `case` is just used to set the bit with number given in `input24` can be made with: ``` LIBRARY IEEE; USE IEEE.NUMERIC_STD.ALL; ARCHITECTURE syn OF mdl IS SIGNAL output : STD_LOGIC_VECTOR(3 DOWNTO 0); BEGIN PROCESS (input24) IS BEGIN output <= (OTHERS => '0'); output(TO_INTEGER(UNSIGNED(input24))) <= '1'; END PROCESS; output0 <= output(0); output1 <= output(1); output2 <= output(2); output3 <= output(3); END ARCHITECTURE; ``` Otherwise, if the `output` signal is not used, then the `case` can still be simplified through a default assign as '0' to the outputs, thus with the code: ``` ARCHITECTURE syn OF mdl IS BEGIN PROCESS (input24) IS BEGIN output0 <= '1' ; output1 <= '0' ; output2 <= '0' ; output3 <= '0' ; CASE input24 IS WHEN "00" => output0 <= '1' ; WHEN "01" => output1 <= '1'; WHEN "10" => output2 <= '1' ; WHEN "11" => output3 <= '1' ; WHEN OTHERS => output0 <= 'X'; output1 <= 'X'; output2 <= 'X'; output3 <= 'X'; END CASE; END PROCESS; END ARCHITECTURE; ```
47,591,425
I am trying to place a button after an already existing button on another website. I'm trying to test it out in Chrome console, but can't figure it out. ``` var buttonPosition = document.getElementById('<button class="button black ">Black</button>'); ``` This is the button that I want to place my button behind. I then tried using the `.insertAdjacementHTML` function to get the button placed behind "button black" ``` buttonPosition.insertAdjacentHTML("afterend", "<button>Hello</button"); ``` Then I get the error message > > "Uncaught TypeError: buttonPosition.insertAdjacentHTML is not a > function > at :1:16" > > > This could be a rookie error, as I am very new to coding. Any help at all will be greatly appreciated. Thanks.
2017/12/01
[ "https://Stackoverflow.com/questions/47591425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9038538/" ]
That's because the value of your `getElementById()` is not an element's ID name but an element. Try adding an ID on your button then pass its ID name to `getElementById()` as the value, like this: HTML ``` <button class="button black" id="btn">Your button with an ID</button> ``` Javascript ``` var btn = document.getElementById('btn'); // The button itself with an ID of 'btn' var newButton = '<button>New button</button>'; // New button to be inserted btn.insertAdjacentHTML('afterend', newButton); ```
55,940,758
I have a components.js file that looks like this: ``` import { lookCoordinate } from './tools.js'; // I get: SyntaxError: Unexpected token { Vue.component('coordform', { template: `<form id="popup-box" @submit.prevent="process" v-if="visible"><input type="text" autofocus refs="coordinput" v-model="coords"></input></form>`, data() { { return { coords: '', visible: false } } }, created() { window.addEventListener('keydown', this.toggle) }, destroyed() { window.removeEventListener('keydown', this.toggle) }, methods: { toggle(e) { if (e.key == 'g') { if (this.visible) { this.visible = false; } else this.visible = true; } }, process() { lookCoordinate(this.coords) // Tried to import from tools.js } } }); ``` But I'm getting: `Uncaught SyntaxError: Unexpected token {` How do I import a function from another plain JS file and use it within a Vue component? Thanks.
2019/05/01
[ "https://Stackoverflow.com/questions/55940758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/162414/" ]
You will get this error if trying to load a Javascript file without ES6 support enabled. The parser does not understand the syntax of `import` is as it begins parsing the file. Check your webpack or vue-cli settings to make sure that you are transpiling the code. For instance, a browser does not know what `import` means, and neither does plain old node unless enabling experimental support. You can also change it to: ``` const lookCoordinate = require('./tools.js').lookCoordinate; ``` and see if that gives you an error. That format does almost exactly the same thing. If using `import` from a browser, also enable module support, as suggested by Orkhan Alikhanov in the comments. ``` It is supported if you add script with type="module". e.g: <script type="module" src="main.js"></script> ```
22,750,482
I am writing a program that converts strings to linked lists, and alters them, in C. For some reason after I call my reverse function, and then print the list, it will print a new line before printing the reversed list. for example, say my 'list' contains... a->p->p->l->e->NULL in main() if i call... `print(list); print(list);` my output: ``` apple apple ``` BUT, in main() if i call... `print(list); list=reverse(list); print(list);` my output: ``` apple /*empty line*/ elppa ``` here is my rev() ``` node *rev(node *head){ node *r_head = NULL; while (head) { node *next = head->next; head->next = rev_head; r_head = head; head = next; } return r_head; } ```
2014/03/30
[ "https://Stackoverflow.com/questions/22750482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2755244/" ]
[`Proc#curry`](http://ruby-doc.org/core-2.0/Proc.html#method-i-curry) > > Returns a curried proc. If the optional arity argument is given, it determines the number of arguments. A *curried* `proc` receives some arguments. If a *sufficient number* of arguments are supplied, it passes the supplied arguments to the original `proc` and *returns the result*. Otherwise, returns another curried proc that takes the rest of arguments. > > > Now coming to your code : ``` def f(x, y=2) x**y end a = method(:f).to_proc b = a.curry.curry[4] b.class # => Fixnum b # => 16 print 1.upto(5).map(&b) # wrong argument type Fixnum (expected Proc) (TypeError) ``` Look the documentation now - A *curried* `proc` receives some arguments. If a s\*ufficient number\* of arguments are supplied, it passes the supplied arguments to the original `proc` and *returns the result*. In your code, when you did `a.curry`, it returns a *curried proc*. Why? Because your method `f` has *one optional* and *one required* argument, but you didn't provide any. Now you call again `a.curry.curry[4]`, so on the previous *curried proc* which is still waiting for at-least one argument, this time you gave to it by using `curry[4]`. Now *curried* `proc` object gets called with `4, 2` as arguments, and evaluated to a `Fixnum` object `8` and assigned to `b`. **b is not a proc object**, rather a `Fixnum` object. Now, `1.upto(5).map(&b)` here - `&b` means, you are telling convert the `proc` object assgined to `b` to a block. But **NO**, `b` is not holding `proc` object, rather `Fixnum` object `8`. So Ruby **complains** to you. Here the message comes as **wrong argument type Fixnum (expected Proc) (TypeError)**. Now coming to your second part of code. Hold on!! :-) Look below : ``` def f(x, y) x**y end a = method(:f).to_proc b = a.curry.curry[4] b.class # => Proc b # => #<Proc:0x87fbb6c (lambda)> print 1.upto(5).map(&b) # >> [4, 16, 64, 256, 1024] ``` Now, your method `f` needs 2 mandatory argument `x, y`. `a.curry`, nothing you passed so a **curried proc** is returned. Again `a.curry.curry[4]`, humm you passed one required argument, which is `4` out of 2. So again a **curried proc** returned. Now `1.upto(5).map(&b)`, same as previous `b` expects a `proc`, and you fulfilled its need, as now b is `proc` object. `&b` converting it to a block as below : ``` 1.upto(5).map { |num| b.call(num) } ``` which in turn outputs as - `[4, 16, 64, 256, 1024]`. **Summary** Now suppose you defined a `proc` as below : ``` p = Proc.new { |x, y, z = 2| x + y + z } ``` Now you want to make `p` as *curried proc*. So you did `p.curry`. Remember you didn't pass any *arity* when called `curry`. Now point is a *curried proc* will wait to evaluate and return the result of `x + y + z`, unless and until, you are giving it all the required arguments it needs to produce it results. That means `p.curry` gives you a *curried proc* object, then if you do `p.curry[1]` ( mean you are now passing value to `x` ), again you got a *curried proc*. Now when you will write `p.curry[1][2]`, all required arguments you passed ( mean you are now passing value to `y` ), so now `x + y + z` will be called.
2,509,233
Part of a complex query that our app is running contains the lines: ...(inner query) ``` SELECT ... NULL as column_A, NULL as column_B, ... FROM ... ``` This syntax of creating columns with **null** values is not allowed in DB2 altough it is totally OK in **MSSQL** and **Oracle** DBs. Technically I can change it to: ``` '' as column_A, '' as column_B, ``` But this doesn't have exactly the same meaning and can damage our calculation results. How can I create columns with null values in DB2 using other syntax??
2010/03/24
[ "https://Stackoverflow.com/questions/2509233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/242389/" ]
DB2 is strongly typed, so you need to tell DB2 what kind of column your NULL is: ``` select ... cast(NULL as int) as column_A, cast(NULL as varchar(128)) as column_B, ... FROM ... ```
12,823
I've been trying to create a short-cut key for grabbing part of the screen. If I run the command `/usr/bin/gnome-screenshot --area` the program I want runs and does what I want. When I createa a custom action in the keyboard shortcuts menu, and I activate the command (using ctrl-prnscr) the command fires up but behaves as though the `--area` option isn't there (it grabs the whole screen instead of giving me a cursor to choose with). If I run `ps -eaf |grep screen` I get: ``` $ ps -eaf |grep screen yfarjoun 2082 1 0 Oct29 ? 00:00:21 gnome-screensaver yfarjoun 17730 1 0 17:34 ? 00:00:00 gnome-screenshot --area yfarjoun 17735 17730 1 17:34 ? 00:00:00 gnome-screenshot --area yfarjoun 17741 2599 0 17:34 pts/0 00:00:00 grep --color=auto screen ``` So the option is definitely transfered to the command.... Why is it not honoring the option? How can I fix this?
2010/11/12
[ "https://askubuntu.com/questions/12823", "https://askubuntu.com", "https://askubuntu.com/users/4863/" ]
It works for me when pressing the shortcut twice (fast). This seems to have worked at some point but doesn't anymore (see [this thread](http://ubuntuforums.org/showthread.php?t=1199669) at ubuntuforums.org - it doesn't work for me, with or without the '-i' switch). There's already a bug report opened: <https://bugs.launchpad.net/ubuntu/+source/gnome-utils/+bug/549935>
10,724,253
This should be pretty simple, yet it's blowing up. Any ideas? ``` d = BigDecimal.new("2.0") YAML::load({:a => d}.to_yaml) TypeError: BigDecimal can't be coerced into BigDecimal from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/inspector.rb:86:in `inspect' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/inspector.rb:86:in `inspect' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/inspector.rb:86:in `block in <module:IRB>' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/inspector.rb:30:in `call' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/inspector.rb:30:in `inspect_value' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/context.rb:260:in `inspect_last_value' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb.rb:311:in `output_value' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb.rb:160:in `block (2 levels) in eval_input' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb.rb:273:in `signal_status' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb.rb:156:in `block in eval_input' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/ruby-lex.rb:243:in `block (2 levels) in each_top_level_statement' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/ruby-lex.rb:229:in `loop' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/ruby-lex.rb:229:in `block in each_top_level_statement' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/ruby-lex.rb:228:in `catch' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb/ruby-lex.rb:228:in `each_top_level_statement' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb.rb:155:in `eval_input' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb.rb:70:in `block in start' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb.rb:69:in `catch' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/lib/ruby/1.9.1/irb.rb:69:in `start' from /Users/benjohnson/.rvm/rubies/ruby-1.9.3-p125/bin/irb:16:in `<main>'Maybe IRB bug! ```
2012/05/23
[ "https://Stackoverflow.com/questions/10724253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/507718/" ]
This is a bug that has been [reported](https://github.com/tenderlove/psych/issues/31) and [fixed](https://github.com/tenderlove/psych/commit/33ce8650bac29190dde937b1b7d3e21fd06926e7). The best solution would be upgrade to the latest Ruby (the fix is in patch level 194 onwards). If you can’t upgrade your Ruby version, you can get the fix by installing the [Psych gem](https://rubygems.org/gems/psych). If you do this you’ll need to add `gem 'psych'` before you `require 'yaml'` (or add it to your `Gemfile` if you’re using Bundler) to load the code from the gem rather than from the standard library..
32,878,678
Currently incredibly confused about how I would go about moving the logic for determining if a string is a palindrome from the main method into a method named checkPalindrome? My method should have a single String argument and return a boolean value, but I'm still unsure of how to do this. ``` import java.util.Scanner; public class PalindromeCheckMethod { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter a String: "); String s = input.nextLine(); boolean isPalindrome = checkPalindrome(s); String msg = "not a palindrome"; if (isPalindrome) { msg = "a palindrome"; } System.out.printf("%s is %s.%n", s, msg); s = s.toLowerCase(); String resultString = ""; for (int i = 0; i < s.length(); i++) { if (Character.isLetter(s.charAt(i))) resultString += s.charAt(i); } s = resultString; int low = 0; int high = s.length() - 1; if (high >= 0) { while (low < high) { if (s.charAt(low) != s.charAt(high)) { isPalindrome = false; break; } low++; high--; } } else { isPalindrome = false; } if (isPalindrome) System.out.println(s + " is a palindrome. "); else System.out.println(s + " is not a palindrome. "); } private static boolean checkPalindrome(String s) { return false; } } ```
2015/10/01
[ "https://Stackoverflow.com/questions/32878678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5016178/" ]
``` static boolean checkPalindrome(String str) { int strEndPoint=str.length()-1; int strStartPoint=0; boolean isPalindrome=true; while(strStartPoint<=strEndPoint) { if(str.charAt(strStartPoint)!=str.charAt(strEndPoint)) { isPalindrome=false; break; } strStartPoint++; strEndPoint--; } return isPalindrome; ``` }
33,421
I have a acquaintance who lives in the United States with a young daughter who will be starting Kindergarten next year. However, her preschool feels she should be "held back", because among other things, she does not appear to be interested in writing her name. I do not live in the United States, so perhaps I am in the wrong, but is this a scam? It certainly sounds like a scam. Preschools are paid institutions, while Kindergarten is free (public school system). In my country, you do not need to "graduate" kindergarten to be accepted into 1st grade. Thus, holding someone back from kindergarten sounds ridiculous. Even if she performs poorly, I don't see how this would harm her academic career. I do feel that delaying her education by a year will be detrimental. I am advising this acquaintance that this sounds like a scam, but I could be in the wrong. What is consensus on this?
2018/03/07
[ "https://parenting.stackexchange.com/questions/33421", "https://parenting.stackexchange.com", "https://parenting.stackexchange.com/users/14007/" ]
I'd say in this case the preschool is offering advice and not necessarily perpetrating a scam, at least by a simple definition. Preschool is optional in the USA. It can be free if you meet some wage requirements, or if you're part of a church, work, or academic program that offers it as incentive or grace. You can't fail per say, but part of their job is to evaluate growth and maturity. In our district, the Kindergarten entry requirement is you must be at least 5 years old with a cut off birthday of something like September 1st. If you don't meet that you can take an early entrance exam which involves writing your name, following simple instructions, ability to walk single file from point A to point B, etc. I saw a kid fail in the lobby because he cried when it came time to separate from family. They're looking for a certain maturity level as well, and a preschool will have some idea of the expectations. The USA, which is ranked something like 14th in the world for education, allows for districts like ours to have zero say in whether or not a child is held back in one of the K-12 levels. You can get straight F's and the parents can still advance their child. So even in official education levels the idea of being held back is more of a suggestion than anything. Unless the preschool advisor also happens to own the institution, I'd say they probably have no real benefit from trying to scam you into staying longer. In your case, I would say that if they meet the age requirements, then enroll them in Kindergarten. Kinder is not a daycare. They have an actual curriculum and writing your name is a part of it.
23,123,035
Ideally I'd like `ctrl`+`space` to bring up "search everywhere" from anywhere in windows (8.1) and also dismiss it if it's already active (with something like #IfWinActive ...). So far I've been able to make `ctrl`+`space` simulate pressing the `winkey` with the following AutoHotKey script: ``` <^Space:: KeyWait Ctrl Send {RWin} return ``` ...but not `winkey`+`s`. It feels sort of hackish anyway because it doesn't initiate "on press." It only initiates once I've released the `ctrl` key. P.S. If I can't get this figured out I'm taking suggestions for a good third party launcher application --- EDIT: Thanks to Robert. Here is the result: ``` <^Space:: SendInput {RWin Down}s{RWin Up} return ```
2014/04/17
[ "https://Stackoverflow.com/questions/23123035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/624041/" ]
One way to do this is through: ``` SendInput, {RWin Down}s{RWin Up} ```
55,062,489
I have queries that can return large resultsets (> 100K rows). I need to display the number of results to the user and the user is able to page through the results in our application. However, nobody is going to page through 100K items when 25 are displayed on a page. So I want to limit the number of pageable results to 5K while still displaying the total number of results to the user. Of course, I can fire two seperate queries to the database: one counting all results, one returning the TOP(5000). But the queries can be expensive. Is there a smart way to combine these two queries into one? The queries below are over simplified: ``` SELECT COUNT(*) FROM TABLE WHERE field = 1; SELECT TOP(5000) * FROM TABLE Where field = 1; ``` Can anyone help?
2019/03/08
[ "https://Stackoverflow.com/questions/55062489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1207701/" ]
Add max rating programmatically , It should fix the issue ``` ratingBar.setMax(5); ``` **Edit:** replace your rating bar with and check ``` <LinearLayout android:layout_width="wrap_content" android:layout_height="45dp" android:layout_alignParentEnd="true" android:layout_below="@+id/eventsubtitle"> <RatingBar android:layout_width="wrap_content" android:layout_height="45dp" android:id="@+id/ratingbar" android:stepSize="1.0"/> </LinearLayout> ```
10,876,621
Consider a simple example like this which links two sliders using signals and slots: ``` from PySide.QtCore import * from PySide.QtGui import * import sys class MyMainWindow(QWidget): def __init__(self): QWidget.__init__(self, None) vbox = QVBoxLayout() sone = QSlider(Qt.Horizontal) vbox.addWidget(sone) stwo = QSlider(Qt.Horizontal) vbox.addWidget(stwo) sone.valueChanged.connect(stwo.setValue) if __name__ == '__main__': app = QApplication(sys.argv) w = MyMainWindow() w.show() sys.exit(app.exec_()) ``` How would you change this so that the second slider moves in the opposite direction as the first? Slider one would be initialized with these values: ``` sone.setRange(0,99) sone.setValue(0) ``` And slider two would be initialized with these values: ``` stwo.setRange(0,99) stwo.setValue(99) ``` And then the value of stwo would be `99 - sone.sliderPosition`. How would you implement the signal and slot to make this work? I would appreciate a working example that builds on the simple example above.
2012/06/04
[ "https://Stackoverflow.com/questions/10876621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/463994/" ]
Your example is a bit broken, because you forgot to set the parent of the layout, and also to save the slider widgets as member attributes to be accessed later... But to answer your question, its really as simple as just pointing your connection to your own function: ``` class MyMainWindow(QWidget): def __init__(self): QWidget.__init__(self, None) vbox = QVBoxLayout(self) self.sone = QSlider(Qt.Horizontal) self.sone.setRange(0,99) self.sone.setValue(0) vbox.addWidget(self.sone) self.stwo = QSlider(Qt.Horizontal) self.stwo.setRange(0,99) self.stwo.setValue(99) vbox.addWidget(self.stwo) self.sone.valueChanged.connect(self.sliderChanged) def sliderChanged(self, val): self.stwo.setValue(self.stwo.maximum() - val) ``` Note how `sliderChanged()` has the same signature as the original `setValue()` slot. Instead of connecting one widget directly to the other, you connect it to a custom method and then transform the value to what you want, and act how you want (setting a custom value on `stwo`)
67,782,043
First of all ============ I searched for it for a long time, and I have **already seen** many questions including the two: [How to draw Arc between two points on the Canvas?](https://stackoverflow.com/questions/11131954/how-to-draw-arc-between-two-points-on-the-canvas) [How to draw a curved line between 2 points on canvas?](https://stackoverflow.com/questions/37432826/how-to-draw-a-curved-line-between-2-points-on-canvas/37446243#37446243) Although they seem like the same question, I'm very sure they are **not** the same. In the first question, the center of the circle is known, and in the second, it draws a Bezier curve not an arc. Description =========== Now we have two points `A` and `B` and the curve radius given, how to draw the arc as the image shows? [![image](https://i.stack.imgur.com/RMxUP.png)](https://i.stack.imgur.com/RMxUP.png) Since `Path.arcTo`'s required arguments are `RectF`, `startAngle` and `sweepAngle`, there seems hardly a easy way. My current solution =================== I now have my solution, I'll show that in the answer below. Since the solution is so complex, I wonder if there is a easier way to solve it?
2021/06/01
[ "https://Stackoverflow.com/questions/67782043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12611441/" ]
Probably there is no easier way. All what can do would be to refine your solution by geometrical approach. Since the center of circle is always on the perpendicular bisector of the chord, it's not required to solve so generalized equations. By the way, it's not clear how you defined Clockwise/Counter-clockwise. Arc's winding direction should be determined independently of node-placements (=A, B's coordinates). As is shown in the figure below, on the straight path from A to B, the center O is to be placed righthandside(CW) or lefthandside(CCW). That's all. [![Path.ArcTo with radius and end-points](https://i.stack.imgur.com/tqDep.png)](https://i.stack.imgur.com/tqDep.png) And, some more aspects to be altered: 1. It's better to calculate startAngle by atan2(). Because acos() has singularity at some points. 2. It's also possible to calculate sweepAngle with asin(). After all the code can be slightly simplified as follows. ``` @Throws(Exception::class) private fun Path.arcFromTo2( x1: Float, y1: Float, x2: Float, y2: Float, r: Float, clockwise: Boolean = true ) { val d = PointF((x2 - x1) * 0.5F, (y2 - y1) * 0.5F) val a = d.length() if (a > r) throw Exception() val side = if (clockwise) 1 else -1 val oc = sqrt(r * r - a * a) val ox = (x1 + x2) * 0.5F - side * oc * d.y / a val oy = (y1 + y2) * 0.5F + side * oc * d.x / a val startAngle = atan2(y1 - oy, x1 - ox) * 180F / Math.PI.toFloat() val sweepAngle = side * 2.0F * asin(a / r) * 180F / Math.PI.toFloat() arcTo( ox - r, oy - r, ox + r, oy + r, startAngle, sweepAngle, false ) } ```
2,674,964
Is it possible to develop an application in groovy using GWT components? Luis
2010/04/20
[ "https://Stackoverflow.com/questions/2674964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/72420/" ]
If you want to use Groovy on the server-side and GWT for the UI, that is certainly possible. You can use Grails (a Groovy web framework on the server), and the [Grails GWT plugin](http://www.grails.org/plugin/gwt) to help you integrate GWT with this framework.
55,466,506
I'm new to Hibernate and I've a basic question. I have two entity classes User and Comments with the relationship defined as One toMany from user to comments and manytoOne from comments to user. Now, if my UI sends me back some comments with comment\_text and user\_id what is the best way to save it? By defining @ManyToOne Private User user; I need to use the whole user object to store this information however, all I need is to store comment with user\_id in the table and query user information when I need it. I'm new to Hibernate so it may be really just basics but can someone please help me?
2019/04/02
[ "https://Stackoverflow.com/questions/55466506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11296633/" ]
The relationship between users and comments is many-to-many, so you can try to create a table with the following fields: * key * commenter * commented * comment-text
198,993
I must admit, I entirely did not understand why > > Queenie > > > chose to join Grindelwald at the climax of *The Crimes of Grindelwald.* She seems like the least likely, given her relationship with > > Jacob. > > > Can anyone explain?
2018/11/20
[ "https://scifi.stackexchange.com/questions/198993", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/50565/" ]
At the start of the film we see that Queenie is struggling with the idea that Jacob can't/won't marry her because she'd become an outcast in wizarding society (essentially exiled from her home country) and he'd either be killed or obliviated. > > **JACOB:** *Okay, wait. **We talked about this, like, a million times. If we get married and they find out, they’re gonna throw you in jail,** sweetheart. I can’t have that. **They don’t like people like me marrying people like you.** I ain’t a wizard. I’m just me.* > > > [Fantastic Beasts: The Crimes of Grindelwald - The Original Screenplay](https://www.waterstones.com/book/fantastic-beasts-the-crimes-of-grindelwald-the-original-screenplay/j-k-rowling/9781408711705) > > > When she meets Grindelwald, not only does he not turn out to be the psychopathic monster she's been told he is, but he also spins her a convincing lie about being free to love and marry muggles after the rebellion's completed. > > **GRINDELWALD:** *I would never see you harmed, ever. It is not your fault that your sister is an Auror. **I wish you were working with me now towards a world where we wizards are free to live openly, and to love freely.*** > > > What's not clear (and may be explained later) is whether he's merely highly persuasive or whether his "silver tongue" is literally a form of magical enchantment. Either way, she makes her choice as a result of this conversation. > > **QUEENIE:** [a decision] *Jacob, he’s the answer. **He wants what we want.*** > > > --- In an interview, the actress who portrays Queenie Alison Sudol says that it breaks down to three main elements; That those close to her don't value her magical gifts, that she feels abandoned by her sister (and by Jacob) and that Grindelwald appears to be promising a world in which those with her kinds of views will be valued. > > *“I feel like in some ways she’s too there and that’s part of the problem. **She’s tapping into all human beings at all times and that’s a lot for one person to hold and everybody closest to her is always going, ‘Don’t read my mind.’ So she has a huge power and yet is made to feel like she’s nothing and that’s bad**. That could make anyone feel crazy. And women historically have this huge intuition and have been punished for that intuition forever. How many women have been in a mental institution because they’ve been called crazy when they’re just not allowed to be honest or be who they are?”* > > > *“Jacob doesn’t come with her,” she explains. **“It’s not so much about Jacob not coming with her to the dark side, it’s like, ‘Jacob, walk with me, we’re in this together.’ And she doesn’t have those two, so who does she have?** Newt’s kind of betrayed her — he called her out, it was embarrassing. What does she have?”* > > > *“I still believe in her heart of hearts she’s going over to fight what she believes in,” Sudol says. **“Grindelwald is saying, ‘we’re creating a different world’ and the world that she is in is broken. I don’t believe she’s turning evil. It’s more like she’s trying to find somebody who is giving her an option. He’s manipulating her but he’s manipulating everybody**. He even did that with Dumbledore.”* > > > [EW.COM - Interview](https://ew.com/movies/2018/11/20/crimes-of-grindelwald-alison-sudol-queenie/) > > >
45,401,378
so im making the board game GO for javascript and im having trouble counting the territories. If you didnt know, GO is like a complex checkers where you place stones horizontally and vertically instead of diagonally. A territory comes when the game has ended and you have made a border of your stones (the board edges count as anyones). [![territory](https://i.stack.imgur.com/nIizS.png)](https://i.stack.imgur.com/nIizS.png) So the image above is what i have so far. White = player 1, Black = player 2, Green = territory So the green only comes at the end of the game. The game has now finished, black has control of the top left corner of the board taking 2 prisoners. The group inside has been identified and coloured in green. Problem is, how do i know what player the green territory belongs to? Any human can see black owns all sides/ border of the territory (remember the board edges are anyones). It starts to get hard when there are prisoners inside. I could just check every cell adjacent to every green cell. If there is black and white, its not a territory but that wouldnt work if there is prisoners. One way im thinking might be an option is to try identify the border going around it. If i can do that i can easily check whos territory it is. Calculating the border peices would be easy with a square but a circle or any morphed shape? im not sure. Any help is appriciated :)
2017/07/30
[ "https://Stackoverflow.com/questions/45401378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6799727/" ]
I managed to do this very effectively in the end using my own algorithm. It will first identify the territory in question and get the lowX, lowY, highX, highY. So in this case it would be 0, 0, 5, 5 respectivly. I then do a for loop like this: ``` for (var j = lowX; j < highX + 1; j++) { var lowColumnY = null; var highColumnY = null; for (var k = 0; k < territories[i].length; k++) { if (territories[i][k].x == j) { if ((lowColumnY == null) || (territories[i][k].y < lowColumnY)) { lowColumnY = territories[i][k].y; console.log(lowColumnY); } if ((territories[i][k].y > highColumnY) || (highColumnY == null)) { highColumnY = territories[i][k].y; } } } ``` So that scrolls through all the columns of the territory and works out the low and high point which are the first 2 variables declared. I then repeat the for loop for the Y and in the end im left with every coordinate of the border. I have demonstrated this by drawing red circles so its easy to visualist and as you can see it doesnt interfere with any prisoners. [![territory](https://i.stack.imgur.com/jJsIU.png)](https://i.stack.imgur.com/jJsIU.png) So lastly i just check each colour of the stones where the red circles are. If there is any conflicting colours, it cant be a territory. As in this case the only colour was black, we know its a black territory.
17,149,200
I have graph class that looks like: ``` class Graph { public: typedef unsigned int size_type; typedef std::list<size_type> Neighbours; protected: size_type m_nodes_count, m_edges_count; public: Graph(size_type nodes_count = 0) : m_nodes_count(nodes_count), m_edges_count(0) {} virtual bool is_edge(size_type from, size_type to) = 0; virtual Neighbours neighbours(size_type node) = 0; virtual Graph& add_edge(size_type from, size_type to) = 0; virtual void delete_edge(size_type from, size_type to) = 0; size_type nodes_count() { return m_nodes_count; } size_type edges_count() { return m_edges_count; } virtual ~Graph() {} }; class AdjList : public Graph { private: typedef std::list<size_type> Row; std::vector<Row> m_list; public: AdjList(size_type nodes_count) : Graph(nodes_count) { m_list.resize(nodes_count); } AdjList(const AdjList& g) : AdjList(g.m_nodes_count) { for (int i = 0; i < nodes_count(); i++) std::copy(g.m_list[i].begin(), g.m_list[i].end(), std::back_inserter(m_list[i])); } virtual bool is_edge(size_type from, size_type to) override { return std::find(m_list[from].begin(), m_list[from].end(), to) != m_list[from].end(); } virtual Graph& add_edge(size_type from, size_type to) override { if (!is_edge(from, to) && !is_edge(to, from)) { m_list[from].push_back(to); m_list[to].push_back(from); m_edges_count++; } return *this; } virtual void delete_edge(size_type from, size_type to) override { m_list[from].remove(to); m_list[to].remove(to); m_edges_count--; } virtual Neighbours neighbours(size_type node) { return m_list[node]; } }; ``` but when I try to get `graph.neighbours(v)` I get big amount of trash in it: ``` (gdb) p graph $1 = {<Graph> = {_vptr.Graph = 0x406210 <vtable for AdjList+16>, m_nodes_count = 3, m_edges_count = 3}, m_list = std::vector of length 3, capacity 3 = {std::list = {[0] = 2, [1] = 1}, std::list = {[0] = 0, [1] = 2}, std::list = {[0] = 0, [1] = 1}}} (gdb) p graph.neighbours(0) $2 = std::list = {[0] = 2, [1] = 1, [2] = 4294956560, [3] = 2, [4] = 1, [5] = 4294956560, [6] = 2, [7] = 1, [8] = 4294956560, [9] = 2, [10] = 1, [11] = 4294956560, [12] = 2, [13] = 1, [14] = 4294956560, [15] = 2, [16] = 1, [17] = 4294956560, [18] = 2, [19] = 1, [20] = 4294956560, [21] = 2, [22] = 1, [23] = 4294956560, [24] = 2, [25] = 1,... ``` How to fix that?
2013/06/17
[ "https://Stackoverflow.com/questions/17149200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1017941/" ]
`gdb` is probably getting confused by an **implementation detail** the `std::list`. E.g. the old [SGI STL `list`](http://www.sgi.com/tech/stl/stl_list.h) was implemented as a **circular list**. Inside the `list` object, there is only a singly `_List_node<_Tp>` pointer called `_M_node`. The constructor puts the internal `_M_next` pointer of the final node element equal to `_M_node` itself. The reason Standard Library implementations of `std::list` use this circular implementation is to avoid special cases for the final element (e.g. they could also use a a sentinel element with a `nullptr` next pointer). Matt Austern has a nice [ACCU presentation](http://www.accu-usa.org/Slides/SinglyLinkedLists.ppt) about this (but the link is currently to a corrupted file, see [archived version here](http://web.archive.org/web/20090618135116/http://www.accu-usa.org/Slides/SinglyLinkedLists.ppt)). This circular implementation explains why your `gdb` output for `g.neighbors()` has the repeating pattern of `[0] = 2, [1] = 1, [2] = 4294956560, /* etcetera */`. The value 4294956560 is simply the memory address of the internal `_M_node` variable of your `std::list`, so if `gdb` only does simnple pointer chasing, it will get confused. Notice that it is less than `2^32`, i.e. you are probably compiling this for 32-bits. You should probably verify this in your own `<list>` header of the Standard Library on your system. A bug report for `gdb` might also be in order.
3,071,254
> > If $A\_1,A\_2,\dots,A\_m$ are independent and $\mathbb{P}(A\_i)=p$ for > $i=1,\dots,m$, find the probability that: > > > * none of the $A\_i$ occur, > * an even number of the $A\_i$ occur. > > > For the first question, I would say the required probability is: $$ 1 - \mathbb{P}(\cup\_i A\_i) = 1- \mathbb{P}(\cap\_i A\_i^c) = 1 - \prod\_{i=1}^m (1-p) = 1 - (1-p)^m. $$ The independence requirement is what allows to expand: $$ \mathbb{P}(\cap\_i A\_i^c) = \prod\_i\mathbb{P}(A\_i^c). $$ As for the second point, I was thinking for example that the case that exactly 2 events out of $m$ occur is: $$ {m \choose 2}p^2(1-p)^{m-2}, $$ the case that exactly four events occur is: $$ {m\choose 4}p^4(1-p)^{m-4}, $$ and so on, and then we would have to sum over all the even numbers less or equal than $m$. I am not sure of my answers though.
2019/01/12
[ "https://math.stackexchange.com/questions/3071254", "https://math.stackexchange.com", "https://math.stackexchange.com/users/517825/" ]
$\DeclareMathOperator{\im}{Im}\DeclareMathOperator{sp}{Span}\require{AMScd}$First, let us understand where all the maps are going in the Smith normal form: \begin{CD} \mathbb{Z}^4 @>A>> \mathbb{Z}^3\\ @APAA @AAQA \\ \mathbb{Z}^4 @>>D> \mathbb{Z}^3 \end{CD} $P$ and $Q$ are isomorphisms (invertible), $D$ is diagonal and $A = QDP^{-1}$. The point of $P$ and $Q$ is that they are a change of basis such that in the new basis, $A$ acts diagonally. We want to compute the image of $A$, or equivalently, the image of $QDP^{-1}$. First, I claim that $\im(A) = \im(QD)$ and this is because $P$ is invertible. > > Let $y \in \im(A)$. Then $y = Ax = QDP^{-1}$ for some $x$. So $y = QD(P^{-1}x)$ is in the image of $QD$. Next, let $y \in \im(QD)$. Then $y = QDx$ for some $x$. Since $P$ (and also $P^{-1}$) is invertible, there must be some $x'$ such that $x = P^{-1}x'$ (namely: $x' = Px$). Then $y = QDP^{-1}x' = Ax' \in \im{A}$. > > > The general rule here is that if $A = BC$ and $C$ is invertible, then $\im(A) = \im(B)$. Next, given any matrix, the image of that matrix is the same as the column space. > > To demonstrate, let $B$ have columns $v\_1, \dots, v\_n$ and let $x = (x\_1,\dots,x\_n)$. Then > $$ Bx = \begin{pmatrix} v\_1 & \cdots & v\_n \end{pmatrix} \begin{pmatrix} x\_1 \\ \vdots \\ x\_n \end{pmatrix} = x\_1v\_1 + \cdots + x\_nv\_n \in \sp\{v\_1,\dots,v\_n\}$$ > And conversely, any element $x\_1v\_1 + \cdots + x\_n v\_n \in \sp\{v\_1,\dots,v\_n\}$ can be written as $Bx$ where $x = (x\_1,\dots,x\_n)$. > > > So what we have shown is that $\im(A) = \im(QD) = \sp\{\text{columns of $QD$}\}$. Now the last step is what I said near the beginning: $P$ and $Q$ represent a change of basis. So the columns of $Q$ are a basis for $\mathbb{Z}^3$ and the columns of $P$ are a basis for $\mathbb{Z}^4$. (In fact, the same is true for $P^{-1}, Q^{-1}$ as well as $P^T$ and $Q^T$ or, more generally, any invertible matrix.) So the columns of $Q$ are a basis for $\mathbb{Z^3}$ and the (non-zero) columns of $QD$ are a basis for $\im(A)$. Then it's just a matter of understanding how diagonal matrices act on other matrices. Multiplying by a diagonal matrix on the right multiplies the columns by the corresponding diagonal element. Multiplying by a diagonal matrix on the left multiplies the rows by the corresponding diagonal element. This is why $QD$ is obtained from $Q$ by multiplying the columns by $-1, -2$, and $2$ respectively.
69,062,041
Example: =MIN({"510";"515";"503";"";"";""}) How to get the min value of this array from **non-empty** items. Item *503* to be the minimum here and is the answer.
2021/09/05
[ "https://Stackoverflow.com/questions/69062041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1979578/" ]
This problem is about creating [disjoint sets](https://en.wikipedia.org/wiki/Disjoint-set_data_structure) and so I would use union-find methods. Now Python is not particularly known for being fast, but for the sake of showing the algorithm, here is an implementation of a `DisjointSet` class without libraries: ``` class DisjointSet: class Element: def __init__(self): self.parent = self self.rank = 0 def __init__(self): self.elements = {} def find(self, key): el = self.elements.get(key, None) if not el: el = self.Element() self.elements[key] = el else: # Path splitting algorithm while el.parent != el: el, el.parent = el.parent, el.parent.parent return el def union(self, key=None, *otherkeys): if key is not None: root = self.find(key) for otherkey in otherkeys: el = self.find(otherkey) if el != root: # Union by rank if root.rank < el.rank: root, el = el, root el.parent = root if root.rank == el.rank: root.rank += 1 def groups(self): result = { el: [] for el in self.elements.values() if el.parent == el } for key in self.elements: result[self.find(key)].append(key) return result ``` Here is how you could use it for this particular problem: ``` def solve(lists): disjoint = DisjointSet() for lst in lists: disjoint.union(*lst) groups = disjoint.groups() return [lst and groups[disjoint.find(lst[0])] for lst in lists] ``` Example call: ``` data = [ [0, 5, 101], [8, 9, 19, 21], [], [78, 79], [5, 7, 63, 64] ] result = solve(data) ``` The result will be: ``` [[0, 5, 101, 7, 63, 64], [8, 9, 19, 21], [], [78, 79], [0, 5, 101, 7, 63, 64]] ``` Note that I added an empty list in the input list, so to illustrate that this boundary case remains unaltered. NB: There are libraries out there that provide union-find/disjoint set functionality, each with a slightly different API, but I suppose that using one of those can give a better performance.
66,582,173
I am looking for an RAM efficient way to calculate the median over a complement set with the help of data.table. For a set of observations from different groups, I am interested in an implementation of a **median of "other groups"**. I.e., if a have a data.table with one value column and one grouping column, I want for each group calculate the median of values in all other group *except the current* group. E.g. for group 1 we calculate the median from all values except the values that belong to group 1, and so on. A concrete example data.table ``` dt <- data.table(value = c(1,2,3,4,5), groupId = c(1,1,2,2,2)) dt # value groupId # 1: 1 1 # 2: 2 1 # 3: 3 2 # 4: 4 2 # 5: 5 2 ``` I would like the medianOfAllTheOtherGroups to be defined as 1.5 for group 2 and defined as 4 for group 1, repeated for each entry in the same data.table: ``` dt <- data.table(value = c(1,2,3,4,5), groupId = c(1,1,2,2,2), medianOfAllTheOtherGroups = c(4, 4, 1.5, 1.5, 1.5)) dt # value groupId medianOfAllTheOtherGroups # 1: 1 1 4.0 # median of all groups _except_ 1 # 2: 2 1 4.0 # 3: 3 2 1.5 # median of all groups _except_ 2 # 4: 4 2 1.5 # 5: 5 2 1.5 ``` To calculate the median for each group only once and not for each observation, we went for an implementation with a loop. The current complete implementation works nice for small data.tables as input, but suffers from large RAM consumption for larger data sets a lot with the medians called in a loop as bottleneck (Note: for the real use case we have a dt with 3.000.000 rows and 100.000 groups). I have worked very little with improving RAM consumption. Can an expert help here to improve RAM for the minimal example that I provide below? MINIMAL EXAMPLE: ``` library(data.table) set.seed(1) numberOfGroups <- 10 numberOfValuesPerGroup <- 100 # Data table with column # groupIds - Ids for the groups available # value - value we want to calculate the median over # includeOnly - boolean that indicates which example should get a "group specific" median dt <- data.table( groupId = as.character(rep(1:numberOfGroups, each = numberOfValuesPerGroup)), value = round(runif(n = numberOfGroups * numberOfValuesPerGroup), 4) ) # calculate the median from all observations for those groups that do not # require a separate treatment medianOfAllGroups <- median(dt$value) dt$medianOfAllTheOtherGroups <- medianOfAllGroups # generate extra data.table to collect results for selected groups includedGroups <- dt[, unique(groupId)] dt_otherGroups <- data.table(groupId = includedGroups, medianOfAllTheOtherGroups = as.numeric(NA) ) # loop over all selected groups and calculate the median from all observations # except of those that belong to this group for (id in includedGroups){ dt_otherGroups[groupId == id, medianOfAllTheOtherGroups := median(dt[groupId != id, value])] } # merge subset data to overall data.table dt[dt_otherGroups, medianOfAllTheOtherGroups := i.medianOfAllTheOtherGroups, on = c("groupId")] ``` PS: here the example output for 10 groups with 100 observations each: ``` dt # groupId value medianOfAllTheOtherGroups # 1: 1 0.2655 0.48325 # 2: 1 0.3721 0.48325 # 3: 1 0.5729 0.48325 # 4: 1 0.9082 0.48325 # 5: 1 0.2017 0.48325 # --- # 996: 10 0.7768 0.48590 # 997: 10 0.6359 0.48590 # 998: 10 0.2821 0.48590 # 999: 10 0.1913 0.48590 # 1000: 10 0.2655 0.48590 ``` Some numbers for different settings of the minimal example (tested on a Mac Book Pro with 16Gb RAM): | NumberOfGroups | numberOfValuesPerGroup | Memory (GB) | Runtime (s) | | --- | --- | --- | --- | | 500 | 50 | 0.48 | 1.47 | | 5000 | 50 | 39.00 | 58.00 | | 50 | 5000 | 0.42 | 0.65 | All memory values were extracted from the output of profvis, see example screenshot for the smallest example here: [![profvisoutput](https://i.stack.imgur.com/gfwcv.png)](https://i.stack.imgur.com/gfwcv.png)
2021/03/11
[ "https://Stackoverflow.com/questions/66582173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12172058/" ]
Approach for exact results: Median is "the middle" value of a **sorted** vector. (or mean of two middle values for even length vector) If we know the length of the sorted vector of others, we can directly look up the corresponding vector element(s) index for the median thus avoiding actually computing the median n\*groupId times: ``` library(data.table) set.seed(1) numberOfGroups <- 5000 numberOfValuesPerGroup <- 50 dt <- data.table( groupId = as.character(rep(1:numberOfGroups, each = numberOfValuesPerGroup)), value = round(runif(n = numberOfGroups * numberOfValuesPerGroup), 4) ) # group count match table + idx position for median of others nrows <- dt[, .N] dt_match <- dt[, .(nrows_other = nrows- .N), by = .(groupId_match = groupId)] dt_match[, odd := nrows_other %% 2] dt_match[, idx1 := ceiling(nrows_other/2)] dt_match[, idx2 := ifelse(odd, idx1, idx1+1)] setkey(dt, value) dt_match[, medianOfAllTheOtherGroups := dt[groupId != groupId_match][c(idx1, idx2), sum(value)/2], by = groupId_match] dt[dt_match, medianOfAllTheOtherGroups := i.medianOfAllTheOtherGroups, on = c(groupId = "groupId_match")] ``` There might be more data.table-ish ways improving performance further, I guess. Memory/runtime for numberOfGroups = 5000 and numberOfValuesPerGroup = 50: **20GB, 27000ms**
17,447
I'm new to Arduino and microcontroller . I want to connect my Arduino Mega to three slaves which Arduino Unos. I know that these slaves will share MISO, MOSI, and SCK lines. However, SS is unique to each slave. For single slave, the SS is pin 53. So, for three slaves, which other two pins can I use as SS? Thank you for your help.
2015/11/03
[ "https://arduino.stackexchange.com/questions/17447", "https://arduino.stackexchange.com", "https://arduino.stackexchange.com/users/14543/" ]
To better understand how you can do this it is good to understand first just what goes on when a button bounces. It is, literally, bouncing - just like a ball when you drop it. Due to the fact that it's either connected to ground or pulled up to +5V by the pullup resistor it's either going to be LOW or HIGH with very little time between when it's not in either state, so we can pretty much ignore the rise and fall times of the signal. It's either connected to ground, or it's not connected to ground. And we're only really interested in when it's connected to ground. More importantly we're interested in *how long* it's been connected to ground for. By remembering the time it transitioned from HIGH to LOW and then comparing that time to the current time you can know how long it has been connected to ground. By noticing when it's no longer connected to ground and "forgetting" the time you remembered you can start counting afresh with the next transition from HIGH to LOW. Take the following diagram for instance: [![enter image description here](https://i.stack.imgur.com/S2wVC.png)](https://i.stack.imgur.com/S2wVC.png) The blue line is the state of the button. As you can see it starts HIGH, then it gets pressed to be LOW and bounces between HIGH and LOW a number of times before it settles on being LOW. The red line is the difference between a timestamp that is set to be equal to `millis()` at the moment the button transitions from HIGH to LOW and the current `millis()` value, and is ignored when the button is HIGH. As you can see the difference between that timestamp and the current `millis()` value steadily increases. Whenever the button bounces to the HIGH state it resets that difference, and it starts again with the next LOW transition. When the button has finished bouncing there is nothing to change the state of the timestamp, so the difference keeps increasing. Eventually that difference will pass a trigger point (the yellow line in this diagram) and at that point you can be fairly sure that the button has finished bouncing and you should react to it. To translate that into some code, you may end up with something like this (untested): ``` // Two variables to store remembered state information - the time // of the last HIGH-LOW transition and the previous state of the // button. static uint32_t debounceTime = 0; static uint8_t buttonState = HIGH; // Check to see if the button has changed state if (digitalRead(buttonPin) != buttonState) { // Remember the new state buttonState = digitalRead(buttonPin); // If the new state is LOW ... if (buttonState == LOW) { // ... then record the time stamp debounceTime = millis(); } else { // ... otherwise set the time stamp to 0 for "don't care". debounceTime = 0; } } // If the time stamp is more than 0 and the difference between now and // then is greater than 10ms ... if (debounceTime > 0 && (millis() - debounceTime > 10)) { // ... set the time stamp to 0 to say we have finished debouncing debounceTime = 0; // and do whatever it is you need to do. digitalWrite(ledPin, HIGH); } ``` There are various tweaks and additions that could be made to that method, but that gives you the basic idea of how you split the debouncing away from the reacting, and it's the *results* of the debouncing that you react to, not the button state itself.
195,030
I'm just throwing this out there for discussion/answering: If person A sat in a chair all his life, in a house on earth (let's say 100 years), and person B flew around in earth's atmosphere at let's say 1000km/h or 1000mph (which ever is easiest to comprehend) for 100 years. Would there be a time difference for those people at the end of their life? would person B's clock have ran slower than person A, as person B was traveling at a speed closer to the speed of light, or is this speed too slow to be relevant?
2015/07/20
[ "https://physics.stackexchange.com/questions/195030", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/86302/" ]
> > Let's say a field of stars all die within a short amount of time. Just > for argument's sake they produce a debris field of iron ( or any other > heavy element). Provided that there is enough time the debris will > agglomerate, we know this. > > > My question: Given enough mass, will this agglomeration of heavy > elements fuse into even heavier elements? > > > Short answer, no, as others have said. At least, not in the stellar fusion sense, because heavier than Iron doesn't fuse in stellar fusion. Heavier than Iron fuses in supernova explosions. Quick Source: <http://curious.astro.cornell.edu/copyright-notice/85-the-universe/supernovae/general-questions/418-how-are-elements-heavier-than-iron-formed-intermediate> More info here: [Origin of elements heavier than Iron (Fe)](https://physics.stackexchange.com/questions/7131/origin-of-elements-heavier-than-iron-fe) > > To be plain, I am not talking about stellar fusion or whether there is > enough latent energy to continue fusion at an already existing core. I > want to know if there was enough collective mass in the debris field, > could the field itself, coalesce to the point where the heavy elements > will fuse. > > > Lets examine what happens when the iron coalesces, and in reality, it's unlikely that you'd have Iron and nothing else. It's hard to imagine a share of hydrogen, helium, carbon, etc, wouldn't be present, but assuming just Iron: First, you get something similar to a planet or a planet core. That gets bigger as more coalesces. Then something cool happens (or, well, hot more specifically), but it's kinda neat. At a certain point, the planet stops getting bigger and starts getting smaller, and as it gets smaller, it gets hotter, not from fusion, just the energy of coalescing. In time, it could glow hot like the sun, but much smaller than a sun. If I was to guess, the peak size might be around the size of Neptune. (Peak hydrogen planet size is about the size of Jupiter, peak Iron planet size would, I would think, be a fair bit smaller). Eventually, with enough mass, you get something something similar to a white dwarf. Iron white dwarfs don't exist because stars that become white dwarfs don't get to the Iron creation stage. There's some metallicity, but essentially, white dwarfs are carbon/Oxygen, or, smaller ones can be made of Helium and sometimes, there's some Neon, Magnesium - more on that here: <https://en.wikipedia.org/wiki/White_dwarf> Your scenario would essentially become an Iron white dwarf. Then, as with any white dwarf, at a certain mass, it reaches the Chandrasekhar limit and the inside of the star would begin to degenerate into a Neutron Star and once that process begins, it moves quickly and you basically have a really really really big boom and a type 1a supernova. And during the supernova, a lot of the Iron would fuse into heavier elements, but it would kind of happen all of a sudden, in the reasonably short period of time.
34,066,607
When I have to write a reference to a callable function I use the standard syntax of PHP [defined as](http://php.net/manual/it/language.types.callable.php): > > A PHP function is **passed by its name as a string**. Any built-in or user-defined function can be used *[... omitted...]*. > > > A method of an instantiated object is passed as an array containing an object at index 0 and the **method name** *(aka string)* > at index 1. > > > Static class methods can also be passed without instantiating an object of that class by passing the **class name** *(still a string)* > instead of an object at index 0. > > > As of PHP 5.2.3, it is also possible to pass *(the string)* **'ClassName::methodName'**. > > > Apart from common user-defined function, anonymous functions can also be passed to a callback parameter. > > > All of these ways are not "IDE friendly" for operations like *function name refactor* or *find usage of*. In my answer I propose a solution, but there are other approaches that can be applied, even totally different, that allow to IDE to "find" the invocation of the methods?
2015/12/03
[ "https://Stackoverflow.com/questions/34066607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7002281/" ]
You already are next to the shortest thing you can do You can perfectly call your anonymous function directly in your function call without using a variable For instance, you can replace: ``` $callable=function($param) use ($object){ return $object->myMethod($param); } call_user_func($callable, $param); ``` by: ``` call_user_func(function($param) use ($object){ return $object->myMethod($param); }, $param); ``` You will have to wait for [arrow functions](https://wiki.php.net/rfc/arrow_functions) in future PHP versions, and you should be able to use something like: ``` call_user_func(fn($a) => $object->myMethod($a), $param); ```
34,440,838
WebBrowser control has a ContextMenuStrip property that can be set to a context menu. But this menu appears by right-click, how can I show it by left-click? There is no `Click` event for WebBrowser control and the `MousePosition` of `WebBrowser.Document` click event is not precise. It seems it depends on the element the mouse is over and also if the browser scrolls isn't shown in right place.
2015/12/23
[ "https://Stackoverflow.com/questions/34440838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2651073/" ]
You can assign a handler to [`Click`](https://msdn.microsoft.com/en-us/library/system.windows.forms.htmldocument.click(v=vs.110).aspx) event or other mouse events of [`Document`](https://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.document(v=vs.110).aspx) and show the context menu at [`Cursor.Position`](https://msdn.microsoft.com/en-us/library/system.windows.forms.cursor.position(v=vs.110).aspx). You can also prevent the default click action `e.ReturnValue = false;`. ``` private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { this.webBrowser1.Document.Click += Document_Click; } void Document_Click(object sender, HtmlElementEventArgs e) { //To prevent the default click action you can uncomment next line: //e.ReturnValue = false; this.contextMenuStrip1.Show(Cursor.Position); } ```
70,423,477
I have a C++ class which I intend to call from python's mpi4py interface such that each node spawns the class. On the C++ side, I'm using the [Open MPI](https://www.open-mpi.org/) library (installed via [homebrew](https://formulae.brew.sh/formula/open-mpi)) and [pybind11](https://github.com/pybind/pybind11). The C++ class is as follows: ```cpp #include <pybind11/pybind11.h> #include <iostream> #include <chrono> #include <thread> #include <vector> #include <mpi.h> // #define PyMPI_HAVE_MPI_Message 1 // #include <mpi4py/mpi4py.h> namespace py = pybind11; class SomeComputation { float multiplier; std::vector<int> test; MPI_Comm comm_; public: void Init() { int rank; MPI_Comm_rank(comm_, &rank); test.clear(); test.resize(10, rank); } void set_comm(MPI_Comm comm){ this->comm_ = comm; } SomeComputation(float multiplier_) : multiplier(multiplier_){} ~SomeComputation() { std::cout << "Destructor Called!\n"; } float compute(float input) { std::this_thread::sleep_for(std::chrono::milliseconds((int)input * 10)); for (int i = 0; i != 10; ++i) { std::cout << test[i] << " "; } std::cout << std::endl; return multiplier * input; } }; PYBIND11_MODULE(module_name, handle) { py::class_<SomeComputation>(handle, "Cpp_computation") .def(py::init<float>()) // args of constructers are template args .def("set_comm", &SomeComputation::set_comm) .def("compute", &SomeComputation::compute) .def("cpp_init", &SomeComputation::Init); } ``` and here's the python interface spawning the same C++: ```py from build.module_name import * import time from mpi4py import MPI comm = MPI.COMM_WORLD rank = comm.Get_rank() m = Cpp_computation(44.0) # send communicator to cpp m.cpp_init() i = 0 while i < 5: print(m.compute(i)) time.sleep(1) i+=1 ``` I've already tried "[Sharing an MPI communicator using pybind11](https://stackoverflow.com/q/52657173/4593199)" but I'm stuck at a long unhelpful error ([full message](https://pastebin.com/raw/zfEJGh27)): ```none [...] /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:1398:22: required from 'pybind11::class_<type_, options>& pybind11::class_<type_, options>::def(const char*, Func&&, const Extra& ...) [with Func = void (SomeComputation::*)(ompi_communicator_t*); Extra = {}; type_ = SomeComputation; options = {}]' /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:79:7: required from here /opt/homebrew/Cellar/gcc/11.2.0_3/include/c++/11/type_traits:1372:38: error: invalid use of incomplete type 'struct ompi_communicator_t' 1372 | : public integral_constant<bool, __is_base_of(_Base, _Derived)> | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~ In file included from /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:6: /opt/homebrew/Cellar/open-mpi/4.1.2/include/mpi.h:419:16: note: forward declaration of 'struct ompi_communicator_t' 419 | typedef struct ompi_communicator_t *MPI_Comm; | ^~~~~~~~~~~~~~~~~~~ [...] /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:1398:22: required from 'pybind11::class_<type_, options>& pybind11::class_<type_, options>::def(const char*, Func&&, const Extra& ...) [with Func = void (SomeComputation::*)(ompi_communicator_t*); Extra = {}; type_ = SomeComputation; options = {}]' /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:79:7: required from here /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/detail/descr.h:40:19: error: invalid use of incomplete type 'struct ompi_communicator_t' 40 | return {{&typeid(Ts)..., nullptr}}; | ^~~~~~~~~~ In file included from /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:6: /opt/homebrew/Cellar/open-mpi/4.1.2/include/mpi.h:419:16: note: forward declaration of 'struct ompi_communicator_t' 419 | typedef struct ompi_communicator_t *MPI_Comm; | ^~~~~~~~~~~~~~~~~~~ [...] from /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:1: /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/detail/descr.h:40:42: error: could not convert '{{<expression error>, nullptr}}' from '<brace-enclosed initializer list>' to 'std::array<const std::type_info*, 3>' 40 | return {{&typeid(Ts)..., nullptr}}; | ^ | | | <brace-enclosed initializer list> [...] In file included from /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:1: /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h: In instantiation of 'void pybind11::cpp_function::initialize(Func&&, Return (*)(Args ...), const Extra& ...) [with Func = pybind11::cpp_function::cpp_function<void, SomeComputation, ompi_communicator_t*, pybind11::name, pybind11::is_method, pybind11::sibling>(void (SomeComputation::*)(ompi_communicator_t*), const pybind11::name&, const pybind11::is_method&, const pybind11::sibling&)::<lambda(SomeComputation*, ompi_communicator_t*)>; Return = void; Args = {SomeComputation*, ompi_communicator_t*}; Extra = {pybind11::name, pybind11::is_method, pybind11::sibling}]': [..] /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:1398:22: required from 'pybind11::class_<type_, options>& pybind11::class_<type_, options>::def(const char*, Func&&, const Extra& ...) [with Func = void (SomeComputation::*)(ompi_communicator_t*); Extra = {}; type_ = SomeComputation; options = {}]' /Users/purusharth/Documents/hiwi/pympicontroller/main.cpp:79:7: required from here /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:266:73: in 'constexpr' expansion of 'pybind11::detail::descr<18, SomeComputation, ompi_communicator_t>::types()' /Users/purusharth/Documents/hiwi/pympicontroller/pybind11/include/pybind11/pybind11.h:266:39: error: 'constexpr' call flows off the end of the function 266 | PYBIND11_DESCR_CONSTEXPR auto types = decltype(signature)::types(); | ^~~~~ ``` The error points to `.def("set_comm", &SomeComputation::set_comm)` What is the cause of these errors, and how should they be resolved? UPDATE: Added answer below by using custom type caster as explained in [this answer](https://stackoverflow.com/questions/49259704/pybind11-possible-to-use-mpi4py). But is it the *only* way to go about it?
2021/12/20
[ "https://Stackoverflow.com/questions/70423477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4593199/" ]
I understand that you would like to have an explanation and not just a code dump or some comments. So, let me try to explain you. As you know: Numbers like 12345 in a base 10 numbering system or decimal system are build of a digit and a power of 10. Mathematically you could write 12345 also a `5*10^0 + 4*10^1 + 3*10^2 + 2*10^3 + 1*10^4`. Or, we can write: ``` number = 0; number = number + 1; number = number * 10; number = number + 2; number = number * 10; number = number + 3; number = number * 10; number = number + 4; number = number * 10; number = number + 5; ``` That is nothing new. But it is important to understand, how to get back the digits from a number. Obviously we need to make an integer division by 10 somewhen. But this alone does not give us the digits. If we perform a division o 12345 by 10, then the result is 1234.5. And for the intger devision it os 1234 with a rest of 5. And now, we can see that the rest is the digit that we are looking for. And in C++ we have a function that gives us the rest of an integer division. It is the modulo operator %. Let us look, how this works: ``` int number = 12345; int digit = number % 10; // Result will be 5 // Do something with digit number = number / 10; // Now number is 1234 (Integer division will truncate the fraction) digit = number % 10; // Result is now 4 // Do something with digit number = number / 10; // Now number is 123 (Integer division will truncate the fraction) digit = number % 10; // Result is now 3 // Do something with digit number = number / 10; // Now number is 12 (Integer division will truncate the fraction) digit = number % 10; // Result is now 2 // Do something with digit number = number / 10; // Now number is 1 (Integer division will truncate the fraction) digit = number % 10; // Result is now 1 number = number / 10; // Now number is 0, and we can stop the operation. ``` And later we can do all this in a loop. Like with ``` int number = 12345; while (number > 0) { int digit = number % 10; // Extract next digit from number // Do something with digit number /= 10; } ``` And thats it. Now we extracted all digits. --- Next is counting. We have 10 different digits. So, we could now define 10 counter variables like "int counterFor0, counterFor1, counterFor2 ..... , counterFor9" and the compare the digit with "0,1,2,...9" and then increment the related counter. But that is too much typing work. But, luckily, we have arrays in C++. So we can define an array with 10 counters like: `int counterForDigit[10]`. OK, understood. You remember that we had in the above code a comment "// Do something with digit ". And this we will do now. If we have a digit, then we use that as an index in our array and increment the related counter. So, finally. One possible solution would be: ``` #include <iostream> int main() { // Test number. Can be anything int number = 12344555; // Counter for our digits int counterForDigits[10]{}; // The {} will initialize all values in the array with 0 // Extract all digits while (number > 0) { // Get digit int digit = number % 10; // Increment related counter counterForDigits[digit]++; // Get next number number /= 10; } // Show result for (int k = 0; k < 10; ++k) std::cout << k << " : " << counterForDigits[k] << '\n'; } ``` If you do not want to show 0 outputs, then please add `if (counterForDigits[k] > 0)` after the `for` statement. If you should have further questions, then please ask
191,621
I want to retrieve a record from SharePoint list by passing field value to CAML query using javascript,I tried below code ``` function retrieveDetails(name) { var ctx = new SP.ClientContext(appWebUrl);//Get the SharePoint Context object based upon the URL var myList = ctx.get_web().get_lists().getByTitle("PersonalDetails"); var query = new SP.CamlQuery(); query.set_viewXml('<View><Query><Where><eq><FieldRef Name=\'Name\'/><Value Type=\'Text\'>' + name + '</Value><FieldRef Name=\'email\'/><Value Type=\'Text\'></Value></eq>" + "</Where></Query><RowLimit>100</RowLimit></View>'); var items = myList.getItems(query); ctx.load(items); ctx.executeQueryAsync(onQuerySucceeded, onQueryFailed); function onQuerySucceeded() { Roomdetailstable(items); } function onQueryFailed(sender, args) { alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace()); } } function details(items) { var itemInfo = ''; var enumerator = items.getEnumerator(); while (enumerator.moveNext()) { var currentListItem = enumerator.get_current(); var rnmae = currentListItem.get_item('Name'); document.getElementById("rnme").innerHTML = rnmae ; var emailid= currentListItem.get_item('email'); document.getElementById("emailid").innerHTML = emailid; } } ``` but it is showing error like below [![enter image description here](https://i.stack.imgur.com/9ruAA.png)](https://i.stack.imgur.com/9ruAA.png)
2016/08/24
[ "https://sharepoint.stackexchange.com/questions/191621", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/52922/" ]
resolved this issue by removing `<Query></Query>` from my caml query ``` function retrieveDetails(name) { var ctx = new SP.ClientContext(appWebUrl);//Get the SharePoint Context object based upon the URL var myList = ctx.get_web().get_lists().getByTitle("PersonalDetails"); var query = new SP.CamlQuery(); query.set_viewXml('<View><Where><eq><FieldRef Name=\'Name\'/><Value Type=\'Text\'>' + name + '</Value><FieldRef Name=\'email\'/><Value Type=\'Text\'></Value></eq>" + "</Where><RowLimit>100</RowLimit></View>'); var items = myList.getItems(query); ctx.load(items); ctx.executeQueryAsync(onQuerySucceeded, onQueryFailed); function onQuerySucceeded() { Roomdetailstable(items); } function onQueryFailed(sender, args) { alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace()); } } function details(items) { var itemInfo = ''; var enumerator = items.getEnumerator(); while (enumerator.moveNext()) { var currentListItem = enumerator.get_current(); var rnmae = currentListItem.get_item('Name'); document.getElementById("rnme").innerHTML = rnmae ; var emailid= currentListItem.get_item('email'); document.getElementById("emailid").innerHTML = emailid; } } ```
21,394,573
I would like to get the value for of a hiddenfield if a checkbox is checked on my gridview my gridview: ``` <asp:GridView ID="gv_enfant" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3" DataSourceID="SqlDataSource1" Width="533px"> <Columns> <asp:TemplateField HeaderText="Select"> <ItemTemplate> <asp:CheckBox ID="CheckBoxenfant" runat="server" /> <asp:HiddenField ID="codeenfant" runat="server" Value='<%# Eval("codeEnfants") %>' /> </ItemTemplate> .............. </asp:GridView> ``` and here is how I loop trhough the rows and check: ``` string myid = string.Empty; for (int i = 0; i < gv_enfant.Rows.Count; i++) { CheckBox chbox = (CheckBox)gv_enfant.Rows[i].Cells[0].FindControl("CheckBoxenfant"); if (chbox.Checked) { myid = ((HiddenField)gv_enfant.Rows[i].Cells[0].FindControl("codeenfant")).Value; } } ``` I put a breakpoint on the condition, debugger never hit that line
2014/01/28
[ "https://Stackoverflow.com/questions/21394573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Late answer, but if it still helps (or for anyone else) you should be able to do the following with SQL 2008. ``` DECLARE @point GEOMETRY = GEOMETRY::STPointFromText('POINT(0 0)', 0); DECLARE @line GEOMETRY = GEOMETRY::STLineFromText('POINT(10 10, 20 20)', 0); SELECT STIntersection(@point.STBuffer(@point.STDistance(@line))); ``` Essentially, you calculate the distance between the two geometries,use that as a buffer on the point which should result in the geometries touching, and take the intersection (point) of that.
48,395,984
I have the following vuejs component. I know that it is a pretty simple example, but still it does not load correctly. Find below my code: ```js Vue.component('my-component', { template: '<div>{{ msg }}</div>', data: { msg: 'hello' } }); new Vue({ el: '#app-6' }); ``` ```html <!DOCTYPE html> <html lang="en"> <meta> <meta charset="UTF-8"> <title>Components in Vue.js</title> </meta> <body> <div id="app-6"> test <my-component></my-component> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.6/vue.min.js"></script> </body> </html> ``` Any suggestions what I am doing wrong? I appreciate your replies!
2018/01/23
[ "https://Stackoverflow.com/questions/48395984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2847689/" ]
Data Must be a function always ```js var data={msg: 'hello'} Vue.component('my-component', { template: '<div>{{ msg }}</div>', data:function() { return data; } }); new Vue({ el: '#app-6' }); ``` ```html <!DOCTYPE html> <html lang="en"> <meta> <meta charset="UTF-8"> <title>Components in Vue.js</title> </meta> <body> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.6/vue.min.js"></script> <div id="app-6"> test <my-component></my-component> </div> </body> </html> ```
51,195,379
Strange issue... This is using VisualStudio Community 2017 and is a C++CLI WinForms project. **BGStatsInterface.cpp** ``` #include "BGStatsInterface.h" using namespace System; using namespace System::Windows::Forms; [STAThreadAttribute] void Main(array<String^>^ args) { Application::EnableVisualStyles(); Application::SetCompatibleTextRenderingDefault(false); BattlegroundStats::BGStatsInterface form; Application::Run(%form); } ``` **BGStatsInterface.h** ``` #pragma once #include <windows.h> #include "LuaReader.h" namespace BattlegroundStats { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; using namespace System::IO; public ref class BGStatsInterface : public System::Windows::Forms::Form { public: BGStatsInterface(void) { InitializeComponent(); this->MinimizeBox = false; this->MaximizeBox = false; } static System::Windows::Forms::TextBox^ textBoxLog; static System::Void addMsg(String^ text) { textBoxLog->AppendText(text + "\n"); } protected: ~BGStatsInterface() { if (components) { delete components; } } private: LuaReader ^ reader = gcnew LuaReader(); private: System::Windows::Forms::Button^ b1; private: System::ComponentModel::Container ^components; #pragma region Windows Form Designer generated code void InitializeComponent(void) { this->textBoxLog = (gcnew System::Windows::Forms::TextBox()); this->b1 = (gcnew System::Windows::Forms::Button()); this->SuspendLayout(); // // textBoxLog // this->textBoxLog->BackColor = System::Drawing::SystemColors::ControlLightLight; this->textBoxLog->Cursor = System::Windows::Forms::Cursors::IBeam; this->textBoxLog->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 6.75F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->textBoxLog->Location = System::Drawing::Point(10, 80); this->textBoxLog->Multiline = true; this->textBoxLog->Name = L"textBoxLog"; this->textBoxLog->ReadOnly = true; this->textBoxLog->ScrollBars = System::Windows::Forms::ScrollBars::Vertical; this->textBoxLog->Size = System::Drawing::Size(280, 90); this->textBoxLog->TabIndex = 6; this->textBoxLog->TabStop = false; this->textBoxLog->GotFocus += gcnew System::EventHandler(this, &BGStatsInterface::textBoxLog_HideCaret); // // b1 // this->b1->Location = System::Drawing::Point(100, 30); this->b1->Name = L"b1"; this->b1->Size = System::Drawing::Size(75, 23); this->b1->TabIndex = 7; this->b1->Text = L"DoSomething"; this->b1->UseVisualStyleBackColor = true; this->b1->Click += gcnew System::EventHandler(this, &BGStatsInterface::b1_Click); // // BGStatsInterface // this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->ClientSize = System::Drawing::Size(301, 411); this->Controls->Add(this->b1); this->Controls->Add(this->textBoxLog); this->FormBorderStyle = System::Windows::Forms::FormBorderStyle::FixedSingle; this->MaximumSize = System::Drawing::Size(317, 450); this->MinimumSize = System::Drawing::Size(317, 450); this->Name = L"BGStatsInterface"; this->Text = L"Test"; this->ResumeLayout(false); this->PerformLayout(); } #pragma endregion System::Void textBoxLog_HideCaret(System::Object^ sender, System::EventArgs^ e) { TextBox^ focus = safe_cast<TextBox^>(sender); HideCaret((HWND)focus->Handle.ToPointer()); } System::Void b1_Click(System::Object^ sender, System::EventArgs^ e) { reader->DoSomething(); addMsg("DoingSomethingA"); System::Diagnostics::Debug::WriteLine("DoingSomethingA"); } }; } ``` **LuaReader.cpp** ``` #include "LuaReader.h" #include "BGStatsInterface.h" // PointA- This is where I'm having the issue. using namespace System; LuaReader::LuaReader(){} System::Void LuaReader::DoSomething() { BattlegroundStats::BGStatsInterface::addMsg("DoingSomethingB"); System::Diagnostics::Debug::WriteLine("DoingSomethingB"); } ``` **LuaReader.h** ``` #pragma once #include "GameCollection.h" // PointB - Another issue here. ref class LuaReader { public: LuaReader(); GameCollection^ gameData = gcnew GameCollection(); System::String^ _fileName; System::Void DoSomething(); }; #endif ``` **GameCollection.cpp** ``` #include "GameCollection.h" GameCollection::GameCollection(){} ``` **GameCollection.h** ``` #pragma once using namespace System; ref class GameCollection { public: GameCollection(); }; ``` **The Problem:** In LuaReader.cpp If I include BGStatsInterface.h (needed so it can access the addMsg method), noted by PointA, it wont compile and will generate the errors listed below. However, if I remove the GameCollection.h include from LuaReader.h (needed so I can create the GameCollection object), noted at PointB, it has no issues with BGStatsInterface.h included in the LuaReader.cpp file and everything compiles/runs without issues. I don't know what to do... Why does it only work if I don't create the GameCollection object in LuaReader.h? What have I done wrong? **Errors:** ``` Severity Code Description Project File Line Suppression State Error (active) E1986 an ordinary pointer to a C++/CLI ref class or interface class is not allowed BattlegroundStats c:\Program Files (x86)\Windows Kits\10\Include\10.0.16299.0\um\servprov.h 91 Error (active) E0266 "IServiceProvider" is ambiguous BattlegroundStats c:\Program Files (x86)\Windows Kits\10\Include\10.0.16299.0\um\servprov.h 115 Error (active) E0266 "IServiceProvider" is ambiguous BattlegroundStats c:\Program Files (x86)\Windows Kits\10\Include\10.0.16299.0\um\servprov.h 239 Error (active) E0266 "IServiceProvider" is ambiguous BattlegroundStats c:\Program Files (x86)\Windows Kits\10\Include\10.0.16299.0\um\servprov.h 249 Error (active) E0266 "IServiceProvider" is ambiguous BattlegroundStats c:\Program Files (x86)\Windows Kits\10\Include\10.0.16299.0\um\urlmon.h 6867 Error (active) E0266 "IServiceProvider" is ambiguous BattlegroundStats c:\Program Files (x86)\Windows Kits\10\Include\10.0.16299.0\um\urlmon.h 6869 Error C3699 '*': cannot use this indirection on type 'IServiceProvider' BattlegroundStats c:\program files (x86)\windows kits\10\include\10.0.16299.0\um\servprov.h 91 Error C2371 'IServiceProvider': redefinition; different basic types BattlegroundStats c:\program files (x86)\windows kits\10\include\10.0.16299.0\um\servprov.h 98 Error C2872 'IServiceProvider': ambiguous symbol BattlegroundStats c:\program files (x86)\windows kits\10\include\10.0.16299.0\um\servprov.h 115 Error C2872 'IServiceProvider': ambiguous symbol BattlegroundStats c:\program files (x86)\windows kits\10\include\10.0.16299.0\um\servprov.h 239 Error C2872 'IServiceProvider': ambiguous symbol BattlegroundStats c:\program files (x86)\windows kits\10\include\10.0.16299.0\um\servprov.h 249 Error C2872 'IServiceProvider': ambiguous symbol BattlegroundStats c:\program files (x86)\windows kits\10\include\10.0.16299.0\um\urlmon.h 6867 Error C2872 'IServiceProvider': ambiguous symbol BattlegroundStats c:\program files (x86)\windows kits\10\include\10.0.16299.0\um\urlmon.h 6869 ```
2018/07/05
[ "https://Stackoverflow.com/questions/51195379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7194063/" ]
This happens when using #include Windows.h as it defines ::IServiceProvider while the framework has System::IServiceProvider, then when there's a using namespace System in scope somewhere it becomes ambiguous. Solution is to simply put the delcarations in your own namespace.
32,356,907
I have basic order form (4 inputs only for testing purposes), i want to count number of inputs (total items) where value is filled in and higher then 0 (basicaly how many products has been ordered, no to confuse with their quantities). When i add products is fine, problems start when I remove items( set them to 0). Could you help me to work it out. Working jsfiddle: <http://jsfiddle.net/nitadesign/97tnrepg/33/> And few lines to bring your attention into a right place: ``` function GetOrder(curId){ var order = null; for(i = 0; i< orders.length; i++){ if(orders[i].id == curId){ order = orders[i]; break; } } return order; } function CalculateTotal(){ var total = 0; for(i = 0; i< orders.length; i++){ total = total + orders[i].packTotal; } console.log(total); if(total > 0){ $("#order_total").html('Total Items:' + i + '<br>' + 'Order Subtotal: ' + total); $("#order_total").show(); $('.submitorder').show(); } if(total == 0){ $("#order_total").html('Your shopping basket is empty'); $("#order_total").show(); $('.submitorder').hide(); } } ``` Thanks a lot for your help in advance!
2015/09/02
[ "https://Stackoverflow.com/questions/32356907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1826668/" ]
Just use a jquery selector and loop through it. ``` $("input").change(function(){ var counter = 0; $("input").each(function(){ if($(this).val() != "" && $(this).val() != 0) counter++; }); $("#order_total").html('Total Items:' + counter + '<br>' + 'Order Subtotal: ' + total); }); ```
9,553,939
I'm trying to crawl FTP and pull down all the files recursively. Up until now I was trying to pull down a directory with ``` ftp.list.each do |entry| if entry.split(/\s+/)[0][0, 1] == "d" out[:dirs] << entry.split.last unless black_dirs.include? entry.split.last else out[:files] << entry.split.last unless black_files.include? entry.split.last end ``` But turns out, if you split the list up until last space, filenames and directories with spaces are fetched wrong. Need a little help on the logic here.
2012/03/04
[ "https://Stackoverflow.com/questions/9553939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/853685/" ]
You can also use a regular expression. I put one together. Please verify if it works for you as well as I don't know it your dir listing look different. You have to use Ruby 1.9 btw. ``` reg = /^(?<type>.{1})(?<mode>\S+)\s+(?<number>\d+)\s+(?<owner>\S+)\s+(?<group>\S+)\s+(?<size>\d+)\s+(?<mod_time>.{12})\s+(?<path>.+)$/ match = entry.match(reg) ``` You are able to access the elements by name then `match[:type]` contains a `'d'` if it's a directory, a space if it's a file. All the other elements are there as well. Most importantly `match[:path]`.
13,539,692
Say we have the following classes: ``` class DoubleOhSeven { public static void doSomethingClassy(); public static void neverDoThisClassy(); } class Dude { public void doSomething(); public void neverDoThis(); } public class Party { public static void main(String[] args){ DoubleOhSeven.doSomething(); Dude guy = new Dude; guy.doSomething(); } } ``` Of course, all the methods will be compiled into their respective `.class`: do the unused static/instance methods occupy memory at run time? What about unused inherited or imported methods?
2012/11/24
[ "https://Stackoverflow.com/questions/13539692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/390897/" ]
The unused methods are still there occupying memory as part of the class / object, even if they're not directly called. If they were optimised away, then that would make reflective calls on these methods impossible. One could argue that an optimisation could be generated that only stored the method stub in memory, and garbage collected the method contents (which would then be re-fetched from the class file if a call was made.) However, I'm not aware of a VM which does this, and it would be hard to justify due to the likely minimal gains in memory and tradeoff in speed whenever such a method was called. Unused inherited methods would be exactly the same.
26,404
In our web-application(built on Bootstrap and Angular), certain tabs in the navbar are displayed only to particular users. Certain input boxes/ buttons are enabled only to certain users. I want to write test scripts using Selenium/ Sikuli to test this functionality and I want your suggestions in this approach. One of the ideas is to navigate to different pages in the UI, and use Selenium's `isDisplayed()` and `isEnabled()` functions and make assertions. And capture screenshots accordingly? The other idea is to use Sikuli and match certain submenus being present on hover, capture screenshots and compare with the expected. Which approach do you guys think is the better one to use? Also, please suggest if there's another way to do it. Would also be so glad if you guys can provide me a generic method to test this.
2017/03/26
[ "https://sqa.stackexchange.com/questions/26404", "https://sqa.stackexchange.com", "https://sqa.stackexchange.com/users/24825/" ]
I think the name comes from the resulting graph over-time, which is called a stairstep graph. I don't think it is official, but more some terms added together which seemed logical. The step load pattern increases the user load periodically during the load test. Creating a stairstep graph where you show number of users vs time: [![enter image description here](https://i.stack.imgur.com/shNoy.png)](https://i.stack.imgur.com/shNoy.png) This instead of a continuous increase over time. Let say you increase the number of users by 60 each minute. This would generate a stairstep. You could also add a user each second increasing it linear. Other reads: * How to: Change the Load Pattern: <https://msdn.microsoft.com/en-us/library/ms182586(v=vs.80).aspx>
64,872,442
I deployed a Rails application in Digital Ocean Ubuntu Server using Capistrano. For some reason the puma server suddenly stops. I'm not sure what's the reason. That's why I created a script **/home/deploy/startup-script.sh** the script contains the commands to startup the Rails application in daemon ``` #!/bin/bash echo "Running Puma Server" touch hello.txt cd /srv/www/apps/app/current bundle exec puma -C /srv/www/apps/app/shared/puma.rb --daemon ``` then I run this script every minute using Cron. My **crontab -e** contains ``` * * * * * ./startup-script.sh ``` After 1 minute I noticed that it created a hello.txt file but my puma server is not running. But when I run it manually using `./startup-script.sh` it will run the server. **puma\_error.log** ``` Puma starting in single mode... * Version 4.3.1 (ruby 2.6.0-p0), codename: Mysterious Traveller * Min threads: 0, max threads: 8 * Environment: production * Daemonizing... === puma startup: 2020-09-21 05:16:28 +0000 === === puma startup: 2020-09-21 05:17:39 +0000 === * Listening on tcp://0.0.0.0:9292 === puma startup: 2020-09-21 06:11:35 +0000 === - Gracefully stopping, waiting for requests to finish === puma shutdown: 2020-09-21 06:11:35 +0000 === ``` **production.log** ``` Item Load (0.3ms) SELECT "items".* FROM "items" WHERE "items"."id" = $1 LIMIT $2 [["id", 208], ["LIMIT", 1]] CACHE Unit Load (0.0ms) SELECT "units".* FROM "units" WHERE "units"."id" = $1 LIMIT $2 [["id", 4], ["LIMIT", 1]] Item Load (0.3ms) SELECT "items".* FROM "items" WHERE "items"."id" = $1 LIMIT $2 [["id", 215], ["LIMIT", 1]] CACHE Unit Load (0.0ms) SELECT "units".* FROM "units" WHERE "units"."id" = $1 LIMIT $2 [["id", 4], ["LIMIT", 1]] Item Load (0.2ms) SELECT "items".* FROM "items" WHERE "items"."id" = $1 LIMIT $2 [["id", 198], ["LIMIT", 1]] CACHE Unit Load (0.0ms) SELECT "units".* FROM "units" WHERE "units"."id" = $1 LIMIT $2 [["id", 10], ["LIMIT", 1]] Rendering text template Rendered text template (0.0ms) Sent data Delivery Receipt 12-2020-001.pdf (0.5ms) Completed 200 OK in 4326ms (Views: 0.3ms | ActiveRecord: 37.4ms) ``` **puma\_access.log** ``` === puma startup: 2020-12-01 01:07:13 +0000 === ``` When starting the `startup-script.sh` script I'm getting this ``` Running Puma Server Puma starting in single mode... * Version 4.3.1 (ruby 2.6.0-p0), codename: Mysterious Traveller * Min threads: 0, max threads: 8 * Environment: production * Daemonizing... ``` My droplet is still running but the puma running on port 9292 disappears when crashes, so I suspect this is puma error.
2020/11/17
[ "https://Stackoverflow.com/questions/64872442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1077711/" ]
I agree with OP that, the simple predicate of the O(N) algo might not work on the stack-based solution when looking for the first element > 2x in the remaining array. I found a O(NlogN) solution for this btw. It uses a **Min-heap** to maintain the frontier elements we are interested in. ### Pseudo-code: ``` def get_2x_elements(input_list, multipler = 2): H = [] #min-heap with node-values as tuples (index, value) R = [-1 for _ in range(len(input_list))] # results-list for index, value in enumerate(input_list): while multiplier*H[0][1] < value: minval = extractMinFromHeap(H) R[minval[0]] = value insertToMinHeap(H, (index, value)) return R ``` ### Complexity-analysis: ``` 1. Insertion/Extraction from min-heap = O(logN) 2. Number of such operations = N Total-complexity = O(NlogN) ``` PS: This assumes we need the `first >2x element` from the remaining part of the list. Re: I made a Java verion implementation of your idea. Thanks @Serial Lazer ```java private static class ValueAndIndexPair implements Comparable<ValueAndIndexPair>{ public final double value; public final int index; public ValueAndIndexPair(double value, int index) { this.value = value; this.index = index; } @Override public int compareTo(ValueAndIndexPair other) { return Double.compare(value, other.value); } } public static double[] returnNextNTimeLargerElementIndex(final List<Double> valueList, double multiplier) { double[] result = new double[valueList.size()]; PriorityQueue<ValueAndIndexPair> minHeap = new PriorityQueue<>(); // Initialize O(n) for (int i = 0; i < valueList.size(); i++) { result[i] = -1.0; } if (valueList.size() <= 1) return result; minHeap.add(new ValueAndIndexPair(valueList.get(0) * multiplier, 0)); for (int i = 1; i <valueList.size(); i++) { double currentElement = valueList.get(i); while (!minHeap.isEmpty() && minHeap.peek().value < currentElement) { result[minHeap.poll().index] = currentElement; } minHeap.add(new ValueAndIndexPair(currentElement * multiplier, i)); } return result; } ```
29,578,436
I am new to Swift I am using MPMovieviewcontroller when i click next or previous button then no event occurs here is code ``` import UIKit import MediaPlayer class ViewController: UIViewController { var i : Int = 0 var movieplayer : MPMoviePlayerController! var arr = ["Akbar","Serial","ak"] override func viewDidLoad() { super.viewDidLoad() UIApplication.sharedApplication().beginReceivingRemoteControlEvents() self.becomeFirstResponder() startplaying() } override func canBecomeFirstResponder() -> Bool { return true } override func remoteControlReceivedWithEvent(event: UIEvent) { if event.subtype == UIEventSubtype.RemoteControlNextTrack { i++ startplaying() println(event.subtype) } } func startplaying() { if i <= 2 { let path = NSBundle.mainBundle().pathForResource(arr[i], ofType: "mov") let url = NSURL.fileURLWithPath(path!) movieplayer = MPMoviePlayerController(contentURL: url) } movieplayer.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height) movieplayer.view.sizeToFit() movieplayer.scalingMode = MPMovieScalingMode.AspectFill movieplayer.fullscreen = true movieplayer.controlStyle = MPMovieControlStyle.Fullscreen movieplayer.movieSourceType = MPMovieSourceType.File movieplayer.prepareToPlay() self.view.addSubview(movieplayer.view) } ``` When i debug this code then remoteControlReceivedWithEvent function did not execute I get donm help from [here](https://stackoverflow.com/questions/3593683/how-can-i-know-users-click-fast-forward-and-fast-rewind-buttons-on-the-playback)
2015/04/11
[ "https://Stackoverflow.com/questions/29578436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4741194/" ]
Try this ``` func startplaying() { if i <= 2 { let path = NSBundle.mainBundle().pathForResource(arr[i], ofType: "mov") let url = NSURL.fileURLWithPath(path!) movieplayer.contentURL = NSURL.fileURLWithPath(url) } ``` Read more: [Play MP4 using MPMoviePlayerController() in Swift](https://stackoverflow.com/questions/24350482/play-mp4-using-mpmovieplayercontroller-in-swift)
15,700,850
I am having some trouble finding a solution in mySQL, I have 2 tables where in the one I have my images and in the other I have my votes and image\_id that I bind together using this line: ``` $sql = "SELECT `image` FROM `sh_images`, `sh_votes` WHERE `sh_images`.`id`=`sh_votes`.`image_id` ORDER BY `vote` DESC"; ``` Everything works fine except that the images that aren't voted yet aren't showing. So do you have a solution for me?
2013/03/29
[ "https://Stackoverflow.com/questions/15700850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2223874/" ]
You should be using `LEFT JOIN` on this. `LEFT JOIN` is different from `INNER JOIN` (*which is what you are doing right now*). `LEFT JOIN` displays all the records define on the *LeftHand side* whether it has a matching record or none on the *RightHand side* table on the result. ``` SELECT image, vote FROM sh_images LEFT JOIN sh_votes ON sh_images.id = sh_votes.image_id ORDER BY vote DESC ``` * [SQLFiddle Demo](http://www.sqlfiddle.com/#!2/747ce/3) To further gain more knowledge about joins, kindly visit the link below: * [Visual Representation of SQL Joins](http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html)
31,470,858
I have two variables `@date` of type `datetime` and `@time` of type `time`. I want to add both to get another `datetime` variable. And I want to perform further calculations on it. Ex: ``` Declare @date datetime Declare @time time ``` I want something like this ``` @date = @date + @time (but not concatenation) SELECT @Startdate = DATEADD(DAY, -1, @date ) ``` Is there any way?
2015/07/17
[ "https://Stackoverflow.com/questions/31470858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2045931/" ]
You can tranform your time to seconds and add them to your datetime value: ``` DECLARE @datetime DATETIME = GETDATE(), @time TIME = '01:16:24', @timeinseconds INT PRINT 'we add ' + CAST(@time AS VARCHAR(8)) + ' to ' + CONVERT(VARCHAR,@datetime,120)+ ':' SELECT @timeinseconds = DATEPART(SECOND, @time) + DATEPART(MINUTE, @time) * 60 + DATEPART(HOUR, @time) * 3600 SET @datetime = DATEADD(SECOND,@timeinseconds,@datetime) PRINT 'The result is: ' + CONVERT(VARCHAR,@datetime,120) ``` Output: ``` we add 01:16:24 to 2015-07-17 09:58:45: The result is: 2015-07-17 11:15:09 ```
210,792
I don't know if it's heartless,but when I'm in a situation that is really sad(like a funeral) I always have this urge to laugh.Of course I try not to burst out in laughter but I guess it's how I cope with these things. Is there a word that can describe this?I don't mind if it would be used for the urge,the behaviour,the feeling.I'm just really interested how to express this kind of thing without having to say that I really,really have to laugh.
2014/11/28
[ "https://english.stackexchange.com/questions/210792", "https://english.stackexchange.com", "https://english.stackexchange.com/users/99370/" ]
**Nervous-laughter** should be a appropriate word. And in a novel I read a word **painful-dimples**, It sounds compatible too. But `painful-dimples` kind of word is not heard or seen usually.
4,587,392
Is it possible to create an instance of an interface in Java? Somewhere I have read that using inner anonymous class we can do it as shown below: ```java interface Test { public void wish(); } class Main { public static void main(String[] args) { Test t = new Test() { public void wish() { System.out.println("output: hello how r u"); } }; t.wish(); } } ``` ```none cmd> javac Main.java cmd> java Main output: hello how r u ``` Is it correct here?
2011/01/03
[ "https://Stackoverflow.com/questions/4587392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/547709/" ]
You can never instantiate an interface in java. You can, however, refer to an object that implements an interface by the type of the interface. For example, ``` public interface A { } public class B implements A { } public static void main(String[] args) { A test = new B(); //A test = new A(); // wont compile } ``` What you did above was create an Anonymous class that implements the interface. You are creating an Anonymous object, not an object of type `interface Test`.
1,053,217
Hey I would like to know the correct approach to this problem. I think I'm close but I'm confusing myself. How many sets of size five are there from the natural numbers 1-100 that contain exactly two odd numbers? First we would select 2 odd numbers (50 choose 2) Then sum it with (50 choose 3)? For the even #s?
2014/12/05
[ "https://math.stackexchange.com/questions/1053217", "https://math.stackexchange.com", "https://math.stackexchange.com/users/197861/" ]
Not sum it, multiply it. This is because for **every way** of choosing the odds, there are $\binom{50}{3}$ ways to choose the evens.
54,913,904
I'm trying to select the number of free beds per floor and the number of rooms in which those beds exist. I think I'm having trouble because I first have to calculate how many beds are free in each room, which I'm doing by subtracting the number of beds in the room minus the people that are assigned to that room. Can I `GROUP BY` the current query in a way that achieves the desired result? The tables used are these: ``` CREATE TABLE IF NOT EXISTS planta( codigo int PRIMARY KEY NOT NULL AUTO_INCREMENT, especialidad varchar(25) NOT NULL ) ENGINE=InnoDB; CREATE TABLE IF NOT EXISTS habitacion( id int PRIMARY KEY NOT NULL AUTO_INCREMENT, numero_camas int NOT NULL, planta_id int NOT NULL, FOREIGN KEY (planta_id) REFERENCES planta(codigo) )ENGINE=InnoDB; CREATE TABLE IF NOT EXISTS paciente( dni varchar(9) PRIMARY KEY NOT NULL, num_ss varchar(10) NOT NULL, nombre varchar(20) NOT NULL, direccion varchar(50) NOT NULL, tratamiento mediumtext NOT NULL, diagnostico mediumtext NOT NULL, habitacion_id int NOT NULL, medico_id int NOT NULL, FOREIGN KEY (habitacion_id) REFERENCES habitacion(id), FOREIGN KEY (medico_id) REFERENCES medico(num_colegiado) )ENGINE=InnoDB; ``` The query is this: ``` SELECT planta.codigo AS Floor_id, habitacion.id AS Room_id, numero_camas - count(dni) AS Free_beds FROM habitacion, paciente, planta WHERE planta_id = planta.codigo AND habitacion_id = habitacion.id GROUP BY planta.codigo, habitacion.id; ``` It returns this result: ``` Floor id | Room id | Free beds 1 1 1 1 2 1 2 3 3 ``` But I want this: ``` Floor id | Rooms | Free beds 1 2 2 2 1 3 ```
2019/02/27
[ "https://Stackoverflow.com/questions/54913904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11127217/" ]
*Never* use commas in the `FROM` clause. *Always* use proper, explicit, **standard** `JOIN` syntax. You just need the correct `GROUP BY` logic. I think it is like this ``` SELECT pl.codigo AS Floor_id, count(count distinct h.id) as num_rooms, MAX(numero_camas) - count(distinct h.id) AS Free_beds FROM habitacion h join paciente p on p.habitacion_id = h.id -- just a guess that this is the right join condition planta pl on h.planta_id = pl.codigo GROUP BY pl.codigo ```
51,386,234
I'm trying to solve this issue. I have multiple inputs and I would like to compare if everyone has value == 0 and is also checked. I don't know how to do it - I spend almost day searching and finding a way how to do it and don't have clue how to go further. I tried to find if one input is checked and has that value. Thank U for Your help. ```js $(document).on('change','select, input', function() { console.log('input/select has been changed'); var $this = $(this); var $inputValue = $this.val(); console.log('input Value is ' + $inputValue); if ($inputValue == 0 && $this.is(':checked')) { console.log('One input is checked and has 0 value'); } if ('all first inputs are checked and has 0 value') { console.warn('Could U help me?'); } }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <div class="destinations"> <ul> <li> <label> <input type="checkbox" name="destination" value="0"> </label> </li> <li> <label> <input type="checkbox" name="destination" value="5"> </label> </li> <li> <label> <input type="checkbox" name="destination" value="3"> </label> </li> </ul> </div> <div class="languages"> <ul> <li> <label> <input type="radio" name="language" value="0"> </label> </li> <li> <label> <input type="radio" name="language" value="5"> </label> </li> <li> <label> <input type="radio" name="language" value="3"> </label> </li> </ul> </div> <div class="rooms"> <ul> <li> <label> <input type="checkbox" name="room" value="0"> </label> </li> <li> <label> <input type="checkbox" name="room" value="5"> </label> </li> <li> <label> <input type="checkbox" name="room" value="3"> </label> </li> </ul> </div> </body> ```
2018/07/17
[ "https://Stackoverflow.com/questions/51386234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7345069/" ]
I don't recommend W3Schools as a respectable tutorial source, and this is a great example why not: they don't teach good habits like error handling. Because you copied and pasted the example as they had it, your error is rather cryptic. However with good error handling, your error would be caught earlier and give you a much better indication of what went wrong. With that in mind, try this: ``` var http = require('http'); var fs = require('fs'); http.createServer(function (req, res) { //Open a file on the server and return it's content: fs.readFile('demofile1.html', function(err, data) { if (err) throw err; // crash with actual error instead of assuming success res.writeHead(200, {'Content-Type': 'text/html'}); res.write(data); return res.end(); }); }).listen(8080); ```
4,606,187
Show that the series $\sum^\infty\_{k=1}\frac{1}{k^4}$ is bounded. What I've tried: Since $\frac{1}{2^4}+\frac{1}{3^4}\leq \frac{1}{2^4}+\frac{1}{2^4}=\frac{1}{2^3}$ $\frac{1}{4^4}+\frac{1}{5^4}+\frac{1}{6^4}+\frac{1}{7^4}\leq \frac{1}{4^4}+\frac{1}{4^4}+\frac{1}{4^4}+\frac{1}{4^4}=\frac{1}{4^3}$ and so on. So the series in question is less than $1+\frac{1}{2^3}+\frac{1}{4^3}+\frac{1}{8^3}...$. If I can show the latter is bounded I'm done. But I can't so maybe there is and easier solution?
2022/12/27
[ "https://math.stackexchange.com/questions/4606187", "https://math.stackexchange.com", "https://math.stackexchange.com/users/995106/" ]
First, be careful with your index of summation - your series is not defined at $k = 0$. Anyways, note that $\frac{1}{k^4} \leq \frac{1}{k^2}$ for each positive integer $k$. Thus, $$\sum\_{k=1}^\infty \frac{1}{k^4} \leq \sum\_{k=1}^\infty \frac{1}{k^2} = \frac{\pi^2}{6}$$
46,502,470
I have made an image gallery, made up by two rows each with tree images. I've made my site responsive, but for some reason, the images does not resize/adjust according to the screen. I've attached the picture, and as is visible the images does not adjust to the screen. [Screen shot of site](https://i.stack.imgur.com/GjWXb.png) ```css .image3 { height: 300px; width: 370px; border: 5px solid; color: grey; } ``` ```html <div class="wrapper"> <div class="row"> <img src="img/gallery1.jpg" alt="Iphone" class="image3"> <img src="img/static1.squarespace2.jpg" alt="Iphone" class="image3"> <img src="img/apple-iphone-8.jpg" alt="Iphone" class="image3"> </div> <div class="row"> <img src="img/iphone-8-concept.jpg" alt="Iphone" class="image3"> <img src="img/gallery1.jpg" alt="Iphone" class="image3"> <img src="img/gallery1.jpg" alt="Iphone" class="image3"> </div> </div> ```
2017/09/30
[ "https://Stackoverflow.com/questions/46502470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6669176/" ]
The image does not resize because you gave them a absolute width. If you give the element a `max-width` and `max-height` of 100% it should be responsive. So like this: ```css .image3 { max-height: 100%; max-width: 100%; border-style: solid; border-width: 5px; color: grey; } ``` ```html <div class="row"> <div class="wrapper"> <img src="img/gallery1.jpg" alt="Iphone" class="image3" /> <img src="img/static1.squarespace2.jpg" alt="Iphone" class="image3" /> <img src="img/apple-iphone-8.jpg" alt="Iphone" class="image3" /> </div> <div class="row"> <img src="img/iphone-8-concept.jpg" alt="Iphone" class="image3" /> <img src="img/gallery1.jpg" alt="Iphone" class="image3" /> <img src="img/gallery1.jpg" alt="Iphone" class="image3" /> </div> ``` Pixels are not responsive to the screen's size **Note: See response from MarioZ below**
185,586
The basic search capabilities of MediaWiki (at least, the version we're running - 1.7.1) are pretty poor. I'd like to improve them with an extension, but there are a lot of options and I'd like to have a good starting point. For what it's worth, the wiki is an internal one; we don't have the option, for example, of using the Google search extension, because it's not going to be able to crawl the wiki's contents. I need a solution that will run entirely on the wiki server. Here are the wiki version details: ``` MediaWiki: 1.7.1 PHP: 5.2.8 (apache2handler) MySQL: 4.1.21-log ``` What are my options?
2010/09/28
[ "https://serverfault.com/questions/185586", "https://serverfault.com", "https://serverfault.com/users/2741/" ]
1. Dont do email marketing. Don't. Streamsend, Mailchimp or Constant Contact are spammers by any other name. A pig with lipstick is still a pig. 2. If you must, just customize an existing solution. Very customizable: [sendmail](http://www.sendmail.org)
1,115,775
I have installed VirtualBox 5.0.14 on an Lubuntu 15.10 host, and created a virtual machine with Lubuntu 14.04.5 LTS as the guest OS. I would like to set up a host-only network adapter in VirtualBox so that I can access an Apache webserver running inside the guest OS from a webbrowser running on the host system. So far I have created a host-only adapter `vboxnet0` which I can ping successfully from the host OS. However, I cannot access port 80 using a webbrowser or any other means. What can I do to get to the cause of the problem and configure things properly? VM network settings ------------------- [![enter image description here](https://i.stack.imgur.com/FfbPh.png)](https://i.stack.imgur.com/FfbPh.png) VirtualBox `vboxnet0` settings ------------------------------ [![enter image description here](https://i.stack.imgur.com/OPqpj.png)](https://i.stack.imgur.com/OPqpj.png) [![enter image description here](https://i.stack.imgur.com/sNQu2.png)](https://i.stack.imgur.com/sNQu2.png) Test results inside guest ------------------------- After booting the VM and starting Apache (using `sudo service apache2 start`) I can access a test page on `http://localhost/` using Firefox inside the guest OS without problems. The corresponding Apache VirtualHost is defined as `<VirtualHost *:80>` in `/etc/apache2/sites-enabled/000-default.conf`, so I don't see why it wouldn't be accessible from any host. Also, sshd and MySQL server are running on the guest. I can ssh to localhost and nmap shows all relevant ports open (22, 80, 3306). Test results on host -------------------- On the host OS, `vboxnet0` appears as follows and is pingable: ``` % ifconfig vboxnet0 vboxnet0 Link encap:Ethernet HWaddr 0a:00:27:00:00:00 inet addr:192.168.10.10 Bcast:192.168.10.255 Mask:255.255.255.0 UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:192 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:0 (0.0 B) TX bytes:16176 (16.1 KB) % ping 192.168.10.10 PING 192.168.10.10 (192.168.10.10) 56(84) bytes of data. 64 bytes from 192.168.10.10: icmp_seq=1 ttl=64 time=0.023 ms ``` However, none of the ports are accessible: ``` % nmap 192.168.10.10 -p 22,80,3306 Starting Nmap 6.47 ( http://nmap.org ) at 2016-08-20 21:29 CEST Nmap scan report for 192.168.10.10 Host is up (0.000027s latency). PORT STATE SERVICE 22/tcp closed ssh 80/tcp closed http 3306/tcp closed mysql Nmap done: 1 IP address (1 host up) scanned in 0.07 seconds ``` Trying to match IP address -------------------------- As per comment by @MarkoPolo: Even though `192.168.10.10` is pingable from the host OS, I cannot access this IP address from the guest OS. In fact, the guest OS has an IP address from the DHCP range specified in for `vboxnet0`: ``` eth1 Link encap:Ethernet HWaddr 08:00:27:0d:b4:6a inet addr:192.168.56.101 Bcast:192.168.56.255 Mask:255.255.255.0 inet6 addr: fe80::a00:27ff:fe0d:b46a/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:2 errors:0 dropped:0 overruns:0 frame:0 TX packets:11 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:1180 (1.1 KB) TX bytes:1422 (1.4 KB) ``` The IP address `192.168.56.101` is not reachable from the host OS, i.e. not pingable, no access using webbrowser. I tried updating the IP address of `eth1` to `192.168.10.10` using `ifconfig`. Then, Apache is reachable on `http://192.168.10.10` from the guest OS, however, still no access (aside from ping) is possible from the host OS.
2016/08/20
[ "https://superuser.com/questions/1115775", "https://superuser.com", "https://superuser.com/users/526082/" ]
### Shorter answer. Based on what I know about default VirtualBox network settings, your host only connection that uses `192.168.10.10` is on the incorrect subnet and that adjustment is being done in the wrong area to get this thing working. When setting up a host only adapter on the host OS, the IPv4 address should be `192.168.56.1`. And then—after that is setup—on the guest OS set the `eth1` interface to use an IP address like `192.168.56.10`. ### Longer answer. When using VirtualBox the internal pseudo-software router is set to work on the `192.168.56.x` range of IP addresses. The DHCP server range—which you should not set static IP addresses on would be in the range of `192.168.56.101` to `192.168.56.254` and to set a static IP address, you would need to set an IP address between `192.168.56.2` to `192.168.56.100`. So I would recommend that your guest OS config use (Lubuntu 14.04.5 LTS) use an IP address such as `192.168.56.10`. But don’t set that `192.168.56.10` value in the “Adapter” area as you have it set up. Instead, adjust your adapter settings to be as follows; see Mac OS X screenshot below for reference: * IPv4 Address: `192.168.56.1` * IPv4 Network Mask: `255.255.255.0` * IPv6 Address: [Leave Blank] * IPv6 Network Mask Length: `0` [![Screenshot of the network settings for a host only interface in the Mac OS X version of VirtualBox.](https://i.stack.imgur.com/5ThnN.png)](https://i.stack.imgur.com/5ThnN.png) And then on your guest OS (Lubuntu 14.04.5 LTS), it seems odd to me that your `eth1` setting would be the DHCP setting and have the address of `192.168.56.101`. I use Ubuntu 14.04.5 with a very similar host only connection for Apache development on the second adapter as well, and my setup is broken down like this: * `eth0` with an IP address of `10.0.2.15`. * `eth1` with an IP address of `192.168.56.10`. And my settings in `/etc/network/interfaces` are as follows: ``` auto eth1 iface eth1 inet static address 192.168.56.10 netmask 255.255.255.0 ``` So double-check that IP address on the host only connection and double-check your network interfaces config as well.
8,638,109
I saw a class "AttributeSelectedClassifier" was once created in the following ways: ``` AttributeSelectedClassifier classifier = new AttributeSelectedClassifier(); classifier.setClassifier(base); classifier.setEvaluator(eval); ``` This above one looks natural to me. But how about the following one. ``` classifier = new AttributeSelectedClassifier(); ((AttributeSelectedClassifier)classifier).setClassifier(base); ((AttributeSelectedClassifier)classifier).setEvaluator(eval); ``` I think it should be right, but I am not quite sure about the way of of defining classifier as ((AttributeSelectedClassifier)classifier), how to understand this usage?
2011/12/26
[ "https://Stackoverflow.com/questions/8638109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/288609/" ]
This means that the classifier variable is declared as a superclass or superinterface of `AttributeSelectedClassifier`, and that you need to call a method which is not defined in the class or interface, but only on `AttributeSelectedClassifier`. This notation *casts* the variable to `AttributeSelectedClassifier`: ``` Object classifier = new AttributeSelectedClassifier(); // classifier is a AttributeSelectedClassifier, but references as Object // to call the following method, we need to cast it to AttributeSelectedClassifier ((AttributeSelectedClassifier)classifier).setClassifier(base); ((AttributeSelectedClassifier)classifier).setEvaluator(eval); ``` This is usually the sign of a design problem. Either the methods should be in the superclass or interface, or the variable should be declared as `AttributeSelectedClassifier`.
113,098
I’m building a character for a one shot and my DM has okay’d my character being a vampire using the rules from the *Monster Manual* (under the ["Player Characters as Vampires"](https://www.dndbeyond.com/sources/mm/monsters-v#RegionalEffects) sidebar on p. 295). What I am unsure on is what exactly it means when it says I gain the traits: > > In addition, the character gains the vampire’s damage resistances, darkvision, traits, and actions. > > > Does this mean PC vampires gain the Shapechanger, Legendary Resistance, Misty Escape, Regeneration, Spider Climb, and the Vampire Weaknesses traits? If so this seems very strong, especially the Legendary Resistances and the regeneration. I would be grateful for any clarification.
2018/01/09
[ "https://rpg.stackexchange.com/questions/113098", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/35947/" ]
RAW: yes, you gain the traits listed ------------------------------------ You have listed the traits correctly. According to the rules as written, not even Legendary Resistance gets special treatment. It is most likely because a PC-turned-vampire is more often than not an NPC. If you (or your GM or both of you) consider this to be too powerful, you could say that the transformation is not yet complete: > > The game statistics of a player character transformed into a vampire > spawn and then a vampire... (MM 295) > > > And use the traits of the vampire spawn, found on the next page of the MM. You would "lose" Shapechanger, Misty Escape, Legendary Resistance, Children of the Night (action), and Charm (action), and the Regeneration is weaker. You could also say that Str, Dex, and Con are set to 16 only, as those are the stats of a spawn.
46,586,701
I am trying to compare the current row value to the previous row value but only within the same group. I have Group1 (Plant), ChildGroup1 (DeviceTag), Details Group, I have tried this code within the Fill property but it does not work, it just seems to change the color of the first row every time per group regardless of the value of the previous row. ``` =IIf(Fields!DeviceTag.Value <> Previous(Fields!DeviceTag.Value), "Yellow", "White") ``` So my data set looks like this: ``` Plant DeviceTag Description Location A Tag1 ABCD West Tag1 WXYZ West DeviceTag Group 1 _____________________________________________ A Tag2 EFGH East Tag2 IJKL East DeviceTag Group 2 Tag2 IJKL West ``` In both these DeviceTag Groups, the description changed so I would like to change the color of ABCD to yellow and EFGH to yellow but not WXYZ because it is not in the same group as EFGH. Also the Second row that says East should be Yellow since it is different than the previous West location. In Crystal Reports you would do: ``` if {#ChangeCounter}=1 then nocolor else if currentfieldvalue <> previous({DataSet.Field}) then cryellow else nocolor ``` Where the formula #ChangeCounter is just 1 Clear as mud??
2017/10/05
[ "https://Stackoverflow.com/questions/46586701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4996493/" ]
I always find this kind of thing easier to do in the dataset query (assuming you can control the query in the dataset). Manipulate your final dataset (the one SSRS will receive) to have another column which tells SSRS to color the cell or not. And keep your business logic in the DB query. You could number each row (within each group) using `row_number()` and then join the table back into itself on the new row number column. Something like this perhaps? I am not sure I 100% follow your cell shading logic and I am sure your dataset is larger than what you provided, but you may be able to adapt this to meet your needs. ``` ;with Data as ( select 'A' as Plant, 'Tag1' as DeviceTag, 'ABCD' as Description, 'West' as Location union all select 'A' as Plant, 'Tag1' as DeviceTag, 'WXYZ' as Description, 'West' as Location union all select 'A' as Plant, 'Tag2' as DeviceTag, 'EFGH' as Description, 'East' as Location union all select 'A' as Plant, 'Tag2' as DeviceTag, 'IJKL' as Description, 'East' as Location union all select 'A' as Plant, 'Tag2' as DeviceTag, 'IJKL' as Description, 'West' as Location ), DataWithRowNumbers as ( select *, row_number() over (partition by DeviceTag order by Description) as DeviceTagGroupRowNumber from Data ) select a.*, case when a.Description != b.Description then 'Yellow' else 'Transparent' end as CellColor from DataWithRowNumbers a left join DataWithRowNumbers b on a.DeviceTag = b.DeviceTag and a.DeviceTagGroupRowNumber = b.DeviceTagGroupRowNumber - 1 ``` Then you can set the background in the cell (in SSRS) to an expression which will just be `Fields!CellColor.Value`.
61,575,944
I want to create a menu that works with embedded systems. I use C. This is how I plan to make it: 1. First, the pressed keys are identified by the interrupts. 2. A array is update on those identifications. 3. Find the corresponding term acording to array content. 4. The operation is performed. My array is like this. Array nth item represent different levels. Each element represent level item number. ``` uint8_t menu_map[5] = {2, 3, 1, 0, 0}; ``` My question is: How to choose a function pointer or structure acording to array content? like this(acording to array content i mentioned as before example). ``` function_23100(){ // Function content } ``` Is there a way to do that? Is there any other good alternative to do this kind of menu?
2020/05/03
[ "https://Stackoverflow.com/questions/61575944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
There are several ways to archive but in the end, they are both hard to maintain and cause performance down. Let's say you would build a lookup table to ref to, assume you have 4 buttons, an array with 5 entries -> the size of lookup table(worse case) is `4x4x4x4x4 = 1024` entries. Finding the corresponding action in this table per each button press is not that good in term of performance. Let's back to what you wanna to archive, check below code for your ref. By create a menu tree, bind callback to each menu item and keep track the path of current menu item, it's not that difficult to travel back and forth in menu tree. Once you enter a specific menu item, it's easy to access to its callback by the pointer that was assigned to. ``` #include <stdio.h> #define MENU(name, text, nr_item, ...) \ static menu_t name = { \ { text, NULL, nr_item, __VA_ARGS__ }, { 0 }, -1 \ } #define MENU_ITEMS(...) (menu_item_t[]) { __VA_ARGS__ } #define MAX_DEPTH 10 #define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0])) typedef struct menu_item menu_item_t; struct menu_item { const char *text; void (*action)(menu_item_t*); int nr_of_children; menu_item_t *children; }; typedef struct { menu_item_t item; menu_item_t* _history[MAX_DEPTH]; int _history_index; } menu_t; static inline void print_menu_history(menu_t *menu) { int i = 0; for (i = 0; i < MAX_DEPTH; i++) { if (!menu->_history[i]) break; printf("> %s ", menu->_history[i]->text); } printf("\n"); } static inline void print_menu(menu_t *menu) { menu_item_t *item = menu->_history[menu->_history_index]; int i; printf("= %s\n", item->text); for (i = 0; i < item->nr_of_children; i++) { printf("- [%2d] %s\n", i, item->children[i].text); } printf("==========================================\n"); print_menu_history(menu); printf("==========================================\n"); } static inline void add_item_to_history(menu_t *menu, int position) { if (menu->_history_index < 0) { menu->_history_index = 0; menu->_history[menu->_history_index] = &menu->item; } else { if (position < menu->_history[menu->_history_index]->nr_of_children) menu->_history[++menu->_history_index] = &menu->_history[menu->_history_index]->children[position]; } } static inline void exec_menu_action(menu_t *menu, int position) { if (menu->_history[menu->_history_index]->action) menu->_history[menu->_history_index]->action(menu->_history[menu->_history_index]); } static inline void exit_menu(menu_t *menu) { if (menu->_history_index > 0) menu->_history[menu->_history_index--] = NULL; print_menu(menu); } static inline void enter_menu(menu_t *menu, int position) { add_item_to_history(menu, position); exec_menu_action(menu, position); print_menu(menu); } static void menu_item_action(menu_item_t *item) { if (item) printf("=========='%s' selected\n", item->text); } MENU(main_menu, "Menu", 2, MENU_ITEMS( { "Item 1", menu_item_action, 3, MENU_ITEMS( { "Item 1.1", menu_item_action, 3, MENU_ITEMS( { "Item 1.1.1", menu_item_action, 0, NULL }, { "Item 1.1.2", menu_item_action, 0, NULL }, { "Item 1.1.3", menu_item_action, 0, NULL } ) }, { "Item 1.2", menu_item_action, 0, NULL }, { "Item 1.3", menu_item_action, 0, NULL } ) }, { "Item 2", menu_item_action, 2, MENU_ITEMS( { "Item 2.1", menu_item_action, 0, NULL }, { "Item 2.2", menu_item_action, 0, NULL } ) } ) ); int main(int argc, char *argv[]) { unsigned char c = 0; int samples[] = {1, 0, 1, 0, 0}; enter_menu(&main_menu, -1); for (c = 0; c < ARRAY_SIZE(samples); c++) { enter_menu(&main_menu, c); } while(c != 'q') { c = getchar(); if ('b' == c) exit_menu(&main_menu); if ((c <= '9') && (c >= '0')) enter_menu(&main_menu, c - '0'); } return 0; } ```
42,641,707
When I do numpy indexing, sometimes the index can be an empty list, in that way I want numpy to also return a empty array. For example: ``` a = np.array([1, 2, 3]) b = [] print a[b] ``` This works perfectly fine! when the result gives me: ``` result:[] ``` But when I use ndarray as indexer, strange things happened: ``` a = np.array([1, 2, 3]) b = [] c = np.array(b) print a[c] ``` This gives me an error: ``` IndexError: arrays used as indices must be of integer (or boolean) type ``` However, When I do this: ``` a = np.array([1, 2, 3]) b = [] d = np.arange(0, a.size)[b] print a[d] ``` Then it works perfectly again: ``` result:[] ``` But when I check the type of c and d, they returns the same! Even the shape and everything: ``` print type(c), c.shape print type(d), d.shape result:<type 'numpy.ndarray'> (0L,) result:<type 'numpy.ndarray'> (0L,) ``` So I was wondering if there is anything wrong with it? How come a[c] doesn't work but a[d] works? Can you explain it for me? Thank you!
2017/03/07
[ "https://Stackoverflow.com/questions/42641707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7650964/" ]
numpy doesn't know what type the empty array is. Try: ``` c = np.array(b, dtype=int) ```
60,777,481
I am trying to implement recycler View in android but after adding it to the app it is not showing anything. I have searched online yet I am not able to figure out what am I doing wrong. Also When I declare dashpercent and dashsubject (mentioned in adapter) in class RecyclerViewHolder extends RecyclerView.ViewHolder the on writing : ``` @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { dashboard_recycler_components data = dashlist.get(position); String sub = data.Subject; holder.dashpercent.setText(data.percentage); holder.dashsubject.setText(data.Subject); } ``` then dashpercent and dashsubject give an error that they are not declared. Adapter ``` package com.example.attendance; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ProgressBar; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private ArrayList<dashboard_recycler_components> dashlist; RecyclerAdapter(ArrayList<dashboard_recycler_components> a) { this.dashlist = a; } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from((parent.getContext())); View view = inflater.inflate(R.layout.attendace_card, parent, false); return new RecyclerViewHolder(view); } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { dashboard_recycler_components data = dashlist.get(position); String sub = data.Subject; TextView dashpercent = (TextView) holder.itemView.findViewById(R.id.dashPercent); TextView dashsubject = (TextView) holder.itemView.findViewById(R.id.dashSubject); ProgressBar dashProgress = (ProgressBar) holder.itemView.findViewById(R.id.recycler_progress); dashpercent.setText(data.percentage); dashsubject.setText(data.Subject); } @Override public int getItemCount() { return dashlist.size(); } public class RecyclerViewHolder extends RecyclerView.ViewHolder { RecyclerViewHolder(@NonNull View itemView) { super(itemView); } } } ``` dashboadfragment: ``` package com.example.attendance; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.ListAdapter; import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; public class dashboardfragment extends Fragment { @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { ArrayList<dashboard_recycler_components> subList = new ArrayList<>(); dashboard_recycler_components a = new dashboard_recycler_components("DSA",33); dashboard_recycler_components b = new dashboard_recycler_components("DSA",33); dashboard_recycler_components c = new dashboard_recycler_components("DSA",33); dashboard_recycler_components d = new dashboard_recycler_components("DSA",33); dashboard_recycler_components e = new dashboard_recycler_components("DSA",33); dashboard_recycler_components f = new dashboard_recycler_components("DSA",33); dashboard_recycler_components g = new dashboard_recycler_components("DSA",33); dashboard_recycler_components h = new dashboard_recycler_components("DSA",33); dashboard_recycler_components i = new dashboard_recycler_components("DSA",33); dashboard_recycler_components j = new dashboard_recycler_components("DSA",33); subList.add(a); subList.add(b); subList.add(c); subList.add(d); subList.add(e); subList.add(f); subList.add(g); subList.add(h); subList.add(i); subList.add(j); View v = inflater.inflate(R.layout.fragment_dashboard,container,false); RecyclerView recycle = (RecyclerView)v.findViewById(R.id.recycler_view1); recycle.setLayoutManager(new LinearLayoutManager(getActivity())); recycle.setAdapter(new RecyclerAdapter(subList)); return v; } } ``` dashbord\_recycler\_componets: ``` package com.example.attendance; public class dashboard_recycler_components { int percentage; String Subject; public dashboard_recycler_components(String a , int b){ this.percentage = b; this.Subject = a; } public int getPercentage() { return percentage; } public String getSubject() { return Subject; } public void setPercentage(int percentage) { this.percentage = percentage; } public void setSubject(String subject) { this.Subject = subject; } } ``` MainActivity: ``` package com.example.attendance; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import android.os.Bundle; import android.view.MenuItem; import android.widget.ProgressBar; import com.google.android.material.bottomnavigation.BottomNavigationView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); BottomNavigationView bottomNav = findViewById(R.id.bottom_nav_bar); bottomNav.setOnNavigationItemSelectedListener(navListener); getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, new homefragment()).commit(); } private BottomNavigationView.OnNavigationItemSelectedListener navListener = new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) { Fragment frag = null; switch (menuItem.getItemId()) { case R.id.dashboard: frag = new dashboardfragment(); break; case R.id.profile: frag = new profilefragment(); break; case R.id.home: frag = new homefragment(); break; } getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, frag).commit(); return true; } }; } ```
2020/03/20
[ "https://Stackoverflow.com/questions/60777481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12505541/" ]
Another option is to match 8 times either a digit OR a space not preceded by a digit and then match a digit at the end. ``` (?<![\d\h])(?>\d|(?<!\d)\h){8}\d ``` *In parts* * `(?<![\d\h])` Negative lookbehind, assert what is on the left is not a horizontal whitespace char or digit * `(?>` Atomic group (no backtracking) + `\d` Match a digit + `|` Or + `\h(?<!\d\h)` Match a horizontal whitespace char asserting that it is not preceded by a digit * `){8}` Close the group and repeat 8 times * `\d` Match the last digit [Regex demo](https://regex101.com/r/d6P6MI/1) | [R demo](https://ideone.com/sdRSch) Example code, using *perl=TRUE* ``` x <- "123456789 kfasdf 3456789asdf a 1 12345 789 1 9 a 678a" regmatches(x, gregexpr("(?<![\\d\\h])(?>\\d|(?<!\\d)\\h){8}\\d", x, perl=TRUE)) ``` Output ``` [[1]] [1] "123456789" " 3456789" " 1" ``` If there can not be a digit present after matching the last 9th digit, you could end the pattern with a negative lookahead asserting not a digit. ``` (?<![\d\h])(?>\d|(?<!\d)\h){8}\d(?!\d) ``` [Regex demo](https://regex101.com/r/8qz1cd/1) If there can not be any digits on any side: ``` (?<!\d)(?>\d|(?<!\d)\h){8}\d(?!\d) ``` [Regex demo](https://regex101.com/r/mtGB7T/1)
49,272,176
I'm trying to initialise a value in dictionary as follow, ``` var og:image: String ``` But after `og:` it tries to assign the type considering `og` as the variable to site\_name, which is obviously wrong. > > Is there a way to assign `og:image` as variable to `String` type using > special or escape characters? > > > In [reference](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/LexicalStructure.html#//apple_ref/swift/grammar/decimal-digits) to this, apple does not provide any meaningful explanations to variable naming conventions in such a situation. Edit-1: Here is code snippet to clarify dictionary `usage` is in JSON parsing data structure, ``` struct Metadata: Decodable{ var metatags : [enclosedTags] } struct enclosedTags: Decodable{ var image: String var title: String var description: String var og:site_name: String } ```
2018/03/14
[ "https://Stackoverflow.com/questions/49272176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5484311/" ]
You cannot use : (colon). But if you really want: ``` var ogCOLONimage: String ``` Joking apart. You could use a Dictionary or something like that: ``` var images: [String: String] = ["og:image" : "your string"] ``` Now you can access your `og:image` data with `images["og:image"]`.
59,251,902
I have this block of code, and the post works perfectly fine if i comment out the .then part, but if i leave it in, the post will not go through. How might I go about fixing this? ``` axios.post('http://localhost:5000/exercises/add', exercise) .then(res => console.log(res.data)) .then(window.location.href = '/') .catch(err => console.log(err)) ```
2019/12/09
[ "https://Stackoverflow.com/questions/59251902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12363032/" ]
You have 2 `then` for some reason which is not needed. Try combining the two together ```js axios.post('http://localhost:5000/exercises/add', exercise) .then(res => { console.log(res.data) window.location.href = '/' }) .catch(err => console.log(err)) ```
48,490
I spend about $20-30 a week on my debit card, with periodic $200-300 purchases every few months. I've thought about getting a credit card the moment I turn 18 and using it to buy everything, then immediately paying it off. Assuming I only use it to buy things I can afford (which I trust myself to do), essentially treating it as a debit card, is this a good idea? Or should I wait until I'm a bit older? Assume that I will only spend money I have in my bank account at the time I spend it and that I will keep track of how much I spent and never spend more than I have. Joe Taxpayer recommended I post an update: I ended up getting a card, and from my perspective the only thing that's changed is that it takes things ~24 hours to show up on my statement and I don't have to enter a PIN when I checkout. Should I add this to the question? I know on other SE sites people generally don't like updates in the questions
2015/05/28
[ "https://money.stackexchange.com/questions/48490", "https://money.stackexchange.com", "https://money.stackexchange.com/users/13558/" ]
Yes, it is a very good idea to start your credit history early. It sounds like you have a good understanding of the appropriate use of credit, as a substitute for cash rather than a supplement to income. As long as you keep your expenses under control and pay off your card each month, I see no problems with the idea. Try to find a card with no annual fees, a low interest rate if possible (which will be difficult at your age), and with some form of rewards such as cash back. Look for a reputable issuing bank, and keep the account open even after you get a new card down the road. Your credit score is positively correlated with having an account open for a long time, having a good credit usage to credit limit ratio, and having accounts in good standing and paid on time.
10,997,719
I'm in the process of learning Databases and SQL. From what I have read adding an index to a table can increase performance to from around (log(n)) to even constant time. Considering the increased space usage, at what point does it make sense to add an index to a table? For example if i was using an employees table at how many records would the table have to have before you would add an index? In this specific case would a clustered index make sense?
2012/06/12
[ "https://Stackoverflow.com/questions/10997719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1207026/" ]
Here are two examples that might help you think about this. These are not to be relied on as technically accurate (e.g. because of the effect of consecutive reads on the disk being more efficient than random seeks) but they are an illustration. The first example is to think of a small table that is a couple of blocks in size. To find a particular row in the table, the database would read those two blocks and get the data you require. If there were an index on that table, the index is likely to be smaller than the table. Maybe one block in size. If the optimiser chose to use this index then the database would read the one block index and then read the one block of the table containing the row you require. As mentioned above this is only an example and is meant to model reality rather than be accurate. In reality, Oracle will often do a full table scan of a table with an index even if the index would return as little as 5% of the rows (or is it less now with 11G?). The second example involves making data modifications on the table. Whenever a change to a row in a table is made (`INSERT`, `UPDATE`, `DELETE`, `MERGE`), every index on the table will need to be updated. So, indexes may make queries faster and updates slower. And indexes take up space. That's the price you pay. You ask "at how many records would the table have to have before you would add an index"? I think you are looking at it the wrong way because that shouldn't be for you to worry about. Add the index when the table has zero rows. The optimiser will work out the right thing to do. If it is quicker to use the index, it will use it. If it is quicker to avoid the index and do a full scan of the table then it will do that. I would generally index columns that are used for the primary key and foreign keys plus any columns that are used frequently for access. In general, I wouldn't worry too much about the space used by an index unless the tables are very large (in which case it might be worth looking at bitmap indexes). It is a trade off of space vs time but an index is going to be smaller than the table that is being indexed. Another option if you are worried about space it to compress the index. This shouldn't have much impact on the performance but will take less space. Note that this is different to table compression. This is a long way of giving the Tom Kyte answer of "It depends". The best thing you can probably do is benchmark your particular problem and go from there. You seem to be trying to do premature optimisation which is never a good thing.
26,455,856
so this is my code ``` function func_readmsg () { $targetmessage = $_POST['inquiry_no']; $result = mysqli_query(mysqli_connect("localhost", "root", "", "dbbyahenijuan"), "SELECT * FROM tblinquiry where finquiry_no='$targetmessage' "); while($row = mysqli_fetch_array($result)) { global $sender, $message, $date; $sender = $row['ffull_name']; $message = $row['fmessage']; $date = $row['fdate']; } echo " <script> $(document).ready(function(){ $('#messagewindow').fadeIn('show'); }); </script>"; } function func_delmsg () { echo $targetmessage; } ``` I need to transfer or read the value of `$targetmessage` from `func_readmsg` to `func_delmsg`. I have already tried `$GLOBALS['targetmessage']`, `global $targetmessage`. Please help.
2014/10/19
[ "https://Stackoverflow.com/questions/26455856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4159902/" ]
First, add a method to your class that determines if a String is numeric: ``` private boolean isNumeric(String number) { try { Integer.parseInt(number); return true; } catch(NumberFormatException e) { return false; } } ``` The way this method works is that we attempt to parse the String as an int, and if that fails, because we are using a try/catch statement, we can prevent the program from throwing an error and instead just `return false;`. If it doesn't fail, it will continue on to the `return true;` Now that we have a way of determining what is an isn't a number, we can rework the `while` loop to take advantage of the new method: ``` Scanner scanner = new Scanner(f); int lineCount = 0; int caseNumber = -1; String contents = ""; while(scanner.hasNextLine()) { lineCount++; String line = scanner.nextLine().trim(); if(lineCount == 1) { if(line.startsWith("case")) { String subStr = line.substring(line.indexOf("e") + 1, line.indexOf(":")); if(isNumeric(subStr)) caseNumber = Integer.parseInt(subStr); } } else if(isNumeric(line)) contents += line; } scanner.close(); System.out.println("Case Number: " + caseNumber); System.out.println("Case Contents: " + contents); System.out.println("Line Count: " + lineCount); ``` Here is what I changed: First, I added a new `int caseNumber` to represent the case number. Then I added a new `String contents` to represent the contents of the case. Next, I changed: ``` String line = scanner.nextLine(); ``` to ``` String line = scanner.nextLine().trim(); ``` and got rid of the other `String line1 = line.trim();` because there is no reason to create two new variables when we can do both operations on just one. Next I added an if-statement to see if we are on the first line so we can determine the case number. If the line starts with `"case"` then we take the substring from `e` to `:`, represented as `subStr`, to get the case number. Run `subStr` through our `isNumeric` method, and we can determine if the case number can be parsed as an int. If that returns true, we set `caseNumber` equal to `Integer.parseInt(subStr)` which will turn the String into an int. Then I added an else-statement to handle all the lines after the first line. For each of these lines, all we have to do is determine if the line is a number using `isNumeric`. If it is numeric, we append it to the end of `contents` using the `+=` operator. If it isn't, we skip over it. Lastly, I made sure to **close the scanner** by executing `scanner.close()` so that we don't have a resource leak. And there you go! I hope you can understand and learn from all the changes made. Here is the output of this program: ``` Case Number: 0 Case Contents: 000000100 Line Count: 19 ``` --- To answer your follow-up question: Here is the while loop that will allow you to print out multiple cases and their contents: ``` Scanner scanner = new Scanner(f); int lineCount = 0; int caseNumber = -1; String contents = ""; while(scanner.hasNextLine()) { lineCount++; String line = scanner.nextLine().trim(); if(line.startsWith("case")) { if(!contents.isEmpty()) { System.out.println("Case Number: " + caseNumber); System.out.println("Case Contents: " + contents); caseNumber = -1; contents = ""; } String subStr = line.substring(line.indexOf("e") + 1, line.indexOf(":")); if(isNumeric(subStr)) caseNumber = Integer.parseInt(subStr); } else if(isNumeric(line)) contents += line; } scanner.close(); System.out.println("Case Number: " + caseNumber); System.out.println("Case Contents: " + contents); System.out.println("Line Count: " + lineCount); ``` Here is what I changed from the previous answer to make it work: First I removed the if-statement that checks if the lineCount == 1, and attached the else-statement to the end of the second if-statement that checks if the line begins with "case". So in other words, this: ``` if(lineCount == 1) { if(line.startsWith("case")) { ... } } else if(isNumeric(line)) ... ``` Became this: ``` if(line.startsWith("case")) { ... } else if(isNumeric(line)) ... ``` Next, I added a new if-statement within the `if(line.startsWith("case"))` statement that checks if we are on a new case or not. Basically what it does is check if the `contents` string is empty. If it is, we are on case `0`. If it isn't, we are on a case greater than `0`. If the statement is true, we print out the case number and contents, then reset the values of the two variables so they can be used again: ``` if(!contents.isEmpty()) { System.out.println("Case Number: " + caseNumber); System.out.println("Case Contents: " + contents); caseNumber = -1; contents = ""; } ``` And that's it! Really! Here is the output: ``` Case Number: 0 Case Contents: 000000100 Case Number: 1 Case Contents: 101001001 Line Count: 38 ``` Enjoy!
20,778,839
I'm trying to automate a click when visting a website. This is the HTML I'm looking at. ``` <div class="box_wrapper"> <a id="itemcode_11094414" class="box">7.5</a> <a id="itemcode_11094415" class="box">8</a> <a id="itemcode_11094416" class="box">8.5</a> </div> ``` when I select the size, say for instance size 8, the class= tag turns to "box active" like so, ``` <div class="box_wrapper"> <a id="itemcode_11094414" class="box">7.5</a> <a id="itemcode_11094415" class="box active">8</a> <a id="itemcode_11094416" class="box">8.5</a> </div> ``` How can I go loop through the class and select a desired size? Also, I was just tinkering around and noticed that I had a hard time simulating a click on the add to cart and other buttons. For the add to cart the HTML looks like this, ``` <div class="add_to_cart"> <div class="add_to_cart_left"> <img id="add_to_bag_btn" alt="Add To Bag" src="/images/add_to_bag.gif"></img> <img id="add_to_bag_btn_processing" alt="" src="/images/add_to_bag_processing.gif"></img> </div> </div> ``` Is this the correct chunk of HTML I should be looking at for a simulation of a click?
2013/12/26
[ "https://Stackoverflow.com/questions/20778839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2535164/" ]
The problem is the 9 patch itself: it's **malformed**. The black line on the **left side** is simply WRONG (it "touches" the lens). It should be a single pixel near the lower part, so that its prolongation doesn't touch the lens. This is it ![enter image description here](https://i.stack.imgur.com/ZRPC5.png) Note that the lens will be **up-right aligned**. If you want it **centered**, you have to add another black pixel near the upper left border (but you have to replace some pixels near the upper lens frame, too). Also not thet you don't need the horizontal part being that wide, you can make it **much narrower**, to save on the final patch size.
31,701,201
I got this in my folders : [![enter image description here](https://i.stack.imgur.com/rNh5D.png)](https://i.stack.imgur.com/rNh5D.png) But on my android device, i have a file not found error because it looks for andoid\_assets instead... [![enter image description here](https://i.stack.imgur.com/4d0Jd.png)](https://i.stack.imgur.com/4d0Jd.png) Where can i set my folder path ?
2015/07/29
[ "https://Stackoverflow.com/questions/31701201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3498177/" ]
No, because Google Filters the Apps in the Store: More about how Google filters: [Filters on Google Play](http://developer.android.com/google/play/filters.html)
64,528
I am planning to study abroad in Japan in two years through my college for a year at a Japanese speaking university. I also have goals/aspirations to one day work/live in Japan. Is it weird/acceptable to give myself a kanji name based off of meaning or sound of my current name? My name is Ruth which means "friend" and "beautiful" so I was thinking of 朋麗 (ともれい). Or, I could use kanji based off of my sound to have a name that means 'dragon state' or "state of the dragon" (I was also born in the year of the dragon so it may be fitting) but sounds like Ruth 竜州 (りゅうす). I know a closer approximation would be ルース, but I like the idea of my name meaning dragon if I were to go that route. I also have an idea for my surname, which means "gentle beauty" and I came to the kanji 泰美 (やすみ). So either 泰美竜州 or 泰美朋麗. Is it weird for foreigners to do this when they move to Japan or Study abroad in Japan? I know some people who came to study abroad in the US from China and Korea and they both took American names. Is the reverse true for in Japan? Can I do this if I'm expecting to work in Japan? Could I use this name on legal documents in Japan if I did choose to use a kanji name? I'm really curios about the whole prospect.
2018/12/21
[ "https://japanese.stackexchange.com/questions/64528", "https://japanese.stackexchange.com", "https://japanese.stackexchange.com/users/32328/" ]
Firstly, for legal documents you should always be writing your name as it appears on your passport. When documents ask for your name, age, etc. they're trying to confirm your identity. If you supply a false name then they won't be able to tell whether you're a real person or not. As for the social part, I think it's up to the people who will be calling you what you want to be called. After you've made some friends at your new University, ask them if it's weird for you to take on a Japanese alias. I had one friend who came to work in Australia from Korea who had also worked / lived in Japan. He has unique Japanese, Korean and English names. I hope you have a great trip!
106,380
What web server code should I consider using for file hosting? (http deamon, i dont think i can choose FS. I may be able to choose an randomly offer linux distro the host offers) The web server will only host files, with no need for cookies, reading a database, etc. The requirements are; 1. Must be able to rewrite urls. Eg; /name/file-id.ext may resolve to /n/a/name/MainFolder/id/ext with file being a nice human readable name for the user when the user clicks save as. 2. Stream FLVs, MP3, OGG, MP4 3. Allow file transfer resuming I imagine there's no such thing as a server that can't handle raw files like rar,exe,3ds or even a 1gb file with no extension, is this the case? A plus would be if it could also serve thumbnails well but that may not be an issue.
2010/01/26
[ "https://serverfault.com/questions/106380", "https://serverfault.com", "https://serverfault.com/users/-1/" ]
I would recommend looking into Puppet/Facter or OCS Inventory NG. Puppet ------ Puppet (which uses Facter), can be used to push out updates and configure nodes. It retrives information (or facts) about your nodes via Facter. Even though Puppet (via Facter) doesn't know who the primary user is, you can add facts (information) to your nodes that Facter will pick up on, and report back to the central server. It also includes a powerful Domain Specific Language written using Ruby, but very easy to learn even if you have no ruby experience. They have a great user group if you have any questions and are currently working on additional external software like Puppet Dashboard to make it easier to manage your infrastructure. One downside of Puppet is that it only works on Linux machines currently. This can be a non-issue if you are only concerned with Linux machines. Website: <http://docs.reductivelabs.com/> OCS Invetory NG --------------- OCS Invetory NG also does updates and can gather a lot of information off nodes. It is easy to use. The central server interface is accessed via a browser. From this interface you can see view your nodes, and get reports that contain detailed information on the hardware and software installed. This product works for both Linux and Windows environments. Website: <http://www.ocsinventory-ng.org/> Summary ------- Both products have a client/server architecture in which you have to install client software on each node for information to be polled and updates to be pushed out. Each product is open source, so licensing is not an issue. Puppet is a very powerful tool. With its own DSL, you can for the most part do anything you need. It is scalable and has been used by many big companies such as Google and Redhat. OCS Inventory NG is an easy to use tool that works both on Windows and Linux environments. It is accessed through a web interface in which you can have printable reports. If you have a mixed infrastructure (Windows and Linux) you may want to go with OCS, but if you are using solely Linux machines, Puppet is the best tool out their to manage your infrastructure.
26,126,363
I am trying to call a web service of a shipping company in my php code and get the result xml. I have this sample code and i want to know if there is an alternative using curl. Code: ``` function doPost($_postContent) { $postContent = "xml_in=".$_postContent; $host="test.company.com"; $contentLen = strlen($postContent); $httpHeader ="POST /shippergate2.asp HTTP/1.1\r\n" ."Host: $host\r\n" ."User-Agent: PHP Script\r\n" ."Content-Type: application/x-www-form-urlencoded\r\n" ."Content-Length: $contentLen\r\n" ."Connection: close\r\n" ."\r\n"; $httpHeader.=$postContent; $fp = fsockopen($host, 81); fputs($fp, $httpHeader); $result = ""; while(!feof($fp)) { // receive the results of the request $result .= fgets($fp, 128); } // close the socket connection: fclose($fp); $result = explode("\r\n\r\n", $result,3); } ``` Can i call it using curl?
2014/09/30
[ "https://Stackoverflow.com/questions/26126363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1059261/" ]
You can use the `CURLOPT_PORT` option to change the port to 81. See <http://php.net/manual/en/function.curl-setopt.php> ``` $url = "http://test.company.com/shippergate2.asp"; $ch = curl_init(); curl_setopt($ch, CURLOPT_PORT, 81); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_USERAGENT, "PHP Script"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postContent); $data = curl_exec($ch); ```
52,349,928
How could I create a conditional statement that prevents entering the fail state, and asks the user for new data when either the data is invalid or the data is not 1, 2, 3 OR 4 ? ``` int choice; while ( !choice || choice != 1 || 2 || 3 || 4){ cout << "Entry Invalid. Enter again: "; cin >> choice } ``` For example, If the user enters 'f', then the fail state would be taken care of, and the program would ask for new data. And when they enter 5, the program would say "Not a valid number", and ask for new data.
2018/09/16
[ "https://Stackoverflow.com/questions/52349928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9183124/" ]
Let's suppose your input `011R0` is stored in array `buf` then to print ASCII value of each character, you'll have to access each character and print it as if you are printing an integer: ``` int i; while(buf[i]) { printf("%d\n",buf[i]); ++i; } ``` By using indices `[i]` one can access each character if the string. Besides that have a look at this: [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong)
990,285
$e^x$$(1+e^x)^{1\over{2}}$ why can't use integration by part, What is meant by in the form of f(g(x))g'(x)? Can you give a few example? Thank you
2014/10/25
[ "https://math.stackexchange.com/questions/990285", "https://math.stackexchange.com", "https://math.stackexchange.com/users/173339/" ]
Integration by substitution says that $$ \int f(g(x))g'(x) \; dx = \int f(u)\;du $$ where $u = g(x)$. This is a tool that will let you compute the integral of all functions that look exactly like $f(g(x))g'(x)$. When you first see this, you might be thinking that this seems like a very specialised rule that only seem good for very special cases. But it turns out that this is very useful. In your example, you have $$ \int (1 + e^x)^{1/2}e^x\; dx. $$ If you want to know whether or not you can use substitution you just have to determine if it is possible to write $(1 + e^x)^{1/2}e^x$ as $f(g(x))g'(x)$ for some functions $f$ and $g$. Mabe by trail and error you find that indeed if $f(x) = x^{1/2}$ and $g(x) = 1+e^x$, then $f(g(x))g'(x) = (1 + e^x)^{1/2}e^x$. And so with $u = g(x) = 1+e^x$, you get $$ \int (1 + e^x)^{1/2}e^x\; dx = \int u^{1/2} \; du = \frac{2}{3}u^{3/2} + C = \frac{2}{3}(1+e^x)^{3/2} + C. $$ --- You ask why you you can't use integration by parts. Integration by parts says that $$ \int f(x)g'(x)\; dx = f(x)g(x) - \int f'(x)g(x)\; dx. $$ So you would have to find $f$ and $g$ such that $f(x)g'(x) = e^x(1+e^e)^{1/2}$. You can of course choose $f(x) = (1 + e^x)^{1/2}$ and $g(x) = e^x$, so then you get $$ (1 + e^x)^{1/2}e^x - \int \frac{1}{2}(1+e^x)^{1/2}e^xe^x\;dx. $$ This is perfectly fine, but it doesn't do you any good. You wanted to find one complicated integral and now you just have another complicated integral. So you *can* use integration by parts, but, again, it doesn't help you much. It would be a good exercise to try other choices of $f$ and $g$ to convince yourself that this indeed doesn't help much.
29,390,701
I am working in codeigniter. My problem is i want to show all rows having same id. But when i perform group\_by it only outputs one row of that group. below is my model ``` function category_content(){ $this->db->select('*'); $this->db->from('category'); $this->db->group_by('category_id'); $query = $this->db->get(); return $query->result_array(); } ``` Please help.
2015/04/01
[ "https://Stackoverflow.com/questions/29390701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2717813/" ]
As per the sql properties `Group By` groups all the matching records and will show you only one. It seems you want to sort them by id. Then its better to use `order by`
4,124,091
I use Visual Studio 2008 Professional with .NET 3.5 SP1 installed. It is not showing Entity Model when I select "New Project". The MSDN links show that it was included with .NET 3.5 SP1. Why it is not appearing on my VS 2008?
2010/11/08
[ "https://Stackoverflow.com/questions/4124091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194328/" ]
You probably need to install *VS2008* SP1, which contains the tooling used to develop against .Net 3.5 SP1.
73,033,294
I', trying to run this functin only on mobile devices which is less than 768px , it works on this screen width but it also ignore the condition and works on larger screens than 768px, i tried to clear interval but there is something wrong with my code ```js $(document).ready(function () { $(window).on("resize", function (e) { checkScreenSize(); clearInterval(intervalId) }); checkScreenSize(); function checkScreenSize() { var newWindowWidth = $(window).width(); if (newWindowWidth < 768) { const divs = [...document.querySelectorAll(".tagline2")]; divs.i = 0; intervalId = setInterval(function () { divs[divs.i++].classList.remove("move"); divs[divs.i = divs.i % divs.length].classList.add("move") }, 3000); } } }); ``` ```css .move {background-color:red} ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="infobarContainer"> <div class="tagline tagline2 move"> USP 1 </div> <div class="tagline tagline2"> USP 2 </div> <div class="tagline tagline2"> USP 3 </div> <div class="tagline tagline2"> USP 4 </div> </div> ```
2022/07/19
[ "https://Stackoverflow.com/questions/73033294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19351845/" ]
If you want to use it later you create it in a macro variable and reference it later with a &variableName Let's assume: * data set name is myDataset * variable name is value * Single observation/row in the data set * Macro variable output name is myValue ``` *create fake data; data myDataset; date = mdy(7, 18, 2022); format date ddmmyyn8.; value = 15; output; run; ``` ``` data _null_; *_null_ means SAS will not create a data set as output; set myDataset; *indicate the input data set; call symputx('myValue', value, 'g'); *create the variable with a global scope; run; ``` Then to use it later, say filter all people under the age of myValue. ``` data below15; set sashelp.class; where age <= &myValue; run; ``` Here is more references on Macro variables. <https://stats.oarc.ucla.edu/sas/seminars/sas-macros-introduction/> Generally speaking though, avoiding macros at the beginning is recommended. You should code without macros as much as possible. There are often other ways of doing things.
4,118,439
In problem 33 iv Chapter 5 of Spivak's *Calculus*, there is a comment in the solution manual that (in essence) remarks $\lim\_{x \to \infty} \sin x$ **does not exist**. I wanted to see if I could prove this statement by negating the formal definition of $\lim\_{x \to \infty}f(x)=L \iff \exists L \in \mathbb R \Big [ \forall \epsilon \gt 0 \ \exists N \in \mathbb R \text { s.t. } \forall x \in \mathbb R \big ( x \gt N \rightarrow \lvert f(x) - L \rvert \lt \epsilon \big ) \Big ]$ i.e. I wanted to write a proof that: > > $\forall L \in \mathbb R \Big [\exists \epsilon \gt 0 \text{ s.t. } \forall N \in \mathbb R \ \exists x \in \mathbb R \text{ s.t. }\big (x \gt N \land \lvert \sin(x) - L \rvert \geq \epsilon \big) \Big]$ > > > I'll write what I have so far and highlight the missing piece that I am finding difficult to navigate around. As an "FYI" for those unfamiliar with Spivak's *Calculus*, the subject of Continuous Functions is not found until chapter 6, and I suspect that my issue arises from trig functions being more..."tackle-able"...once continuity is rigorously defined. --- Relevant Lemma: $\lvert \sin(x) \rvert \leq 1 \quad$ (I do not believe this statement, in and of itself, requires knowledge of continuous functions) Consider two cases: $\lvert L \rvert \gt 1$ or $\lvert L \rvert \leq 1$. --- **Case 1**: Note that $\lvert L \rvert \gt 1 \implies \frac{\lvert L \rvert -1}{2}\gt 0$ Let $0 \lt\epsilon \lt \frac{\lvert L \rvert -1}{2}$ . Therefore $-\epsilon \gt \frac{1-\lvert L \rvert}{2}$. From which it follows: $$ \lvert L \rvert - \epsilon \gt \frac{2 \lvert L \rvert +1 - \lvert L \rvert}{2}=\frac{\lvert L \rvert +1}{2}\gt 1$$ By our lemma, we then have: $$\lvert L\rvert - \epsilon \gt 1 \geq \lvert \sin(x) \rvert$$. Rearranging: $$ \lvert L \rvert \gt 1 + \epsilon \geq \lvert \sin(x) \rvert + \epsilon$$ $$ \lvert L \rvert - \lvert \sin(x) \rvert \gt \epsilon$$ Invoking one of the triangle inequality variants, we finally have: $$ \lvert \sin(x) - L \rvert = \lvert L - \sin(x) \rvert \geq \lvert L \rvert - \lvert \sin(x) \rvert \gt \epsilon$$ Note that $\forall x \in \mathbb R$, the above statement is true. Therefore, any $N \in \mathbb R$ can be chosen and one can always find an $x \gt N$, for which the desired criteria is met. --- **Case 2**: $\lvert L \rvert \leq 1$ Consider an $\epsilon \lt \frac{1}{2}$. For example, $\epsilon = \frac{1}{4}$ Here is where I am basically stumped in the absence of knowing anything about continuous functions. My hunch is that because $\lvert L \rvert \leq 1$, I can effectively assert that $\exists c \in \mathbb R \big [ \sin(c) = L \big ]$. Now, invoking the same triangle inequality variant as before, we know that: $$ \lvert \sin(c) - \sin(x) \rvert \geq \lvert \sin(c) \rvert - \lvert \sin(x) \rvert $$ So if I can show that: $\exists x \in \mathbb R \big [\lvert \sin(c) \rvert - \lvert \sin(x) \rvert \gt \frac{1}{4} \big ]$, we are good to go. Once again, I assume that I need some notion of continuous functions in order to prove this. More generally, in order to apply this argument to any $N \in \mathbb R$, I would like to prove the slightly more refined: $$ \exists x \in [c - \pi, c + \pi] \text{ s.t. } \Big ( \lvert \sin(c) \rvert - \lvert \sin(x) \rvert \gt \frac{1}{4} \Big )$$ (noting the $c$ value that produces $\sin(c)=L$ can be replaced by $c+2\pi n$ for any any integer $n$). If there is a method to circumvent continuous functions, I would greatly appreciate the insight! Thank you!
2021/04/27
[ "https://math.stackexchange.com/questions/4118439", "https://math.stackexchange.com", "https://math.stackexchange.com/users/544640/" ]
> > i.e. I wanted to write a proof that: > > > $$\forall L \in \mathbb R \Big [\exists \epsilon \gt 0 \text{ s.t. } \forall N \in \mathbb R \ \exists x \in \mathbb R \text{ s.t. }\big (x \gt N \land \lvert \sin(x) - L \rvert \geq \epsilon \big) \Big]$$ > > > We can do this using $\varepsilon = \frac{1}{2}$. **Case 1:** $L > 0$ Here for any $N$ we can always find $x > N$ of the form $x = \frac{3\pi}{2} + 2k\pi$ where $k \in \mathbb{N}$. For such $x$ we have $$\sin x = -1.$$ Since $L > 0$ we have \begin{align} |\sin x - L|&= |-1 - L| \\ & = 1 + L \\ & > \frac{1}{2} \end{align} **Case 2** $L < 0$ This case is nearly identical to the case for $L > 0$. For any $N$ we can always find $x > N$ of the form $x = \frac{\pi}{2} + 2k\pi$ where $k \in \mathbb{N}$. For such $x$ we have $$\sin x = 1.$$ Since $L < 0$ we have \begin{align} |\sin x - L|&= |1 - L| \\ & = 1 + |L| \\ & > \frac{1}{2} \end{align} **Case 3** $L = 0$ This case can be dealt with immediately by re-using either of the $x$ from the previous two cases: If $x = \frac{\pi}{2} + 2k\pi$, then \begin{align} |\sin x - L|&= |1 - 0| \\ & = 1 \\ & > \frac{1}{2} \end{align} Of course, this all depends on knowing the behavior of $\sin$: that $\sin$ wavers between $1$ and $-1$ "forever" and so on. Given this behavior, one would expect intuitively that the limit doesn't exist, i.e. $\sin x$ wouldn't "settle" upon some single value for large $x$. Later in the book Spivak defines the trigonometric functions formally in a way that conforms with the geometric/unit circle versions with which you are probably already familiar. Continuity plays a big part in these later definitions. Here though, the main thing is just the periodic nature of $\sin$. Finally, you may be somewhat leery of statements like: > > ...for any $N$ we can always find $x > N$ of the form $x = \frac{3\pi}{2} + 2k\pi$ where $k \in \mathbb{N}$. > > > This has at its heart the idea that given any real number $N$ we can find a natural number $n$ with $n > N$. *This* fact is employed in a few places early on in the text, but isn't formally proven until Chapter 8 (3rd Ed.) "Least Upper Bounds". Spivak cops to this "cheating" at the end of that chapter. (As an aside, an earlier problem in Chapter 5, 5-12 gives a very useful result: If $f(x) \leq g(x)$ for all $x$ (or even just for all $x$ in a neighborhood of $a$) then $\lim\_{x\to a} f(x) \leq \lim\_{x\to a} g(x)$, provided these limits exist. This can be shown to hold if we replace $a$ with $\infty$. This, combined with your lemma that $|\sin x| \leq 1$ can be used to rule out your Case 1, i.e. since $-1 \leq \sin x \leq 1$ we must also have $-1 \leq \lim\_{x \to \infty}\sin x \leq 1$, if that limit exists.)
7,391,333
I am trying to implement a simple contact manager using the VirtualStringTree component. I have it set up to look like a list-view component with only three columns that will all contain text: ![Layout](https://i.stack.imgur.com/fBlWS.jpg) For the data structure, I am using svTree by Linas, which was mentioned in another Stack Overflow question. I have declared a record like this: ``` type TMainData = record Name, Email, Password: string; end; ``` In the form's OnCreate I have this: ``` procedure TForm1.FormCreate(Sender: TObject); begin MyTree := TSVTree<TMainData>.Create(False); MyTree.VirtualTree := vst1; end; ``` I am adding the data from TEdits like this: ``` procedure TForm1.BuildStructure; var svNode: TSVTreeNode<TMainData>; Data: TMainData; begin MyTree.BeginUpdate; try Data.Name := edtname.Text; Data.Email := edtEmail.Text; Data.Password := edtPassword.Text; svNode := MyTree.AddChild(nil, Data); finally MyTree.EndUpdate; end; Label1.Caption := 'Count: '+IntToStr(MyTree.TotalCount); end; ``` How can I save this into a stream or a file to be loaded back? I have tried using `MyTree.SaveToFile('C:/Test.dat')` and `MyTree.LoadFromFile('C:/Test.dat')`, but when it's loaded back the tree view contains no data, only a blank row.
2011/09/12
[ "https://Stackoverflow.com/questions/7391333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/471837/" ]
You need to set OnLoadNode and OnSaveNode procedures for your TSVTree and implement your logic here. You can look at Project2 in the Demos folder. E.g.: ``` uses uSvHelpers; MyTree.OnSaveNode := DoSave; MyTree.OnLoadNode := DoLoad; procedure TForm1.DoLoad(Sender: TSVTree<TMainData>; Node: TSVTreeNode<TMainData>; Stream: TStream); var obj: TMainData; begin // if Assigned(Node) then begin //read from stream //read in correct order obj.Name := Stream.AsString; obj.Email := Stream.AsString; obj.Password := Stream.AsString; Node.FValue := obj; end; end; procedure TForm1.DoSave(Sender: TSVTree<TMainData>; Node: TSVTreeNode<TMainData>; Stream: TStream); begin if Assigned(Node) then begin //read from stream Stream.WriteString(Node.FValue.Name); Stream.WriteString(Node.FValue.Email); Stream.WriteString(Node.FValue.Password); end; end; ``` After that you can just call `MyTree.SaveToFile('C:/Test.dat')` or `MyTree.LoadFromFile('C:/Test.dat')`. In my demo and this example i've used another unit (uSvHelpers) which implements TStream helper for more OO stream support. You can of course use your own way to write your data information to stream.
27,443,929
I'm trying to get a dropdown show the right value when editing using a viewmodel but it only works when i pass the complete model to the view. When I do it like this and there is already a contact selected it shows that contact in the edit screen. **Model** ``` public class ClientModel { public int ID { get; set; } public int ContactID { get; set; } //Other atributes } ``` **View EditContact** ``` @model Project.Models.ClientModel @Html.DropDownListFor(model => model.ContactID , (SelectList)ViewBag.ContactID, "select a contact") ``` **Controller** ``` public ActionResult EditContact(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } var Contact = db.Contacts.ToList(); ViewBagID.Contact = new SelectList(Contact.AsEnumerable(), "ID", "name", "Contact"); ClientModel model= db.ClientModel.Find(id); return View(model); } ``` But when I do it like this and there is already a contact selected the dropdownlist shows select contact. **Model** ``` public class ClientModel { public int ID { get; set; } public int ContactID { get; set; } //Other atributes } ``` **ViewModel** ``` public class ClientEditContactModel { public int ID { get; set; } public int ContactID { get; set; } } ``` **View EditContact** ``` @model Project.Models.ClientEditContactModel @Html.DropDownListFor(model => model.ContactID, (SelectList)ViewBag.ContactID, "select a contact") ``` **Controller** ``` public ActionResult EditContact(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } var Contact = db.Contacts.ToList(); ViewBag.ContactID = new SelectList(Contact.AsEnumerable(), "ID", "name", "Contact"); ClientModel client= db.ClientModel.Find(id); ClientEditContactModel model = new ClientEditContactModel(); model.ID = client.ID; model.ContactID = client.ContactID return View(model); } ``` How do i fix this with the viewmodel? **Edit** I've made some typo's in my code so I fixed them but because of them i found the answer see below.
2014/12/12
[ "https://Stackoverflow.com/questions/27443929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4252392/" ]
I found the answer after some more research here <https://stackoverflow.com/a/11949123/4252392>. The problem was that ViewBag's name is the same as the model's property. So i changed the Viewbag's name. **New Controller** ``` public ActionResult EditContact(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } var Contact = db.Contacts.ToList(); ViewBag.ContactIDList = new SelectList(Contact.AsEnumerable(), "ID", "name", "Contact"); ClientModel client= db.ClientModel.Find(id); ClientEditContactModel model = new ClientEditContactModel(); model.ID = client.ID; model.ContactID = client.ContactID return View(model); } ``` **New View** ``` @model Project.Models.ClientEditContactModel @Html.DropDownListFor(model => model.ContactID, (SelectList)ViewBag.ContactIDList, "select a contact") ```
36,635,623
I have this function which is making a request to an api with `get`. the response is coming back and expected and I am printing out each name of the objects returned to the terminal. But when I use the same for loop to print data in the template only the name of the last object is being rendered on the template page. I was thinking maybe I am not executing my for loop properly but if that was true then why is my data outputting correctly in terminal. In my view ``` def graphs(request): if request.user.is_authenticated(): data = [] r = requests.get('https://api.deckbrew.com/mtg/cards') jsonList = r.json() cardData = {} for cards in jsonList: cardData['name'] = cards['name'] # Only last object name print(cards['name']) # Prints to termainl correct data.append(cardData) return render(request, 'graphs/graphs.html', {'data': data}) else: return redirect('index') ``` This is in my template # I only get the last objects name ``` {% for card in data %} <tr> <td>{{ card.name }}</td> </tr> {% endfor %} ``` When I move the data.append inside the for loop it appends the same name to the list for each time there is a card in the response. ``` for cards in jsonList: cardData['name'] = cards['name'] print(cards['name']) data.append(cardData) ``` [![enter image description here](https://i.stack.imgur.com/ZqTaW.png)](https://i.stack.imgur.com/ZqTaW.png)
2016/04/14
[ "https://Stackoverflow.com/questions/36635623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2218253/" ]
It's because you declared ``` cardData = {} ``` outside your loop and the same instance is being written over and the same dictionary is being pushed onto the array. On the last iteration the entire list has the last name. Move that declaration inside the loop. Or better still, just append each card onto the list. Your indentation is wrong too. You only ever put the last instance on the results list. Do this: ``` for cards in jsonList: data.append(cards) ```
33,797,766
I am developing a Messaging system.I need Scroll bar to be fixed down ,Because when new data arrives It should automatically go down.How to do that in HTML/CSS Don't mine if this full code is in a unprofessional way.. [![enter image description here](https://i.stack.imgur.com/FJhFJ.png)](https://i.stack.imgur.com/FJhFJ.png) Home.php ``` <?php // Turn off all error reporting error_reporting(0); //shop not login users from entering if(isset($_SESSION['id'])){ $user_id = $_SESSION['id']; }else{ } require_once("./inc/connect.inc.php"); ?> <header> <link rel="stylesheet" href="home - Copy.css" /> <nav> <h3><a class="h3" href="#">CP</a></h3> <div><a href="logout.php"><span>Logout</span></a></div> <div> <?php //Start your session session_start(); //Read your session (if it is set) if (isset($_SESSION['user_login'])){ echo '<div id="ull">'.strtoupper($_SESSION['user_login']).'</div>'; } ?> </div> </nav> <body> <div class="shead"> <div class="a1"> <li >Frequent Member</li> <div class="fm"> <ul> <?php //show all the users expect me $user_id = $_SESSION['id']; $q = mysql_query("SELECT * FROM `users` WHERE id!='$user_id'"); //display all the results while($row = mysql_fetch_assoc($q)){ echo " <div class='usernames'> <a id=\"usernames\" href='home.php?id={$row['id']}'>{$row['username']}</a> </div> "; } ?> </ul> </div> </div> <div class="a2"> <li >Site's Popular in Your College</li></div> </div> </header> <div class="rss"> <?php // include('rssclass.php'); //include('rss.php'); ?> </div> <div class="message-right"> <!-- display message --> <div class="display-message"> <?php //check $_GET['id'] is set if(isset($_GET['id'])){ $user_two = trim(mysql_real_escape_string( $_GET['id'])); //check $user_two is valid $q = mysql_query( "SELECT `id` FROM `users` WHERE id='$user_two' AND id!='$user_id'"); //valid $user_two if(mysql_num_rows($q) == 1){ //check $user_id and $user_two has conversation or not if no start one $conver = mysql_query( "SELECT * FROM conversation WHERE (user_one='$user_id' AND user_two='$user_two') OR (user_one='$user_two' AND user_two='$user_id')"); //they have a conversation if(mysql_num_rows($conver) == 1){ //fetch the converstaion id $fetch = mysql_fetch_assoc($conver); $conversation_id = $fetch['id']; }else{ //they do not have a conversation //start a new converstaion and fetch its id $q = mysql_query( "INSERT INTO `conversation` VALUES ('','$user_id',$user_two)"); $conversation_id = mysql_insert_id($con); } }else{ die("Invalid $_GET ID."); } }else { die("Click On the Person to start Chating."); } ?> </div> <script type="text/javascript"> var objDiv = document.getElementById("display-message"); objDiv.scrollTop = objDiv.scrollHeight; </script> <div class="send-message"> <!-- store conversation_id, user_from, user_to so that we can send send this values to post_message_ajax.php --> <input type="hidden" id="conversation_id" value="<?php echo base64_encode($conversation_id); ?>"> <input type="hidden" id="user_form" value="<?php echo base64_encode($user_id); ?>"> <input type="hidden" id="user_to" value="<?php echo base64_encode($user_two); ?>"> <div class="textbox"> <input class="t_box" type="text" id="message" placeholder="Enter Your Message"/> <button class="t_btn" id="reply">Reply</button> <span id="error"></span> </div> </div> </div> <!-- <div class="textbox"> <form action="#" method="post"> <input type="text" name="msg_body" class="t_box" id="t_box" > <input type="submit" class="t_btn" id="t_btn" name="submit" value="Send"> </form> </div>--> <script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" src="js/script.js"></script> </body> ``` Getmsg.php ``` <?php require_once("./inc/connect.inc.php"); if(isset($_GET['c_id'])){ //get the conversation id and $conversation_id = base64_decode($_GET['c_id']); //fetch all the messages of $user_id(loggedin user) and $user_two from their conversation $q = mysql_query( "SELECT * FROM `messages` WHERE conversation_id='$conversation_id'"); //check their are any messages if(mysql_num_rows($q) > 0){ while ($m = mysql_fetch_assoc($q)) { //format the message and display it to the user $user_form = $m['user_from']; $user_to = $m['user_to']; $message = $m['message']; //get name and image of $user_form from `user` table $user = mysql_query( "SELECT username FROM `users` WHERE id='$user_form'"); $user_fetch = mysql_fetch_assoc($user); $user_form_username = $user_fetch['username']; //display the message echo " <div class='message'> <div class='text-con'> <a href='#''>{$user_form_username}:</a> <p> {$message}<p> </div> </div> <hr>"; } }else{ echo "No Messages"; } } ``` ?>
2015/11/19
[ "https://Stackoverflow.com/questions/33797766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5569126/" ]
As @TheAppMentor said code looks fine. Make sure you entered correct cell identifier. Then make sure you connected your view controller to correct class (it's my common mistake). Also make sure that something else in this cell hasn't the same tag. You can also print all subviews to check what's inside.
3,955,878
I am currently using apTreeshape to simulate phylogenetic trees using the "Yule-Hardy" Method. What I want to do is randomly generate between 20 and 25 different numbers for three different groupings (small, medium and large trees) and then generate about 40 trees for every random number chosen from within the grouping. I know how I would do this in Python of Matlab, but in R things seem to behave a bit differently. My thought was that if I were to generate a vector full of random numbers (one for each size grouping) and then use that to generate a vector which would basically contain all of the repeated values of each random number. Here is what I have: ``` sm_leaves<-c(sample(3:50,25,replace=F)); s_leafy<-numeric(); for (i in 1:length(sm_leaves)) { for (j in 1:10) { s_leafy[j+i-1]=sm_leaves[i]; } } ``` This is giving me output like: ``` > s_leafy [1] 5 38 6 22 29 20 19 46 9 18 39 50 34 11 43 7 8 32 10 42 14 37 [23] 23 13 28 28 28 28 28 28 28 28 28 28 ``` But What I want is something more like: ``` > s_leafy [1] 5 5 5 5 5 5 5 5 5 5 38 38 38 38 38 38 38 38 38 ... 28 28 28 28 28 28 28 28 28 28 ``` My reason for doing this is merely so that I can append this vector to a data frame along with all of the randomly generated trees - I need 2000 of them, so doing this by hand ain't quite practical. All I have really been able to deduce from my previous attempts to solve this problem is that generally speaking while loops should be used instead of for loops, and many people have talked about using expand.grid, but I don't think that the latter is particularly useful in this case. Thanks for reading, I hope my problem isn't too trivial (although I wouldn't be surprised if it were).
2010/10/18
[ "https://Stackoverflow.com/questions/3955878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/478864/" ]
Using 'rep' is clearly the answer for how to do this quickly in R, but why doesn't your code work? A little investigation reveals why. First, take out the randomness and give yourself a simple, reproducible example. Set sm\_leaves to c(3,4,5) and see what happens. You get: 3 4 5 5 5 5 5 5 5 5 5 5 which still looks wrong. You expected ten 3s, ten 4s, ten 5s right? Hmmm. Add a print statement to your loop to see where the values are being stuck: ``` > for (i in 1:length(sm_leaves)) { for (j in 1:10) { print(j+i-1) s_leafy[j+i-1]=sm_leaves[i]; } } [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 [1] 6 [1] 7 [1] 8 [1] 9 [1] 10 [1] 2 [1] 3 [1] 4 [1] 5 [1] 6 ...etc.... ``` Oops. Your vector index is wrong. j+i-1 is jumping back after every inner loop and overwriting the earlier values. You want: ``` s_leafy[j + (i - 1)*10]=sm_leaves[i]; ``` So maybe this is just a simple case of you missing the \*10 in the expression! Note however that a lot of simple vector manipulation is best done using R's functions such as rep, and seq, and "[", as explained in the other answers here.
180,737
Please, help me to put a proper word collocation into a sentence. I need to describe in an office announcement that a new printer is set for satisfy any employee (printing) need. I found the phrase *"to support needs"*, but I am not sure about it. The context is here: > > Dear Colleagues, > > > We would like to inform you that the new printer is now available on the 9th floor of the 3rd tower. It was set to simplify the access to the printer and support needs of the growing number of employees of the recently opened floors of the third tower. > > > Any help would be appreciated!
2018/09/25
[ "https://ell.stackexchange.com/questions/180737", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/81713/" ]
It doesn't end with '**s**' because it's the (bare) **infinitive**, which is used without '**to**' after verbs like **hear**, bid, let, make, see, need, dare, etc. <https://www.englishgrammar.org/bare-infinitive-2/>
64,443,026
In JSX/TSX syntax from react, all inputs seems to be define with the same props declaration which is `InputHTMLAttributes`: ```js interface InputHTMLAttributes<T> extends HTMLAttributes<T> { accept?: string; alt?: string; autoComplete?: string; autoFocus?: boolean; capture?: boolean | string; // https://www.w3.org/TR/html-media-capture/#the-capture-attribute checked?: boolean; crossOrigin?: string; disabled?: boolean; form?: string; formAction?: string; formEncType?: string; formMethod?: string; formNoValidate?: boolean; formTarget?: string; height?: number | string; list?: string; max?: number | string; maxLength?: number; min?: number | string; minLength?: number; multiple?: boolean; name?: string; pattern?: string; placeholder?: string; readOnly?: boolean; required?: boolean; size?: number; src?: string; step?: number | string; type?: string; value?: string | ReadonlyArray<string> | number; width?: number | string; onChange?: ChangeEventHandler<T>; } ``` I want to define a specific type for only an input of type `number` so that TypeScript complains if I use a `checked` or `disabled` prop on it: ```html <!-- invalid `checked` prop --> <input type="number" step="any" min="0" max="100" value="22.33" checked={true} /> ``` So is there already a type definition for that coming from React? I know that I can just define it like the following but I would prefer to use an official source: ```js interface InputNumberProps { type: 'number'; max?: number | string; min?: number | string; ... } ```
2020/10/20
[ "https://Stackoverflow.com/questions/64443026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8583669/" ]
Multiply, then reset negative values: ``` # transpose and multiply per row res <- t(m) * v res <- t(res) # then reset negatives to original value res[m < 0] <- m[ m < 0 ] res # a b c # [1,] -1 -1 -1 # [2,] 4 6 -9 # [3,] 6 6 -3 # [4,] 8 -4 -2 ```
68,819
[Cosmic rays](https://en.wikipedia.org/wiki/Cosmic_ray) are energetic particles coming from space that hit the Earth's atmosphere and produce a lot of [secondary radiation](https://en.wikipedia.org/wiki/Air_shower_(physics)) (some of which we see in visible light as aurorae). Would it make sense for an organism floating in the upper atmosphere, or even on the brink of space, to try and make this energy work for them, as plants do using the photons from sunlight to split water? Or are cosmic rays too destructive, or too unwieldy, or too sparse for such use? The question is not confined to Earth, of course, or to organisms similar to those living on today's Earth. I'm trying to decide if a microbial biosphere could live off cosmic radiation and its subproducts. P.S.: [This post](https://worldbuilding.stackexchange.com/questions/36534/no-sunlight-just-high-energy-radiation) touches on some of the same points as my question, though I'm thinking more about a rogue planet far from any star-like energy source (i. e. no pulsars or black holes nearby).
2017/01/21
[ "https://worldbuilding.stackexchange.com/questions/68819", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/31844/" ]
I would say that yes, it's borderline possible. The organism should be very resistant to ionizing radiation; a Universe that allows [*Deinococcus radiodurans*](https://en.wikipedia.org/wiki/Deinococcus_radiodurans) to exist would have little trouble in producing this new critter, even limiting ourselves to DNA. The organism would of course need to consume ordinary matter to replicate; it would therefore find it way more convenient to (also) extract what energy it can from that matter. Actually it's likely that the capability of absorbing cosmic radiation would evolve from the former; the organism acquires matter and this interacts with cosmic radiation, supplying harvestable energy. Once this kind of matter is more and more incorporated into the new generations of the organism, it will "optimize" itself to directly take advantage of the radiation. An organism could not begin directly using cosmic radiation, since to do that it would need chemicals and structures that would be already pretty complex. It would need to start from simple chemical reactions, and evolve to first defend against, then make use of the radiation. The most obvious evolution pressure line would be if the defense takes the form of some radiation-hardy chemical, which is transformed on impact generating much higher-energy compounds that would be initially disposed of. Afterwards, any mutation allowing to extract energy from such compounds would have an enormous evolutionary value. This is not unlike what already happened to [radiotrophic fungi](https://en.wikipedia.org/wiki/Radiotrophic_fungus), which produce a special kind of melanin that is capable of harvesting energy from gamma radiations. It would be more difficult (!) for our hypothetic organism, in that cosmic rays are much more penetrating and energetic than gamma rays and therefore require proportionally more massive interception. And, of course, the organism would need to live somewhere with *a lot* of cosmic rays. One possibility would be some sort of low-temperature outer space slug capable of accreting a "black ice" carapace. It would migrate to the safe center of cometary nuclei to spawn, then come out when the carapace is thick enough to both defend the young slug and supply it with energy. The slug would need to have a very low metabolic rate, and be based on a totally different organic chemistry than Earth organisms. --- There's something along these lines in ["Camelot 30K"](https://en.wikipedia.org/wiki/Camelot_30K) by physicist Robert L. Forward, where a (macroscopic) lifeform is presented that harvests atomic nuclei transmuted by the impact of cosmic rays on distant comets. > > *"The initial energy source for the kerac civilization comes from the background cosmic radiation, which creates long-lived excited molecules and free radicals in the ice over long periods of time"*. He drew an arrow leading to another box that he drew in the rotund shape of an iceworm. *"Out on the farms, the iceworms and young heullers tunnel through the untouched ice around the periphery of Camalor. They extract free radicals frozen into the pristine ice and use them as a source of energy to grow and continue tunneling. Those long-lived free radicals are the first level energy source of the kerack food chain, since the iceworms and heullers are harvested as meat. While the iceworms are doing that, they also extract from the dirty ice all the unstable radioisotopes that the dirt and ice contain."* > > > (While different organisms are named - *iceworms*, *heullers*, *keracks* - it is posited in the book that they are actually all alternate phenotypes of a *single* organism, the kerack hive drone, not unlike what happens with bees).
60,078,041
I am trying to create a regular expression to separate each word from `.` (dot) in JavaScript. ``` function myFunction() { var url = "in.k1.k2.k3.k4.com" var result var match if (match = url.match(/^[^\.]+\.(.+\..+)$/)) { console.log(match); } } ``` Actual result is: ``` match[0] : in.k1.k2.k3.k4.com match[1] : k1.k2.k3.k4.com ``` Expected result is: ``` match[0] : in.k1.k2.k3.k4.com match[1] : k1.k2.k3.k4.com match[2] : k2.k3.k4.com match[3] : k3.k4.com match[4] : k4.com ``` Please help me to create perfect regular expression.
2020/02/05
[ "https://Stackoverflow.com/questions/60078041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12337410/" ]
In order to store more than one JSON record, use an array, as when loading you can just load JSON types (an an array is the ideal JSON type you're looking for for that use case). In that case, to read all scores: ```py scores = [] with open ("score.json") as json_data: scores = json.load(json_data) ``` But most important, to write them to a file: ```py scores.append(score) json_dump = json.dumps(scores) f = open("score.json","w") f.write(json_dump) f.close() ``` **Update** The last code can also be written using `json.dump`: ```py scores.append(score) f = open("score.json","w") json.dump(scores, f) f.write(json_dump) f.close() ```
50,598,509
I want to change CSV file content: ``` itemId,url,name,type 1|urlA|nameA|typeA 2|urlB|nameB|typeB 3|urlC,urlD|nameC|typeC 4|urlE|nameE|typeE ``` into an array: ``` [itemId,url,name,type] [1,urlA,nameA,typeA] [2,urlB,nameB,typeB] [**3**,**urlC**,nameC,typeC] [**3**,**urlD**,nameC,typeC] [4,urlE,nameE,typeE] ``` Could anybody teach me how to do it? Finally, I'm going to DL url files(.jpg)
2018/05/30
[ "https://Stackoverflow.com/questions/50598509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5448792/" ]
The header row has a different separator than the data. That's a problem. You need to change the header row to use `|` instead of `,`. Then: ``` require 'csv' require 'pp' array = Array.new CSV.foreach("test.csv", col_sep: '|', headers: true) do |row| if row['url'][/,/] row['url'].split(',').each do |url| row['url'] = url array.push row.to_h.values end else array.push row.to_h.values end end pp array => [["1", "urlA", "nameA", "typeA"], ["2", "urlB", "nameB", "typeB"], ["3", "urlC", "nameC", "typeC"], ["3", "urlD", "nameC", "typeC"], ["4", "urlE", "nameE", "typeE"]] ```
142,696
I have not given this too much thought until recently, when a bit of a back and forth happened with a client. So, when I start a new document in InDesign, **for CMYK print**, how to I know how to setup the color settings ? Many times I will just not look at this and go with whatever is set by default, but apparently this may affect things. Is this just a case of choosing between the "Europe General Purpose" vs the "North America General Purpose" presets, or is there more to this ? Are the "Coated FOGRA39"/"US Web Coated (SWOP)" the most widely used standards that will generally work for printers in the EU/US ? What about web documents in RGB ? Like, when you design a presentation that will not go to a CMYK printer, what's the proper colour space to use for that ? [![enter image description here](https://i.stack.imgur.com/W9GZ7.jpg)](https://i.stack.imgur.com/W9GZ7.jpg) [![enter image description here](https://i.stack.imgur.com/cHb5b.jpg)](https://i.stack.imgur.com/cHb5b.jpg)
2020/10/29
[ "https://graphicdesign.stackexchange.com/questions/142696", "https://graphicdesign.stackexchange.com", "https://graphicdesign.stackexchange.com/users/62949/" ]
Why bother about color profiles? ================================ First of all you need to accept that *different printers follow different standards*. The same CMYK numbers will look differently when printed according to different standards. It's not possible to make a PDF which will be perfect under all circumstances. Unless I absolutely have to, I wouldn't export a PDF for print before knowing where the document will be printed, on which kind of paper and which ICC profile the print house recommends for that paper. To use the wrong profile can affect the colors on the final print, but even if there is little difference between the profile you choose and the recommended one, there is also a responsibility issue. If you receive a print where you think the colors are a little bit off and the print house discovers that you didn't use the recommended profile, they might park the complaint right there. Always best to keep your path clean. Setting up your document ======================== Setting up *Working Spaces* in the *Color Settings* affects *new* documents, but you can always change the settings for an existing document later by using *Edit > Assign Profiles*. You can also choose a different profile when exporting a PDF. So you are not confined by what the settings where when you created your document. The main reason for caring about which profile to use for your InDesign document from the beginning is that it affects the *preview*. In a print document, when you turn on *View > Overprint Preview* the graphics and images are displayed *as they would look if they were printed according to the Document CMYK*. RGB swatches ------------ Although all swatches in a print document will be CMYK by default, it's also possible to make RGB swatches. They are assumed to have the RGB profile chosen as *Document RGB* and with *Overprint Preview* turned on they are displayed as if they were converted from that to the CMYK profile chosen as *Document CMYK*. RGB images with an embedded profile ----------------------------------- If you are a little in doubt about color profiles and don't know exactly what you are doing and why, I would always recommend to only place RGB images with an embedded color profile. With *Overprint Preview* turned on they are displayed as if they were converted from their embedded RGB profile to the CMYK profile chosen as *Document CMYK*. For example an RGB image looking like this: [![](https://i.stack.imgur.com/r2UTA.png)](https://i.stack.imgur.com/r2UTA.png) Will look like this with *Document CMYK* set to *Coated FOGRA39*: [![](https://i.stack.imgur.com/ghLFm.png)](https://i.stack.imgur.com/ghLFm.png) But with *Document CMYK* set to *PSO Uncoated*, it will look more faded because the gamut is smaller: [![](https://i.stack.imgur.com/kxZyD.png)](https://i.stack.imgur.com/kxZyD.png) Untagged RGB images ------------------- RGB images without an embedded profile are a common cause of a shift in colors from screen to print. They are displayed in Adobe's applications as if they had the profile chosen as *Working RGB* in Photoshop or *Document RGB* in InDesign. So if your Photoshop for example has *Adobe RGB* as *Working RGB* and your InDesign document has *sRGB* as *Document RGB*, the untagged images will be displayed differently in those two applications. Here is how an untagged image (which is is in reality an sRGB image) is displayed when InDesign assumes *sRGB*: [![](https://i.stack.imgur.com/HEr6w.png)](https://i.stack.imgur.com/HEr6w.png) And here is how it looks if InDesign assumes *Adobe RGB*: [![](https://i.stack.imgur.com/IQHXG.png)](https://i.stack.imgur.com/IQHXG.png) Untagged RGB images should be opened in Photoshop and have a profile assigned. 99% of the time it's *sRGB*, but if it doesn't look right you can try *Adobe RGB*. It's a guess. CMYK swatches ------------- You probably make your swatches as CMYK swatches like most of us do. This is fine, but be aware that *a CMYK color is not an absolute color*. You are "hard coding" the percentages and the color will appear differently when printed according to different standards. A mistake I often experience is people creating a document without thinking about the CMYK profile and thereby unconsciously choosing *U.S. Web Coated (SWOP) v2* which is standard in Adobe's applications. Then they carefully fine-tune their CMYK swatches until they look as they want on screen. When they export a PDF they suddenly remember that they need to choose the correct color profile. They convert with *Preserve Numbers* to keep the black swatch at 100% black and thereby assign another color profile to the document. All the CMYK values are unchanged, but the intent of the document changes and when they see the document in Acrobat they notice that the colors have shifted. The colors they see when designing in *U.S. Web Coated (SWOP) v2* might look like this: [![](https://i.stack.imgur.com/znHfk.png)](https://i.stack.imgur.com/znHfk.png) But after exporting and assigning *Uncoated FOGRA29* the colors look different: [![](https://i.stack.imgur.com/2UNa6.png)](https://i.stack.imgur.com/2UNa6.png) CMYK images with an embedded profile ------------------------------------ Depending on how your *Color Management Policies* is set up, CMYK images with an embedded profile will either be *Preserved*, *Ignored* or *Converted*. You can see a detailed description of each in the *Color Settings* dialogue. I wouldn't recommend for you to place CMYK images unless you know what you are doing and why. Untagged CMYK images -------------------- Has the same problem as untagged RGB images. You don't know which profile it was converted to. InDesign just displays the image as if it was printed according to *Document CMYK*. If that profile isn't the same as the image was originally converted to, there will be a shift in colors. Avoid this issue. Common standards ================ If you are forced to guess which profile to use, here is a list of commonly used profiles. Europe ------ ### Coated paper * Coated FOGRA39 * ISO Coated v2 * ISO Coated v2 300% * etc. ### Uncoated paper * Uncoated FOGRA29 * ISO Uncoated * PSO Uncoated * etc. North America ------------- *(Americans, help me out here!)* A way to make a general PDF? ============================ I'm not sure I would recommend it, but if you really want to make documents which could be used on any printer, you could make a mix of RGB and CMYK. Keep the black text as 100% CMYK black and all neutral objects and images in percentages of black. All other objects and images could then be in RGB. This would enable a print house to convert your PDFs to any profile they wish without too much hassle.
55,064,957
With my current code, I'm trying to clear the corresponding cells (columns K:N) when the column (C:J) is blank. It's the reference of Rng. I think it's an `If Then` statement but not sure how to fit it within the code... I understand this is long but any help would be fantastic! For example, if C30:J30 is empty it clears K30:N30. Is it a `If Then` statement with `ClearContents`? Or if C15:J15 is blank then clear K15:N15, etc. I'm looking for help on clearing cells that are on the same row as the "Active" criteria. But, only after it is copied from "Future Project Hopper" to "CPD-Carryover,Complete&Active". Trying to make sure it's not confusing when I copy/clear C to J and am left with some data in columns K to N. I'm making this for other individuals to use to easily move Active projects from one sheet to another. ``` Const cCrit As Variant = "D" ' Criteria Column Letter/Number Const cCols As String = "C:J" ' Source/Target Data Columns Const cFRsrc As Long = 15 ' Source First Row Dim ws1 As Worksheet ' Source Workbook Dim ws2 As Worksheet ' Target Workbook Dim rng As Range ' Filter Range, Copy Range Dim lRow As Long ' Last Row Number Dim FRtgt As Long ' Target First Row Dim Answer As VbMsgBoxResult ' Message Box Dim Error1 As VbMsgBoxResult ' Message Box for Errors ' Create references to worksheets. With ThisWorkbook Set ws1 = .Worksheets("Future Project Hopper") Set ws2 = .Worksheets("CPD-Carryover,Complete&Active") End With Answer = MsgBox("Do you want to run the Macro?", vbYesNo, "Run Macro") If Answer <> vbYes Then Exit Sub ' In Source Worksheet With ws1 ' Clear any filters. .AutoFilterMode = False ' Calculate Last Row. lRow = .Cells(.Rows.Count, cCrit).End(xlUp).row ' Calculate Filter Column Range. Set rng = .Cells(cFRsrc, cCrit).Resize(lRow - cFRsrc + 1) ' Make an offset for the filter to start a row before (above) and ' end a row after (below). With rng.Offset(-1).Resize(lRow - cFRsrc + 3) ' Filter data in Criteria Column. .AutoFilter Field:=1, Criteria1:="Active" End With ' Create a reference to the Copy Range. Set rng = .Columns(cCols).Resize(rng.Rows.Count).Offset(cFRsrc - 1) _ .SpecialCells(xlCellTypeVisible) ' Clear remaining filters. .AutoFilterMode = False End With ' Calculate Target First Row. FRtgt = ws2.Cells(ws2.Rows.Count, cCrit).End(xlUp).row + 1 ' Copy Range and paste to Target Worksheet and clear contents of future project hopper rng.Copy ws2.Columns(cCols).Resize(1).Offset(FRtgt - 1).PasteSpecial xlPasteValues rng.Rows.ClearContents ```
2019/03/08
[ "https://Stackoverflow.com/questions/55064957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10964535/" ]
That's because `www.amazon.de` *is* a relative link. To link a different domain (host), you need to begin the [authority component](https://en.wikipedia.org/wiki/Uniform_Resource_Identifier#Generic_syntax) with double slashes: `//www.amazon.de`, or with the scheme included `https://www.amazon.de`.