qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
20,108,899
I am using the autoreload-server example which is working great for reloading namespaces on changes to the .clj files using ns-tracker. <https://github.com/pedestal/samples/blob/master/auto-reload-server/dev/dev.clj> However, it is not picking up changes to enlive templates in the resources/public dir. I've added my template paths to the vector in defn watch: ``` `([] (watch ["src" "resources" "resources/public" "public"]))` ``` As well as this in the namespaces that use enlive deftemplate: `(net.cgrand.reload/auto-reload *ns*)` However this does not work. My assumption is ns-tracker only works for clj files, and that I am using the enlive reload feature incorrectly. Is anyone using enlive and have this figured out, or have any ideas to try?
2013/11/20
[ "https://Stackoverflow.com/questions/20108899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/76815/" ]
The only mention of `type_info` on that page is > > TypeInfo is a simple wrapper around type\_info class that lets us store it as a key in std::map. > > > C++11 has `std::type_index` in `<typeindex>` which fulfills exactly this role. In general elements of a `map` do not need to be assignable, nor as of C++11 copyable, but `type_info` still cannot be used directly because you simply cannot construct one except by `typeid` expression. The specification for `std::type_index` notes that it may contain a pointer to `std::type_info` to simplify implementation. "Wrapper" does not imply inheritance or direct membership. An class which wraps by reference is also known as a *proxy.*
I asked myself the same question about this exact article, but then I realized that the code listing should have been provided, and it was. So `TypeInfo` is a straightforward wrapper around `type_info`. ``` class TypeInfo{ public: explicit TypeInfo(const type_info& info) : _typeInfo(info) {}; bool operator < (const TypeInfo& rhs) const{ return _typeInfo.before(rhs._typeInfo) != 0; } private: const type_info& _typeInfo; }; ```
83,389
Sorry for asking such a basic question. I am reading books on OpenGL4 but in most examples they generally render only objects. So I understand how to deal with vertex buffers and vertex array buffers, etc. but my question is does it work when you have say hundred of objects to draw? Should you have 1 vbo for example and replace the data in the buffer each time you need to draw a new object? Should you have hundreds of vbos? By my understanding was that you were limited in the number of buffers you could create (using getBuffer()). How would one typically do this? Thank you.
2014/09/13
[ "https://gamedev.stackexchange.com/questions/83389", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/18490/" ]
Even when you have hundreds of objects to draw, typically those are many copies of the *same* object. E.g., you might a stack of 10 crates, or two goblins, or a hundred trees. You only need to store this identical data once. You'd then have a structure similar to: ``` struct Material { Shader shader; vector<Texture> textures; UniformMap parameters; }; struct Mesh { VBO vertices; IBO indices; InputLayout layout; Material mat; size_t startIndex; size_t numIndices; }; struct MeshInstance { Mesh* mesh; Matrix4x4 transform; }; ``` You'd then be able to have many `MeshInstance` objects for each `Mesh` object. Rendering is (in the naive, simple case with bad perf) something like: ``` for (auto& object : objects) { device.BindLayout(object->mesh.layout); device.BindMaterial(object->mesh.mat); device.BindVBO(object->mesh.vbo); device.BindIBO(object->mesh.ibo); device.SetUniform(object->transform); device.Draw(object->mesh.startIndex, object->mesh.numIndices); } ``` The good version would sort objects by material/buffer and possibly using instanced drawing rather than setting a uniform and making a draw call for each individual object, but the gist is pretty much the same. If you have a lot of unique objects, you may indeed need many different `Mesh` objects. Note in the above definition that there are both `startIndex` and `numIndices`. This is important: it allows you to put multiple models into a single VBO/IBO! For example, the goblin might use indices 0-10,000 and a tree might be at indices 10,001-12,400 and a crate could be 12,400-12,423. This reduces the number of buffers you need but not the number of vertices you need, of course. Cutting down on buffers has speed advantages in that you no longer need to swap buffer bindings when drawing any of the objects that share that buffer, of course; do the same with texture atlasing (or array textures) and you can get very high draw-call rates. If you have still more objects than can possibly fit in the limitations of your GPUs memory... have less objects. You can't expect to have more data than the machine can handle and expect a magic trick to make it work. A game for instance will carefully control how many assets are needed at any given time; you won't see one of every enemy on screen at once, for example. Many games need to implement sophisticated streaming technologies in order to allow large open worlds or exceptionally long/detailed linear levels and then still have to put constraints on designers to keep distinct objects and level features spread out and not over-concentrated in one area.
You probably would want to do it like this: Have a VBO (+index buffer) for each mesh in the scene (a mesh is just the collection of vertices and indices). Have your objects separately hold a reference to their meshes and store their transformation. From there you can have multiple objects referencing the same mesh with different transformations which is memory efficient and you can sort your drawing to bind each mesh's VBO once while drawing. A bit more advanced technique would be geometry instancing which could be done as the next step. This way you won't even have to do a draw call for each object separately.
10
I've read that corn based food could be harmful to dogs. Is this true? If so, what would be a good alternative?
2013/10/08
[ "https://pets.stackexchange.com/questions/10", "https://pets.stackexchange.com", "https://pets.stackexchange.com/users/22/" ]
The subject of corn and grain based dog food is one that is contentious and subject to a lot of debate. Numerous studies have been done on this subject and many heated opinions exist on this. Many veterinarians believe in corn based dog food and how it is highly digestible and contains many health benefits for a dog. <http://avetsguidetolife.blogspot.com/2013/04/corn-in-foodno-its-not-bad.html> Here is an excerpt from a dog food company that sells corn based dog food that claims that "Cornphobia" is a scare tactic marketing campaign pioneered by luxury dog food manufacturers. > > Some of the first dog food companies that thrived were Science Diet, Iams, Eukanuba and Purina; that was some pretty stiff competition! A common denominator to their dog food formula was corn. The popular marketing game of "they have it and we do not" began the gloomy demonizing of corn. > > > <http://www.kumpi.com/corn.php> On the opposing side here is another vet that speaks vocally against corn based diets in dog food on his blog. > > I argued against the notions put forth by nutritionists interviewed for a veterinary news magazine article that 1) ingredients in pet food aren’t important, 2) that dogs require grain-based fiber to be healthy, and 3) that dogs are omnivores (they are scavenging carnivores). I also pointed out that many veterinary nutritionists have financial ties to some of the largest pet food manufacturers in the world. > > > <http://healthypets.mercola.com/sites/healthypets/archive/2013/01/02/veterinary-nutritionists-favor-commercial-food.aspx> The fact of the matter is that there are veterinarians on both sides of the debate both making claims of financial bias by the others. Well then what about studies? There are many studies done on the subject and most of these are funded by the very industry groups that would stand to benefit or lose greatly by the findings of such studies. Few long term studies have been done on the long term effects that such a diet can cause. Without being able to find an official study on corn based diets and weight, I will only share my personal experiences and what I have witnessed. I do not feed my dog corn based food, and he is the most fit and athletic basset hound that I and universally all of my friends with basset hounds have seen. The vet regularly complements me on having a basset hound that is a healthy weight and how unusual it is for this breed that is typically prone to being overweight or obese. I have never known an overweight dog that was on a non-corn diet. Every overweight dog I know of ate cheap corn based dog food. This is not a study and there clearly might be a correlation between the much higher price of non corn based dog food and the tendency for more educated consumers with more spending money to purchase said food.
I've had a few vets, and all of them say that corn based food is bad. This may be a biased opinion since they each sell some kind of specialty brand pet food. Their explanation is that while domesticated dogs can eat corn based food because they get used to it, their digestive system is built to handle meat. When I asked what other brands aside from the ones they sell would they recommend, almost all of them said [Nutro](http://en.wikipedia.org/wiki/Nutro_Products) is the best brand to feed a dog. Benefits include: * It's easier for them to digest, so they poop less * Their coat feels better * They shed less When I switched my dogs to Nutro, I've witnessed those results, except for the shedding less, as my dogs don't shed. Keep in mind that Nutro may be an expensive purchase.
10
I've read that corn based food could be harmful to dogs. Is this true? If so, what would be a good alternative?
2013/10/08
[ "https://pets.stackexchange.com/questions/10", "https://pets.stackexchange.com", "https://pets.stackexchange.com/users/22/" ]
I've had a few vets, and all of them say that corn based food is bad. This may be a biased opinion since they each sell some kind of specialty brand pet food. Their explanation is that while domesticated dogs can eat corn based food because they get used to it, their digestive system is built to handle meat. When I asked what other brands aside from the ones they sell would they recommend, almost all of them said [Nutro](http://en.wikipedia.org/wiki/Nutro_Products) is the best brand to feed a dog. Benefits include: * It's easier for them to digest, so they poop less * Their coat feels better * They shed less When I switched my dogs to Nutro, I've witnessed those results, except for the shedding less, as my dogs don't shed. Keep in mind that Nutro may be an expensive purchase.
Dogs were domesticated from wild dogs and wolves, with domestic dogs being found around 30,000 years ago. Some wolves are thought to have evolved around 700,000 years ago. Their main caloric and nutrient source is other animals, thus in oversimplified terms they are though of as carnivores. While they like to munch on a bit of plant matter every now and then and eat the stomach contents of the animals they kill, they did not roam the land looking for corn to eat. Corn is much cheaper than meat so using it allows for pet food manufacturers to keep costs down. Corn was selectively bread only very recently for human consumption and is not all that great a food source as it is full of sugars, and is not particularly nutrient rich. Arbitrarily changing the diet of a 700,000 year old specie carries with is some health risk. Many American cats and dogs suffer from obesity. We see a similar problem in humans where our historical diets have been altered for convenience or culturally-learned flavor preference resulting in obesity, atherosclerosis disease, diabetes, GI tract cancers, etc. The high-quality dog foods which are mainly made from meat are good alternatives. Better yet get with your veterinarian and make home-made dog food with the proper nutrient balance and whatever added vitamins are recommended. It won't have all the preservatives, dyes, and fillers the store bought pet food has, and the meat will be higher quality. Your vet won't tell you to add a bunch of corn, although dogs do need some grains/veggies to simulate what is found inside the animals they used to eat). The down side is this can be pricey and time consuming so it is not an attractive option to many. Personally I use high quality store bought foods.
10
I've read that corn based food could be harmful to dogs. Is this true? If so, what would be a good alternative?
2013/10/08
[ "https://pets.stackexchange.com/questions/10", "https://pets.stackexchange.com", "https://pets.stackexchange.com/users/22/" ]
The subject of corn and grain based dog food is one that is contentious and subject to a lot of debate. Numerous studies have been done on this subject and many heated opinions exist on this. Many veterinarians believe in corn based dog food and how it is highly digestible and contains many health benefits for a dog. <http://avetsguidetolife.blogspot.com/2013/04/corn-in-foodno-its-not-bad.html> Here is an excerpt from a dog food company that sells corn based dog food that claims that "Cornphobia" is a scare tactic marketing campaign pioneered by luxury dog food manufacturers. > > Some of the first dog food companies that thrived were Science Diet, Iams, Eukanuba and Purina; that was some pretty stiff competition! A common denominator to their dog food formula was corn. The popular marketing game of "they have it and we do not" began the gloomy demonizing of corn. > > > <http://www.kumpi.com/corn.php> On the opposing side here is another vet that speaks vocally against corn based diets in dog food on his blog. > > I argued against the notions put forth by nutritionists interviewed for a veterinary news magazine article that 1) ingredients in pet food aren’t important, 2) that dogs require grain-based fiber to be healthy, and 3) that dogs are omnivores (they are scavenging carnivores). I also pointed out that many veterinary nutritionists have financial ties to some of the largest pet food manufacturers in the world. > > > <http://healthypets.mercola.com/sites/healthypets/archive/2013/01/02/veterinary-nutritionists-favor-commercial-food.aspx> The fact of the matter is that there are veterinarians on both sides of the debate both making claims of financial bias by the others. Well then what about studies? There are many studies done on the subject and most of these are funded by the very industry groups that would stand to benefit or lose greatly by the findings of such studies. Few long term studies have been done on the long term effects that such a diet can cause. Without being able to find an official study on corn based diets and weight, I will only share my personal experiences and what I have witnessed. I do not feed my dog corn based food, and he is the most fit and athletic basset hound that I and universally all of my friends with basset hounds have seen. The vet regularly complements me on having a basset hound that is a healthy weight and how unusual it is for this breed that is typically prone to being overweight or obese. I have never known an overweight dog that was on a non-corn diet. Every overweight dog I know of ate cheap corn based dog food. This is not a study and there clearly might be a correlation between the much higher price of non corn based dog food and the tendency for more educated consumers with more spending money to purchase said food.
Dogs were domesticated from wild dogs and wolves, with domestic dogs being found around 30,000 years ago. Some wolves are thought to have evolved around 700,000 years ago. Their main caloric and nutrient source is other animals, thus in oversimplified terms they are though of as carnivores. While they like to munch on a bit of plant matter every now and then and eat the stomach contents of the animals they kill, they did not roam the land looking for corn to eat. Corn is much cheaper than meat so using it allows for pet food manufacturers to keep costs down. Corn was selectively bread only very recently for human consumption and is not all that great a food source as it is full of sugars, and is not particularly nutrient rich. Arbitrarily changing the diet of a 700,000 year old specie carries with is some health risk. Many American cats and dogs suffer from obesity. We see a similar problem in humans where our historical diets have been altered for convenience or culturally-learned flavor preference resulting in obesity, atherosclerosis disease, diabetes, GI tract cancers, etc. The high-quality dog foods which are mainly made from meat are good alternatives. Better yet get with your veterinarian and make home-made dog food with the proper nutrient balance and whatever added vitamins are recommended. It won't have all the preservatives, dyes, and fillers the store bought pet food has, and the meat will be higher quality. Your vet won't tell you to add a bunch of corn, although dogs do need some grains/veggies to simulate what is found inside the animals they used to eat). The down side is this can be pricey and time consuming so it is not an attractive option to many. Personally I use high quality store bought foods.
28,755,145
I am trying to launch Guestbook.go example from kubernetes doc as follows: <https://github.com/GoogleCloudPlatform/kubernetes/tree/master/examples/guestbook-go> I have modified the guestbook-service.json in the above link to include PublicIPs ``` { "apiVersion": "v1beta1", "kind": "Service", "id": "guestbook", "port": 3000, "containerPort": "http-server", "publicIPs": ["10.39.67.97","10.39.66.113"], "selector": { "name": "guestbook" } } ``` I have one master and two minions as shown below: ``` centos-minion -> 10.39.67.97 centos-minion2 -> 10.39.66.113 ``` I am using my publicIPs as my minions eth0 IP. But the iptables get created only on one of the minions: ``` [root@ip-10-39-67-97 ~]# iptables -L -n -t nat Chain KUBE-PORTALS-HOST (1 references) target prot opt source destination DNAT tcp -- 0.0.0.0/0 10.254.208.93 /* redis-slave */ tcp dpt:6379 to:10.39.67.240:56872 DNAT tcp -- 0.0.0.0/0 10.254.223.192 /* guestbook */ tcp dpt:3000 to:10.39.67.240:58746 DNAT tcp -- 0.0.0.0/0 10.39.67.97 /* guestbook */ tcp dpt:3000 to:10.39.67.240:58746 DNAT tcp -- 0.0.0.0/0 10.39.66.113 /* guestbook */ tcp dpt:3000 to:10.39.67.240:58746 DNAT tcp -- 0.0.0.0/0 10.254.0.2 /* kubernetes */ tcp dpt:443 to:10.39.67.240:33003 DNAT tcp -- 0.0.0.0/0 10.254.0.1 /* kubernetes-ro */ tcp dpt:80 to:10.39.67.240:58434 DNAT tcp -- 0.0.0.0/0 10.254.131.70 /* redis-master */ tcp dpt:6379 to:10.39.67.240:50754 ``` So even if i redundancy with my Pods if i bring down the minion with that IPTABLE my external publicIP entry point dies.. I am sure i have conceptual misunderstanding.. Can anyone help
2015/02/26
[ "https://Stackoverflow.com/questions/28755145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3006942/" ]
(sorry for the delay in answering your question) PublicIPs are defined on every host node, so if you make sure that you round-robin packets into the host nodes from your external load balancer, (e.g. an edge router) then you can have redundancy, even if one of the host machines fails. --brendan
You should use `kubectl proxy  --accept-hosts='^*$' --address='0.0.0.0' --port=8001` to expose your kube-proxy port to the public IP or internal iP
7,215,653
First, I could not ask this on most hardware forums, because they are mostly populated by gamers. Additionally, it is difficult to get an opinion from sysadmins, because they have a fairly different perspective as well. So perhaps, amongst developers, I might be able to deduce a realistic trend. What I want to know is, if I regularly fire up netbeans/eclipse, mysql workbench, 3 to 5 browsers with multi-tabs, along with apache-php / mysql running in the background, perhaps gimp/adobe photoshop from time to time, does the quad core perform considerably faster than a dual core? provided the assumption is that the quad has a slower i.e. clockspeed ~2.8 vs a 3.2 dual-core ? My only relevant experience is with the old core 2 duo 2.8 Ghz running on 4 Gig ram performed considerably slower than my new Core i5 quad core on 2.8 Ghz (desktops). It is only one sample data, so I can't see if it hold true for everyone. The end purpose of all this is to help me decide on buying a new laptop ( 4 cores vs 2 cores have quite a difference, currently ).
2011/08/27
[ "https://Stackoverflow.com/questions/7215653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/915637/" ]
<http://www.intel.com/content/www/us/en/processor-comparison/comparison-chart.html> I did a comparison for you as a fact. Here Quad core is 2.20 GHz where dual core is 2.3 GHz. Now check out this comparison and see the "Max Turbo Frequency". You will notice that even though quad core has less GHz but when it hit turbo it passes the dual core. Second thing to consider is Cache size. Which does make a huge difference. Quad core will always have more Cache. In this example it has 6MB but some has up to 8MB. Third is, Max memory bandwidth, Quad core has 25.6 vs dual core 21.3 means more faster speed in quad core. Fourth important factor is graphics. Graphics Base Frequency is 650MHz in quad and 500MHz in dual. Fifth, Graphics Max Dynamic Frequency is 1.30 for quad and 1.10 for dual. Bottom line is if you can afford it quad not only gives you more power punch but also allow you to add more memory later. As max memory size with Quad is 16GB and dual restricts you to 8GB. Just to be future proof I will go with Quad. One more thing to add is simultaneous thread processing is 4 in dual core and 8 in quad, which does make a difference.
Even if they were equivalent speeds, the quad core is executing twice as many instructions per cycle as the duo core. 0.4 Mhz isn't going to make a huge difference.
7,215,653
First, I could not ask this on most hardware forums, because they are mostly populated by gamers. Additionally, it is difficult to get an opinion from sysadmins, because they have a fairly different perspective as well. So perhaps, amongst developers, I might be able to deduce a realistic trend. What I want to know is, if I regularly fire up netbeans/eclipse, mysql workbench, 3 to 5 browsers with multi-tabs, along with apache-php / mysql running in the background, perhaps gimp/adobe photoshop from time to time, does the quad core perform considerably faster than a dual core? provided the assumption is that the quad has a slower i.e. clockspeed ~2.8 vs a 3.2 dual-core ? My only relevant experience is with the old core 2 duo 2.8 Ghz running on 4 Gig ram performed considerably slower than my new Core i5 quad core on 2.8 Ghz (desktops). It is only one sample data, so I can't see if it hold true for everyone. The end purpose of all this is to help me decide on buying a new laptop ( 4 cores vs 2 cores have quite a difference, currently ).
2011/08/27
[ "https://Stackoverflow.com/questions/7215653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/915637/" ]
The problem with multi-processors/multi-core processors has been and still is memory bandwidth. Most applications in daily use have not been written to economize on memory bandwidth. This means that for typical, everyday use you'll run out of bandwidth when your apps are doing something (i e not waiting for user input). Some applications - such as games and parts of operating systems - attempt to address this. Their parallellism loads a chunk of data into a core, spends some time processing it - without accessing memory further - and finally writes the modified data back to memory. During the processing itself the memory bus is free and other cores can load and store data. In a well-designed, parallel code essentially any number of cores can be working on different parts of the same task so long as the total amount of processing - number of cores \* processing time - is less than or equal to the total time doing memory work - number of cores \* (read time + write time). A code designed and balanced for a specific number of cores will be efficient for fewer but not for more cores. Some processors have multiple data buses to increase the overall memory bandwidth. This works up to a certain point after which the next-higher memory - the L3 cache- becomes the bottleneck.
Even if they were equivalent speeds, the quad core is executing twice as many instructions per cycle as the duo core. 0.4 Mhz isn't going to make a huge difference.
7,215,653
First, I could not ask this on most hardware forums, because they are mostly populated by gamers. Additionally, it is difficult to get an opinion from sysadmins, because they have a fairly different perspective as well. So perhaps, amongst developers, I might be able to deduce a realistic trend. What I want to know is, if I regularly fire up netbeans/eclipse, mysql workbench, 3 to 5 browsers with multi-tabs, along with apache-php / mysql running in the background, perhaps gimp/adobe photoshop from time to time, does the quad core perform considerably faster than a dual core? provided the assumption is that the quad has a slower i.e. clockspeed ~2.8 vs a 3.2 dual-core ? My only relevant experience is with the old core 2 duo 2.8 Ghz running on 4 Gig ram performed considerably slower than my new Core i5 quad core on 2.8 Ghz (desktops). It is only one sample data, so I can't see if it hold true for everyone. The end purpose of all this is to help me decide on buying a new laptop ( 4 cores vs 2 cores have quite a difference, currently ).
2011/08/27
[ "https://Stackoverflow.com/questions/7215653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/915637/" ]
<http://www.intel.com/content/www/us/en/processor-comparison/comparison-chart.html> I did a comparison for you as a fact. Here Quad core is 2.20 GHz where dual core is 2.3 GHz. Now check out this comparison and see the "Max Turbo Frequency". You will notice that even though quad core has less GHz but when it hit turbo it passes the dual core. Second thing to consider is Cache size. Which does make a huge difference. Quad core will always have more Cache. In this example it has 6MB but some has up to 8MB. Third is, Max memory bandwidth, Quad core has 25.6 vs dual core 21.3 means more faster speed in quad core. Fourth important factor is graphics. Graphics Base Frequency is 650MHz in quad and 500MHz in dual. Fifth, Graphics Max Dynamic Frequency is 1.30 for quad and 1.10 for dual. Bottom line is if you can afford it quad not only gives you more power punch but also allow you to add more memory later. As max memory size with Quad is 16GB and dual restricts you to 8GB. Just to be future proof I will go with Quad. One more thing to add is simultaneous thread processing is 4 in dual core and 8 in quad, which does make a difference.
The problem with multi-processors/multi-core processors has been and still is memory bandwidth. Most applications in daily use have not been written to economize on memory bandwidth. This means that for typical, everyday use you'll run out of bandwidth when your apps are doing something (i e not waiting for user input). Some applications - such as games and parts of operating systems - attempt to address this. Their parallellism loads a chunk of data into a core, spends some time processing it - without accessing memory further - and finally writes the modified data back to memory. During the processing itself the memory bus is free and other cores can load and store data. In a well-designed, parallel code essentially any number of cores can be working on different parts of the same task so long as the total amount of processing - number of cores \* processing time - is less than or equal to the total time doing memory work - number of cores \* (read time + write time). A code designed and balanced for a specific number of cores will be efficient for fewer but not for more cores. Some processors have multiple data buses to increase the overall memory bandwidth. This works up to a certain point after which the next-higher memory - the L3 cache- becomes the bottleneck.
22,364,468
I have a problem using python. I have a txt file, and it contains 500 abstracts from 500 papers, and what i want to do is to split this txt file into 500 file, with each txt file contains only 1 abstract. for now, I found out, for each abstract, there is one line at the end, starting with "PMID", so I'm thinking split the file by this line. but I'm really new to python. any idea? thanks in advance. The txt file looks like this: ``` 1. Ann Intern Med. 2013 Dec 3;159(11):721-8. doi:10.7326/0003-4819-159-11-201312030-00004. text text text texttext texttext texttext texttext texttext texttext texttext text text texttext texttext texttext texttext texttext text text texttext texttext texttext texttext text PMID: 24297188 [PubMed - indexed for MEDLINE] 2. Am J Cardiol. 2013 Sep 1;112(5):688-93. doi: 10.1016/j.amjcard.2013.04.048. Epub 2013 May 24. text texttext texttext texttext texttext texttext texttext texttext texttext text text texttext texttext texttext texttext texttext texttext texttext texttext text PMID: 23711805 [PubMed - indexed for MEDLINE] 3. Am J Cardiol. 2013 Aug 15;112(4):513-9. doi: 10.1016/j.amjcard.2013.04.015. Epub 2013 May 11. text texttext texttext texttext texttext texttext texttext texttext texttext text text texttext texttext texttext texttext texttext texttext texttext texttext text PMID: 23672989 [PubMed - indexed for MEDLINE] ``` and so on.
2014/03/12
[ "https://Stackoverflow.com/questions/22364468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2942662/" ]
Nope! `cat` does not buffer the entire file contents in memory before emitting any. Instead it reads and writes content in chunks determined by its internal buffer sizes. If you wish to remove I/O disk overhead from your performance benchmark, I suggest you have plenty of ram and then `cat` the file to `/dev/null` *before* starting your benchmark: ``` cat source_file > /dev/null; my_compression_program < source_file > /dev/null ``` This will cause the file to first be inserted into the kernel's filesystem cache before your program ever runs. It will then be streamed out from memory.
You could use tmpfs (on \*nix like OSs) if your libs really need a file handle. If not, your test program should just initialize some memory, possibly by reading a file, and compress that. In both cases you should consider turning off swapping for the test.
22,364,468
I have a problem using python. I have a txt file, and it contains 500 abstracts from 500 papers, and what i want to do is to split this txt file into 500 file, with each txt file contains only 1 abstract. for now, I found out, for each abstract, there is one line at the end, starting with "PMID", so I'm thinking split the file by this line. but I'm really new to python. any idea? thanks in advance. The txt file looks like this: ``` 1. Ann Intern Med. 2013 Dec 3;159(11):721-8. doi:10.7326/0003-4819-159-11-201312030-00004. text text text texttext texttext texttext texttext texttext texttext texttext text text texttext texttext texttext texttext texttext text text texttext texttext texttext texttext text PMID: 24297188 [PubMed - indexed for MEDLINE] 2. Am J Cardiol. 2013 Sep 1;112(5):688-93. doi: 10.1016/j.amjcard.2013.04.048. Epub 2013 May 24. text texttext texttext texttext texttext texttext texttext texttext texttext text text texttext texttext texttext texttext texttext texttext texttext texttext text PMID: 23711805 [PubMed - indexed for MEDLINE] 3. Am J Cardiol. 2013 Aug 15;112(4):513-9. doi: 10.1016/j.amjcard.2013.04.015. Epub 2013 May 11. text texttext texttext texttext texttext texttext texttext texttext texttext text text texttext texttext texttext texttext texttext texttext texttext texttext text PMID: 23672989 [PubMed - indexed for MEDLINE] ``` and so on.
2014/03/12
[ "https://Stackoverflow.com/questions/22364468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2942662/" ]
Nope! `cat` does not buffer the entire file contents in memory before emitting any. Instead it reads and writes content in chunks determined by its internal buffer sizes. If you wish to remove I/O disk overhead from your performance benchmark, I suggest you have plenty of ram and then `cat` the file to `/dev/null` *before* starting your benchmark: ``` cat source_file > /dev/null; my_compression_program < source_file > /dev/null ``` This will cause the file to first be inserted into the kernel's filesystem cache before your program ever runs. It will then be streamed out from memory.
If you don't have enough memory to hold the file in memory, you have to do I/O. If you do have plenty of memory then just run the benchmark twice, linux will keep the file in the page cache, see * <http://en.wikipedia.org/wiki/Page_cache> * <http://www.tldp.org/LDP/lki/lki-4.html>
3,462,079
I have an array of thousands of quads; 4-sided 3D polygons. All I know are the coordinates of the quad corners. A subset of these quads define the closed outer shell of a 3D shape. The remaining quads are on the inside of this closed solid. How do I figure out which quads are part of the shell and which quads are part of the interior? This is not performance critical code. --- Edit: Further constraints on the shape of the shell * There are no holes inside the shape, it is a single surface. * It contains both convex and concave portions. * I have a few points which are known to be on the inside of the shell.
2010/08/11
[ "https://Stackoverflow.com/questions/3462079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/81947/" ]
This might be hard to implement if your shape self intersects, but if you can find one quad that you know is on the surface (possibly one furthest away from the centroid) then map out concentric circles of quads around it. Then find a continuous ring of quads outside that and so on, until you end up at the "opposite" side. If your quads intersect, or are internally connected, then that's more difficult. I'd try breaking apart those which intersect, then find all the possible smooth surfaces, and pick the one with the greatest internal volume.
How about this? Calculate the normal vector of a quad (call this the 'current' quad). Do an intersection test with that vector and all the remaining quads. If it intersects another quad in the positive portion of the vector you know the current quad is an internal quad. Repeat for all the remaining quads. This assumes the quads 'face' outward.
3,462,079
I have an array of thousands of quads; 4-sided 3D polygons. All I know are the coordinates of the quad corners. A subset of these quads define the closed outer shell of a 3D shape. The remaining quads are on the inside of this closed solid. How do I figure out which quads are part of the shell and which quads are part of the interior? This is not performance critical code. --- Edit: Further constraints on the shape of the shell * There are no holes inside the shape, it is a single surface. * It contains both convex and concave portions. * I have a few points which are known to be on the inside of the shell.
2010/08/11
[ "https://Stackoverflow.com/questions/3462079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/81947/" ]
How about this? Calculate the normal vector of a quad (call this the 'current' quad). Do an intersection test with that vector and all the remaining quads. If it intersects another quad in the positive portion of the vector you know the current quad is an internal quad. Repeat for all the remaining quads. This assumes the quads 'face' outward.
You may be able to make your problem easier by reducing the number of quads that you have to deal with. You know that some of the quads form a closed shell. Therefore, those quads are connected at their edges. If three mutually adjacent edges of a quad (that is, the edges form a closed loop) overlap the edge of another quad, then these quads might be part of the shell (these mutually adjacent edges serve as the boundary of a 2D region; let's call that region the "connected face" of the quad). Make a list of these "shell candidates". Now, look through this list and throw out any candidate who has an edge that does not overlap with another candidate (that is, the edge overlaps an edge of a quad that is not in the list). Repeat this culling process until you are no longer able to remove any quads. What you have left should be your shell. Create a "non-shell quads" list containing all of the quads not in the "shell" list. Draw a bounding box (or sphere, ellipse, etc) around this shell. Now, look through your list of non-shell quads, and throw out any quads that lie *outside* of the bounding region. These are definitely not in the interior. Take the remaining non-shell quads. These may or may not be in the interior of the shape. For each of these quads, draw lines perpendicular to the quad from the center of each face that end on the surface of the bounding shape. Trace each line and count how many times the line crosses through the "connected face" of a quad in your shell list. If this number is odd, then that vertex lies in the interior of the shape. If it is even, the vertex is on the exterior. You can determine whether a quad is inside or outside based on whether its vertices are inside or outside.
3,462,079
I have an array of thousands of quads; 4-sided 3D polygons. All I know are the coordinates of the quad corners. A subset of these quads define the closed outer shell of a 3D shape. The remaining quads are on the inside of this closed solid. How do I figure out which quads are part of the shell and which quads are part of the interior? This is not performance critical code. --- Edit: Further constraints on the shape of the shell * There are no holes inside the shape, it is a single surface. * It contains both convex and concave portions. * I have a few points which are known to be on the inside of the shell.
2010/08/11
[ "https://Stackoverflow.com/questions/3462079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/81947/" ]
This might be hard to implement if your shape self intersects, but if you can find one quad that you know is on the surface (possibly one furthest away from the centroid) then map out concentric circles of quads around it. Then find a continuous ring of quads outside that and so on, until you end up at the "opposite" side. If your quads intersect, or are internally connected, then that's more difficult. I'd try breaking apart those which intersect, then find all the possible smooth surfaces, and pick the one with the greatest internal volume.
It can be done quite easily if the shape is convex. When the shape is concave it is much harder. In the convex case find the centroid by computing the average of all of the points. This gives a point that is in the interior for which the following property holds: > > If you project four rays from the > centroid to each corner of a quad you > define a pyramid cut into two parts, > one part contains space interior to > the shape and the other part defines > space that might be exterior to the > shape. > > > These two volumes give you a decision process to check if a quad is on the boundary or not. If any point from another quad occurs in the outside volume then the quad is not on the boundary and can be discarded as an interior quad. Edit: Just seen your clarification above. In the harder case that the shape is concave then you need one of two things; 1. A description (parameterisation) of the shape that you can use to choose quads with, or 2. Some other property such as all of the boundary quads being contiguous Further edit: Just realised that what you are describing would be a concave hull for the points. Try looking at some of the results in [this search page](http://www.google.com/search?q=concave+hull+algorithm).
3,462,079
I have an array of thousands of quads; 4-sided 3D polygons. All I know are the coordinates of the quad corners. A subset of these quads define the closed outer shell of a 3D shape. The remaining quads are on the inside of this closed solid. How do I figure out which quads are part of the shell and which quads are part of the interior? This is not performance critical code. --- Edit: Further constraints on the shape of the shell * There are no holes inside the shape, it is a single surface. * It contains both convex and concave portions. * I have a few points which are known to be on the inside of the shell.
2010/08/11
[ "https://Stackoverflow.com/questions/3462079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/81947/" ]
It can be done quite easily if the shape is convex. When the shape is concave it is much harder. In the convex case find the centroid by computing the average of all of the points. This gives a point that is in the interior for which the following property holds: > > If you project four rays from the > centroid to each corner of a quad you > define a pyramid cut into two parts, > one part contains space interior to > the shape and the other part defines > space that might be exterior to the > shape. > > > These two volumes give you a decision process to check if a quad is on the boundary or not. If any point from another quad occurs in the outside volume then the quad is not on the boundary and can be discarded as an interior quad. Edit: Just seen your clarification above. In the harder case that the shape is concave then you need one of two things; 1. A description (parameterisation) of the shape that you can use to choose quads with, or 2. Some other property such as all of the boundary quads being contiguous Further edit: Just realised that what you are describing would be a concave hull for the points. Try looking at some of the results in [this search page](http://www.google.com/search?q=concave+hull+algorithm).
You may be able to make your problem easier by reducing the number of quads that you have to deal with. You know that some of the quads form a closed shell. Therefore, those quads are connected at their edges. If three mutually adjacent edges of a quad (that is, the edges form a closed loop) overlap the edge of another quad, then these quads might be part of the shell (these mutually adjacent edges serve as the boundary of a 2D region; let's call that region the "connected face" of the quad). Make a list of these "shell candidates". Now, look through this list and throw out any candidate who has an edge that does not overlap with another candidate (that is, the edge overlaps an edge of a quad that is not in the list). Repeat this culling process until you are no longer able to remove any quads. What you have left should be your shell. Create a "non-shell quads" list containing all of the quads not in the "shell" list. Draw a bounding box (or sphere, ellipse, etc) around this shell. Now, look through your list of non-shell quads, and throw out any quads that lie *outside* of the bounding region. These are definitely not in the interior. Take the remaining non-shell quads. These may or may not be in the interior of the shape. For each of these quads, draw lines perpendicular to the quad from the center of each face that end on the surface of the bounding shape. Trace each line and count how many times the line crosses through the "connected face" of a quad in your shell list. If this number is odd, then that vertex lies in the interior of the shape. If it is even, the vertex is on the exterior. You can determine whether a quad is inside or outside based on whether its vertices are inside or outside.
3,462,079
I have an array of thousands of quads; 4-sided 3D polygons. All I know are the coordinates of the quad corners. A subset of these quads define the closed outer shell of a 3D shape. The remaining quads are on the inside of this closed solid. How do I figure out which quads are part of the shell and which quads are part of the interior? This is not performance critical code. --- Edit: Further constraints on the shape of the shell * There are no holes inside the shape, it is a single surface. * It contains both convex and concave portions. * I have a few points which are known to be on the inside of the shell.
2010/08/11
[ "https://Stackoverflow.com/questions/3462079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/81947/" ]
This might be hard to implement if your shape self intersects, but if you can find one quad that you know is on the surface (possibly one furthest away from the centroid) then map out concentric circles of quads around it. Then find a continuous ring of quads outside that and so on, until you end up at the "opposite" side. If your quads intersect, or are internally connected, then that's more difficult. I'd try breaking apart those which intersect, then find all the possible smooth surfaces, and pick the one with the greatest internal volume.
Consider that all of the quads live inside a large sealed box. Pick one quad. Do raytracing; treat that quad as a light source, and treat all other quads as reflective and fuzzy, where a hit to a quad will send light in all directions from that surface, but not around corners. If no light rays hit the external box after all nodes have had a chance to be hit, treat that quad as internal. If it's convex, or internal quads didn't share edges with external quads, there are easier ways.
3,462,079
I have an array of thousands of quads; 4-sided 3D polygons. All I know are the coordinates of the quad corners. A subset of these quads define the closed outer shell of a 3D shape. The remaining quads are on the inside of this closed solid. How do I figure out which quads are part of the shell and which quads are part of the interior? This is not performance critical code. --- Edit: Further constraints on the shape of the shell * There are no holes inside the shape, it is a single surface. * It contains both convex and concave portions. * I have a few points which are known to be on the inside of the shell.
2010/08/11
[ "https://Stackoverflow.com/questions/3462079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/81947/" ]
This might be hard to implement if your shape self intersects, but if you can find one quad that you know is on the surface (possibly one furthest away from the centroid) then map out concentric circles of quads around it. Then find a continuous ring of quads outside that and so on, until you end up at the "opposite" side. If your quads intersect, or are internally connected, then that's more difficult. I'd try breaking apart those which intersect, then find all the possible smooth surfaces, and pick the one with the greatest internal volume.
You may be able to make your problem easier by reducing the number of quads that you have to deal with. You know that some of the quads form a closed shell. Therefore, those quads are connected at their edges. If three mutually adjacent edges of a quad (that is, the edges form a closed loop) overlap the edge of another quad, then these quads might be part of the shell (these mutually adjacent edges serve as the boundary of a 2D region; let's call that region the "connected face" of the quad). Make a list of these "shell candidates". Now, look through this list and throw out any candidate who has an edge that does not overlap with another candidate (that is, the edge overlaps an edge of a quad that is not in the list). Repeat this culling process until you are no longer able to remove any quads. What you have left should be your shell. Create a "non-shell quads" list containing all of the quads not in the "shell" list. Draw a bounding box (or sphere, ellipse, etc) around this shell. Now, look through your list of non-shell quads, and throw out any quads that lie *outside* of the bounding region. These are definitely not in the interior. Take the remaining non-shell quads. These may or may not be in the interior of the shape. For each of these quads, draw lines perpendicular to the quad from the center of each face that end on the surface of the bounding shape. Trace each line and count how many times the line crosses through the "connected face" of a quad in your shell list. If this number is odd, then that vertex lies in the interior of the shape. If it is even, the vertex is on the exterior. You can determine whether a quad is inside or outside based on whether its vertices are inside or outside.
3,462,079
I have an array of thousands of quads; 4-sided 3D polygons. All I know are the coordinates of the quad corners. A subset of these quads define the closed outer shell of a 3D shape. The remaining quads are on the inside of this closed solid. How do I figure out which quads are part of the shell and which quads are part of the interior? This is not performance critical code. --- Edit: Further constraints on the shape of the shell * There are no holes inside the shape, it is a single surface. * It contains both convex and concave portions. * I have a few points which are known to be on the inside of the shell.
2010/08/11
[ "https://Stackoverflow.com/questions/3462079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/81947/" ]
Consider that all of the quads live inside a large sealed box. Pick one quad. Do raytracing; treat that quad as a light source, and treat all other quads as reflective and fuzzy, where a hit to a quad will send light in all directions from that surface, but not around corners. If no light rays hit the external box after all nodes have had a chance to be hit, treat that quad as internal. If it's convex, or internal quads didn't share edges with external quads, there are easier ways.
You may be able to make your problem easier by reducing the number of quads that you have to deal with. You know that some of the quads form a closed shell. Therefore, those quads are connected at their edges. If three mutually adjacent edges of a quad (that is, the edges form a closed loop) overlap the edge of another quad, then these quads might be part of the shell (these mutually adjacent edges serve as the boundary of a 2D region; let's call that region the "connected face" of the quad). Make a list of these "shell candidates". Now, look through this list and throw out any candidate who has an edge that does not overlap with another candidate (that is, the edge overlaps an edge of a quad that is not in the list). Repeat this culling process until you are no longer able to remove any quads. What you have left should be your shell. Create a "non-shell quads" list containing all of the quads not in the "shell" list. Draw a bounding box (or sphere, ellipse, etc) around this shell. Now, look through your list of non-shell quads, and throw out any quads that lie *outside* of the bounding region. These are definitely not in the interior. Take the remaining non-shell quads. These may or may not be in the interior of the shape. For each of these quads, draw lines perpendicular to the quad from the center of each face that end on the surface of the bounding shape. Trace each line and count how many times the line crosses through the "connected face" of a quad in your shell list. If this number is odd, then that vertex lies in the interior of the shape. If it is even, the vertex is on the exterior. You can determine whether a quad is inside or outside based on whether its vertices are inside or outside.
49,955,821
I have code like this, I want to check in the time range that has overtime and sum it. currently, am trying `out.hour+1` with this code, but didn't work. ``` overtime_all = 5 overtime_total_hours = 0 out = datetime.time(14, 30) while overtime_all > 0: overtime200 = object.filter(time__range=(out, out.hour+1)).count() overtime_total_hours = overtime_total_hours + overtime200 overtime_all -=1 print overtime_total_hours ``` how to add `1` hour every loop?...
2018/04/21
[ "https://Stackoverflow.com/questions/49955821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9380270/" ]
Your scope variable `x` should hold the value of `data.contacts[1]`, to get the value of `Gge's` with single quote from company name. There is no such scenario in AngularJS where it omits the single quote from the JSON value. Be sure of your JSON again. ```js var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { var data = { "contacts":[ { "id":"1","company":"Cutting","contact":"Russell Chimera" }, { "id":"2","company":"Gge\'s","contact":"Marci" } ] }; $scope.x = data.contacts[1]; }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <div ng-app="myApp" ng-controller="myCtrl"> {{x.company}} </div> ```
Please check this :"Gge\'s" . Please try to put unicode of ' this then try to parse it then it will resolve the problem.
49,955,821
I have code like this, I want to check in the time range that has overtime and sum it. currently, am trying `out.hour+1` with this code, but didn't work. ``` overtime_all = 5 overtime_total_hours = 0 out = datetime.time(14, 30) while overtime_all > 0: overtime200 = object.filter(time__range=(out, out.hour+1)).count() overtime_total_hours = overtime_total_hours + overtime200 overtime_all -=1 print overtime_total_hours ``` how to add `1` hour every loop?...
2018/04/21
[ "https://Stackoverflow.com/questions/49955821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9380270/" ]
Your scope variable `x` should hold the value of `data.contacts[1]`, to get the value of `Gge's` with single quote from company name. There is no such scenario in AngularJS where it omits the single quote from the JSON value. Be sure of your JSON again. ```js var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { var data = { "contacts":[ { "id":"1","company":"Cutting","contact":"Russell Chimera" }, { "id":"2","company":"Gge\'s","contact":"Marci" } ] }; $scope.x = data.contacts[1]; }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <div ng-app="myApp" ng-controller="myCtrl"> {{x.company}} </div> ```
You must know that the JSON key "contacts", has a JSON array as its value. to access your value "Gge\'s", you will have to access, ``` x = data.contacts[1].company; ``` where your data is : ``` data = {"contacts":[{"id":"1","company":"Cutting","contact":"Russell Chimera"},{"id":"2","company":"Gge\'s","contact":"Marci"}]} ```
49,955,821
I have code like this, I want to check in the time range that has overtime and sum it. currently, am trying `out.hour+1` with this code, but didn't work. ``` overtime_all = 5 overtime_total_hours = 0 out = datetime.time(14, 30) while overtime_all > 0: overtime200 = object.filter(time__range=(out, out.hour+1)).count() overtime_total_hours = overtime_total_hours + overtime200 overtime_all -=1 print overtime_total_hours ``` how to add `1` hour every loop?...
2018/04/21
[ "https://Stackoverflow.com/questions/49955821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9380270/" ]
Your scope variable `x` should hold the value of `data.contacts[1]`, to get the value of `Gge's` with single quote from company name. There is no such scenario in AngularJS where it omits the single quote from the JSON value. Be sure of your JSON again. ```js var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { var data = { "contacts":[ { "id":"1","company":"Cutting","contact":"Russell Chimera" }, { "id":"2","company":"Gge\'s","contact":"Marci" } ] }; $scope.x = data.contacts[1]; }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <div ng-app="myApp" ng-controller="myCtrl"> {{x.company}} </div> ```
In my case I just removed commented lines in JSON file(post in postman) as JSON won't take comments in them.
49,955,821
I have code like this, I want to check in the time range that has overtime and sum it. currently, am trying `out.hour+1` with this code, but didn't work. ``` overtime_all = 5 overtime_total_hours = 0 out = datetime.time(14, 30) while overtime_all > 0: overtime200 = object.filter(time__range=(out, out.hour+1)).count() overtime_total_hours = overtime_total_hours + overtime200 overtime_all -=1 print overtime_total_hours ``` how to add `1` hour every loop?...
2018/04/21
[ "https://Stackoverflow.com/questions/49955821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9380270/" ]
You must know that the JSON key "contacts", has a JSON array as its value. to access your value "Gge\'s", you will have to access, ``` x = data.contacts[1].company; ``` where your data is : ``` data = {"contacts":[{"id":"1","company":"Cutting","contact":"Russell Chimera"},{"id":"2","company":"Gge\'s","contact":"Marci"}]} ```
Please check this :"Gge\'s" . Please try to put unicode of ' this then try to parse it then it will resolve the problem.
49,955,821
I have code like this, I want to check in the time range that has overtime and sum it. currently, am trying `out.hour+1` with this code, but didn't work. ``` overtime_all = 5 overtime_total_hours = 0 out = datetime.time(14, 30) while overtime_all > 0: overtime200 = object.filter(time__range=(out, out.hour+1)).count() overtime_total_hours = overtime_total_hours + overtime200 overtime_all -=1 print overtime_total_hours ``` how to add `1` hour every loop?...
2018/04/21
[ "https://Stackoverflow.com/questions/49955821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9380270/" ]
You must know that the JSON key "contacts", has a JSON array as its value. to access your value "Gge\'s", you will have to access, ``` x = data.contacts[1].company; ``` where your data is : ``` data = {"contacts":[{"id":"1","company":"Cutting","contact":"Russell Chimera"},{"id":"2","company":"Gge\'s","contact":"Marci"}]} ```
In my case I just removed commented lines in JSON file(post in postman) as JSON won't take comments in them.
1,821,700
According to Mathematica, $$\sum\_{k=0}^\infty \frac{(G+k)\_{G-1}}{2^k}=2(G-1)!(2^{G}-1)$$ where $$(G+k)\_{G-1}=\frac{(G+k)!}{(G+k-G+1)!}=\frac{(G+k)!}{(k+1)!}$$ is the falling factorial. I would like to compute this analytically, but I have nothing I've been doing works. A proof by induction led me to a more complex summation, and I can split it or simplify the falling factorial. Is there any possible way to evaluate this without resorting to Mathematica? Any help and/or references would be greatly appreciated.
2016/06/11
[ "https://math.stackexchange.com/questions/1821700", "https://math.stackexchange.com", "https://math.stackexchange.com/users/223401/" ]
Generating functions to the rescue! \begin{align\*} \sum\_{k=0}^\infty x^k &= \frac1{1-x} \\ \sum\_{k=0}^\infty x^{G+k} &= \frac{x^G}{1-x} = \frac1{1-x} - 1 - x - \cdots - x^{G-1} \\ \frac{d^{G-1}}{dx^{G-1}} \sum\_{k=0}^\infty x^{G+k} &= \frac{d^{G-1}}{dx^{G-1}} \bigg( \frac1{1-x} - 1 - x - \cdots - x^{G-1} \bigg) \\ \sum\_{k=0}^\infty (G+k)\_{G-1} x^{k+1} &= \frac{(G-1)!}{(1-x)^G} - (G-1)! \\ \sum\_{k=0}^\infty (G+k)\_{G-1} \big(\tfrac12\big)^{k+1} &= \frac{(G-1)!}{(1-\frac12)^G} - (G-1)! \\ \frac12 \sum\_{k=0}^\infty \frac{(G+k)\_{G-1}}{2^k} &= 2^G(G-1)! - (G-1)!. \end{align\*} (The original series, and thus all subsequent series, have radius of convergence $1$, so plugging in $x=\frac12$ is valid.)
Assuming $G>0$, by using the Taylor series of the exponential function and the identity $m!=\int\_{0}^{+\infty}x^m e^{-x}\,dx$ we have: > > $$\begin{eqnarray\*}\sum\_{k\geq 0}\frac{(G+k)!}{2^k(k+1)!}&=&\sum\_{k\geq 0}\frac{1}{2^k(k+1)!}\int\_{0}^{+\infty}x^{G+k}e^{-x}\,dx\\[0.2cm]&=&\int\_{0}^{+\infty}x^G e^{-x}\sum\_{k\geq 0}\frac{x^k}{2^k(k+1)!}\,dx\\[0.2cm]&=&\int\_{0}^{+\infty}2x^{G-1}(e^{-x/2}-e^{-x})\,dx\\[0.2cm]&=&2^{G+1}(G-1)!-2(G-1)!\\[0.2cm]&=&\color{red}{2(2^G-1)(G-1)!}\end{eqnarray\*}$$ > > > as wanted.
1,821,700
According to Mathematica, $$\sum\_{k=0}^\infty \frac{(G+k)\_{G-1}}{2^k}=2(G-1)!(2^{G}-1)$$ where $$(G+k)\_{G-1}=\frac{(G+k)!}{(G+k-G+1)!}=\frac{(G+k)!}{(k+1)!}$$ is the falling factorial. I would like to compute this analytically, but I have nothing I've been doing works. A proof by induction led me to a more complex summation, and I can split it or simplify the falling factorial. Is there any possible way to evaluate this without resorting to Mathematica? Any help and/or references would be greatly appreciated.
2016/06/11
[ "https://math.stackexchange.com/questions/1821700", "https://math.stackexchange.com", "https://math.stackexchange.com/users/223401/" ]
We have $$S=\sum\_{k\geq0}\frac{\left(G+k\right)!}{\left(k+1\right)!}\left(\frac{1}{2}\right)^{k}=\left(G-1\right)!\sum\_{k\geq0}\dbinom{G+k}{G-1}\left(\frac{1}{2}\right)^{k} $$ and [since holds](https://math.stackexchange.com/questions/1658490/prove-that-sum-limits-k-0r-binomnkk-binomnr1r-using-combinatoric-a?rq=1) $$\dbinom{G+k}{G-1}=\sum\_{m=0}^{G-1}\dbinom{k+m}{m} $$ we have, exchanging the sum with the series $$S=\left(G-1\right)!\sum\_{m=0}^{G-1}\sum\_{k\geq0}\dbinom{k+m}{m}\left(\frac{1}{2}\right)^{k} $$ now note that $$\frac{\left(k+m\right)!}{m!}=\left(k+m\right)\left(k+m-1\right)\cdots\left(k+m-\left(k-1\right)\right)=\left(-1\right)^{k}\left(-\left(m+1\right)\right)\_{k}$$ where $\left(x\right)\_{k}$ is the [Pochhammer' symbol](http://mathworld.wolfram.com/PochhammerSymbol.html), so by the [generalized binomial theorem](https://en.wikipedia.org/wiki/Binomial_theorem#Newton.27s_generalised_binomial_theorem) we have $$\sum\_{k\geq0}\dbinom{k+m}{m}\left(\frac{1}{2}\right)^{k}=\sum\_{k\geq0}\dbinom{-\left(m+1\right)}{k}\left(-\frac{1}{2}\right)^{k}$$ $$=\frac{1}{\left(1-\frac{1}{2}\right)^{m+1}}=2^{m+1} $$ and finally $$\sum\_{m=0}^{G-1}2^{m+1}=2\left(2^{G}-1\right)$$ so > > $$\sum\_{k\geq0}\frac{\left(G+k\right)!}{\left(k+1\right)!}\left(\frac{1}{2}\right)^{k}=2\left(G-1\right)!\left(2^{G}-1\right).$$ > > >
Assuming $G>0$, by using the Taylor series of the exponential function and the identity $m!=\int\_{0}^{+\infty}x^m e^{-x}\,dx$ we have: > > $$\begin{eqnarray\*}\sum\_{k\geq 0}\frac{(G+k)!}{2^k(k+1)!}&=&\sum\_{k\geq 0}\frac{1}{2^k(k+1)!}\int\_{0}^{+\infty}x^{G+k}e^{-x}\,dx\\[0.2cm]&=&\int\_{0}^{+\infty}x^G e^{-x}\sum\_{k\geq 0}\frac{x^k}{2^k(k+1)!}\,dx\\[0.2cm]&=&\int\_{0}^{+\infty}2x^{G-1}(e^{-x/2}-e^{-x})\,dx\\[0.2cm]&=&2^{G+1}(G-1)!-2(G-1)!\\[0.2cm]&=&\color{red}{2(2^G-1)(G-1)!}\end{eqnarray\*}$$ > > > as wanted.
160,689
Below image shows the shape I'm trying to make seamless, I have mirrored it once along the highlighted edge and ensured the stack is in order to avoid a crease. [![Image 1](https://i.stack.imgur.com/7s7DS.png)](https://i.stack.imgur.com/7s7DS.png) However in the below image, after I've made an array of the shape I'm getting a crease on the array seams. Is there a way to remove/blend this crease as well as in the previous mirror? [![enter image description here](https://i.stack.imgur.com/K0QJO.png)](https://i.stack.imgur.com/K0QJO.png)
2019/12/11
[ "https://blender.stackexchange.com/questions/160689", "https://blender.stackexchange.com", "https://blender.stackexchange.com/users/71245/" ]
Stack order: Mirror Array (With Merge option ON) Subsurf
In your mirror modifier ensure the clipping box is checked. Seams or creases are often caused by the mirror edge not lining up properly, double vertices for it the edges overlapping or not meeting. Clipping ensure the vertices can't go past the center line of the object, where it is being mirrored.
15,353,520
This is a code to exit the application. ``` if (NavigationService.CanGoBack) { while (NavigationService.RemoveBackEntry() != null) { NavigationService.RemoveBackEntry(); } } ``` Can anybody tell me if it is permitted from Windows Phone Certification Requirements perspective????
2013/03/12
[ "https://Stackoverflow.com/questions/15353520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1458198/" ]
You should not disrupt the normal application flow by doing this. The user expects to close the application either by hitting the back button, or the Windows key. The user might also expect to resume the application work via Fast App Switching. Besides, your method won't exit the application because at one point you will hit the main page, where it can't go back. After that, back entry removal will not be possible. Bottom line: **don't do this.** A good explanation from Peter Torr is available [here](http://blogs.msdn.com/b/ptorr/archive/2010/08/01/exiting-a-windows-phone-application.aspx).
In one of my application, my task was to exit when a user reset his/her account. The application is in the store so there is no problem. i'm sure you can achieve exit with this code and it will be ok: ``` var g = new Microsoft.Xna.Framework.Game(); g.Exit(); ``` just add reference to `Microsoft.Xna.Framework.Game` [look at this link](http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh184840%28v=vs.105%29.aspx) > > **5.1.2 - App closure** > > > ``` The app must handle exceptions raised by the any of the managed or native System API and not close unexpectedly. During the certification process, the app is monitored for unexpected closure. An app that closes unexpectedly fails certification. The app must continue to run and remain responsive to user input after the exception is handled. ``` For example you just need a message, so **THE EXIT** will be expected.
55,243,773
I have installed jupypter on Ubuntu 18.04. when I try to open .ipynb file it says trying to connect to server and fails eventaully. When I looked at the console I saw the following error : ImportError: cannot import name 'create\_prompt\_application' as follows ``` [I 14:37:41.311 NotebookApp] KernelRestarter: restarting kernel (4/5), new random ports Traceback (most recent call last): File "/usr/lib/python3.6/runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "/usr/lib/python3.6/runpy.py", line 85, in _run_code exec(code, run_globals) File "/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py", line 15, in <module> from ipykernel import kernelapp as app File "/usr/local/lib/python3.6/dist-packages/ipykernel/__init__.py", line 2, in <module> from .connect import * File "/usr/local/lib/python3.6/dist-packages/ipykernel/connect.py", line 13, in <module> from IPython.core.profiledir import ProfileDir File "/usr/lib/python3/dist-packages/IPython/__init__.py", line 49, in <module> from .terminal.embed import embed File "/usr/lib/python3/dist-packages/IPython/terminal/embed.py", line 18, in <module> from IPython.terminal.interactiveshell import TerminalInteractiveShell File "/usr/lib/python3/dist-packages/IPython/terminal/interactiveshell.py", line 20, in <module> from prompt_toolkit.shortcuts import create_prompt_application, create_eventloop, create_prompt_layout, create_output ImportError: cannot import name 'create_prompt_application' [W 14:37:44.322 NotebookApp] KernelRestarter: restart failed ``` Some posts related to IPyton are suggesting that prompt-toolkit should be downgraded. I run deptree to get dependency tree as follows, which shows that prompt-toolkit 2.0.9 is installed and required version for jupyter-console should be between 2.0.0 and 2.0.1 ``` - jupyter-console [required: Any, installed: 6.0.0] - ipykernel [required: Any, installed: 5.1.0] - ipython [required: >=5.0.0, installed: 5.5.0] - pexpect [required: Any, installed: 4.2.1] - jupyter-client [required: Any, installed: 5.2.4] - jupyter-core [required: Any, installed: 4.4.0] - traitlets [required: Any, installed: 4.3.2] - python-dateutil [required: >=2.1, installed: 2.6.1] - pyzmq [required: >=13, installed: 18.0.1] - tornado [required: >=4.1, installed: 6.0.1] - traitlets [required: Any, installed: 4.3.2] - tornado [required: >=4.2, installed: 6.0.1] - traitlets [required: >=4.1.0, installed: 4.3.2] - ipython [required: Any, installed: 5.5.0] - pexpect [required: Any, installed: 4.2.1] - jupyter-client [required: Any, installed: 5.2.4] - jupyter-core [required: Any, installed: 4.4.0] - traitlets [required: Any, installed: 4.3.2] - python-dateutil [required: >=2.1, installed: 2.6.1] - pyzmq [required: >=13, installed: 18.0.1] - tornado [required: >=4.1, installed: 6.0.1] - traitlets [required: Any, installed: 4.3.2] - prompt-toolkit [required: >=2.0.0,<2.1.0, installed: 2.0.9] ``` Any thoughts on what could be wrong and what should I do? Thanks
2019/03/19
[ "https://Stackoverflow.com/questions/55243773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3468778/" ]
`sudo pip3 uninstall ipython` `sudo pip3 install ipython` the error solved for me Try it out. `sudo pip3 install 'prompt-toolkit<2.1.0,>=2.0.0' --force-reinstall`
For me the solution was to follow these steps: ``` python3 -m venv venv source venv/bin/activate pip install jupyter python -m jupyter notebook ``` I hope this helps anybody.
55,243,773
I have installed jupypter on Ubuntu 18.04. when I try to open .ipynb file it says trying to connect to server and fails eventaully. When I looked at the console I saw the following error : ImportError: cannot import name 'create\_prompt\_application' as follows ``` [I 14:37:41.311 NotebookApp] KernelRestarter: restarting kernel (4/5), new random ports Traceback (most recent call last): File "/usr/lib/python3.6/runpy.py", line 193, in _run_module_as_main "__main__", mod_spec) File "/usr/lib/python3.6/runpy.py", line 85, in _run_code exec(code, run_globals) File "/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py", line 15, in <module> from ipykernel import kernelapp as app File "/usr/local/lib/python3.6/dist-packages/ipykernel/__init__.py", line 2, in <module> from .connect import * File "/usr/local/lib/python3.6/dist-packages/ipykernel/connect.py", line 13, in <module> from IPython.core.profiledir import ProfileDir File "/usr/lib/python3/dist-packages/IPython/__init__.py", line 49, in <module> from .terminal.embed import embed File "/usr/lib/python3/dist-packages/IPython/terminal/embed.py", line 18, in <module> from IPython.terminal.interactiveshell import TerminalInteractiveShell File "/usr/lib/python3/dist-packages/IPython/terminal/interactiveshell.py", line 20, in <module> from prompt_toolkit.shortcuts import create_prompt_application, create_eventloop, create_prompt_layout, create_output ImportError: cannot import name 'create_prompt_application' [W 14:37:44.322 NotebookApp] KernelRestarter: restart failed ``` Some posts related to IPyton are suggesting that prompt-toolkit should be downgraded. I run deptree to get dependency tree as follows, which shows that prompt-toolkit 2.0.9 is installed and required version for jupyter-console should be between 2.0.0 and 2.0.1 ``` - jupyter-console [required: Any, installed: 6.0.0] - ipykernel [required: Any, installed: 5.1.0] - ipython [required: >=5.0.0, installed: 5.5.0] - pexpect [required: Any, installed: 4.2.1] - jupyter-client [required: Any, installed: 5.2.4] - jupyter-core [required: Any, installed: 4.4.0] - traitlets [required: Any, installed: 4.3.2] - python-dateutil [required: >=2.1, installed: 2.6.1] - pyzmq [required: >=13, installed: 18.0.1] - tornado [required: >=4.1, installed: 6.0.1] - traitlets [required: Any, installed: 4.3.2] - tornado [required: >=4.2, installed: 6.0.1] - traitlets [required: >=4.1.0, installed: 4.3.2] - ipython [required: Any, installed: 5.5.0] - pexpect [required: Any, installed: 4.2.1] - jupyter-client [required: Any, installed: 5.2.4] - jupyter-core [required: Any, installed: 4.4.0] - traitlets [required: Any, installed: 4.3.2] - python-dateutil [required: >=2.1, installed: 2.6.1] - pyzmq [required: >=13, installed: 18.0.1] - tornado [required: >=4.1, installed: 6.0.1] - traitlets [required: Any, installed: 4.3.2] - prompt-toolkit [required: >=2.0.0,<2.1.0, installed: 2.0.9] ``` Any thoughts on what could be wrong and what should I do? Thanks
2019/03/19
[ "https://Stackoverflow.com/questions/55243773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3468778/" ]
It is best to upgrade `jupyter-console` with this command: ``` pip3 install --upgrade --force jupyter-console ``` Then it will be compatible with later versions of `prompt-toolkit`. More details in [this github issue](https://github.com/jupyter/jupyter_console/issues/158).
For me the solution was to follow these steps: ``` python3 -m venv venv source venv/bin/activate pip install jupyter python -m jupyter notebook ``` I hope this helps anybody.
108,301
Can I get an illustration on how a choir master can conduct a piece of music written in 6/8 time? Thanks.
2020/12/04
[ "https://music.stackexchange.com/questions/108301", "https://music.stackexchange.com", "https://music.stackexchange.com/users/73427/" ]
Since 6/8 is essentially two time, down up works just fine. Each movement will encompass three quavers, so instead of counting 1 2 3 4 5 6, the count will be **1**(2 3) **2**(2 3). If it's incredibly slow, there could be an opportunity to count two lots of three, but that would be unusual.
In concert band, I've seen slow 6/8 time - or slow 6/4 time - conducted like 4/4 time, except with an extra flick of the hand at Beats "2" and "3" of the 4/4 conducting pattern. The conducting pattern for slow 6/8 time therefore looks like this from your point of view: Down -> Left -> Flick -> Right -> Flick -> Up Fast 6/8 ended up getting conducted like 2/4 time, except with the "upstrokes" of 2/4 time being transferred to beats 3 and 6 of 6/8 time. I have no reason to believe that choir masters conduct differently, especially since I've also been in 2 school choirs.
108,301
Can I get an illustration on how a choir master can conduct a piece of music written in 6/8 time? Thanks.
2020/12/04
[ "https://music.stackexchange.com/questions/108301", "https://music.stackexchange.com", "https://music.stackexchange.com/users/73427/" ]
In conducting course I attended, we were taught four patterns. It depends on tempo and which beats are stressed. 1. If the tempo is fast and 1st and 4th beats are stressed, you conduct like 2/4 (on the stressed beats). 2. If the tempo is fast and 1st, 3rd and 5th beats are stressed, you conduct like 3/4 (on the stressed beats). 3. If the tempo is slow and 1st and 4th beats are stressed, you conduct every beat in this way: down (and outside), inside, inside, outside, outside, up. 4. If the tempo is slow and 1st, 3rd and 5th beats are stressed, you conduct every beat in this way: down (and inside), inside, outside, outside, inside (and slightly up), up. (It is like 3/4, but you make two beats in one direction.) Of course, there are also different patterns, but for rare situations.
In concert band, I've seen slow 6/8 time - or slow 6/4 time - conducted like 4/4 time, except with an extra flick of the hand at Beats "2" and "3" of the 4/4 conducting pattern. The conducting pattern for slow 6/8 time therefore looks like this from your point of view: Down -> Left -> Flick -> Right -> Flick -> Up Fast 6/8 ended up getting conducted like 2/4 time, except with the "upstrokes" of 2/4 time being transferred to beats 3 and 6 of 6/8 time. I have no reason to believe that choir masters conduct differently, especially since I've also been in 2 school choirs.
67,973,126
``` interface FormValues { key: string; value: any; } const array: FormValues[] = [ { key: 'A', value: 1 // number }, { key: 'A', value: 1 // number }, { key: 'A', value: 'str' // string }, { key: 'C', value: { a: 1, b: '2' } // object }, { key: 'C', value: ['a','2'] // array }, { key: 'C', value: ['a','2'] // array } { key: 'B', value: true // boolean } ] ``` I want to filter the objects based on field `value`, which can have a value of any type. I tried to do it like this; my solution is not working for nested object checks. ``` const key = 'value'; const arrayUniqueByKey = [...new Map(array.map(item => [item[key], item])).values()]; ``` output : ``` [{ key: 'A', value: 1 // number }, { key: 'A', value: 'str' // string }, { key: 'C', value: { a: 1, b: '2' } // object }, { key: 'C', value: ['a','2'] // array }, { key: 'B', value: true // boolean }] ```
2021/06/14
[ "https://Stackoverflow.com/questions/67973126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5031009/" ]
You need to decide what makes two distinct objects "equal". In JavaScript, all built-in comparisons of objects (which includes arrays) are [by reference](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#comparing_objects). That means `['a','2'] === ['a','2']` is `false` because two distinct array objects exist, despite having the same contents. See [How to determine equality for two JavaScript objects?](https://stackoverflow.com/questions/201183/how-to-determine-equality-for-two-javascript-objects) for more information. I will take the approach that you would like two values to be considered equal if they serialize to the same value via a modified version of [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) where the order of property keys are guaranteed to be the same (so `{a: 1, b: 2}` and `{b: 2, a: 1}` will be equal no matter how those are stringified). I use a version from [this answer](https://stackoverflow.com/a/53593328/2887218) to do so: ``` function JSONstringifyOrder(obj: any, space?: number) { var allKeys: string[] = []; var seen: Record<string, null | undefined> = {}; JSON.stringify(obj, function (key, value) { if (!(key in seen)) { allKeys.push(key); seen[key] = null; } return value; }); allKeys.sort(); return JSON.stringify(obj, allKeys, space); } ``` And now I can use that to make the keys of your `Map`: ``` const arrayUniqueByKey = [...new Map(array.map( item => [JSONstringifyOrder(item[key]), item] )).values()]; ``` And you can verify that it behaves as you'd like: ``` console.log(arrayUniqueByKey); /* [{ "key": "A", "value": 1 }, { "key": "A", "value": "str" }, { "key": "C", "value": { "a": 1, "b": "2" } }, { "key": "C", "value": [ "a", "2" ] }, { "key": "B", "value": true }] */ ``` [Playground link to code](https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgGIHsoFsBqcA2ArhAM7IDeAUMjcgNYQCeAXMiWFKAOYDc1tANwLFWcEIz4BfSpQToQ7ZHChQ4LNJlzDSAbQC6yALzId-GlVqX6TVgHIAgrYA0Zq0KIRWARmQB6X8gghFgARtCuki6WFlY0DOoOzq6W7iLIPv6BwWFQEVG0MbHxdo75sameyLbsULZ+ATXcea6FVsVVAMJJsTQVrORK3k7IIXYATHWS9cjoIQBWEAhgzdHJtO22XWVu2qw6tnDOVRMGmcqqjCsFa3E2nd09fSYHR7Yn0+dqV+Y31gkAQg9yrtkBxiNMQuh0PgIGIIpQ9DIYIQQEtgPJkAApADKAHkAHKNEBcYAwRi4qAAE2gAApZnNROJhiQAA6ICAAflYQVC0AAlBRXEIoEp8PgANJMEisIlcfRGEx6PgpZRsCAQECsABKi0wlIAPLLhkExcgAD7IFHUmCgCCUgB8CvIkmVtBxBIAdLLSYw6fNhsjUWB0SBkDT4sMKgLWpZSWGAIThpjIUBqjV86O-SwECVSj0swgkAAWScYfJ4aZAOniBmMJvwrti0h6yCgEDAhCgoYqjeQknLrhzksYJC9mDANIHljbHa7WLx+K9HG4Pr9c2GQ6lzLZSAH0lk8kU8QVtgqtj4B4UYCUKjUAFUQMAAI7Ef6MYcKnQe78gCAAd2QABZOAWRpT5GA9LAQJpVxgEgLAjEdHR3UJZdiR9ClqSgGk4IgLBqyYPQ+WGXCsERDMPQqEhJyVGQ5AUaEIA9fB0C4MDb0YB9n1fd8mAHXwACoTBiAAieIRNYET7BE-IRIqCT0koSJBRoMSmAUqSZP4OTtA0moRKU4ZRPEySOi01T5P6VwRLgBSvG2ESQg0sYDJoaRlOM9TTPM5AdI8BTTEsGyfNUlz+ERDztJM3z-h8vziAUsEICUgwBN8SggA)
This will combine any duplicate keys, creating a new property `values` to hold the array of combined values (from like keys). ```js const array = [{key: 'A', value: 1},{key: 'A', value: 'str'},{key: 'C', value: { a: 1, b: '2'}},{key: 'B',value: true}] const arrayUniqueByKey = [array.reduce((b, a) => { let f = b.findIndex(c => c.key === a.key) if (f === -1) return [...b, a]; else { b[f].values = [...[b[f].value], a.value]; return b } }, [])]; console.log(arrayUniqueByKey) ```
67,973,126
``` interface FormValues { key: string; value: any; } const array: FormValues[] = [ { key: 'A', value: 1 // number }, { key: 'A', value: 1 // number }, { key: 'A', value: 'str' // string }, { key: 'C', value: { a: 1, b: '2' } // object }, { key: 'C', value: ['a','2'] // array }, { key: 'C', value: ['a','2'] // array } { key: 'B', value: true // boolean } ] ``` I want to filter the objects based on field `value`, which can have a value of any type. I tried to do it like this; my solution is not working for nested object checks. ``` const key = 'value'; const arrayUniqueByKey = [...new Map(array.map(item => [item[key], item])).values()]; ``` output : ``` [{ key: 'A', value: 1 // number }, { key: 'A', value: 'str' // string }, { key: 'C', value: { a: 1, b: '2' } // object }, { key: 'C', value: ['a','2'] // array }, { key: 'B', value: true // boolean }] ```
2021/06/14
[ "https://Stackoverflow.com/questions/67973126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5031009/" ]
You need to decide what makes two distinct objects "equal". In JavaScript, all built-in comparisons of objects (which includes arrays) are [by reference](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects#comparing_objects). That means `['a','2'] === ['a','2']` is `false` because two distinct array objects exist, despite having the same contents. See [How to determine equality for two JavaScript objects?](https://stackoverflow.com/questions/201183/how-to-determine-equality-for-two-javascript-objects) for more information. I will take the approach that you would like two values to be considered equal if they serialize to the same value via a modified version of [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) where the order of property keys are guaranteed to be the same (so `{a: 1, b: 2}` and `{b: 2, a: 1}` will be equal no matter how those are stringified). I use a version from [this answer](https://stackoverflow.com/a/53593328/2887218) to do so: ``` function JSONstringifyOrder(obj: any, space?: number) { var allKeys: string[] = []; var seen: Record<string, null | undefined> = {}; JSON.stringify(obj, function (key, value) { if (!(key in seen)) { allKeys.push(key); seen[key] = null; } return value; }); allKeys.sort(); return JSON.stringify(obj, allKeys, space); } ``` And now I can use that to make the keys of your `Map`: ``` const arrayUniqueByKey = [...new Map(array.map( item => [JSONstringifyOrder(item[key]), item] )).values()]; ``` And you can verify that it behaves as you'd like: ``` console.log(arrayUniqueByKey); /* [{ "key": "A", "value": 1 }, { "key": "A", "value": "str" }, { "key": "C", "value": { "a": 1, "b": "2" } }, { "key": "C", "value": [ "a", "2" ] }, { "key": "B", "value": true }] */ ``` [Playground link to code](https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgGIHsoFsBqcA2ArhAM7IDeAUMjcgNYQCeAXMiWFKAOYDc1tANwLFWcEIz4BfSpQToQ7ZHChQ4LNJlzDSAbQC6yALzId-GlVqX6TVgHIAgrYA0Zq0KIRWARmQB6X8gghFgARtCuki6WFlY0DOoOzq6W7iLIPv6BwWFQEVG0MbHxdo75sameyLbsULZ+ATXcea6FVsVVAMJJsTQVrORK3k7IIXYATHWS9cjoIQBWEAhgzdHJtO22XWVu2qw6tnDOVRMGmcqqjCsFa3E2nd09fSYHR7Yn0+dqV+Y31gkAQg9yrtkBxiNMQuh0PgIGIIpQ9DIYIQQEtgPJkAApADKAHkAHKNEBcYAwRi4qAAE2gAApZnNROJhiQAA6ICAAflYQVC0AAlBRXEIoEp8PgANJMEisIlcfRGEx6PgpZRsCAQECsABKi0wlIAPLLhkExcgAD7IFHUmCgCCUgB8CvIkmVtBxBIAdLLSYw6fNhsjUWB0SBkDT4sMKgLWpZSWGAIThpjIUBqjV86O-SwECVSj0swgkAAWScYfJ4aZAOniBmMJvwrti0h6yCgEDAhCgoYqjeQknLrhzksYJC9mDANIHljbHa7WLx+K9HG4Pr9c2GQ6lzLZSAH0lk8kU8QVtgqtj4B4UYCUKjUAFUQMAAI7Ef6MYcKnQe78gCAAd2QABZOAWRpT5GA9LAQJpVxgEgLAjEdHR3UJZdiR9ClqSgGk4IgLBqyYPQ+WGXCsERDMPQqEhJyVGQ5AUaEIA9fB0C4MDb0YB9n1fd8mAHXwACoTBiAAieIRNYET7BE-IRIqCT0koSJBRoMSmAUqSZP4OTtA0moRKU4ZRPEySOi01T5P6VwRLgBSvG2ESQg0sYDJoaRlOM9TTPM5AdI8BTTEsGyfNUlz+ERDztJM3z-h8vziAUsEICUgwBN8SggA)
You can use [Array.prototype.reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) combined with [JSON.stringify()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) and finaly get the `result` array of values with [Object.values()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values) ```js const array = [{key: 'A',value: 1,},{key: 'A',value: 1,},{key: 'A',value: 'str',},{key: 'C',value: { a: 1, b: '2' },},{key: 'C',value: ['a', '2'],},{key: 'C',value: ['a', '2'],},{key: 'B',value: true}] const result = Object.values(array.reduce((a, c) => ((a[JSON.stringify(c)] = c), a), {})) console.log(result) ```
60,290,139
I write add-ins for Revit. These add-ins depend on the Revit API libraries. These libraries change with each new version of Revit (2018, 2019, 2020, etc). Unfortunately they are not backward compatible so I can't use my add-in from 2018 with 2020. This means that I maintain separate repositories of my own code for 2018, 2019, and 2020. I'm currently using pull requests so that if I make a change in 2018 I can move it across to 2019 and 2020. The problem is that when the request comes across it updates my 2019/2020 libraries back to reference the 2018 libraries. Then I have to go back in and make sure that it references the correct library. How should I be doing this to avoid this issue every time that I need to push a change to other versions?
2020/02/18
[ "https://Stackoverflow.com/questions/60290139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/180529/" ]
Are you sure that your 2018 add-in cannot be used in Revit 2020? In many cases, if not most, the opposite is true. In general, you can use an add-in compiled for a previous version of Revit in later versions as well. If you are making calls to Revit API functionality that changed between the versions, you can handle that by compiling for the earlier version of Revit and adding .NET runtime functionality to check at runtime whether to call the old or new version of the Revit API. The calls that changed can be updated dynamically for the new version at runtime. Look at [The Building Coder](https://thebuildingcoder.typepad.com) [Multi-Version Add-in](https://thebuildingcoder.typepad.com/blog/2012/07/multi-version-add-in.html) for a full implementation sample. That said, I still totally agree with your question per se; in many cases, you will want a separate clean updated version of your add-in for each version of Revit, to avoid complexity and enhance code readability. For that, I totally agree with Ôrel on maintaining a separate branch for each version and merging updates into other branches.
I have the same issue with an Add-in I wrote. Due to an API change, I have to make separate versions depending on the year associated with the Addin. I set-up a solution with separate projects for each version and shared code and libraries to reduce the amount of duplicate code. Unfortunately, I set this up after creating the second version, so not all of the code has been properly sub-divided. However, this should give you an idea of how this could be set-up. You can see this in the github repository: [CreateSheets](https://github.com/morbius1st/CreateSheets). Note that, although this does reduce the the amount of code, it takes a bit of extra work as changes to shared code needs to consider every version.
39,949,818
Trying to place an element after match second or more dots in a text if it has a specific number of characters. Example: ``` <div id="mytext"> This is just a example. I need to find a solution. I will appreciate any help. Thank you. </div> <script> var chars = 55; if ($('#mytext').text().length > chars){ //add <br> after first dot found after number of chars specified. } </script> ``` ... The output would be: ``` This is just a example. I need to find a solution. I will appreciate any help.<br> Thank you. ```
2016/10/10
[ "https://Stackoverflow.com/questions/39949818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6047145/" ]
You can try this ```js var chars = 55; if ($('#mytext').text().length > chars){ var text = $('#mytext').text(); // div text var chars_text = text.substring(0, chars); // chars text var rest = text.replace(chars_text, '').replace(/\./g,'. <span>After Dot</span>'); // rest of text and replace dot of rest text with span $('#mytext').html(chars_text+rest); // apply chars and rest after replace to the div again } ``` ```css span{ color: red; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="mytext"> This is just a example. I need to find a solution. I will appreciate any help. Thank you. </div> ``` > > Note: if you just need to replace the next one dot after chars you can > use `'.'` instead of `/\./g` > > >
this way : With JQUERY Substring ``` <p> this is test string with jquery . test 1 2 3 4 45 5 . test test test </p> <b></b> <script> var a = $('p').text(); var _output = ''; var _allow_index = 40; if (a.length > _allow_index) { var x = a.split('.'); for(var i=0; i<x.length; i++) { if (_output.length < _allow_index) { _output+=x[i]+'.'; } } } else { _output = a; } $('b').html(_output + '<br>'+a.substr(_output.length,a.length)); </script> ```
39,949,818
Trying to place an element after match second or more dots in a text if it has a specific number of characters. Example: ``` <div id="mytext"> This is just a example. I need to find a solution. I will appreciate any help. Thank you. </div> <script> var chars = 55; if ($('#mytext').text().length > chars){ //add <br> after first dot found after number of chars specified. } </script> ``` ... The output would be: ``` This is just a example. I need to find a solution. I will appreciate any help.<br> Thank you. ```
2016/10/10
[ "https://Stackoverflow.com/questions/39949818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6047145/" ]
You can try this ```js var chars = 55; if ($('#mytext').text().length > chars){ var text = $('#mytext').text(); // div text var chars_text = text.substring(0, chars); // chars text var rest = text.replace(chars_text, '').replace(/\./g,'. <span>After Dot</span>'); // rest of text and replace dot of rest text with span $('#mytext').html(chars_text+rest); // apply chars and rest after replace to the div again } ``` ```css span{ color: red; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="mytext"> This is just a example. I need to find a solution. I will appreciate any help. Thank you. </div> ``` > > Note: if you just need to replace the next one dot after chars you can > use `'.'` instead of `/\./g` > > >
Doing that doesn't seem to be a very good practise, for instance length may vary for localised languages. Besides, you're assuming you have a plain text, rather than an HTML text and length is different in both cases. You may want to use html() instead of text(). However here is a way for the given case: ``` var container = $('#mytext'); var length = 55; var insert = '<br/>'; var text = container.text().trim(); // text() or html() var dotPosAfterLength = text.indexOf(".", length); if (dotPosAfterLength != -1) { container.html( text.substring(0, dotPosAfterLength+1) +insert +text.substring(dotPosAfterLength+1) ); } ```
39,949,818
Trying to place an element after match second or more dots in a text if it has a specific number of characters. Example: ``` <div id="mytext"> This is just a example. I need to find a solution. I will appreciate any help. Thank you. </div> <script> var chars = 55; if ($('#mytext').text().length > chars){ //add <br> after first dot found after number of chars specified. } </script> ``` ... The output would be: ``` This is just a example. I need to find a solution. I will appreciate any help.<br> Thank you. ```
2016/10/10
[ "https://Stackoverflow.com/questions/39949818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6047145/" ]
You can try this ```js var chars = 55; if ($('#mytext').text().length > chars){ var text = $('#mytext').text(); // div text var chars_text = text.substring(0, chars); // chars text var rest = text.replace(chars_text, '').replace(/\./g,'. <span>After Dot</span>'); // rest of text and replace dot of rest text with span $('#mytext').html(chars_text+rest); // apply chars and rest after replace to the div again } ``` ```css span{ color: red; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="mytext"> This is just a example. I need to find a solution. I will appreciate any help. Thank you. </div> ``` > > Note: if you just need to replace the next one dot after chars you can > use `'.'` instead of `/\./g` > > >
You just need to add this property in CSS. ``` <div id="mytext"> This is just a example. I need to find a solution. I will appreciate any help. Thank you. </div> <style> div#mytext{ word-wrap: break-word; } </style> ```
73,736,884
I have to produce randomly generated, normally distributed numbers, based on an astronomical table containing a most probable value and a standard deviation. The peculiar thing is that the standard deviation is not given by one, but two numbers - an upper standard deviation of the error and a lower, something like this: ``` mass_object, error_up, error_down 7.33, 0.12, 0.07 9.40, 0.04, 0.02 6.01, 0.11, 0.09 ... ``` For example, this means for the first object that if a random mass `m` gets generated with `m<7.33`, then probably it will be further away from `7.33` than in the case that `m>7.33`. So I am looking now for a way to randomly generate the numbers and this way has to include the 2 possible standard deviations. If I was dealing with just one standard deviation per object, I would create the random number (mass) of the first object like that: ``` mass_random = np.random.normal(loc=7.33, scale=0.12) ``` Do you have ideas how to create these random numbers with upper and lower standard deviation of the scatter? Tnx
2022/09/15
[ "https://Stackoverflow.com/questions/73736884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5838180/" ]
For one, `mb_convert_encoding($payload, 'unicode')` converts the input to UTF-16BE, not UTF-8. You would want `mb_convert_encoding($payload, 'UTF-8')`. For two, using `mb_convert_encoding()` without specifying the *source* encoding causes the function to *assume* that the input is using the system's default encoding, which is frequently incorrect and will cause your data to be mangled. You would want `mb_convert_encoding($payload, 'UTF-8', $source_encoding)`. [Also, you cannot reliably detect string encoding, you need to know what it is.] For three, `mb_convert_encoding()` is entirely the wrong function to use to apply the desired escape sequences to the data. [and good lord are the google results for "php escape UTF-8" *awful*] Unfortunately, PHP doesn't have a UTF-8 escape function that isn't baked into another function, but it's not terribly difficult to write in userland. ```php function utf8_escape($input) { $output = ''; for( $i=0,$l=mb_strlen($input); $i<$l; ++$i ) { $cur = mb_substr($input, $i, 1); if( strlen($cur) === 1 ) { $output .= $cur; } else { $output .= sprintf('\\u%04x', mb_ord($cur)); } } return $output; } $in = "asdf äöå"; var_dump( utf8_escape($in), ); ``` Output: ``` string(23) "asdf \u00e4\u00f6\u00e5" ```
Instead of trying to re-assemble the payload from the already decoded JSON, you should take the data directly as you received it. Facebook sends `Content-Type: application/json`, which means PHP will not populate $\_POST to begin with - but you can read the entire request body using `file_get_contents('php://input')`. Try and calculate the signature based on *that*, that should work without having to deal with any hassles of encoding & escaping.
30,296,949
I'm getting the error message of > > Wrong number of arguments or invalid property assignment > > > at this line: ``` Set hello = Range("O" & row, "Q" & row, "W" & row) ``` However, the macro runs smoothly with `Set hello = Range("O" & row)`. So it means this macro is okay with one cell selection, but getting error with multiple cells selection. I cannot figure out which setting in my macro causes this error. Appreciate your help. ``` Sub ImportDatafromotherworksheet() Dim wkbCrntWorkBook As Workbook Dim wkbSourceBook As Workbook Dim rngSourceRange As Range Dim rngDestination As Range Dim row As Integer Dim hello As Range Set wkbCrntWorkBook = ActiveWorkbook With Application.FileDialog(msoFileDialogOpen) .Filters.Clear .Filters.Add "Excel 2007-13", "*.xlsx; *.xlsm; *.xlsa" .AllowMultiSelect = False .Show If .SelectedItems.Count > 0 Then Workbooks.Open .SelectedItems(1) Set wkbSourceBook = ActiveWorkbook Set rngSourceRange = Application.InputBox(Prompt:="Select source row", Title:="Source Range", Default:="press Ctrl for multiple selection", Type:=8) row = rngSourceRange.row Set hello = Range("O" & row, "Q" & row, "W" & row) wkbCrntWorkBook.Activate Set rngDestination = Application.InputBox(Prompt:="Select destination cell", Title:="Select Destination", Default:="A1", Type:=8) hello.Copy rngDestination rngDestination.CurrentRegion.EntireColumn.AutoFit wkbSourceBook.Close False End If End With End Sub ```
2015/05/18
[ "https://Stackoverflow.com/questions/30296949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4910875/" ]
You might be trying to partition your [`DENSE_RANK`](https://msdn.microsoft.com/en-IN/library/ms173825.aspx) for group. You just need to order them like this `DENSE_RANK()OVER(ORDER BY column1 column2 column3 column4)`. **Complete Query** ``` SELECT column1 column2 column3 column4, ROW_NUMBER()OVER(PARTITION BY column1 column2 column3 column4 ORDER BY (SELECT 1)) as row_num, DENSE_RANK()OVER(ORDER BY column1 column2 column3 column4) as [group] FROM yourtable ```
Try this: ``` DECLARE @t TABLE(column1 VARCHAR(10), column2 VARCHAR(10), column3 VARCHAR(10), column4 VARCHAR(10)) INSERT INTO @t VALUES ('abc', 'pqr', 'austria', 'type1'), ('abc', 'pqr', 'austria', 'type1'), ('abc', 'pqr', 'austria', 'type2'), ('abc', 'pqr', 'austria', 'type2'), ('xyz', 'ppp', 'austria', 'type1'), ('xyz', 'ppp', 'austria', 'type1'), ('xyz', 'ppp', 'austria', 'type2'), ('xyz', 'ppp', 'austria', 'type2') SELECT *, ROW_NUMBER() OVER(PARTITION BY column1, column4 ORDER BY column4) AS rn, DENSE_RANK() OVER(ORDER BY column2, column3, column4) AS dr FROM @t ``` Output: ``` column1 column2 column3 column4 rn dr xyz ppp austria type1 1 1 xyz ppp austria type1 2 1 xyz ppp austria type2 1 2 xyz ppp austria type2 2 2 abc pqr austria type1 1 3 abc pqr austria type1 2 3 abc pqr austria type2 1 4 abc pqr austria type2 2 4 ```
11,537,578
here is the problem ``` public ActionResult One() { if(condition) return View() else return Two() } public ActionResult Two() { return View() } ``` how can I do that without error
2012/07/18
[ "https://Stackoverflow.com/questions/11537578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1333814/" ]
Just return the view by name (`return view("nameOfView")`), or use `RedirectToAction` or `RedirectToRoute`
oh I've solved the problem ``` public ActionResult Two() { return View("Two") } ```
11,537,578
here is the problem ``` public ActionResult One() { if(condition) return View() else return Two() } public ActionResult Two() { return View() } ``` how can I do that without error
2012/07/18
[ "https://Stackoverflow.com/questions/11537578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1333814/" ]
Simply use: ``` public ActionResult One() { if(condition) return View() else return View("Two") } ```
oh I've solved the problem ``` public ActionResult Two() { return View("Two") } ```
11,537,578
here is the problem ``` public ActionResult One() { if(condition) return View() else return Two() } public ActionResult Two() { return View() } ``` how can I do that without error
2012/07/18
[ "https://Stackoverflow.com/questions/11537578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1333814/" ]
Change your code to: ``` public ActionResult One() { if(condition) return View(); else RedirectToAction("Two"); } public ActionResult Two() { return View(); } ```
oh I've solved the problem ``` public ActionResult Two() { return View("Two") } ```
332,208
When I try to convert a word document using the ooextract python script from open office like ``` /usr/local/bin/ooextract.py myDocument.doc myDocument.pdf ``` the open office deamon (sOffice.bin) takes 100% CPU load forever. We are using Open Office 2.6.3 on a virtual machine running debian squeeze 2.6.32-5-amd64 UPDATE: We found out that this appears only with our test document, other documents can be converted without problem. But how can we find out what's wrong with our document. How can we enable traces/loggin o the sOffice.bin process?
2011/09/05
[ "https://superuser.com/questions/332208", "https://superuser.com", "https://superuser.com/users/96752/" ]
I had a similar issue. To debug it, I put the test document under version control and removed significant chunks of it at a time; ensuring I took note of what structures were removed. This let me isolate it to an issue with 2.4.1 and a Table, containing a Row, with lots of text content. The table was allowed to split across pages, the row was not. Rendering to PDF caused a similar 100% CPU usage issue.
It seem to be related to Open Office Version 2.6.3, with Open Office 3.3.0 we do not have the problem anymore.
10,975,372
How to completely disable transparency of given `PNGObject`? By the way I am using PNGImage unit of Version 1.564.
2012/06/11
[ "https://Stackoverflow.com/questions/10975372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/715707/" ]
I don't think it's possible to permanently disable `TPNGObject` image transparency. Or at least I couldn't find a property for doing this. And it should have been controlled by a property since when you assign or load an image, the `TPNGObject` takes the image parameters (including transparency) from the image file assigned. So as a workaround I would prefer to use the `RemoveTransparency` procedure after when you load or assign the image: ``` uses PNGImage; procedure TForm1.Button1Click(Sender: TObject); var PNGObject: TPNGObject; begin PNGObject := TPNGObject.Create; try PNGObject.LoadFromFile('C:\Image.png'); PNGObject.RemoveTransparency; PNGObject.Draw(Canvas, Rect(0, 0, PNGObject.Width, PNGObject.Height)); finally PNGObject.Free; end; end; ```
For just drawing a TPNGObject (Delphi PNGComponents library) to some background color (in example: white) with alpha blending, try this: ``` uses PNGImage, PNGFunctions; procedure TForm1.Button1Click(Sender: TObject); var png: TPNGObject; bmp: TBitmap; begin try // load PNG png := TPNGObject.Create; png.LoadFromFile('MyPNG.png'); // create Bitmap bmp := TBitmap.Create; bmp.Width := png.Width; bmp.Height := png.Height; // set background color to whatever you want bmp.Canvas.Brush.Color := clWhite; bmp.Canvas.FillRect(Rect(0, 0, png.Width, png.Height)); // draw PNG on Bitmap with alpha blending DrawPNG(png, bmp.Canvas, Rect(0, 0, png.Width, png.Height), []); // save Bitmap bmp.SaveToFile('MyBMP.bmp'); finally FreeAndNil(png); FreeAndNil(bmp); end; end; ``` To use the DrawPNG procedure you have to include the PNGFunctions unit.
13,172,265
hello im trying to have multiple jquery cycle galleries on one page. ifeel like i have the code right but its not working... can anyone look at and help? it doesnt seem to finding my .next and .prev classes? jquery: ``` $('.cycle').each(function() { var slideshow = $(this); var next = slideshow.closest('.next'); var prev = slideshow.closest('.prev'); slideshow.cycle({ speed: 0, timeout: 0, next: next, prev: prev, }); }); ``` html: ``` <div id="woodwood" class="drag"> <div class='cycle'> <img src='invites/baldi.png' /> <img src='invites/koerfer.png' /> <img src='invites/williams.png' /> </div> <div class="title"> Invites<br /> 2010 &mdash; 2012 </div> <div class="controls"> <a class='prev'><img src="left.gif"></a> <a class='next'><img src="right.gif"></a> <button>Close</button> </div> </div> ```
2012/11/01
[ "https://Stackoverflow.com/questions/13172265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/537253/" ]
The `closest` selects the closest parent not the closest element, you can use `find` method. ``` var next = slideshow.parent().find('.next'); var prev = slideshow.parent().find('.prev'); ``` Note that IDs must be unique, if you have several wrappers with ID of `woodwood` your markup is invalid.
Problem is with finding `.next` and `.prev` Change theses lines, ``` var next = slideshow.closest('.next'); var prev = slideshow.closest('.prev'); ``` To, ``` var next = $('.next'); var prev = $('.prev'); ``` DEMO: <http://jsfiddle.net/muthkum/egZ3y/1/>
11,476,848
The company I am at is using Netbeans with PHP Codeigniter. Unfortunately, the default Netbeans code "Format" option does not produce the Codeigniter code standard that some of our developers want. Does anyone know of a Netbeans plugin to format code in different way, or based on different standards?
2012/07/13
[ "https://Stackoverflow.com/questions/11476848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/816260/" ]
Try > > Tools -> Options -> Editor -> Formating > > >
Well maybe it is possible to style PHP code like CI does. I tried to find configuration for that (there is import feature in Netbeans), but struggled. What could be possible is to manually match CI PHP code formatting style. You need to go to Tools->Options->Editor->Formatting select PHP from "Language" drop-down menu and set required categories (Alignment, Braces, New Lines and etc.) accordingly. There are lots of configs so this could be done. On the other hand there is no way to export those settings. I have NetBeans 7.1.2. Tried exporting my default settings in case I screw something, changed some fields and imported them back, but after import my original settings were not restored. So it means it is not possible to export those settings, so it could be the reason why there are no such config on internet. So now there is no point setting all those configs: imagine if I reinstall Netbeans, I would need to select all those check-boxes again. Lets try raising this bug in Netbeans forum...
26,245,378
So I have an ajax call like this: ``` $.ajax({ type: "GET", url: "Home/GetFullView", success: function (data) { $("#sched").html(data); }, fail: function () { } }); ``` Where "Home" is the controller and "GetFullView" is the action. Sometimes the call works. However sometimes it crashes the application because it tries this url: "Home/Home/GetFullView". So it's adding "home" once too many times. How can I consistently have it check the same url without doubling the "Home" controller name? If I simply use url: "GetFullView" it also crashes because it looks for "Home" controller.
2014/10/07
[ "https://Stackoverflow.com/questions/26245378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2292081/" ]
Introduce a leading `/` ``` url: "/Home/GetFullView", ```
you need a `local url` like: `url: "/Home/GetFullView"`
26,245,378
So I have an ajax call like this: ``` $.ajax({ type: "GET", url: "Home/GetFullView", success: function (data) { $("#sched").html(data); }, fail: function () { } }); ``` Where "Home" is the controller and "GetFullView" is the action. Sometimes the call works. However sometimes it crashes the application because it tries this url: "Home/Home/GetFullView". So it's adding "home" once too many times. How can I consistently have it check the same url without doubling the "Home" controller name? If I simply use url: "GetFullView" it also crashes because it looks for "Home" controller.
2014/10/07
[ "https://Stackoverflow.com/questions/26245378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2292081/" ]
Introduce a leading `/` ``` url: "/Home/GetFullView", ```
To get your relative path fully qualified, use this: ``` url: "~/Home/GetFullView" ``` This will then give you the right qualified path whether you are at the website or application level.
12,233,436
i have following code i am trying to compare two get in order to get into if statement but i something wrong with is code. **the following code should run if the time is above 23:29 and less then 08:10...** ``` $gettime="04:39"; // getting this from database $startdate = strtotime("23:29"); $startdate1 = date("H:i", $startdate); $enddate = strtotime("08:10"); $enddate1 = date("H:i", $enddate); //this condition i need to run if($gettime >= strtotime($startdate1) && $gettime <= strtotime($enddate1)) { echo"ok working"; } ``` please help me in dis regard thanks
2012/09/02
[ "https://Stackoverflow.com/questions/12233436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1641368/" ]
You are comparing the string with a date. $gettime is a string and you are comparing it with a time object. You need to convert $gettime to a time object by calling $gettime = strtotime($gettime), and then you can compare it using > or < like you have above.
For comparing times, you should use the provided PHP classes The DateTime::diff will return an object with time difference info: <http://www.php.net/manual/en/datetime.diff.php>
12,233,436
i have following code i am trying to compare two get in order to get into if statement but i something wrong with is code. **the following code should run if the time is above 23:29 and less then 08:10...** ``` $gettime="04:39"; // getting this from database $startdate = strtotime("23:29"); $startdate1 = date("H:i", $startdate); $enddate = strtotime("08:10"); $enddate1 = date("H:i", $enddate); //this condition i need to run if($gettime >= strtotime($startdate1) && $gettime <= strtotime($enddate1)) { echo"ok working"; } ``` please help me in dis regard thanks
2012/09/02
[ "https://Stackoverflow.com/questions/12233436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1641368/" ]
Assuming you're receiving the time from the DB in a `date` format (and not as a `string`): change: ``` if($gettime >= strtotime($startdate1) && $gettime <= strtotime($enddate1)) ``` to: ``` if($gettime >= strtotime($startdate1) || $gettime <= strtotime($enddate1)) ```
For comparing times, you should use the provided PHP classes The DateTime::diff will return an object with time difference info: <http://www.php.net/manual/en/datetime.diff.php>
12,233,436
i have following code i am trying to compare two get in order to get into if statement but i something wrong with is code. **the following code should run if the time is above 23:29 and less then 08:10...** ``` $gettime="04:39"; // getting this from database $startdate = strtotime("23:29"); $startdate1 = date("H:i", $startdate); $enddate = strtotime("08:10"); $enddate1 = date("H:i", $enddate); //this condition i need to run if($gettime >= strtotime($startdate1) && $gettime <= strtotime($enddate1)) { echo"ok working"; } ``` please help me in dis regard thanks
2012/09/02
[ "https://Stackoverflow.com/questions/12233436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1641368/" ]
Make sure your comaring the right types of data, time stamps with time stamps and not w/ strings etc... ``` $gettime= strtotime("22:00"); // getting this from database $startdate = strtotime("21:00"); //$startdate1 = date("H:i", $startdate); $enddate = strtotime("23:00"); //$enddate1 = date("H:i", $enddate); //this condition i need to run if($gettime >= $startdate && $gettime <= $enddate) { echo"ok working"; } ```
For comparing times, you should use the provided PHP classes The DateTime::diff will return an object with time difference info: <http://www.php.net/manual/en/datetime.diff.php>
12,233,436
i have following code i am trying to compare two get in order to get into if statement but i something wrong with is code. **the following code should run if the time is above 23:29 and less then 08:10...** ``` $gettime="04:39"; // getting this from database $startdate = strtotime("23:29"); $startdate1 = date("H:i", $startdate); $enddate = strtotime("08:10"); $enddate1 = date("H:i", $enddate); //this condition i need to run if($gettime >= strtotime($startdate1) && $gettime <= strtotime($enddate1)) { echo"ok working"; } ``` please help me in dis regard thanks
2012/09/02
[ "https://Stackoverflow.com/questions/12233436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1641368/" ]
Make sure your comaring the right types of data, time stamps with time stamps and not w/ strings etc... ``` $gettime= strtotime("22:00"); // getting this from database $startdate = strtotime("21:00"); //$startdate1 = date("H:i", $startdate); $enddate = strtotime("23:00"); //$enddate1 = date("H:i", $enddate); //this condition i need to run if($gettime >= $startdate && $gettime <= $enddate) { echo"ok working"; } ```
You are comparing the string with a date. $gettime is a string and you are comparing it with a time object. You need to convert $gettime to a time object by calling $gettime = strtotime($gettime), and then you can compare it using > or < like you have above.
12,233,436
i have following code i am trying to compare two get in order to get into if statement but i something wrong with is code. **the following code should run if the time is above 23:29 and less then 08:10...** ``` $gettime="04:39"; // getting this from database $startdate = strtotime("23:29"); $startdate1 = date("H:i", $startdate); $enddate = strtotime("08:10"); $enddate1 = date("H:i", $enddate); //this condition i need to run if($gettime >= strtotime($startdate1) && $gettime <= strtotime($enddate1)) { echo"ok working"; } ``` please help me in dis regard thanks
2012/09/02
[ "https://Stackoverflow.com/questions/12233436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1641368/" ]
You are comparing the string with a date. $gettime is a string and you are comparing it with a time object. You need to convert $gettime to a time object by calling $gettime = strtotime($gettime), and then you can compare it using > or < like you have above.
You may refer to PHP documentation about `DateTime::diff` function at their website <http://php.net/manual/en/datetime.diff.php> You may also go through this stackoverflow question **[How to calculate the difference between two dates using PHP?](https://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using-php)**
12,233,436
i have following code i am trying to compare two get in order to get into if statement but i something wrong with is code. **the following code should run if the time is above 23:29 and less then 08:10...** ``` $gettime="04:39"; // getting this from database $startdate = strtotime("23:29"); $startdate1 = date("H:i", $startdate); $enddate = strtotime("08:10"); $enddate1 = date("H:i", $enddate); //this condition i need to run if($gettime >= strtotime($startdate1) && $gettime <= strtotime($enddate1)) { echo"ok working"; } ``` please help me in dis regard thanks
2012/09/02
[ "https://Stackoverflow.com/questions/12233436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1641368/" ]
Make sure your comaring the right types of data, time stamps with time stamps and not w/ strings etc... ``` $gettime= strtotime("22:00"); // getting this from database $startdate = strtotime("21:00"); //$startdate1 = date("H:i", $startdate); $enddate = strtotime("23:00"); //$enddate1 = date("H:i", $enddate); //this condition i need to run if($gettime >= $startdate && $gettime <= $enddate) { echo"ok working"; } ```
Assuming you're receiving the time from the DB in a `date` format (and not as a `string`): change: ``` if($gettime >= strtotime($startdate1) && $gettime <= strtotime($enddate1)) ``` to: ``` if($gettime >= strtotime($startdate1) || $gettime <= strtotime($enddate1)) ```
12,233,436
i have following code i am trying to compare two get in order to get into if statement but i something wrong with is code. **the following code should run if the time is above 23:29 and less then 08:10...** ``` $gettime="04:39"; // getting this from database $startdate = strtotime("23:29"); $startdate1 = date("H:i", $startdate); $enddate = strtotime("08:10"); $enddate1 = date("H:i", $enddate); //this condition i need to run if($gettime >= strtotime($startdate1) && $gettime <= strtotime($enddate1)) { echo"ok working"; } ``` please help me in dis regard thanks
2012/09/02
[ "https://Stackoverflow.com/questions/12233436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1641368/" ]
Assuming you're receiving the time from the DB in a `date` format (and not as a `string`): change: ``` if($gettime >= strtotime($startdate1) && $gettime <= strtotime($enddate1)) ``` to: ``` if($gettime >= strtotime($startdate1) || $gettime <= strtotime($enddate1)) ```
You may refer to PHP documentation about `DateTime::diff` function at their website <http://php.net/manual/en/datetime.diff.php> You may also go through this stackoverflow question **[How to calculate the difference between two dates using PHP?](https://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using-php)**
12,233,436
i have following code i am trying to compare two get in order to get into if statement but i something wrong with is code. **the following code should run if the time is above 23:29 and less then 08:10...** ``` $gettime="04:39"; // getting this from database $startdate = strtotime("23:29"); $startdate1 = date("H:i", $startdate); $enddate = strtotime("08:10"); $enddate1 = date("H:i", $enddate); //this condition i need to run if($gettime >= strtotime($startdate1) && $gettime <= strtotime($enddate1)) { echo"ok working"; } ``` please help me in dis regard thanks
2012/09/02
[ "https://Stackoverflow.com/questions/12233436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1641368/" ]
Make sure your comaring the right types of data, time stamps with time stamps and not w/ strings etc... ``` $gettime= strtotime("22:00"); // getting this from database $startdate = strtotime("21:00"); //$startdate1 = date("H:i", $startdate); $enddate = strtotime("23:00"); //$enddate1 = date("H:i", $enddate); //this condition i need to run if($gettime >= $startdate && $gettime <= $enddate) { echo"ok working"; } ```
You may refer to PHP documentation about `DateTime::diff` function at their website <http://php.net/manual/en/datetime.diff.php> You may also go through this stackoverflow question **[How to calculate the difference between two dates using PHP?](https://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using-php)**
58,133,507
I need ti use this `AutoFac` in ASP core 3.0 When I use this code in startu up: ``` public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddControllers(); return services.BuildAutofacServiceProvider(); } ``` It show me this error: > > 'ConfigureServices returning an System.IServiceProvider isn't supported.' > > > And I change the program.cs by this: ``` public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseServiceProviderFactory(new AutofacServiceProviderFactory()) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } ``` But it not solved. This is `BuildAutofacServiceProvider()` Code: ``` public static IServiceProvider BuildAutofacServiceProvider(this IServiceCollection services) { var ContainerBuilder = new ContainerBuilder(); ContainerBuilder.Populate(services); ContainerBuilder.AddService(); var container = ContainerBuilder.Build(); return new AutofacServiceProvider(container); } ``` How can I solve this problem?
2019/09/27
[ "https://Stackoverflow.com/questions/58133507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11196342/" ]
Startup syntax has changed for configuring Autofac for ASP.NET Core 3.0+ In addition to using the following on the host builder ``` .UseServiceProviderFactory(new AutofacServiceProviderFactory()) ``` In `Startup` do the following format ``` public void ConfigureServices(IServiceCollection services) { //... normal registration here // Add services to the collection. Don't build or return // any IServiceProvider or the ConfigureContainer method // won't get called. services.AddControllers(); } // ConfigureContainer is where you can register things directly // with Autofac. This runs after ConfigureServices so the things // here will override registrations made in ConfigureServices. // Don't build the container; that gets done for you. If you // need a reference to the container, you need to use the // "Without ConfigureContainer" mechanism shown later. public void ConfigureContainer(ContainerBuilder builder) { // Register your own things directly with Autofac builder.AddMyCustomService(); //... } ``` Reference [Autofac documentation](https://docs.autofac.org/en/latest/integration/aspnetcore.html#asp-net-core-3-0-and-generic-hosting) for ASP.NET Core 3.0+
Instead of `Host` in Program.cs you can use `WebHost` ``` public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } ``` In this case following code works ``` public IServiceProvider ConfigureServices(IServiceCollection services) { ... var builder = new ContainerBuilder(); builder.Populate(services); var container = builder.Build(); return new AutofacServiceProvider(container); } ```
58,133,507
I need ti use this `AutoFac` in ASP core 3.0 When I use this code in startu up: ``` public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddControllers(); return services.BuildAutofacServiceProvider(); } ``` It show me this error: > > 'ConfigureServices returning an System.IServiceProvider isn't supported.' > > > And I change the program.cs by this: ``` public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseServiceProviderFactory(new AutofacServiceProviderFactory()) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } ``` But it not solved. This is `BuildAutofacServiceProvider()` Code: ``` public static IServiceProvider BuildAutofacServiceProvider(this IServiceCollection services) { var ContainerBuilder = new ContainerBuilder(); ContainerBuilder.Populate(services); ContainerBuilder.AddService(); var container = ContainerBuilder.Build(); return new AutofacServiceProvider(container); } ``` How can I solve this problem?
2019/09/27
[ "https://Stackoverflow.com/questions/58133507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11196342/" ]
Startup syntax has changed for configuring Autofac for ASP.NET Core 3.0+ In addition to using the following on the host builder ``` .UseServiceProviderFactory(new AutofacServiceProviderFactory()) ``` In `Startup` do the following format ``` public void ConfigureServices(IServiceCollection services) { //... normal registration here // Add services to the collection. Don't build or return // any IServiceProvider or the ConfigureContainer method // won't get called. services.AddControllers(); } // ConfigureContainer is where you can register things directly // with Autofac. This runs after ConfigureServices so the things // here will override registrations made in ConfigureServices. // Don't build the container; that gets done for you. If you // need a reference to the container, you need to use the // "Without ConfigureContainer" mechanism shown later. public void ConfigureContainer(ContainerBuilder builder) { // Register your own things directly with Autofac builder.AddMyCustomService(); //... } ``` Reference [Autofac documentation](https://docs.autofac.org/en/latest/integration/aspnetcore.html#asp-net-core-3-0-and-generic-hosting) for ASP.NET Core 3.0+
Instead of Host use WebHost in Program.cs It work for me ...
58,133,507
I need ti use this `AutoFac` in ASP core 3.0 When I use this code in startu up: ``` public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddControllers(); return services.BuildAutofacServiceProvider(); } ``` It show me this error: > > 'ConfigureServices returning an System.IServiceProvider isn't supported.' > > > And I change the program.cs by this: ``` public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseServiceProviderFactory(new AutofacServiceProviderFactory()) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } ``` But it not solved. This is `BuildAutofacServiceProvider()` Code: ``` public static IServiceProvider BuildAutofacServiceProvider(this IServiceCollection services) { var ContainerBuilder = new ContainerBuilder(); ContainerBuilder.Populate(services); ContainerBuilder.AddService(); var container = ContainerBuilder.Build(); return new AutofacServiceProvider(container); } ``` How can I solve this problem?
2019/09/27
[ "https://Stackoverflow.com/questions/58133507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11196342/" ]
Startup syntax has changed for configuring Autofac for ASP.NET Core 3.0+ In addition to using the following on the host builder ``` .UseServiceProviderFactory(new AutofacServiceProviderFactory()) ``` In `Startup` do the following format ``` public void ConfigureServices(IServiceCollection services) { //... normal registration here // Add services to the collection. Don't build or return // any IServiceProvider or the ConfigureContainer method // won't get called. services.AddControllers(); } // ConfigureContainer is where you can register things directly // with Autofac. This runs after ConfigureServices so the things // here will override registrations made in ConfigureServices. // Don't build the container; that gets done for you. If you // need a reference to the container, you need to use the // "Without ConfigureContainer" mechanism shown later. public void ConfigureContainer(ContainerBuilder builder) { // Register your own things directly with Autofac builder.AddMyCustomService(); //... } ``` Reference [Autofac documentation](https://docs.autofac.org/en/latest/integration/aspnetcore.html#asp-net-core-3-0-and-generic-hosting) for ASP.NET Core 3.0+
you must change program.c ``` public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureLogging(options => options.ClearProviders()) .UseStartup<Startup>(); ```
58,133,507
I need ti use this `AutoFac` in ASP core 3.0 When I use this code in startu up: ``` public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddControllers(); return services.BuildAutofacServiceProvider(); } ``` It show me this error: > > 'ConfigureServices returning an System.IServiceProvider isn't supported.' > > > And I change the program.cs by this: ``` public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseServiceProviderFactory(new AutofacServiceProviderFactory()) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } ``` But it not solved. This is `BuildAutofacServiceProvider()` Code: ``` public static IServiceProvider BuildAutofacServiceProvider(this IServiceCollection services) { var ContainerBuilder = new ContainerBuilder(); ContainerBuilder.Populate(services); ContainerBuilder.AddService(); var container = ContainerBuilder.Build(); return new AutofacServiceProvider(container); } ``` How can I solve this problem?
2019/09/27
[ "https://Stackoverflow.com/questions/58133507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11196342/" ]
Instead of `Host` in Program.cs you can use `WebHost` ``` public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } ``` In this case following code works ``` public IServiceProvider ConfigureServices(IServiceCollection services) { ... var builder = new ContainerBuilder(); builder.Populate(services); var container = builder.Build(); return new AutofacServiceProvider(container); } ```
Instead of Host use WebHost in Program.cs It work for me ...
58,133,507
I need ti use this `AutoFac` in ASP core 3.0 When I use this code in startu up: ``` public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddControllers(); return services.BuildAutofacServiceProvider(); } ``` It show me this error: > > 'ConfigureServices returning an System.IServiceProvider isn't supported.' > > > And I change the program.cs by this: ``` public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseServiceProviderFactory(new AutofacServiceProviderFactory()) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } ``` But it not solved. This is `BuildAutofacServiceProvider()` Code: ``` public static IServiceProvider BuildAutofacServiceProvider(this IServiceCollection services) { var ContainerBuilder = new ContainerBuilder(); ContainerBuilder.Populate(services); ContainerBuilder.AddService(); var container = ContainerBuilder.Build(); return new AutofacServiceProvider(container); } ``` How can I solve this problem?
2019/09/27
[ "https://Stackoverflow.com/questions/58133507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11196342/" ]
Instead of `Host` in Program.cs you can use `WebHost` ``` public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } ``` In this case following code works ``` public IServiceProvider ConfigureServices(IServiceCollection services) { ... var builder = new ContainerBuilder(); builder.Populate(services); var container = builder.Build(); return new AutofacServiceProvider(container); } ```
you must change program.c ``` public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureLogging(options => options.ClearProviders()) .UseStartup<Startup>(); ```
58,133,507
I need ti use this `AutoFac` in ASP core 3.0 When I use this code in startu up: ``` public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddControllers(); return services.BuildAutofacServiceProvider(); } ``` It show me this error: > > 'ConfigureServices returning an System.IServiceProvider isn't supported.' > > > And I change the program.cs by this: ``` public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseServiceProviderFactory(new AutofacServiceProviderFactory()) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } ``` But it not solved. This is `BuildAutofacServiceProvider()` Code: ``` public static IServiceProvider BuildAutofacServiceProvider(this IServiceCollection services) { var ContainerBuilder = new ContainerBuilder(); ContainerBuilder.Populate(services); ContainerBuilder.AddService(); var container = ContainerBuilder.Build(); return new AutofacServiceProvider(container); } ``` How can I solve this problem?
2019/09/27
[ "https://Stackoverflow.com/questions/58133507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11196342/" ]
you must change program.c ``` public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureLogging(options => options.ClearProviders()) .UseStartup<Startup>(); ```
Instead of Host use WebHost in Program.cs It work for me ...
25,134,756
Hi guys i am using Html minifier [ref](http://deanhume.com/home/blogpost/a-simple-html-minifier-for-asp-net/2097),but I am getting error in code-`An opening "(" is missing the corresponding closing ").` Is there any possible way to resolve or anyone have used this,please share your way to use this minifier. Adding to this - is there any way to **minimize html** in MVC4? Thanks in advance.
2014/08/05
[ "https://Stackoverflow.com/questions/25134756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3859458/" ]
Thanks for suggestions. I got all of information about the interfaces with the following code. Also, InetAddress class does not work correctly in Linux. (I tried get hardware adress in linux) But the code work on windows and linux correctly. ``` import java.io.*; import java.net.*; import java.util.*; import static java.lang.System.out; public class GetInfo { public static void main(String args[]) throws SocketException { Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces(); for (NetworkInterface netint : Collections.list(nets)) displayInterfaceInformation(netint); } static void displayInterfaceInformation(NetworkInterface netint) throws SocketException { out.printf("Display name: %s\n", netint.getDisplayName()); out.printf("Name: %s\n", netint.getName()); Enumeration<InetAddress> inetAddresses = netint.getInetAddresses(); for (InetAddress inetAddress : Collections.list(inetAddresses)) { out.printf("InetAddress: %s\n", inetAddress); } out.printf("Up? %s\n", netint.isUp()); out.printf("Loopback? %s\n", netint.isLoopback()); out.printf("PointToPoint? %s\n", netint.isPointToPoint()); out.printf("Supports multicast? %s\n", netint.supportsMulticast()); out.printf("Virtual? %s\n", netint.isVirtual()); out.printf("Hardware address: %s\n", Arrays.toString(netint.getHardwareAddress())); out.printf("MTU: %s\n", netint.getMTU()); out.printf("\n"); } } ``` Regards.
You can use the `Inet6Address` subclass see <http://docs.oracle.com/javase/6/docs/api/java/net/Inet6Address.html>
25,134,756
Hi guys i am using Html minifier [ref](http://deanhume.com/home/blogpost/a-simple-html-minifier-for-asp-net/2097),but I am getting error in code-`An opening "(" is missing the corresponding closing ").` Is there any possible way to resolve or anyone have used this,please share your way to use this minifier. Adding to this - is there any way to **minimize html** in MVC4? Thanks in advance.
2014/08/05
[ "https://Stackoverflow.com/questions/25134756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3859458/" ]
``` private static String getIPAddress(boolean v6) throws SocketException { Enumeration<NetworkInterface> netInts = NetworkInterface.getNetworkInterfaces(); for (NetworkInterface netInt : Collections.list(netInts)) { if (netInt.isUp() && !netInt.isLoopback()) { for (InetAddress inetAddress : Collections.list(netInt.getInetAddresses())) { if (inetAddress.isLoopbackAddress() || inetAddress.isLinkLocalAddress() || inetAddress.isMulticastAddress()) { continue; } if (v6 && inetAddress instanceof Inet6Address) { return inetAddress.getHostAddress(); } if (!v6 && inetAddress instanceof InetAddress) { return inetAddress.getHostAddress(); } } } } return null; } ```
You can use the `Inet6Address` subclass see <http://docs.oracle.com/javase/6/docs/api/java/net/Inet6Address.html>
25,134,756
Hi guys i am using Html minifier [ref](http://deanhume.com/home/blogpost/a-simple-html-minifier-for-asp-net/2097),but I am getting error in code-`An opening "(" is missing the corresponding closing ").` Is there any possible way to resolve or anyone have used this,please share your way to use this minifier. Adding to this - is there any way to **minimize html** in MVC4? Thanks in advance.
2014/08/05
[ "https://Stackoverflow.com/questions/25134756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3859458/" ]
Thanks for suggestions. I got all of information about the interfaces with the following code. Also, InetAddress class does not work correctly in Linux. (I tried get hardware adress in linux) But the code work on windows and linux correctly. ``` import java.io.*; import java.net.*; import java.util.*; import static java.lang.System.out; public class GetInfo { public static void main(String args[]) throws SocketException { Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces(); for (NetworkInterface netint : Collections.list(nets)) displayInterfaceInformation(netint); } static void displayInterfaceInformation(NetworkInterface netint) throws SocketException { out.printf("Display name: %s\n", netint.getDisplayName()); out.printf("Name: %s\n", netint.getName()); Enumeration<InetAddress> inetAddresses = netint.getInetAddresses(); for (InetAddress inetAddress : Collections.list(inetAddresses)) { out.printf("InetAddress: %s\n", inetAddress); } out.printf("Up? %s\n", netint.isUp()); out.printf("Loopback? %s\n", netint.isLoopback()); out.printf("PointToPoint? %s\n", netint.isPointToPoint()); out.printf("Supports multicast? %s\n", netint.supportsMulticast()); out.printf("Virtual? %s\n", netint.isVirtual()); out.printf("Hardware address: %s\n", Arrays.toString(netint.getHardwareAddress())); out.printf("MTU: %s\n", netint.getMTU()); out.printf("\n"); } } ``` Regards.
``` private static String getIPAddress(boolean v6) throws SocketException { Enumeration<NetworkInterface> netInts = NetworkInterface.getNetworkInterfaces(); for (NetworkInterface netInt : Collections.list(netInts)) { if (netInt.isUp() && !netInt.isLoopback()) { for (InetAddress inetAddress : Collections.list(netInt.getInetAddresses())) { if (inetAddress.isLoopbackAddress() || inetAddress.isLinkLocalAddress() || inetAddress.isMulticastAddress()) { continue; } if (v6 && inetAddress instanceof Inet6Address) { return inetAddress.getHostAddress(); } if (!v6 && inetAddress instanceof InetAddress) { return inetAddress.getHostAddress(); } } } } return null; } ```
40,706,788
I'm getting the following error: > > the given data failed to pass validation. /home/vagrant/Code/laravel/ptm/vendor/laravel/framework/src/Illuminate/Foundation/Validation/ValidatesRequests.php#89 > > > When I look at the `$data`, it's filled with: ``` array:1 [ "{"_token":"Z5fv3XpoNwoMdJPRP16I09bZeX7Pb6raH30K8n3b","name":"test","id":"","email":"test@example_com","password":"testing"}" ] ``` Here's the code: ``` public function create(Request $request) { $data = $request->all(); $this->validate($request, ['name' => 'required', 'email' => 'required', 'password' => 'required' ]); try { $this->user->create($request); } catch (Exception $e) { return json_encode(array('success' => false, 'message' => 'Something went wrong, please try again later.')); } return json_encode(array('success' => true, 'message' => 'User successfully saved!')); } ```
2016/11/20
[ "https://Stackoverflow.com/questions/40706788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3552264/" ]
It's clearly saying that the `validate()` method is throwing an exception. If you want it to not to throw an exception, update your `App\Exceptions\Handler` class and add `ValidationException` to the `$dontReport` array: ``` class Handler extends ExceptionHandler { /** * A list of the exception types that should not be reported. * * @var array */ protected $dontReport = [ \Illuminate\Auth\AuthenticationException::class, \Illuminate\Auth\Access\AuthorizationException::class, \Symfony\Component\HttpKernel\Exception\HttpException::class, \Illuminate\Database\Eloquent\ModelNotFoundException::class, \Illuminate\Session\TokenMismatchException::class, \Illuminate\Validation\ValidationException::class, // <= Here ]; ``` Read more: [Documentation how to migrate from Laravel 5.1 to 5.2](https://laravel.com/docs/master/upgrade#upgrade-5.2.0) Or you can leave it as it is, and handle the exception in a new `catch` block: ``` public function create(Request $request) { try { $this->validate($request, [ 'name' => 'required', 'email' => 'required', 'password' => 'required' ]); $this->user->create($request); } catch (ValidationException $e) { return response()->json([ 'success' => false, 'message' => 'There were validation errors.', ], 400); } catch (Exception $e) { return response()->json([ 'success' => false, 'message' => 'Something went wrong, please try again later.' ], 400); } return response()->json([ 'success' => true, 'message' => 'User successfully saved!' ], 201); } ```
You might check the blade template for the correct case on the variables. e.g. 'name', 'email' and 'password' are case sensitive and the blade template case of the variables must match the controller's case for the variables.
6,449
Does anyone know what the proper ancient Egyptian name for the Hall of Truth, Hall of Two Truths, or Hall of Judgement is? This is the hall where a soul is weighed on a scale against the feather of Ma'at. I've tried several google searches to no avail. Ma'at means truth, and the words wADyt and iwynt both mean a specific type of columned hall. The word wpt means judgement. I am just uncertain of the order they would go in, or which one is historically accurate. Any help would be greatly appreciated.
2020/07/07
[ "https://mythology.stackexchange.com/questions/6449", "https://mythology.stackexchange.com", "https://mythology.stackexchange.com/users/6739/" ]
[Hebe](https://en.wikipedia.org/wiki/Hebe_(mythology)) ------------------------------------------------------ Hebe was the cup-bearer and poured ambrosia and nectar of the gods. You might know her better as the wife of Hercules, who upon his ascension to Mount Olympus "got" her from his enemy and her mother Hera as reconciliation. > > "Now the gods at the side of Zeus were sitting in council over the golden floor, and among them the goddess Hebe (Youth) poured them nectar as wine, while they in the golden drinking-cups drank to each other, gazing down on the city of the Trojans."Homer, Iliad 4 > > > [Ganymede](https://en.wikipedia.org/wiki/Ganymede_(mythology)) -------------------------------------------------------------- After the marriage between Hercules and Hebe Ganymede became the next cup-bearer. > > "Verily wise Zeus carried off golden-haired Ganymedes (Ganymede) because of his beauty, to be amongst the Deathless Ones and pour drink for the gods in the house of Zeus--a wonder to see--, honoured by all the immortals as he draws the red nectar from the golden bowl deathless and unageing, even as the gods." Homeric Hymn 5 to Aphrodite 203 > > > . > > "He that pours wine for Zeus [Ganymedes] was an oxherd." > Nonnus, Dionysiaca 15. 279 > > > . > > Ganymede was the loveliest born of the race of mortals, and therefore > the gods caught him away to themselves, to be Zeus' wine-pourer, > for the sake of his beauty, so he might be among the immortals. Homer, Iliad, Book 20 > > > [Juventus](https://en.wikipedia.org/wiki/Juventas) -------------------------------------------------- Juventus was the Roman equivalent to Hebe and Ganymede > > "What viands and beverages, what harmonies of music and flowers of > various hue, what delights of touch and smell will you assign to the > gods, so as to keep them steeped in pleasure? The poets array banquets > or nectar and ambrosia, with Juventas (Hebe or Ganymede) in attendance > as cup-bearer." Cicero, De Natura Deorum 1. 40 > > >
In the book Odyssey, it's said that ambrosia was carried to Olympus by doves [1]: > > Here not even a bird may pass, no, not even **the timid doves that bring ambrosia to Father Jove**, but the sheer rock always carries off one of them, and Father Jove has to send another to make up their number > > > Also, Demeter was considered the goddess of crops and agriculture, being intrinsically linked to food. The Roman goddess counterpart is Ceres. [2] Ceraon, Deipneo and Matton are greek semi-gods related to food. More specifically the bread preparation stages. To Romans, Abundantia was the personification of abundance, carring the Cornucopia - presented as a large horn-shaped container overflowing with produce, flowers, or nuts [3][4] --- *References* [1] HOMER. The Odyssey. 1:Translated by Samuel Butler. p. 202. [2] FINLEY, M. I.. The World of Odysseus. 4. ed. New York: New Yorknyrb Classics, 2002. [4] Apollodorus. The Library of Greek Mythology. 1. ed. Oxford University Press, 2008. [4] PARKER, R. Polytheism and Society at Athens. OUP Oxford, 2005.
6,449
Does anyone know what the proper ancient Egyptian name for the Hall of Truth, Hall of Two Truths, or Hall of Judgement is? This is the hall where a soul is weighed on a scale against the feather of Ma'at. I've tried several google searches to no avail. Ma'at means truth, and the words wADyt and iwynt both mean a specific type of columned hall. The word wpt means judgement. I am just uncertain of the order they would go in, or which one is historically accurate. Any help would be greatly appreciated.
2020/07/07
[ "https://mythology.stackexchange.com/questions/6449", "https://mythology.stackexchange.com", "https://mythology.stackexchange.com/users/6739/" ]
In the book Odyssey, it's said that ambrosia was carried to Olympus by doves [1]: > > Here not even a bird may pass, no, not even **the timid doves that bring ambrosia to Father Jove**, but the sheer rock always carries off one of them, and Father Jove has to send another to make up their number > > > Also, Demeter was considered the goddess of crops and agriculture, being intrinsically linked to food. The Roman goddess counterpart is Ceres. [2] Ceraon, Deipneo and Matton are greek semi-gods related to food. More specifically the bread preparation stages. To Romans, Abundantia was the personification of abundance, carring the Cornucopia - presented as a large horn-shaped container overflowing with produce, flowers, or nuts [3][4] --- *References* [1] HOMER. The Odyssey. 1:Translated by Samuel Butler. p. 202. [2] FINLEY, M. I.. The World of Odysseus. 4. ed. New York: New Yorknyrb Classics, 2002. [4] Apollodorus. The Library of Greek Mythology. 1. ed. Oxford University Press, 2008. [4] PARKER, R. Polytheism and Society at Athens. OUP Oxford, 2005.
Demeter was the goddess of the harvest and often put on banquets for the gods and sometimes mortals. You also have Pan who was worshipped as the "party god" and/or Dionysus God of the vine.
6,449
Does anyone know what the proper ancient Egyptian name for the Hall of Truth, Hall of Two Truths, or Hall of Judgement is? This is the hall where a soul is weighed on a scale against the feather of Ma'at. I've tried several google searches to no avail. Ma'at means truth, and the words wADyt and iwynt both mean a specific type of columned hall. The word wpt means judgement. I am just uncertain of the order they would go in, or which one is historically accurate. Any help would be greatly appreciated.
2020/07/07
[ "https://mythology.stackexchange.com/questions/6449", "https://mythology.stackexchange.com", "https://mythology.stackexchange.com/users/6739/" ]
In the book Odyssey, it's said that ambrosia was carried to Olympus by doves [1]: > > Here not even a bird may pass, no, not even **the timid doves that bring ambrosia to Father Jove**, but the sheer rock always carries off one of them, and Father Jove has to send another to make up their number > > > Also, Demeter was considered the goddess of crops and agriculture, being intrinsically linked to food. The Roman goddess counterpart is Ceres. [2] Ceraon, Deipneo and Matton are greek semi-gods related to food. More specifically the bread preparation stages. To Romans, Abundantia was the personification of abundance, carring the Cornucopia - presented as a large horn-shaped container overflowing with produce, flowers, or nuts [3][4] --- *References* [1] HOMER. The Odyssey. 1:Translated by Samuel Butler. p. 202. [2] FINLEY, M. I.. The World of Odysseus. 4. ed. New York: New Yorknyrb Classics, 2002. [4] Apollodorus. The Library of Greek Mythology. 1. ed. Oxford University Press, 2008. [4] PARKER, R. Polytheism and Society at Athens. OUP Oxford, 2005.
**Ganymede** was a Trojan prince. Zeus turned into an eagle and kidnapped the prince, eventually bringing him to the Mount Olympus and giving him the title of the cup-bearer. Ganymede then provided the Gods with ambrosia - drink which made the Gods immortal - in his Crater (cup). In mosaic art Ganymede is shown as a handsome young boy surrounded by Aquila (Zeus as an eagle), holding his Crater. <https://www.theoi.com/Ouranios/Ganymedes.html> via Homer ( Homer's Iliad) and Hesoid (Catalogues of Women Frag)
6,449
Does anyone know what the proper ancient Egyptian name for the Hall of Truth, Hall of Two Truths, or Hall of Judgement is? This is the hall where a soul is weighed on a scale against the feather of Ma'at. I've tried several google searches to no avail. Ma'at means truth, and the words wADyt and iwynt both mean a specific type of columned hall. The word wpt means judgement. I am just uncertain of the order they would go in, or which one is historically accurate. Any help would be greatly appreciated.
2020/07/07
[ "https://mythology.stackexchange.com/questions/6449", "https://mythology.stackexchange.com", "https://mythology.stackexchange.com/users/6739/" ]
[Hebe](https://en.wikipedia.org/wiki/Hebe_(mythology)) ------------------------------------------------------ Hebe was the cup-bearer and poured ambrosia and nectar of the gods. You might know her better as the wife of Hercules, who upon his ascension to Mount Olympus "got" her from his enemy and her mother Hera as reconciliation. > > "Now the gods at the side of Zeus were sitting in council over the golden floor, and among them the goddess Hebe (Youth) poured them nectar as wine, while they in the golden drinking-cups drank to each other, gazing down on the city of the Trojans."Homer, Iliad 4 > > > [Ganymede](https://en.wikipedia.org/wiki/Ganymede_(mythology)) -------------------------------------------------------------- After the marriage between Hercules and Hebe Ganymede became the next cup-bearer. > > "Verily wise Zeus carried off golden-haired Ganymedes (Ganymede) because of his beauty, to be amongst the Deathless Ones and pour drink for the gods in the house of Zeus--a wonder to see--, honoured by all the immortals as he draws the red nectar from the golden bowl deathless and unageing, even as the gods." Homeric Hymn 5 to Aphrodite 203 > > > . > > "He that pours wine for Zeus [Ganymedes] was an oxherd." > Nonnus, Dionysiaca 15. 279 > > > . > > Ganymede was the loveliest born of the race of mortals, and therefore > the gods caught him away to themselves, to be Zeus' wine-pourer, > for the sake of his beauty, so he might be among the immortals. Homer, Iliad, Book 20 > > > [Juventus](https://en.wikipedia.org/wiki/Juventas) -------------------------------------------------- Juventus was the Roman equivalent to Hebe and Ganymede > > "What viands and beverages, what harmonies of music and flowers of > various hue, what delights of touch and smell will you assign to the > gods, so as to keep them steeped in pleasure? The poets array banquets > or nectar and ambrosia, with Juventas (Hebe or Ganymede) in attendance > as cup-bearer." Cicero, De Natura Deorum 1. 40 > > >
Demeter was the goddess of the harvest and often put on banquets for the gods and sometimes mortals. You also have Pan who was worshipped as the "party god" and/or Dionysus God of the vine.
6,449
Does anyone know what the proper ancient Egyptian name for the Hall of Truth, Hall of Two Truths, or Hall of Judgement is? This is the hall where a soul is weighed on a scale against the feather of Ma'at. I've tried several google searches to no avail. Ma'at means truth, and the words wADyt and iwynt both mean a specific type of columned hall. The word wpt means judgement. I am just uncertain of the order they would go in, or which one is historically accurate. Any help would be greatly appreciated.
2020/07/07
[ "https://mythology.stackexchange.com/questions/6449", "https://mythology.stackexchange.com", "https://mythology.stackexchange.com/users/6739/" ]
[Hebe](https://en.wikipedia.org/wiki/Hebe_(mythology)) ------------------------------------------------------ Hebe was the cup-bearer and poured ambrosia and nectar of the gods. You might know her better as the wife of Hercules, who upon his ascension to Mount Olympus "got" her from his enemy and her mother Hera as reconciliation. > > "Now the gods at the side of Zeus were sitting in council over the golden floor, and among them the goddess Hebe (Youth) poured them nectar as wine, while they in the golden drinking-cups drank to each other, gazing down on the city of the Trojans."Homer, Iliad 4 > > > [Ganymede](https://en.wikipedia.org/wiki/Ganymede_(mythology)) -------------------------------------------------------------- After the marriage between Hercules and Hebe Ganymede became the next cup-bearer. > > "Verily wise Zeus carried off golden-haired Ganymedes (Ganymede) because of his beauty, to be amongst the Deathless Ones and pour drink for the gods in the house of Zeus--a wonder to see--, honoured by all the immortals as he draws the red nectar from the golden bowl deathless and unageing, even as the gods." Homeric Hymn 5 to Aphrodite 203 > > > . > > "He that pours wine for Zeus [Ganymedes] was an oxherd." > Nonnus, Dionysiaca 15. 279 > > > . > > Ganymede was the loveliest born of the race of mortals, and therefore > the gods caught him away to themselves, to be Zeus' wine-pourer, > for the sake of his beauty, so he might be among the immortals. Homer, Iliad, Book 20 > > > [Juventus](https://en.wikipedia.org/wiki/Juventas) -------------------------------------------------- Juventus was the Roman equivalent to Hebe and Ganymede > > "What viands and beverages, what harmonies of music and flowers of > various hue, what delights of touch and smell will you assign to the > gods, so as to keep them steeped in pleasure? The poets array banquets > or nectar and ambrosia, with Juventas (Hebe or Ganymede) in attendance > as cup-bearer." Cicero, De Natura Deorum 1. 40 > > >
**Ganymede** was a Trojan prince. Zeus turned into an eagle and kidnapped the prince, eventually bringing him to the Mount Olympus and giving him the title of the cup-bearer. Ganymede then provided the Gods with ambrosia - drink which made the Gods immortal - in his Crater (cup). In mosaic art Ganymede is shown as a handsome young boy surrounded by Aquila (Zeus as an eagle), holding his Crater. <https://www.theoi.com/Ouranios/Ganymedes.html> via Homer ( Homer's Iliad) and Hesoid (Catalogues of Women Frag)
6,449
Does anyone know what the proper ancient Egyptian name for the Hall of Truth, Hall of Two Truths, or Hall of Judgement is? This is the hall where a soul is weighed on a scale against the feather of Ma'at. I've tried several google searches to no avail. Ma'at means truth, and the words wADyt and iwynt both mean a specific type of columned hall. The word wpt means judgement. I am just uncertain of the order they would go in, or which one is historically accurate. Any help would be greatly appreciated.
2020/07/07
[ "https://mythology.stackexchange.com/questions/6449", "https://mythology.stackexchange.com", "https://mythology.stackexchange.com/users/6739/" ]
Demeter was the goddess of the harvest and often put on banquets for the gods and sometimes mortals. You also have Pan who was worshipped as the "party god" and/or Dionysus God of the vine.
**Ganymede** was a Trojan prince. Zeus turned into an eagle and kidnapped the prince, eventually bringing him to the Mount Olympus and giving him the title of the cup-bearer. Ganymede then provided the Gods with ambrosia - drink which made the Gods immortal - in his Crater (cup). In mosaic art Ganymede is shown as a handsome young boy surrounded by Aquila (Zeus as an eagle), holding his Crater. <https://www.theoi.com/Ouranios/Ganymedes.html> via Homer ( Homer's Iliad) and Hesoid (Catalogues of Women Frag)
72,243,659
So I made this basic checkbox price app that updates the food price whenever you click on a checkbox option <https://codepen.io/shodoro/pen/GRQNXyq> However, I had to hard code the prices in the javascript, but I want to know how I can update the prices based on the value in the input tag So for this example in the index.html the value is set to 10, so instead of hard coding the price of 10 in JS, I can just add the value attribute instead ``` <input type="checkbox" name="item1" id="item1" value="10" onClick="updatePrice()"> ``` Also, how would I make my code scalable? because right now I wrote a bunch of if else if else statments manually, however if I were to add 50 new menu items, then that wouldn't be feasible for my JS code. ``` function updatePrice() { let price = 0.00; if (document.getElementById("item1").checked == true) { price = 10; } if (document.getElementById("item2").checked == true && document.getElementById("item1").checked == true) { price = 17; } else if(document.getElementById("item2").checked == true) { price = 7 } if (document.getElementById("item3").checked == true && document.getElementById("item1").checked == true && document.getElementById("item2").checked == true) { price = 20; } else if (document.getElementById("item3").checked == true && document.getElementById("item1").checked == true) { price = 13 } else if (document.getElementById("item3").checked == true && document.getElementById("item2").checked == true) { price = 10 } else if (document.getElementById("item3").checked == true){ price = 3 } document.getElementById("price").innerText = "Your order total is: $" + price; } ``` Lastly, I have the basic total part for the food to work, but I don't know how I would convert my JS code to also include the delivery fees, taxes, tip % added to the final total? Any ideas?
2022/05/14
[ "https://Stackoverflow.com/questions/72243659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19059575/" ]
solution ======== Ok, with some other research i found out how to solve my problem. But firstable I want to thank you guys for recommending me the PyScript library. The problem I was having is that i needed to connect a python file within the pyscript tag. At first i tought that I had to import it with the `import` keyword and than executing the file. But than I discovered that the py-script tag has an `src` attribute and you can link all the external files that you want. So, in the end, iall i had to do was to connect my file is this: ``` <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>newGame</title> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <py-script src= "./python scripts/test_file.py"></py-script> <script src="script.js"></script> </body> <script defer src="https://pyscript.net/alpha/pyscript.js"></script> </html> ```
There is a new library called PyScript (it can help you run python in your HTML), all you need to do to install the cli is doing this command: `pip install pyscript-cli` (This command will install the cli not the library). then you should do this command: `pyscript wrap python_file.py` (NOTE: this will convert the python file to an html file so the python file name would be the name of the html file) And it should be done. The HTML code would be this: ```html <!DOCTYPE html> <html lang="en"> <head> <title>Homepage</title> <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css"/> <script defer src="https://pyscript.net/alpha/pyscript.js"></script> </head> <body> <py-script> Code here </py-script> </body> </html> ```
72,243,659
So I made this basic checkbox price app that updates the food price whenever you click on a checkbox option <https://codepen.io/shodoro/pen/GRQNXyq> However, I had to hard code the prices in the javascript, but I want to know how I can update the prices based on the value in the input tag So for this example in the index.html the value is set to 10, so instead of hard coding the price of 10 in JS, I can just add the value attribute instead ``` <input type="checkbox" name="item1" id="item1" value="10" onClick="updatePrice()"> ``` Also, how would I make my code scalable? because right now I wrote a bunch of if else if else statments manually, however if I were to add 50 new menu items, then that wouldn't be feasible for my JS code. ``` function updatePrice() { let price = 0.00; if (document.getElementById("item1").checked == true) { price = 10; } if (document.getElementById("item2").checked == true && document.getElementById("item1").checked == true) { price = 17; } else if(document.getElementById("item2").checked == true) { price = 7 } if (document.getElementById("item3").checked == true && document.getElementById("item1").checked == true && document.getElementById("item2").checked == true) { price = 20; } else if (document.getElementById("item3").checked == true && document.getElementById("item1").checked == true) { price = 13 } else if (document.getElementById("item3").checked == true && document.getElementById("item2").checked == true) { price = 10 } else if (document.getElementById("item3").checked == true){ price = 3 } document.getElementById("price").innerText = "Your order total is: $" + price; } ``` Lastly, I have the basic total part for the food to work, but I don't know how I would convert my JS code to also include the delivery fees, taxes, tip % added to the final total? Any ideas?
2022/05/14
[ "https://Stackoverflow.com/questions/72243659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19059575/" ]
solution ======== Ok, with some other research i found out how to solve my problem. But firstable I want to thank you guys for recommending me the PyScript library. The problem I was having is that i needed to connect a python file within the pyscript tag. At first i tought that I had to import it with the `import` keyword and than executing the file. But than I discovered that the py-script tag has an `src` attribute and you can link all the external files that you want. So, in the end, iall i had to do was to connect my file is this: ``` <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>newGame</title> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <py-script src= "./python scripts/test_file.py"></py-script> <script src="script.js"></script> </body> <script defer src="https://pyscript.net/alpha/pyscript.js"></script> </html> ```
But than, once i typed in the command and created the html file from the python script, how do I connect it to the "newLevel" page?
4,738,051
Here's what I'm using to create my database: ``` DataMapper.setup(:default,"sqlite://my.db") class Model1 property :some_prop,String ... property :other_prop,String end DataMapper.auto_upgrade! ``` I'm using this in combination with Sinatra. Everything's ok while the script is running, I can use my objects normally. However, I see no file `my.db` on the disk, and everytime I'm restarting the application, I start from scratch, without any objects. What am I doing wrong?
2011/01/19
[ "https://Stackoverflow.com/questions/4738051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31610/" ]
Try putting the full path in there (note there are 3 forward slashes): ``` DataMapper.setup(:default, "sqlite:///path/to/my/database/my.db") ``` Then you should see `my.db` under `/path/to/my/database/`
``` DataMapper.setup(:default, "sqlite3://#{Dir.pwd}/my.db") # your schema DataMapper.finalize DataMapper.auto_upgrade! ``` Also see [docs.](http://datamapper.org/getting-started.html)
79,408
By default, `ParallelTable` will use all the processors available in a PC. Is there a way to set a limit to the number of processors used by `ParallelTable`? For example, suppose I am running a Mathematica Script which has a `ParallelTable` statement on a PC with 8 cores. I want to limit the number of cores used by the script to 4. How can I do this?
2015/04/09
[ "https://mathematica.stackexchange.com/questions/79408", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/534/" ]
Before evaluating `ParallelTable` just launch however many kernels you want to use: ``` LaunchKernels[4] ``` By default `ParallelTable` and the other `Parallel*` functions call `LaunchKernels[]` which will launch whatever you have configured(default is essentially `LaunchKernels[Min[$ProcessorCount, $MaxLicenseSubprocesses]]`).
To demonstrate evaluation in parallel computing on different number of kernels 1)Default list of kernels run for parallel computing ``` `$ConfiguredKernels` (*("<<`1` local kernels>>", 6]}*) ``` 2) Run `ParallelTable` on all kernels: ``` LaunchKernels[]; ParallelTable[Pause[1]; f[i], {i, 6}] // AbsoluteTiming (*{1.009058, {f[1], f[2], f[3], f[4], f[5], f[6]}}*) ``` This result demonstrates how `Pause[1]`is distributed on 6 kernels: Total 6 seconds of pause are executed on 6 Kernels in parallel resulting in 1 seconds of execution 3) Run `ParallelTable` on only two kernels: ``` CloseKernels[]; LaunchKernels[2] ParallelTable[Pause[1]; f[i], {i, 6}] // AbsoluteTiming (*{KernelObject[37, "local"], KernelObject[38, "local"]} *) (*{3.004172, {f[1], f[2], f[3], f[4], f[5], f[6]}}*) ``` This result demonstrates how `Pause[1]` is distributed on 2 kernels: Total 6 seconds of pause are executed on 2 Kernels in parallel resulting in 3 seconds of execution
53,503,798
I'm trying to simulate a race between a red and a blue dot. A dot wins if it equals or exceeds the value inputted into the text box for distance. As of now, when you click the "Take a step!" button, each dot's location/distance goes up by 1. What I'm not sure how to do is get that location/distance to go up by a random integer, in this case, a random integer from 1 to 3. How can I do that? Here's what I have: ``` <!DOCTYPE html> <html lang="en"> <head> <title>Dot Race</title> <link href="dotrace.css" type="text/css" rel="stylesheet" /> <script type="text/javascript"> function TakeAStep() { var x, y, redcount, bluecount, distance; x = Math.floor(Math.random() * 3) + 1; y = Math.floor(Math.random() * 3) + 1; redcount = document.getElementById("reddotspan").innerHTML++; bluecount = document.getElementById("bluedotspan").innerHTML++; distance = parseFloat(document.getElementById("DistanceBox").value); if (redcount >= distance && bluecount >= distance) { alert("They tied!"); } else if (redcount >= distance) { alert("Red wins!"); } else if (bluecount >= distance) { alert("Blue wins!"); } } </script> </head> <body> <h2>Dot Race</h2> <p> Race distance: <input type="text" id="DistanceBox" placeholder="0" /> <br> <span class="red">Red dot location:</span> <span id="reddotspan">0</span> <br> <span class="blue">Blue dot location:</span> <span id="bluedotspan">0</span> <hr> <input type="button" value="Take a step!" onclick="TakeAStep();" /> </p> <div id="OutputDiv"></div> </body> </html> ```
2018/11/27
[ "https://Stackoverflow.com/questions/53503798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10697564/" ]
You are incrementing the value of `redcount` and `bluecount` but that has nothing to do with `x` and `y`. I added these lines after `x=` and `y=`. Seems to fix the root cause. ``` document.getElementById("reddotspan").innerHTML=parseInt(document.getElementById("reddotspan").innerHTML)+x; redcount = document.getElementById("reddotspan").innerHTML; document.getElementById("bluedotspan").innerHTML=parseInt(document.getElementById("bluedotspan").innerHTML)+y; bluecount = document.getElementById("bluedotspan").innerHTML; distance = parseFloat(document.getElementById("DistanceBox").value); ```
You can use: ``` Math.round(Math.random()*3); ``` Math.random() returns a random number between 0 and 1. Multiply by 3 to get 3 as highest number. Round.
53,503,798
I'm trying to simulate a race between a red and a blue dot. A dot wins if it equals or exceeds the value inputted into the text box for distance. As of now, when you click the "Take a step!" button, each dot's location/distance goes up by 1. What I'm not sure how to do is get that location/distance to go up by a random integer, in this case, a random integer from 1 to 3. How can I do that? Here's what I have: ``` <!DOCTYPE html> <html lang="en"> <head> <title>Dot Race</title> <link href="dotrace.css" type="text/css" rel="stylesheet" /> <script type="text/javascript"> function TakeAStep() { var x, y, redcount, bluecount, distance; x = Math.floor(Math.random() * 3) + 1; y = Math.floor(Math.random() * 3) + 1; redcount = document.getElementById("reddotspan").innerHTML++; bluecount = document.getElementById("bluedotspan").innerHTML++; distance = parseFloat(document.getElementById("DistanceBox").value); if (redcount >= distance && bluecount >= distance) { alert("They tied!"); } else if (redcount >= distance) { alert("Red wins!"); } else if (bluecount >= distance) { alert("Blue wins!"); } } </script> </head> <body> <h2>Dot Race</h2> <p> Race distance: <input type="text" id="DistanceBox" placeholder="0" /> <br> <span class="red">Red dot location:</span> <span id="reddotspan">0</span> <br> <span class="blue">Blue dot location:</span> <span id="bluedotspan">0</span> <hr> <input type="button" value="Take a step!" onclick="TakeAStep();" /> </p> <div id="OutputDiv"></div> </body> </html> ```
2018/11/27
[ "https://Stackoverflow.com/questions/53503798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10697564/" ]
``` <!doctype html> <html lang="en"> <head> <title>Dot Race</title> <link href="dotrace.css" type="text/css" rel="stylesheet"></link> <script type="text/javascript"> function TakeAStep() { var x, y, redcount, bluecount, distance; x = Math.floor(Math.random() * 3) + 1 ; y = Math.floor(Math.random() * 3) + 1; current_red = +document.getElementById('reddotspan').innerText; current_blue = +document.getElementById('bluedotspan').innerText; redcount = current_red + x; bluecount = current_blue + y; document.getElementById('reddotspan').innerText = redcount; document.getElementById('bluedotspan').innerText = bluecount; distance = parseFloat(document.getElementById('DistanceBox').value); if (redcount >= distance && bluecount >= distance) { alert('They tied!'); } else if (redcount >= distance) { alert('Red wins!'); } else if (bluecount >= distance) { alert('Blue wins!') } } </script> </head> <body> <h2>Dot Race</h2> <p> Race distance: <input type="text" id="DistanceBox" placeholder="0"> <br> <span class="red">Red dot location:</span> <span id="reddotspan">0</span> <br> <span class="blue">Blue dot location:</span> <span id="bluedotspan">0</span> <hr> <input type="button" value="Take a step!" onclick="TakeAStep();"> </p> <div id="OutputDiv"></div> </body> </html> ```
You can use: ``` Math.round(Math.random()*3); ``` Math.random() returns a random number between 0 and 1. Multiply by 3 to get 3 as highest number. Round.
53,503,798
I'm trying to simulate a race between a red and a blue dot. A dot wins if it equals or exceeds the value inputted into the text box for distance. As of now, when you click the "Take a step!" button, each dot's location/distance goes up by 1. What I'm not sure how to do is get that location/distance to go up by a random integer, in this case, a random integer from 1 to 3. How can I do that? Here's what I have: ``` <!DOCTYPE html> <html lang="en"> <head> <title>Dot Race</title> <link href="dotrace.css" type="text/css" rel="stylesheet" /> <script type="text/javascript"> function TakeAStep() { var x, y, redcount, bluecount, distance; x = Math.floor(Math.random() * 3) + 1; y = Math.floor(Math.random() * 3) + 1; redcount = document.getElementById("reddotspan").innerHTML++; bluecount = document.getElementById("bluedotspan").innerHTML++; distance = parseFloat(document.getElementById("DistanceBox").value); if (redcount >= distance && bluecount >= distance) { alert("They tied!"); } else if (redcount >= distance) { alert("Red wins!"); } else if (bluecount >= distance) { alert("Blue wins!"); } } </script> </head> <body> <h2>Dot Race</h2> <p> Race distance: <input type="text" id="DistanceBox" placeholder="0" /> <br> <span class="red">Red dot location:</span> <span id="reddotspan">0</span> <br> <span class="blue">Blue dot location:</span> <span id="bluedotspan">0</span> <hr> <input type="button" value="Take a step!" onclick="TakeAStep();" /> </p> <div id="OutputDiv"></div> </body> </html> ```
2018/11/27
[ "https://Stackoverflow.com/questions/53503798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10697564/" ]
You were almost there. When you were using the ++ operator, you were modifying the current state of the innerHTML to just add one. Instead, you need to set it equal to the new value. You should also use Number.parseInt so it parses it to a number explicitly. Otherwise, if you do "0" + 1, it will result in "01". ```html <html lang="en"> <head> <title>Dot Race</title> <link href="dotrace.css" type="text/css" rel="stylesheet" /> <script type="text/javascript"> function TakeAStep() { var x, y, newRedNumber, newBlueNumber, distance; x = Math.ceil(Math.random() * 3); y = Math.ceil(Math.random() * 3); newRedNumber = Number.parseInt(document.getElementById('reddotspan').innerHTML) + x; newBlueNumber = Number.parseInt(document.getElementById('bluedotspan').innerHTML) + y; document.getElementById('reddotspan').innerHTML = newRedNumber; document.getElementById('bluedotspan').innerHTML = newBlueNumber; distance = parseFloat(document.getElementById('DistanceBox').value); var outputText = ""; if (newRedNumber >= distance && newBlueNumber >= distance) { outputText = 'They tied!'; } else if (newRedNumber >= distance) { outputText = 'Red wins!'; } else if (newBlueNumber >= distance) { outputText = 'Blue wins!'; } document.getElementById('OutputDiv').innerHTML = outputText; } </script> </head> <body> <h2>Dot Race</h2> <p> Race distance: <input type="text" id="DistanceBox" placeholder="0"> <br> <span class="red">Red dot location:</span> <span id="reddotspan">0</span> <br> <span class="blue">Blue dot location:</span> <span id="bluedotspan">0</span> <hr> <input type="button" value="Take a step!" onclick="TakeAStep();" /> <div id="OutputDiv"></div> </body> </html> ```
You can use: ``` Math.round(Math.random()*3); ``` Math.random() returns a random number between 0 and 1. Multiply by 3 to get 3 as highest number. Round.
53,503,798
I'm trying to simulate a race between a red and a blue dot. A dot wins if it equals or exceeds the value inputted into the text box for distance. As of now, when you click the "Take a step!" button, each dot's location/distance goes up by 1. What I'm not sure how to do is get that location/distance to go up by a random integer, in this case, a random integer from 1 to 3. How can I do that? Here's what I have: ``` <!DOCTYPE html> <html lang="en"> <head> <title>Dot Race</title> <link href="dotrace.css" type="text/css" rel="stylesheet" /> <script type="text/javascript"> function TakeAStep() { var x, y, redcount, bluecount, distance; x = Math.floor(Math.random() * 3) + 1; y = Math.floor(Math.random() * 3) + 1; redcount = document.getElementById("reddotspan").innerHTML++; bluecount = document.getElementById("bluedotspan").innerHTML++; distance = parseFloat(document.getElementById("DistanceBox").value); if (redcount >= distance && bluecount >= distance) { alert("They tied!"); } else if (redcount >= distance) { alert("Red wins!"); } else if (bluecount >= distance) { alert("Blue wins!"); } } </script> </head> <body> <h2>Dot Race</h2> <p> Race distance: <input type="text" id="DistanceBox" placeholder="0" /> <br> <span class="red">Red dot location:</span> <span id="reddotspan">0</span> <br> <span class="blue">Blue dot location:</span> <span id="bluedotspan">0</span> <hr> <input type="button" value="Take a step!" onclick="TakeAStep();" /> </p> <div id="OutputDiv"></div> </body> </html> ```
2018/11/27
[ "https://Stackoverflow.com/questions/53503798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10697564/" ]
You are incrementing the value of `redcount` and `bluecount` but that has nothing to do with `x` and `y`. I added these lines after `x=` and `y=`. Seems to fix the root cause. ``` document.getElementById("reddotspan").innerHTML=parseInt(document.getElementById("reddotspan").innerHTML)+x; redcount = document.getElementById("reddotspan").innerHTML; document.getElementById("bluedotspan").innerHTML=parseInt(document.getElementById("bluedotspan").innerHTML)+y; bluecount = document.getElementById("bluedotspan").innerHTML; distance = parseFloat(document.getElementById("DistanceBox").value); ```
``` <!doctype html> <html lang="en"> <head> <title>Dot Race</title> <link href="dotrace.css" type="text/css" rel="stylesheet"></link> <script type="text/javascript"> function TakeAStep() { var x, y, redcount, bluecount, distance; x = Math.floor(Math.random() * 3) + 1 ; y = Math.floor(Math.random() * 3) + 1; current_red = +document.getElementById('reddotspan').innerText; current_blue = +document.getElementById('bluedotspan').innerText; redcount = current_red + x; bluecount = current_blue + y; document.getElementById('reddotspan').innerText = redcount; document.getElementById('bluedotspan').innerText = bluecount; distance = parseFloat(document.getElementById('DistanceBox').value); if (redcount >= distance && bluecount >= distance) { alert('They tied!'); } else if (redcount >= distance) { alert('Red wins!'); } else if (bluecount >= distance) { alert('Blue wins!') } } </script> </head> <body> <h2>Dot Race</h2> <p> Race distance: <input type="text" id="DistanceBox" placeholder="0"> <br> <span class="red">Red dot location:</span> <span id="reddotspan">0</span> <br> <span class="blue">Blue dot location:</span> <span id="bluedotspan">0</span> <hr> <input type="button" value="Take a step!" onclick="TakeAStep();"> </p> <div id="OutputDiv"></div> </body> </html> ```
53,503,798
I'm trying to simulate a race between a red and a blue dot. A dot wins if it equals or exceeds the value inputted into the text box for distance. As of now, when you click the "Take a step!" button, each dot's location/distance goes up by 1. What I'm not sure how to do is get that location/distance to go up by a random integer, in this case, a random integer from 1 to 3. How can I do that? Here's what I have: ``` <!DOCTYPE html> <html lang="en"> <head> <title>Dot Race</title> <link href="dotrace.css" type="text/css" rel="stylesheet" /> <script type="text/javascript"> function TakeAStep() { var x, y, redcount, bluecount, distance; x = Math.floor(Math.random() * 3) + 1; y = Math.floor(Math.random() * 3) + 1; redcount = document.getElementById("reddotspan").innerHTML++; bluecount = document.getElementById("bluedotspan").innerHTML++; distance = parseFloat(document.getElementById("DistanceBox").value); if (redcount >= distance && bluecount >= distance) { alert("They tied!"); } else if (redcount >= distance) { alert("Red wins!"); } else if (bluecount >= distance) { alert("Blue wins!"); } } </script> </head> <body> <h2>Dot Race</h2> <p> Race distance: <input type="text" id="DistanceBox" placeholder="0" /> <br> <span class="red">Red dot location:</span> <span id="reddotspan">0</span> <br> <span class="blue">Blue dot location:</span> <span id="bluedotspan">0</span> <hr> <input type="button" value="Take a step!" onclick="TakeAStep();" /> </p> <div id="OutputDiv"></div> </body> </html> ```
2018/11/27
[ "https://Stackoverflow.com/questions/53503798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10697564/" ]
You are incrementing the value of `redcount` and `bluecount` but that has nothing to do with `x` and `y`. I added these lines after `x=` and `y=`. Seems to fix the root cause. ``` document.getElementById("reddotspan").innerHTML=parseInt(document.getElementById("reddotspan").innerHTML)+x; redcount = document.getElementById("reddotspan").innerHTML; document.getElementById("bluedotspan").innerHTML=parseInt(document.getElementById("bluedotspan").innerHTML)+y; bluecount = document.getElementById("bluedotspan").innerHTML; distance = parseFloat(document.getElementById("DistanceBox").value); ```
You were almost there. When you were using the ++ operator, you were modifying the current state of the innerHTML to just add one. Instead, you need to set it equal to the new value. You should also use Number.parseInt so it parses it to a number explicitly. Otherwise, if you do "0" + 1, it will result in "01". ```html <html lang="en"> <head> <title>Dot Race</title> <link href="dotrace.css" type="text/css" rel="stylesheet" /> <script type="text/javascript"> function TakeAStep() { var x, y, newRedNumber, newBlueNumber, distance; x = Math.ceil(Math.random() * 3); y = Math.ceil(Math.random() * 3); newRedNumber = Number.parseInt(document.getElementById('reddotspan').innerHTML) + x; newBlueNumber = Number.parseInt(document.getElementById('bluedotspan').innerHTML) + y; document.getElementById('reddotspan').innerHTML = newRedNumber; document.getElementById('bluedotspan').innerHTML = newBlueNumber; distance = parseFloat(document.getElementById('DistanceBox').value); var outputText = ""; if (newRedNumber >= distance && newBlueNumber >= distance) { outputText = 'They tied!'; } else if (newRedNumber >= distance) { outputText = 'Red wins!'; } else if (newBlueNumber >= distance) { outputText = 'Blue wins!'; } document.getElementById('OutputDiv').innerHTML = outputText; } </script> </head> <body> <h2>Dot Race</h2> <p> Race distance: <input type="text" id="DistanceBox" placeholder="0"> <br> <span class="red">Red dot location:</span> <span id="reddotspan">0</span> <br> <span class="blue">Blue dot location:</span> <span id="bluedotspan">0</span> <hr> <input type="button" value="Take a step!" onclick="TakeAStep();" /> <div id="OutputDiv"></div> </body> </html> ```
20,625,101
I'm trying to get this image uploading and converting script working correctly. I had the script uploading any of the valid images and renaming them fine but then I added the conversion code and I can't get it working correctly. I commented out the // imagepng($image); because that caused the success div to fill with �PNG IHDR��G,�} IDATx���i���u'�s�]�%....... I've worked on this for two days looking at a lot of posts on Stack and thought I understood what was needed. If somebody could please look at this and maybe shed some light on my issue I would greatly appreciate it. In the current configuration I receive no errors on the server. Thanks! **PHP** ``` <?php include_once $_SERVER['DOCUMENT_ROOT'].'/include/session.php'; // Detect the file params according to need $filename = $_FILES["myfile"]["name"]; $filesize = $_FILES["myfile"]["size"]; $tmp_name = $_FILES["myfile"]["tmp_name"]; $custnum = $session->custnum; //Users account number from session // Valid extensions for Upload $validExtensions = array('.jpeg', '.jpg', '.gif', '.png'); // Valid size in KB $max_size = 6000; // Detect file extension $extension = strtolower(strrchr($filename, ".")); // Convert filesize in KB $getFileSize = round($filesize / 1024, 1); //Make the storage directory if (!file_exists("maps/accounts/".$custnum)) { mkdir("maps/accounts/".$custnum, 0777, true); } // Location to store the file $path = str_replace('\/\\', '/', dirname(__FILE__)) . "/maps/accounts/".$custnum; if( in_array($extension, $validExtensions) ){ if( $getFileSize < $max_size ){ if(is_dir($path)){ //***********Start of image conversion*********** $srcFile = $tmp_name; list($width_orig, $height_orig, $type) = getimagesize($srcFile); // Get the aspect ratio $ratio_orig = $width_orig / $height_orig; //Set max size $width = 900; $height = 600; // resize to height (orig is portrait) if ($ratio_orig < 1) { $width = $height * $ratio_orig; } // resize to width (orig is landscape) else { $height = $width / $ratio_orig; } // Temporarily increase the memory limit to allow for larger images ini_set('memory_limit', '32M'); switch ($type) { case IMAGETYPE_GIF: $image = imagecreatefromgif($srcFile); break; case IMAGETYPE_JPEG: $image = imagecreatefromjpeg($srcFile); break; case IMAGETYPE_PNG: $image = imagecreatefrompng($srcFile); break; default: throw new Exception('Unrecognized image type ' . $type); } // create a new blank image $newImage = imagecreatetruecolor($width, $height); // Copy the old image to the new image imagecopyresampled($newImage, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig); imagepng($newImage, $path . '/' . $custnum.'.png'); imagedestroy($image); imagedestroy($newImage); //******End of image conversion**************** // Success Message echo "<div id='success' class='alert alert-success'><strong>Your map image was uploaded!</strong> <button type=\"button\" class=\"close\" data-dismiss=\"alert\">&times;</button> </div>"; } else { trigger_errors("Directory not Found!<br /> $path"); } } else { $error_msg = "<strong>Filesize should be less then $max_size KB!</strong><br />Your file is about $getFileSize KB"; trigger_errors($error_msg); } } else { $error_msg = "<strong>File not Supproted for Upload!</strong><br /> Please try with the files that has following extensions: .jpg, .jpeg, .gif, .png"; trigger_errors($error_msg); } // Make function that // generate the Error function trigger_errors( $error_msg ){ echo "<div class='alert alert-error'> <button type=\"button\" class=\"close\" data-dismiss=\"alert\">&times;</button> $error_msg </div>"; } ?> ``` Here's my JQuery Ajax script that is iside the fabric.js kitchensink.js that's calling the above php script. **JQuery Ajax** ``` $('#loading').hide(); $(function(){ var $form = $('#myform'), $result = $('#result'); $('form').on('change','#myfile', function(){ $('#loading').show(); $result.ajaxStart(function(){ }); $form.ajaxForm({ target: $result }).submit(); $( document ).ajaxComplete(function() { $('#loading').delay(1500).hide('slow'); if ($('#success').hasClass('alert-success')){ canvas.setBackgroundImage(fullurl , function() { canvas.renderAll(); });}; }); }); }) ``` Here's my current html that calls the Ajax and php image processor. This html receives the feed back from the php and ajax success or failure to give feedback to the user. **HTML** ``` <div> <form id="myform" action="image_uploader.php" method="post" enctype="multipart/form-data"> <table align="center"> <tr> <td width="100"><label>Select File: </label></td> <td> <input class="btn shape" type="file" id="myfile" name="myfile"> </td> </tr> </table> </form> <div id="loading"><img src="fabric/img/loadingbar.gif" width="200" height="15" alt="" border="0"><img src="fabric/img/uploading-text.GIF" width="128" height="19" alt="" border="0"></div> </div> <div id="result"></div> ```
2013/12/17
[ "https://Stackoverflow.com/questions/20625101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1043630/" ]
You don't need to call `move_uploaded_file` actually. In fact, you'll not get the results you want if you do. ``` // create a new blank image $newImage = imagecreatetruecolor($width, $height); // Copy the old image to the new image imagecopyresampled($newImage, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig); imagepng($newImage, $path . '/' . $custnum); imagedestroy($image); imagedestroy($newImage); ``` The reason you'll want to do this is that the second argument of [imagepng](http://www.php.net/manual/en/function.imagepng.php) can be a path to save the file. Since you've gone to all the trouble of converting the file, calling `move_uploaded_file` will move the **original** file into a png filename. So if I upload a JPEG with your script it would move that JPEG into example.png. In other words, it wouldn't be a PNG, it would still be a JPEG. The reason it's dumping the way you're written is that, without that path, the function returns the raw image so your browser is trying to interpret that binary data as text and, thus, you get gibberish and random characters.
You are just moving the uploaded file.. So.. Remove this line.. ``` header('Content-Type: image/png'); ```
3,369,769
I am trying to find out what is the value of $(-1+i)^{10}$ by using the trigonometric expression, which should simplify it by avoiding to multiply in binomial form. So far I got this (sin==sen, and excuse my shoddy writing): ![1]](https://i.stack.imgur.com/FO0Z0.jpg) But every other calculator I used to test the result says that it's *-*$32i$, and not $32i$, which is driving me mad! I can only guess that I messed u on the argument($\alpha$) Any help is welcome! Edit: Solved, I hadn't added the fractions properly, see comment chain below post
2019/09/25
[ "https://math.stackexchange.com/questions/3369769", "https://math.stackexchange.com", "https://math.stackexchange.com/users/628898/" ]
Write $z=-1 + i$ in polar form. That is $z=\sqrt{2}e^{i\frac{3}{4}\pi}$. Then, $z^{10} = 2^5 e^{i\frac{15}{2}\pi} $. But that an angle of $\frac{15}{2}\pi$ is the same as $\frac{3}{2} \pi$, and $e^{i\frac{3}{2}\pi} = \cos(\frac{3}{2}\pi) + i\sin(\frac{3}{2}\pi) = -i$. Then, $z^{10} = -32i$
$(-1+i)$ is a vector of length $\sqrt{2}$ and an angle of $135$ degrees. The resulting vector has a length of $\sqrt{2}^{10} = 2^5 = 32$ and an angle of $10 \cdot135 = 1350 \equiv 270 \pmod{360}$ degrees, so yes, it's $-32i$.
3,369,769
I am trying to find out what is the value of $(-1+i)^{10}$ by using the trigonometric expression, which should simplify it by avoiding to multiply in binomial form. So far I got this (sin==sen, and excuse my shoddy writing): ![1]](https://i.stack.imgur.com/FO0Z0.jpg) But every other calculator I used to test the result says that it's *-*$32i$, and not $32i$, which is driving me mad! I can only guess that I messed u on the argument($\alpha$) Any help is welcome! Edit: Solved, I hadn't added the fractions properly, see comment chain below post
2019/09/25
[ "https://math.stackexchange.com/questions/3369769", "https://math.stackexchange.com", "https://math.stackexchange.com/users/628898/" ]
$$-1+i=\sqrt2\exp(3\pi i/4)$$ so $$(-1+i)^{10}=32\exp(15\pi i/2)=-32i.$$ Alas, $$\sqrt2\exp(5\pi i/4)=-1-i.$$
Cartesian to polar conversion in complex plane $$a+ib =\sqrt{a^2+b^2} e^{i\cdot \tan^{-1}(b/a)}$$ Raising to $n^{th}$power $$(a+ib)^n =(a^2+b^2)^{n/2} e^{i\cdot n\cdot \tan^{-1}(b/a)}$$ $$(-1+i)^{10}=(\sqrt{2} e^{i \cdot 3 \pi/4})^{10}=32 e^{15i\pi/2}=32~ e^{12 i\pi/2} \,e^{3\pi/2}=32 (1) e^{3\pi/2} =-32i$$ as the radius vector after rotation lands on the negative y-axis in the complex plane.
3,369,769
I am trying to find out what is the value of $(-1+i)^{10}$ by using the trigonometric expression, which should simplify it by avoiding to multiply in binomial form. So far I got this (sin==sen, and excuse my shoddy writing): ![1]](https://i.stack.imgur.com/FO0Z0.jpg) But every other calculator I used to test the result says that it's *-*$32i$, and not $32i$, which is driving me mad! I can only guess that I messed u on the argument($\alpha$) Any help is welcome! Edit: Solved, I hadn't added the fractions properly, see comment chain below post
2019/09/25
[ "https://math.stackexchange.com/questions/3369769", "https://math.stackexchange.com", "https://math.stackexchange.com/users/628898/" ]
$$-1+i=\sqrt2\exp(3\pi i/4)$$ so $$(-1+i)^{10}=32\exp(15\pi i/2)=-32i.$$ Alas, $$\sqrt2\exp(5\pi i/4)=-1-i.$$
Hint: Use <https://en.m.wikipedia.org/wiki/Atan2#Definition_and_computation> arg$(-1+i)=\arctan\dfrac1{-1}+\pi=\dfrac{3\pi}4$ arg$(-1+i)^{10}=10\cdot\dfrac{3\pi}4=\equiv-\dfrac\pi2\pmod{2\pi}$
3,369,769
I am trying to find out what is the value of $(-1+i)^{10}$ by using the trigonometric expression, which should simplify it by avoiding to multiply in binomial form. So far I got this (sin==sen, and excuse my shoddy writing): ![1]](https://i.stack.imgur.com/FO0Z0.jpg) But every other calculator I used to test the result says that it's *-*$32i$, and not $32i$, which is driving me mad! I can only guess that I messed u on the argument($\alpha$) Any help is welcome! Edit: Solved, I hadn't added the fractions properly, see comment chain below post
2019/09/25
[ "https://math.stackexchange.com/questions/3369769", "https://math.stackexchange.com", "https://math.stackexchange.com/users/628898/" ]
$$N=(-1+i)^{10}=(\sqrt{2} e^{3i\pi/4})^{10}=32 e^{15i\pi/2}=32~ e^{7i\pi} ~e^{\pi/2}= -32i.$$
Cartesian to polar conversion in complex plane $$a+ib =\sqrt{a^2+b^2} e^{i\cdot \tan^{-1}(b/a)}$$ Raising to $n^{th}$power $$(a+ib)^n =(a^2+b^2)^{n/2} e^{i\cdot n\cdot \tan^{-1}(b/a)}$$ $$(-1+i)^{10}=(\sqrt{2} e^{i \cdot 3 \pi/4})^{10}=32 e^{15i\pi/2}=32~ e^{12 i\pi/2} \,e^{3\pi/2}=32 (1) e^{3\pi/2} =-32i$$ as the radius vector after rotation lands on the negative y-axis in the complex plane.
3,369,769
I am trying to find out what is the value of $(-1+i)^{10}$ by using the trigonometric expression, which should simplify it by avoiding to multiply in binomial form. So far I got this (sin==sen, and excuse my shoddy writing): ![1]](https://i.stack.imgur.com/FO0Z0.jpg) But every other calculator I used to test the result says that it's *-*$32i$, and not $32i$, which is driving me mad! I can only guess that I messed u on the argument($\alpha$) Any help is welcome! Edit: Solved, I hadn't added the fractions properly, see comment chain below post
2019/09/25
[ "https://math.stackexchange.com/questions/3369769", "https://math.stackexchange.com", "https://math.stackexchange.com/users/628898/" ]
Write $z=-1 + i$ in polar form. That is $z=\sqrt{2}e^{i\frac{3}{4}\pi}$. Then, $z^{10} = 2^5 e^{i\frac{15}{2}\pi} $. But that an angle of $\frac{15}{2}\pi$ is the same as $\frac{3}{2} \pi$, and $e^{i\frac{3}{2}\pi} = \cos(\frac{3}{2}\pi) + i\sin(\frac{3}{2}\pi) = -i$. Then, $z^{10} = -32i$
Cartesian to polar conversion in complex plane $$a+ib =\sqrt{a^2+b^2} e^{i\cdot \tan^{-1}(b/a)}$$ Raising to $n^{th}$power $$(a+ib)^n =(a^2+b^2)^{n/2} e^{i\cdot n\cdot \tan^{-1}(b/a)}$$ $$(-1+i)^{10}=(\sqrt{2} e^{i \cdot 3 \pi/4})^{10}=32 e^{15i\pi/2}=32~ e^{12 i\pi/2} \,e^{3\pi/2}=32 (1) e^{3\pi/2} =-32i$$ as the radius vector after rotation lands on the negative y-axis in the complex plane.
3,369,769
I am trying to find out what is the value of $(-1+i)^{10}$ by using the trigonometric expression, which should simplify it by avoiding to multiply in binomial form. So far I got this (sin==sen, and excuse my shoddy writing): ![1]](https://i.stack.imgur.com/FO0Z0.jpg) But every other calculator I used to test the result says that it's *-*$32i$, and not $32i$, which is driving me mad! I can only guess that I messed u on the argument($\alpha$) Any help is welcome! Edit: Solved, I hadn't added the fractions properly, see comment chain below post
2019/09/25
[ "https://math.stackexchange.com/questions/3369769", "https://math.stackexchange.com", "https://math.stackexchange.com/users/628898/" ]
$$N=(-1+i)^{10}=(\sqrt{2} e^{3i\pi/4})^{10}=32 e^{15i\pi/2}=32~ e^{7i\pi} ~e^{\pi/2}= -32i.$$
Hint: Use <https://en.m.wikipedia.org/wiki/Atan2#Definition_and_computation> arg$(-1+i)=\arctan\dfrac1{-1}+\pi=\dfrac{3\pi}4$ arg$(-1+i)^{10}=10\cdot\dfrac{3\pi}4=\equiv-\dfrac\pi2\pmod{2\pi}$
3,369,769
I am trying to find out what is the value of $(-1+i)^{10}$ by using the trigonometric expression, which should simplify it by avoiding to multiply in binomial form. So far I got this (sin==sen, and excuse my shoddy writing): ![1]](https://i.stack.imgur.com/FO0Z0.jpg) But every other calculator I used to test the result says that it's *-*$32i$, and not $32i$, which is driving me mad! I can only guess that I messed u on the argument($\alpha$) Any help is welcome! Edit: Solved, I hadn't added the fractions properly, see comment chain below post
2019/09/25
[ "https://math.stackexchange.com/questions/3369769", "https://math.stackexchange.com", "https://math.stackexchange.com/users/628898/" ]
$$-1+i=\sqrt2\exp(3\pi i/4)$$ so $$(-1+i)^{10}=32\exp(15\pi i/2)=-32i.$$ Alas, $$\sqrt2\exp(5\pi i/4)=-1-i.$$
$(-1+i)$ is a vector of length $\sqrt{2}$ and an angle of $135$ degrees. The resulting vector has a length of $\sqrt{2}^{10} = 2^5 = 32$ and an angle of $10 \cdot135 = 1350 \equiv 270 \pmod{360}$ degrees, so yes, it's $-32i$.
3,369,769
I am trying to find out what is the value of $(-1+i)^{10}$ by using the trigonometric expression, which should simplify it by avoiding to multiply in binomial form. So far I got this (sin==sen, and excuse my shoddy writing): ![1]](https://i.stack.imgur.com/FO0Z0.jpg) But every other calculator I used to test the result says that it's *-*$32i$, and not $32i$, which is driving me mad! I can only guess that I messed u on the argument($\alpha$) Any help is welcome! Edit: Solved, I hadn't added the fractions properly, see comment chain below post
2019/09/25
[ "https://math.stackexchange.com/questions/3369769", "https://math.stackexchange.com", "https://math.stackexchange.com/users/628898/" ]
$$N=(-1+i)^{10}=(\sqrt{2} e^{3i\pi/4})^{10}=32 e^{15i\pi/2}=32~ e^{7i\pi} ~e^{\pi/2}= -32i.$$
$(-1+i)$ is a vector of length $\sqrt{2}$ and an angle of $135$ degrees. The resulting vector has a length of $\sqrt{2}^{10} = 2^5 = 32$ and an angle of $10 \cdot135 = 1350 \equiv 270 \pmod{360}$ degrees, so yes, it's $-32i$.
3,369,769
I am trying to find out what is the value of $(-1+i)^{10}$ by using the trigonometric expression, which should simplify it by avoiding to multiply in binomial form. So far I got this (sin==sen, and excuse my shoddy writing): ![1]](https://i.stack.imgur.com/FO0Z0.jpg) But every other calculator I used to test the result says that it's *-*$32i$, and not $32i$, which is driving me mad! I can only guess that I messed u on the argument($\alpha$) Any help is welcome! Edit: Solved, I hadn't added the fractions properly, see comment chain below post
2019/09/25
[ "https://math.stackexchange.com/questions/3369769", "https://math.stackexchange.com", "https://math.stackexchange.com/users/628898/" ]
$(-1+i)$ is a vector of length $\sqrt{2}$ and an angle of $135$ degrees. The resulting vector has a length of $\sqrt{2}^{10} = 2^5 = 32$ and an angle of $10 \cdot135 = 1350 \equiv 270 \pmod{360}$ degrees, so yes, it's $-32i$.
Hint: Use <https://en.m.wikipedia.org/wiki/Atan2#Definition_and_computation> arg$(-1+i)=\arctan\dfrac1{-1}+\pi=\dfrac{3\pi}4$ arg$(-1+i)^{10}=10\cdot\dfrac{3\pi}4=\equiv-\dfrac\pi2\pmod{2\pi}$
3,369,769
I am trying to find out what is the value of $(-1+i)^{10}$ by using the trigonometric expression, which should simplify it by avoiding to multiply in binomial form. So far I got this (sin==sen, and excuse my shoddy writing): ![1]](https://i.stack.imgur.com/FO0Z0.jpg) But every other calculator I used to test the result says that it's *-*$32i$, and not $32i$, which is driving me mad! I can only guess that I messed u on the argument($\alpha$) Any help is welcome! Edit: Solved, I hadn't added the fractions properly, see comment chain below post
2019/09/25
[ "https://math.stackexchange.com/questions/3369769", "https://math.stackexchange.com", "https://math.stackexchange.com/users/628898/" ]
Cartesian to polar conversion in complex plane $$a+ib =\sqrt{a^2+b^2} e^{i\cdot \tan^{-1}(b/a)}$$ Raising to $n^{th}$power $$(a+ib)^n =(a^2+b^2)^{n/2} e^{i\cdot n\cdot \tan^{-1}(b/a)}$$ $$(-1+i)^{10}=(\sqrt{2} e^{i \cdot 3 \pi/4})^{10}=32 e^{15i\pi/2}=32~ e^{12 i\pi/2} \,e^{3\pi/2}=32 (1) e^{3\pi/2} =-32i$$ as the radius vector after rotation lands on the negative y-axis in the complex plane.
Hint: Use <https://en.m.wikipedia.org/wiki/Atan2#Definition_and_computation> arg$(-1+i)=\arctan\dfrac1{-1}+\pi=\dfrac{3\pi}4$ arg$(-1+i)^{10}=10\cdot\dfrac{3\pi}4=\equiv-\dfrac\pi2\pmod{2\pi}$
6,838,873
I am making requests in a loop, trying to accumulate the ID's of the objects given back each time and send to the subsequent request so that they do not get returned a second time. However, the accumulator variable (obviously) is outside of `.ajax()` success callback, and is empty when I pass it through the data object of the call. ``` function fill_div(id, count) { var rend = ""; var filler = $('#'+id); for(i = 0; i < count; i++) { $.ajax({'type':'POST', 'url':'/ads/render/', 'dataType':'json', 'data':"rendered="+rend}).success(function(data){ filler.append('<div id="' + data.adid + '"></div>'); rend+=data.mid.toString()+","; _fill_ad(data); }); } } ``` When I look at the request in chrome's inspector, the variable is there in the post data, but there is no value. I feel like I'm getting something messed up with scoping.
2011/07/27
[ "https://Stackoverflow.com/questions/6838873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2128/" ]
It looks like the issue here is that you're expecting the returned values to be appended to the `rend` string in time for the next AJAX call. This isn't going to happen, because making the calls is a synchronous process, but getting the return values is asynchronous. Instead of: ``` AJAX Post 1 (rend='') rend += 'id1,' AJAX Post 2 (rend='id1,') rend += 'id2,' AJAX Post 3 (rend='id1,id2,') // etc ``` the sequence will most like go something like: ``` AJAX Post 1 (rend='') AJAX Post 2 (rend='') AJAX Post 3 (rend='') // etc // ... data is returned, not necessarily in order rend += 'id2,' rend += 'id1,' rend += 'id3,' // etc ``` In order to have each subsequent AJAX call aware of what's been previously returned from the server, you'd have to chain the calls, so that the next AJAX call isn't made until the previous call is completed. You could do this with recursion, like this: ``` function fill_div(id, count) { var rend = ""; var filler = $('#'+id); // inner function for recursion function doAjaxCall(i) { $.ajax({'type':'POST', 'url':'/ads/render/', 'dataType':'json', 'data':{'rendered': rend}) .success(function(data){ filler.append('<div id="' + data.adid + '"></div>'); rend+=data.mid.toString()+","; _fill_ad(data); // now send the next call if (i < count) { doAjaxCall(i+1); } }); } // kick off the series doAjaxCall(0); } ```
Not sure it's the problem, but shouldn't it be like this for a POST ? ``` function fill_div(id, count) { var rend = ""; var filler = $('#'+id); for(i = 0; i < count; i++) { $.ajax({'type':'POST', 'url':'/ads/render/', 'dataType':'json', 'data':{'rendered': rend}) .success(function(data){ filler.append('<div id="' + data.adid + '"></div>'); rend+=data.mid.toString()+","; _fill_ad(data); }); } } ``` (the difference is that the 'data' is an object and not a string)
6,838,873
I am making requests in a loop, trying to accumulate the ID's of the objects given back each time and send to the subsequent request so that they do not get returned a second time. However, the accumulator variable (obviously) is outside of `.ajax()` success callback, and is empty when I pass it through the data object of the call. ``` function fill_div(id, count) { var rend = ""; var filler = $('#'+id); for(i = 0; i < count; i++) { $.ajax({'type':'POST', 'url':'/ads/render/', 'dataType':'json', 'data':"rendered="+rend}).success(function(data){ filler.append('<div id="' + data.adid + '"></div>'); rend+=data.mid.toString()+","; _fill_ad(data); }); } } ``` When I look at the request in chrome's inspector, the variable is there in the post data, but there is no value. I feel like I'm getting something messed up with scoping.
2011/07/27
[ "https://Stackoverflow.com/questions/6838873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2128/" ]
It looks like the issue here is that you're expecting the returned values to be appended to the `rend` string in time for the next AJAX call. This isn't going to happen, because making the calls is a synchronous process, but getting the return values is asynchronous. Instead of: ``` AJAX Post 1 (rend='') rend += 'id1,' AJAX Post 2 (rend='id1,') rend += 'id2,' AJAX Post 3 (rend='id1,id2,') // etc ``` the sequence will most like go something like: ``` AJAX Post 1 (rend='') AJAX Post 2 (rend='') AJAX Post 3 (rend='') // etc // ... data is returned, not necessarily in order rend += 'id2,' rend += 'id1,' rend += 'id3,' // etc ``` In order to have each subsequent AJAX call aware of what's been previously returned from the server, you'd have to chain the calls, so that the next AJAX call isn't made until the previous call is completed. You could do this with recursion, like this: ``` function fill_div(id, count) { var rend = ""; var filler = $('#'+id); // inner function for recursion function doAjaxCall(i) { $.ajax({'type':'POST', 'url':'/ads/render/', 'dataType':'json', 'data':{'rendered': rend}) .success(function(data){ filler.append('<div id="' + data.adid + '"></div>'); rend+=data.mid.toString()+","; _fill_ad(data); // now send the next call if (i < count) { doAjaxCall(i+1); } }); } // kick off the series doAjaxCall(0); } ```
when the function fill\_div executed, there is initialisation on ``` var rend = ""; ``` and when the POST request constructed, ``` 'data':"rendered="+rend ``` rend value will be empty Can you double check the variable name? :)
984,244
I've found a PHP script that lets me do what I asked in [this](https://stackoverflow.com/questions/922148/how-to-make-mechanize-not-fail-with-forms-on-this-page) SO question. I can use this just fine, but out of curiosity I'd like to recreate the following code in Python. I can of course use urllib2 to get the page, but I'm at a loss on how to handle the cookies since mechanize (tested with Python 2.5 and 2.6 on Windows and Python 2.5 on Ubuntu...all with latest mechanize version) seems to break on the page. How do I do this in python? ``` require_once "HTTP/Request.php"; $req = &new HTTP_Request('https://steamcommunity.com'); $req->setMethod(HTTP_REQUEST_METHOD_POST); $req->addPostData("action", "doLogin"); $req->addPostData("goto", ""); $req->addPostData("steamAccountName", ACC_NAME); $req->addPostData("steamPassword", ACC_PASS); echo "Login: "; $res = $req->sendRequest(); if (PEAR::isError($res)) die($res->getMessage()); $cookies = $req->getResponseCookies(); if ( !$cookies ) die("fail\n"); echo "pass\n"; foreach($cookies as $cookie) $req->addCookie($cookie['name'],$cookie['value']); ```
2009/06/11
[ "https://Stackoverflow.com/questions/984244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23972/" ]
Similar to monkut's answer, but a little more concise. ``` import urllib, urllib2 def steam_login(username,password): data = urllib.urlencode({ 'action': 'doLogin', 'goto': '', 'steamAccountName': username, 'steamPassword': password, }) request = urllib2.Request('https://steamcommunity.com/',data) cookie_handler = urllib2.HTTPCookieProcessor() opener = urllib2.build_opener(cookie_handler) response = opener.open(request) if not 200 <= response.code < 300: raise Exception("HTTP error: %d %s" % (response.code,response.msg)) else: return cookie_handler.cookiejar ``` It returns the cookie jar, which you can use in other requests. Just pass it to the `HTTPCookieProcessor` constructor. monkut's answer installs a global `HTTPCookieProcessor`, which stores the cookies between requests. My solution does not modify the global state.
I'm not familiar with PHP, but this may get you started. I'm installing the opener here which will apply it to the urlopen method. If you don't want to 'install' the opener(s) you can use the opener object directly. (opener.open(url, data)). Refer to: <http://docs.python.org/library/urllib2.html?highlight=urllib2#urllib2.install_opener> ``` import urlib2 import urllib # 1 create handlers cookieHandler = urllib2.HTTPCookieProcessor() # Needed for cookie handling redirectionHandler = urllib2.HTTPRedirectHandler() # needed for redirection # 2 apply the handler to an opener opener = urllib2.build_opener(cookieHandler, redirectionHandler) # 3. Install the openers urllib2.install_opener(opener) # prep post data datalist_tuples = [ ('action', 'doLogin'), ('goto', ''), ('steamAccountName', ACC_NAME), ('steamPassword', ACC_PASS) ] url = 'https://steamcommunity.com' post_data = urllib.urlencode(datalist_tuples) resp_f = urllib2.urlopen(url, post_data) ```
35,857,061
I tried to store and reload objects and their references between each other. The problem is when I reload the data from the database the references are not set correctly. Here is an example code which describes the problem. I comment the the expcted state and the real state of the output in the code. ``` [Table(Name = "ClassA")] public class ClassA { public ClassA() { LinksToClassB = new EntitySet<ClassB>(); } [Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert, DbType = "Int NOT NULL IDENTITY")] public int ID { get; set; } [Association] public EntitySet<ClassB> LinksToClassB { get; set; } //=> 1 to n cardinality [Association] public ClassB OneLinkToClassB { get; set; }//=> 1 to 1 cardinality } [Table(Name = "ClassB")] public class ClassB { [Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert, DbType = "Int NOT NULL IDENTITY")] public int ID { get; set; } [Column(CanBeNull = true)] public string Name { get; set; } } public class DatabaseContext : DataContext { public Table<ClassA> ClassATable; public Table<ClassB> ClassBTable; public DatabaseContext(string connection) : base(connection) { } } [TestClass] public class Test { string path = @"F:\Temp\Testspace - Forum Database\database.mdf";//path to database [TestMethod] public void TestMethod() { //creates Database DatabaseContext context = new DatabaseContext(path); if (context.DatabaseExists())//Delete if exists { context.DeleteDatabase(); } context.CreateDatabase(); ClassB b1 = new ClassB(); b1.Name = "name 1"; ClassB b2 = new ClassB(); b2.Name = "name 2"; ClassB b3 = new ClassB(); b3.Name = "name 3"; ClassA a = new ClassA(); //now the references will be added to the object a //in 1-n references a.LinksToClassB.Add(b1); a.LinksToClassB.Add(b2); a.LinksToClassB.Add(b3); //and the has-one reference (OneLinkToClassB) a.OneLinkToClassB = b1; context.ClassATable.InsertOnSubmit(a); context.SubmitChanges(); //store in database //now the database will be reloaded context = new DatabaseContext(path); //Check if all ClassB objects were correctly stored and reloaded foreach (ClassB x in context.ClassBTable) { Console.WriteLine(x.ID + "; " + x.Name); /* -> expected output: 1; name 1 2; name 2 3; name 3 -> real output 1; name 1 2; name 2 3; name 3 -> check! */ } //check if all ClassA objects were correctly stored and reloaded foreach (ClassA x in context.ClassATable)//context.ClassATable has only one entry { Console.WriteLine("check of entitys set"); //check of 1-n references foreach (ClassB b in x.LinksToClassB) { Console.WriteLine(x.ID + " has a link to " + b.ID + ", " + b.Name); /* -> expected output: 1 has a link to 1, name 1 1 has a link to 2, name 2 1 has a link to 3, name 3 -> real output 1 has a link to 1, name 1 -> doesn't match... */ } Console.WriteLine("check of single link"); //check of 1-1 reference Console.WriteLine(x.ID + " has a link to " + x.OneLinkToClassB.ID + ", " + x.OneLinkToClassB.Name); /* -> expected output: 1 has a link to 1, name 1 -> real output this line throws an NullReferenceException */ } } } ``` I hope anyone can give me a hint how to solve this bug in my code :)
2016/03/08
[ "https://Stackoverflow.com/questions/35857061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5289969/" ]
When using 3rd party libraries the following steps have prove useful to me: 1) Create a wrapper element (e.g fullcalendar-wrapper.html ) Inside it put all the script references to the external required scripts 2) Create a custom component that will have the calendar ( e.g calendar-test.html ) * Import the fullcalendar-wrapper like any other dependency * Use the 'ready' event of the component to initialise the calendar. So you should move the code under document.on('ready') to the 'ready' event of your polymer component Right now you are setting up things when the page is ready, but the Polymer system may not be ready yet.
I may assume that the issue is in two included `jQuery` libraries (one from `code.jquery.com` (the 1st `script` tag) and another one from `fullcalendar` (the 3rd `script` tag). Please try to remove one of them. And is there any error message in a Browser Developer Console?
23,199,396
How can I get a result of subtraction in words like "7 seconds"? `strftime` isn't working because the result is Fixnum. ``` a = Time.now b = Time.now #a few seconds later b - a #7.17584 (seconds) ```
2014/04/21
[ "https://Stackoverflow.com/questions/23199396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2394732/" ]
If you are using Rails, you can use [`distance_of_time_in_words`](http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-distance_of_time_in_words): ``` from_time = Time.now distance_of_time_in_words(from_time, from_time + 15.seconds, include_seconds: true) #less than 20 seconds ```
For example as follows: ``` Time.at(Time.now - 7.seconds).strftime("%H:%M:%S") # => "18:41:18" ``` and the difference between two times: ``` Time.at(Time.now - (Time.now - 7.seconds)).strftime("%1S.%5N (seconds)") # 6.99998 ``` Note: The instance method `-` returns the number of seconds between two times, `Time.at` returns a Time object constructed from an Integer, or Float, in seconds. The `%1S` format key for [`strftime`](http://www.ruby-doc.org/core-2.1.1/Time.html#method-i-strftime) allows you to output the number of unpadded seconds.
23,199,396
How can I get a result of subtraction in words like "7 seconds"? `strftime` isn't working because the result is Fixnum. ``` a = Time.now b = Time.now #a few seconds later b - a #7.17584 (seconds) ```
2014/04/21
[ "https://Stackoverflow.com/questions/23199396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2394732/" ]
If you are using Rails, you can use [`distance_of_time_in_words`](http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-distance_of_time_in_words): ``` from_time = Time.now distance_of_time_in_words(from_time, from_time + 15.seconds, include_seconds: true) #less than 20 seconds ```
Depending on your exact needs, you can also write your own method, something like this: ``` def diff_time_in_words(first_time, second_time) (second_time - first_time).round(0).to_s + " seconds" end # nil a = Time.now # 2014-04-21 09:55:55 -0500 b = Time.now # 2014-04-21 09:56:02 -0500 diff_time_in_words(a, b) # "8 seconds" ``` Obviously, this assumes your result is always meant to be expressed in seconds, but it's a start. If you're interested, I could go on.
16,979,390
I have never done anything like this before, that's why I ask for some tips how to solve this problem. I have website which has following links: **Home, Product, Blog, About us, Contact** In Blog section I have installed Wordpress. And here is my problem/question: How can I manage the rest of the pages? I don't know if Wordpress allow manage custom files, so I probably will need to create class to retrieve data from database and put it in these files. I'm wondering if there is any API, plugins, which could let me help in this. Any tips for solving my problem, are welcome and appreciate
2013/06/07
[ "https://Stackoverflow.com/questions/16979390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1409508/" ]
you can load wordpress environment in other php pages by using ``` require( 'blog/wp-load.php' ); ``` where 'blog' being your wordpress install root.
the wordpress should be installed for the entire site. and than what you can do is just make pages, even custom pages with different design for each page on the site. you can read more about it her:[Codex/Page Templates](http://codex.wordpress.org/Page_Templates) and than in the **blog** page you can just create a link to a category or to the regular posts in the system.
8,828,687
Mostly out of curiosity, I would like to know if there are any edge cases that can arise from cases like: ``` <span class="class1 class2 class3 class2 class4">...</span> ``` (`class2` is listed twice) or ``` <span class="class1 class2 class3 class2 class2 class2 class3 class4 class4 class3">...</span> ``` (a more extreme version of the same) This is obviously messy css and not ideal, but **are there any edge cases this creates?**
2012/01/12
[ "https://Stackoverflow.com/questions/8828687", "https://Stackoverflow.com", "https://Stackoverflow.com/users/224354/" ]
**No, none whatsoever**, unless you have the habit of using the `class` attribute: ``` [class="class1 class2"] { /* ... */ } ``` instead of: ``` .class1.class2 { /* ... */ } ``` which is terrible practice, of course. --- Also, although your question isn't tagged [javascript](/questions/tagged/javascript "show questions tagged 'javascript'"), note that if only the first instance of a class is removed and an unlimited number added, say: ``` function addClass(element, cls) { element.className += ' ' + cls; } ``` but ``` function removeClass(element, cls) { return element.className.replace(cls, ' '); } ``` this will cause problems in more ways than one.
No, there is nothing *wrong* with it other than it looks weird. Any re-occurences of a class name won't affect anything, ever. It doesn't "reapply" those styles after applying styles from the class defined before it or anything. Remember that CSS will always select the style defined *last* for that level of specificity. See this [jsFiddle](http://jsfiddle.net/xZmvX/2/) and note how class4 *always* overrides the font color, no matter what combinations of class1, class2, and class3 are used. Ultimately, it's seen as having class name class1, having class name class2, having class name class3, and having class name class4. Repeating them is like clicking on the radio button again. It's already selected, no need to keep clicking it...