qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
|---|---|---|---|---|---|
97,845
|
This is for a book. An ancient, badly damaged, base has been found in the asteroid belt. The base has been open to the vacuum of space, although a large proportion of the base is within the body of the asteroid and not on the surface, so has been protected from solar radiations and micro-meteor impacts.
I wanted the protagonists to discover remains in the base that will allow them to get a rough age but I don't know the limits of carbon dating or if it would even be possible, given the overall conditions caused by a hard vacuum. I don't know if carbon dating is a viable option and, if it isn't, does another another field of science offer a plausible way of getting to the age of the base?
Note -
The base is tens of millions of years old and the majority of it is buried deep under the surface of the asteroid.
The technology basis for the protagonist is roughly fifty years advanced from current day earth. Two major changes are hydrogen-based power units have replaced all fossil fuels and inter-solar system travel is viable but only just starting using ships powered by EM Drives.
The technology basis for the base builders is highly advanced; viable interstellar travel capabilities, for example.
Not sure I understand the reasons for this being put on hold as it would appear to fit in to the "Effects of events or world elements, including biology, technology and magic, on specific aspects of that world's societies, cultures, and environment" caveat of the exchanges rules.
Can you please explain what I am misunderstanding ?
* Edited for spelling, clarity and on hold clarification.
|
2017/11/14
|
[
"https://worldbuilding.stackexchange.com/questions/97845",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/44392/"
] |
Carbon dating is problematic, as you need to know level of Carbon 14 in the atmosphere at the time the animal or plant you are studying died. But there are other radiometric dating methods which might work.
The simplest thing would perhaps be if they found a machine similar to a [radioisotope thermoelectric generator](https://en.wikipedia.org/wiki/Radioisotope_thermoelectric_generator), which is a device that uses a radioactive substance to create electricity. It is today used to power interplanetary probes, among other things.
If the protagonists find a device powered by say plutonium-238, they can look at the ratio of plutonium, uranium and lead to infer the number of years since the plutonium was refined. This is similar to [uranium-lead dating](https://en.wikipedia.org/wiki/Uranium%E2%80%93lead_dating) which is a dating method that can determine the age of rocks that are from a million year old to several billion.
The base may also have a derelict nuclear reactor, similar to that of nuclear-powered submarines today. You can have the protagonists do a similar analysis here.
*Edit: A generator using Americum-241 makes for more straightforward dating, see discussion below*
|
**[One option is to use meteorite impacts](https://pseudoastro.wordpress.com/2008/10/21/dating-planetary-surfaces-with-craters-why-there-is-no-crisis-in-crater-count-dating/)**
miteorite [dating](https://pseudoastro.wordpress.com/2008/10/21/dating-planetary-surfaces-with-craters-why-there-is-no-crisis-in-crater-count-dating/) is usually used to date large impact basins and other planetary structures. It tends to use impacts caused by large objects of tens to hundreds of meters or more in diameter, but there is no reason why this technique shouldn’t be extended to micrometeorites on any surface.
Over thousands of years meteorites would cause a roughening of surfaces in general and pitting in places. Depending on the size of the surface installation and the exact amount of time, a few larger impacts might be seen that were capable of making holes in the outer structural material.
Statistical analysis of the size distribution of such micro craters could provide an estimate of the age of the installation assuming that the structure would have been installed impact free from new materials. The background level of expected impacts could be discovered from examining the surface of the asteroid that was not covered by the base or other nearby planetary bodies using traditional techniques as well as radioisotope dating.
|
97,845
|
This is for a book. An ancient, badly damaged, base has been found in the asteroid belt. The base has been open to the vacuum of space, although a large proportion of the base is within the body of the asteroid and not on the surface, so has been protected from solar radiations and micro-meteor impacts.
I wanted the protagonists to discover remains in the base that will allow them to get a rough age but I don't know the limits of carbon dating or if it would even be possible, given the overall conditions caused by a hard vacuum. I don't know if carbon dating is a viable option and, if it isn't, does another another field of science offer a plausible way of getting to the age of the base?
Note -
The base is tens of millions of years old and the majority of it is buried deep under the surface of the asteroid.
The technology basis for the protagonist is roughly fifty years advanced from current day earth. Two major changes are hydrogen-based power units have replaced all fossil fuels and inter-solar system travel is viable but only just starting using ships powered by EM Drives.
The technology basis for the base builders is highly advanced; viable interstellar travel capabilities, for example.
Not sure I understand the reasons for this being put on hold as it would appear to fit in to the "Effects of events or world elements, including biology, technology and magic, on specific aspects of that world's societies, cultures, and environment" caveat of the exchanges rules.
Can you please explain what I am misunderstanding ?
* Edited for spelling, clarity and on hold clarification.
|
2017/11/14
|
[
"https://worldbuilding.stackexchange.com/questions/97845",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/44392/"
] |
How about if an artifact is found that dates the base. Something like a calendar left by the occupants of the base and one of your characters puzzles out how to read it. Maybe something related to position of the stars relative to the solar system or something.
|
There are a large number of problems with this scenario. First things first Carbon-14 Dating tops out at around 50,000 years. Second Carbon-14 dating relies on the fact that Earth has a steady rate of Carbon-14 creation and terrestrial creatures have a predictable rate of carbon uptake, thus dates in the nuclear age are skewed by fallout from atmospheric testing. Thirdly exposure to vacuum has some strange and unpredictable effects on organic material that would be hard to factor in. Fourth, any radiological dating will be "messed up beyond all recognition" (that's a technical term) by exposure to cosmic radiation outside the shielding of a thick atmosphere and strong magnetosphere.
So that's things you can't easily use, you can possibly use the rate of decay of the construction materials *in vacuum* as a benchmark for the age of the site since that will be fairly uniform, for a given material.
|
1,027,608
|
So, I needed the [Semantics Engineering with PLT Redex](https://mitpress.mit.edu/books/semantics-engineering-plt-redex) textbook to complete a homework assignment this week. I needed it in a digital format because I'm going to [POPL 2016](http://conf.researchr.org/home/POPL-2016) tomorrow and I can't have it delivered to me. Hence, I paid $50 for the eBook so that I could complete my homework.
The problem is that I'm using [Arch Linux](https://www.archlinux.org/) and for some reason [Adobe Digital Editions](https://aur.archlinux.org/packages/adobe-digital-editions/) doesn't work for me. During installation it said that it might not work on a 64-bit system. Anyway, I tried to find an alternative solution and I learned that I could read the book using [Bluefire Reader](http://www.bluefirereader.com/) on my phone.
And it worked. I can read the book, but I don't want to read the book on my little phone screen. So, I transferred the PDF file that Bluefire Reader downloaded to my laptop in hopes that I could open it using a simple PDF reader. Then I double click on the PDF file with a smirk on my face... and it asks me for a password.
I hope you can understand my frustration. All I want to do is read the book that I legally purchased on my laptop so that I can complete my homework and get on with my life. I tried using other eBook readers like [Calibre](http://calibre-ebook.com/) but it requires that I convert my ACSM file to EPUB using Adobe Digital Editions (which doesn't work for me). What other alternatives do I have?
|
2016/01/17
|
[
"https://superuser.com/questions/1027608",
"https://superuser.com",
"https://superuser.com/users/328397/"
] |
I will try to list all the solutions I've found.
First one. Tested solution: working, and very easy.
First install *Wine* on your Linux. Then download Adobe Digital editions.
[Link to download Adobe Digital editions](https://www.adobe.com/fr/solutions/ebook/digital-editions/download.html)
Then, install the file you dowloaded from Adobe (It was ADE\_4.5\_Installer.exe, for me), in the Wine virtual Window. If you don't know how to use wine, see this doc: [How to install and use Wine on Linux](https://www.linux.com/learn/how-install-and-use-wine-run-windows-applications-linux)
Second solution:
Install a virtual Windows on Linux. [How to](http://www.makeuseof.com/tag/set-windows-virtual-machine-linux/).
Third solution: If you failed to install virtual machine or open with Wine, and if you really need this program, install a dual boot on your computer Windows/Linux. [How to dual boot Windows/linux on the same computer](https://www.howtogeek.com/214571/how-to-dual-boot-linux-on-your-pc/%20%22How%20to%20dual%20boot%20Windows/Linux%20on%20the%20same%20computer)
4th solution, use a virtual Android phone (or a real one) and install the Adobe Digital editions for Android.
[Virtual smartphone software, Memu](http://www.memuplay.com)
You can also try to emulate MacOs, or iOS.
There are solutions to remove the DRM, and so convert the acsm into epub, but there are no legal, so I don't think I'm allowed to write them.
|
.acsm can only be used with Adobe Digital Editions and stands for Adobe Content Server Manager.
For more information about Adobe Digital Editions please see <http://www.adobe.com/products/digitaleditions/faq/>
Side note (may not be generally applicable to Digital Editions users): Stated in the agreement (may be of concern in making a program to access .acsm ) for Adobe Content Server section 11.1 you agree not to:
>
> (d) obtain or attempt to obtain any materials or Information through any means > not intentionally made available through the Services;
>
>
>
Interpret this as you will, I will not give you illegal advice.
|
1,027,608
|
So, I needed the [Semantics Engineering with PLT Redex](https://mitpress.mit.edu/books/semantics-engineering-plt-redex) textbook to complete a homework assignment this week. I needed it in a digital format because I'm going to [POPL 2016](http://conf.researchr.org/home/POPL-2016) tomorrow and I can't have it delivered to me. Hence, I paid $50 for the eBook so that I could complete my homework.
The problem is that I'm using [Arch Linux](https://www.archlinux.org/) and for some reason [Adobe Digital Editions](https://aur.archlinux.org/packages/adobe-digital-editions/) doesn't work for me. During installation it said that it might not work on a 64-bit system. Anyway, I tried to find an alternative solution and I learned that I could read the book using [Bluefire Reader](http://www.bluefirereader.com/) on my phone.
And it worked. I can read the book, but I don't want to read the book on my little phone screen. So, I transferred the PDF file that Bluefire Reader downloaded to my laptop in hopes that I could open it using a simple PDF reader. Then I double click on the PDF file with a smirk on my face... and it asks me for a password.
I hope you can understand my frustration. All I want to do is read the book that I legally purchased on my laptop so that I can complete my homework and get on with my life. I tried using other eBook readers like [Calibre](http://calibre-ebook.com/) but it requires that I convert my ACSM file to EPUB using Adobe Digital Editions (which doesn't work for me). What other alternatives do I have?
|
2016/01/17
|
[
"https://superuser.com/questions/1027608",
"https://superuser.com",
"https://superuser.com/users/328397/"
] |
The question is quite old, but people like myself still trip up on DRM locked ebooks. I assume you want to get out of the acsm a DRM-free epub. My instruction is for Ubuntu/Debian using apt-get, but the tools exist for other distros as well. I need a couple of tools in particular: the [DeDRM tool](https://github.com/apprenticeharper/DeDRM_tools/releases) for python2.7 and wine. On wine, we will install Adobe Digital Editions, python and pip for windows
1. Install wine and winetricks because we will run Adobe Digital Editions in wine. By default ubuntu19.10 intalled wine 4 on my machine. Its easier to [upgrade to wine5](https://linuxconfig.org/install-wine-on-ubuntu-20-04-focal-fossa-linux) first. ADE works so much better with wine5.
```
sudo apt-get install winehq-stable winetricks winbind
```
2. Install dotnet40
```
winetricks dotnet40
```
3. Now download [Adobe Digital Editions](https://www.adobe.com/solutions/ebook/digital-editions/download.html) for Windows and install it:
```
wine Downloads/ADE_4.5_Installer.exe
```
4. After installing and launching DigitalEditions you will need to authorize you computer or log in with your [adobe id](https://account.adobe.com/) if you don`t have one create it for free.
5. Open in ADE the acsm file. It will download the epub into your user documents folder (e.g., ~/Documents ) in sub dir "My\ Digital\ Editions". Note that the file is still DRM protected.
6. Now its time to run DeDRM from python wine. Unzip [DeDRM tool Version 6.x](https://github.com/apprenticeharper/DeDRM_tools/releases) and locate the adobekey.py file.
7. Install python, pip and pycryptodome:
```
winetricks python27 # this should also install pip
wine pip install pycryptodome
```
8. Run adobekey.py from the dedrm you downloaded before with wine python:
```
wine ~/.wine/drive_c/Python27/python.exe adobekey.py
```
9. You get the adobekey\_1.der that you need to run the other script:
```
python ineptepub.py adobekey_1.der ~/Path/to/drm_locked.epub your_drm_free_out.epub
```
For pdfs use 'ineptpdf.py' inststead of 'ineptepub.py'. If you get an [error](https://github.com/apprenticeharper/DeDRM_tools/issues/928) in this step about python, adjust the term 'python', to 'python2' or 'python3'.
10. You should get the output:
```
Successfully decrypted drm_locked.epub as your_drm_free_out.epub
```
Done. Read your epub on any epub reader, e.g., okular, readera, lithium.
To be sure, this is quite a few steps. However, ADE is not a good reader, and the reading experience using wine even worse. I disagree that removing DRM is not legal; for personal use [it's perfectly fine](https://gizmodo.com/its-perfectly-legal-to-tell-people-how-to-remove-drm-1670223538) to remove DRM from your purchased ebooks. Publishers, of course, have an interest in reducing and controlling access to the material. [EFF](https://www.eff.org/deeplinks/2017/05/book-review-end-ownership) has some interesting articles on DMCA, DRM, and copyright. Have fun reading.
|
.acsm can only be used with Adobe Digital Editions and stands for Adobe Content Server Manager.
For more information about Adobe Digital Editions please see <http://www.adobe.com/products/digitaleditions/faq/>
Side note (may not be generally applicable to Digital Editions users): Stated in the agreement (may be of concern in making a program to access .acsm ) for Adobe Content Server section 11.1 you agree not to:
>
> (d) obtain or attempt to obtain any materials or Information through any means > not intentionally made available through the Services;
>
>
>
Interpret this as you will, I will not give you illegal advice.
|
1,027,608
|
So, I needed the [Semantics Engineering with PLT Redex](https://mitpress.mit.edu/books/semantics-engineering-plt-redex) textbook to complete a homework assignment this week. I needed it in a digital format because I'm going to [POPL 2016](http://conf.researchr.org/home/POPL-2016) tomorrow and I can't have it delivered to me. Hence, I paid $50 for the eBook so that I could complete my homework.
The problem is that I'm using [Arch Linux](https://www.archlinux.org/) and for some reason [Adobe Digital Editions](https://aur.archlinux.org/packages/adobe-digital-editions/) doesn't work for me. During installation it said that it might not work on a 64-bit system. Anyway, I tried to find an alternative solution and I learned that I could read the book using [Bluefire Reader](http://www.bluefirereader.com/) on my phone.
And it worked. I can read the book, but I don't want to read the book on my little phone screen. So, I transferred the PDF file that Bluefire Reader downloaded to my laptop in hopes that I could open it using a simple PDF reader. Then I double click on the PDF file with a smirk on my face... and it asks me for a password.
I hope you can understand my frustration. All I want to do is read the book that I legally purchased on my laptop so that I can complete my homework and get on with my life. I tried using other eBook readers like [Calibre](http://calibre-ebook.com/) but it requires that I convert my ACSM file to EPUB using Adobe Digital Editions (which doesn't work for me). What other alternatives do I have?
|
2016/01/17
|
[
"https://superuser.com/questions/1027608",
"https://superuser.com",
"https://superuser.com/users/328397/"
] |
I created a program called [Knock](https://github.com/BentonEdmondson/knock) to convert ACSM files to DRM-free EPUB files at the command line:
```
[user@computer:~]$ knock ./example.acsm
downloading the file from Adobe...
removing DRM from the file...
DRM-free EPUB file generated at ./example.epub
```
It doesn't use Adobe Digital Editions and it doesn't use Wine. It is completely free and open-source software for native Linux.
|
.acsm can only be used with Adobe Digital Editions and stands for Adobe Content Server Manager.
For more information about Adobe Digital Editions please see <http://www.adobe.com/products/digitaleditions/faq/>
Side note (may not be generally applicable to Digital Editions users): Stated in the agreement (may be of concern in making a program to access .acsm ) for Adobe Content Server section 11.1 you agree not to:
>
> (d) obtain or attempt to obtain any materials or Information through any means > not intentionally made available through the Services;
>
>
>
Interpret this as you will, I will not give you illegal advice.
|
1,027,608
|
So, I needed the [Semantics Engineering with PLT Redex](https://mitpress.mit.edu/books/semantics-engineering-plt-redex) textbook to complete a homework assignment this week. I needed it in a digital format because I'm going to [POPL 2016](http://conf.researchr.org/home/POPL-2016) tomorrow and I can't have it delivered to me. Hence, I paid $50 for the eBook so that I could complete my homework.
The problem is that I'm using [Arch Linux](https://www.archlinux.org/) and for some reason [Adobe Digital Editions](https://aur.archlinux.org/packages/adobe-digital-editions/) doesn't work for me. During installation it said that it might not work on a 64-bit system. Anyway, I tried to find an alternative solution and I learned that I could read the book using [Bluefire Reader](http://www.bluefirereader.com/) on my phone.
And it worked. I can read the book, but I don't want to read the book on my little phone screen. So, I transferred the PDF file that Bluefire Reader downloaded to my laptop in hopes that I could open it using a simple PDF reader. Then I double click on the PDF file with a smirk on my face... and it asks me for a password.
I hope you can understand my frustration. All I want to do is read the book that I legally purchased on my laptop so that I can complete my homework and get on with my life. I tried using other eBook readers like [Calibre](http://calibre-ebook.com/) but it requires that I convert my ACSM file to EPUB using Adobe Digital Editions (which doesn't work for me). What other alternatives do I have?
|
2016/01/17
|
[
"https://superuser.com/questions/1027608",
"https://superuser.com",
"https://superuser.com/users/328397/"
] |
.acsm can only be used with Adobe Digital Editions and stands for Adobe Content Server Manager.
For more information about Adobe Digital Editions please see <http://www.adobe.com/products/digitaleditions/faq/>
Side note (may not be generally applicable to Digital Editions users): Stated in the agreement (may be of concern in making a program to access .acsm ) for Adobe Content Server section 11.1 you agree not to:
>
> (d) obtain or attempt to obtain any materials or Information through any means > not intentionally made available through the Services;
>
>
>
Interpret this as you will, I will not give you illegal advice.
|
I have also used release of 'knock' downloaded from Web Archive (<https://web.archive.org/web/20221020182238mp_/https://github.com/BentonEdmondson/knock/releases/download/1.3.1/knock-1.3.1-x86_64-linux>). Worked very well - thank you [@BentonEdmontson](https://superuser.com/users/1470682/bentonedmondson) !
|
1,027,608
|
So, I needed the [Semantics Engineering with PLT Redex](https://mitpress.mit.edu/books/semantics-engineering-plt-redex) textbook to complete a homework assignment this week. I needed it in a digital format because I'm going to [POPL 2016](http://conf.researchr.org/home/POPL-2016) tomorrow and I can't have it delivered to me. Hence, I paid $50 for the eBook so that I could complete my homework.
The problem is that I'm using [Arch Linux](https://www.archlinux.org/) and for some reason [Adobe Digital Editions](https://aur.archlinux.org/packages/adobe-digital-editions/) doesn't work for me. During installation it said that it might not work on a 64-bit system. Anyway, I tried to find an alternative solution and I learned that I could read the book using [Bluefire Reader](http://www.bluefirereader.com/) on my phone.
And it worked. I can read the book, but I don't want to read the book on my little phone screen. So, I transferred the PDF file that Bluefire Reader downloaded to my laptop in hopes that I could open it using a simple PDF reader. Then I double click on the PDF file with a smirk on my face... and it asks me for a password.
I hope you can understand my frustration. All I want to do is read the book that I legally purchased on my laptop so that I can complete my homework and get on with my life. I tried using other eBook readers like [Calibre](http://calibre-ebook.com/) but it requires that I convert my ACSM file to EPUB using Adobe Digital Editions (which doesn't work for me). What other alternatives do I have?
|
2016/01/17
|
[
"https://superuser.com/questions/1027608",
"https://superuser.com",
"https://superuser.com/users/328397/"
] |
The question is quite old, but people like myself still trip up on DRM locked ebooks. I assume you want to get out of the acsm a DRM-free epub. My instruction is for Ubuntu/Debian using apt-get, but the tools exist for other distros as well. I need a couple of tools in particular: the [DeDRM tool](https://github.com/apprenticeharper/DeDRM_tools/releases) for python2.7 and wine. On wine, we will install Adobe Digital Editions, python and pip for windows
1. Install wine and winetricks because we will run Adobe Digital Editions in wine. By default ubuntu19.10 intalled wine 4 on my machine. Its easier to [upgrade to wine5](https://linuxconfig.org/install-wine-on-ubuntu-20-04-focal-fossa-linux) first. ADE works so much better with wine5.
```
sudo apt-get install winehq-stable winetricks winbind
```
2. Install dotnet40
```
winetricks dotnet40
```
3. Now download [Adobe Digital Editions](https://www.adobe.com/solutions/ebook/digital-editions/download.html) for Windows and install it:
```
wine Downloads/ADE_4.5_Installer.exe
```
4. After installing and launching DigitalEditions you will need to authorize you computer or log in with your [adobe id](https://account.adobe.com/) if you don`t have one create it for free.
5. Open in ADE the acsm file. It will download the epub into your user documents folder (e.g., ~/Documents ) in sub dir "My\ Digital\ Editions". Note that the file is still DRM protected.
6. Now its time to run DeDRM from python wine. Unzip [DeDRM tool Version 6.x](https://github.com/apprenticeharper/DeDRM_tools/releases) and locate the adobekey.py file.
7. Install python, pip and pycryptodome:
```
winetricks python27 # this should also install pip
wine pip install pycryptodome
```
8. Run adobekey.py from the dedrm you downloaded before with wine python:
```
wine ~/.wine/drive_c/Python27/python.exe adobekey.py
```
9. You get the adobekey\_1.der that you need to run the other script:
```
python ineptepub.py adobekey_1.der ~/Path/to/drm_locked.epub your_drm_free_out.epub
```
For pdfs use 'ineptpdf.py' inststead of 'ineptepub.py'. If you get an [error](https://github.com/apprenticeharper/DeDRM_tools/issues/928) in this step about python, adjust the term 'python', to 'python2' or 'python3'.
10. You should get the output:
```
Successfully decrypted drm_locked.epub as your_drm_free_out.epub
```
Done. Read your epub on any epub reader, e.g., okular, readera, lithium.
To be sure, this is quite a few steps. However, ADE is not a good reader, and the reading experience using wine even worse. I disagree that removing DRM is not legal; for personal use [it's perfectly fine](https://gizmodo.com/its-perfectly-legal-to-tell-people-how-to-remove-drm-1670223538) to remove DRM from your purchased ebooks. Publishers, of course, have an interest in reducing and controlling access to the material. [EFF](https://www.eff.org/deeplinks/2017/05/book-review-end-ownership) has some interesting articles on DMCA, DRM, and copyright. Have fun reading.
|
I will try to list all the solutions I've found.
First one. Tested solution: working, and very easy.
First install *Wine* on your Linux. Then download Adobe Digital editions.
[Link to download Adobe Digital editions](https://www.adobe.com/fr/solutions/ebook/digital-editions/download.html)
Then, install the file you dowloaded from Adobe (It was ADE\_4.5\_Installer.exe, for me), in the Wine virtual Window. If you don't know how to use wine, see this doc: [How to install and use Wine on Linux](https://www.linux.com/learn/how-install-and-use-wine-run-windows-applications-linux)
Second solution:
Install a virtual Windows on Linux. [How to](http://www.makeuseof.com/tag/set-windows-virtual-machine-linux/).
Third solution: If you failed to install virtual machine or open with Wine, and if you really need this program, install a dual boot on your computer Windows/Linux. [How to dual boot Windows/linux on the same computer](https://www.howtogeek.com/214571/how-to-dual-boot-linux-on-your-pc/%20%22How%20to%20dual%20boot%20Windows/Linux%20on%20the%20same%20computer)
4th solution, use a virtual Android phone (or a real one) and install the Adobe Digital editions for Android.
[Virtual smartphone software, Memu](http://www.memuplay.com)
You can also try to emulate MacOs, or iOS.
There are solutions to remove the DRM, and so convert the acsm into epub, but there are no legal, so I don't think I'm allowed to write them.
|
1,027,608
|
So, I needed the [Semantics Engineering with PLT Redex](https://mitpress.mit.edu/books/semantics-engineering-plt-redex) textbook to complete a homework assignment this week. I needed it in a digital format because I'm going to [POPL 2016](http://conf.researchr.org/home/POPL-2016) tomorrow and I can't have it delivered to me. Hence, I paid $50 for the eBook so that I could complete my homework.
The problem is that I'm using [Arch Linux](https://www.archlinux.org/) and for some reason [Adobe Digital Editions](https://aur.archlinux.org/packages/adobe-digital-editions/) doesn't work for me. During installation it said that it might not work on a 64-bit system. Anyway, I tried to find an alternative solution and I learned that I could read the book using [Bluefire Reader](http://www.bluefirereader.com/) on my phone.
And it worked. I can read the book, but I don't want to read the book on my little phone screen. So, I transferred the PDF file that Bluefire Reader downloaded to my laptop in hopes that I could open it using a simple PDF reader. Then I double click on the PDF file with a smirk on my face... and it asks me for a password.
I hope you can understand my frustration. All I want to do is read the book that I legally purchased on my laptop so that I can complete my homework and get on with my life. I tried using other eBook readers like [Calibre](http://calibre-ebook.com/) but it requires that I convert my ACSM file to EPUB using Adobe Digital Editions (which doesn't work for me). What other alternatives do I have?
|
2016/01/17
|
[
"https://superuser.com/questions/1027608",
"https://superuser.com",
"https://superuser.com/users/328397/"
] |
I created a program called [Knock](https://github.com/BentonEdmondson/knock) to convert ACSM files to DRM-free EPUB files at the command line:
```
[user@computer:~]$ knock ./example.acsm
downloading the file from Adobe...
removing DRM from the file...
DRM-free EPUB file generated at ./example.epub
```
It doesn't use Adobe Digital Editions and it doesn't use Wine. It is completely free and open-source software for native Linux.
|
I will try to list all the solutions I've found.
First one. Tested solution: working, and very easy.
First install *Wine* on your Linux. Then download Adobe Digital editions.
[Link to download Adobe Digital editions](https://www.adobe.com/fr/solutions/ebook/digital-editions/download.html)
Then, install the file you dowloaded from Adobe (It was ADE\_4.5\_Installer.exe, for me), in the Wine virtual Window. If you don't know how to use wine, see this doc: [How to install and use Wine on Linux](https://www.linux.com/learn/how-install-and-use-wine-run-windows-applications-linux)
Second solution:
Install a virtual Windows on Linux. [How to](http://www.makeuseof.com/tag/set-windows-virtual-machine-linux/).
Third solution: If you failed to install virtual machine or open with Wine, and if you really need this program, install a dual boot on your computer Windows/Linux. [How to dual boot Windows/linux on the same computer](https://www.howtogeek.com/214571/how-to-dual-boot-linux-on-your-pc/%20%22How%20to%20dual%20boot%20Windows/Linux%20on%20the%20same%20computer)
4th solution, use a virtual Android phone (or a real one) and install the Adobe Digital editions for Android.
[Virtual smartphone software, Memu](http://www.memuplay.com)
You can also try to emulate MacOs, or iOS.
There are solutions to remove the DRM, and so convert the acsm into epub, but there are no legal, so I don't think I'm allowed to write them.
|
1,027,608
|
So, I needed the [Semantics Engineering with PLT Redex](https://mitpress.mit.edu/books/semantics-engineering-plt-redex) textbook to complete a homework assignment this week. I needed it in a digital format because I'm going to [POPL 2016](http://conf.researchr.org/home/POPL-2016) tomorrow and I can't have it delivered to me. Hence, I paid $50 for the eBook so that I could complete my homework.
The problem is that I'm using [Arch Linux](https://www.archlinux.org/) and for some reason [Adobe Digital Editions](https://aur.archlinux.org/packages/adobe-digital-editions/) doesn't work for me. During installation it said that it might not work on a 64-bit system. Anyway, I tried to find an alternative solution and I learned that I could read the book using [Bluefire Reader](http://www.bluefirereader.com/) on my phone.
And it worked. I can read the book, but I don't want to read the book on my little phone screen. So, I transferred the PDF file that Bluefire Reader downloaded to my laptop in hopes that I could open it using a simple PDF reader. Then I double click on the PDF file with a smirk on my face... and it asks me for a password.
I hope you can understand my frustration. All I want to do is read the book that I legally purchased on my laptop so that I can complete my homework and get on with my life. I tried using other eBook readers like [Calibre](http://calibre-ebook.com/) but it requires that I convert my ACSM file to EPUB using Adobe Digital Editions (which doesn't work for me). What other alternatives do I have?
|
2016/01/17
|
[
"https://superuser.com/questions/1027608",
"https://superuser.com",
"https://superuser.com/users/328397/"
] |
I will try to list all the solutions I've found.
First one. Tested solution: working, and very easy.
First install *Wine* on your Linux. Then download Adobe Digital editions.
[Link to download Adobe Digital editions](https://www.adobe.com/fr/solutions/ebook/digital-editions/download.html)
Then, install the file you dowloaded from Adobe (It was ADE\_4.5\_Installer.exe, for me), in the Wine virtual Window. If you don't know how to use wine, see this doc: [How to install and use Wine on Linux](https://www.linux.com/learn/how-install-and-use-wine-run-windows-applications-linux)
Second solution:
Install a virtual Windows on Linux. [How to](http://www.makeuseof.com/tag/set-windows-virtual-machine-linux/).
Third solution: If you failed to install virtual machine or open with Wine, and if you really need this program, install a dual boot on your computer Windows/Linux. [How to dual boot Windows/linux on the same computer](https://www.howtogeek.com/214571/how-to-dual-boot-linux-on-your-pc/%20%22How%20to%20dual%20boot%20Windows/Linux%20on%20the%20same%20computer)
4th solution, use a virtual Android phone (or a real one) and install the Adobe Digital editions for Android.
[Virtual smartphone software, Memu](http://www.memuplay.com)
You can also try to emulate MacOs, or iOS.
There are solutions to remove the DRM, and so convert the acsm into epub, but there are no legal, so I don't think I'm allowed to write them.
|
I have also used release of 'knock' downloaded from Web Archive (<https://web.archive.org/web/20221020182238mp_/https://github.com/BentonEdmondson/knock/releases/download/1.3.1/knock-1.3.1-x86_64-linux>). Worked very well - thank you [@BentonEdmontson](https://superuser.com/users/1470682/bentonedmondson) !
|
1,027,608
|
So, I needed the [Semantics Engineering with PLT Redex](https://mitpress.mit.edu/books/semantics-engineering-plt-redex) textbook to complete a homework assignment this week. I needed it in a digital format because I'm going to [POPL 2016](http://conf.researchr.org/home/POPL-2016) tomorrow and I can't have it delivered to me. Hence, I paid $50 for the eBook so that I could complete my homework.
The problem is that I'm using [Arch Linux](https://www.archlinux.org/) and for some reason [Adobe Digital Editions](https://aur.archlinux.org/packages/adobe-digital-editions/) doesn't work for me. During installation it said that it might not work on a 64-bit system. Anyway, I tried to find an alternative solution and I learned that I could read the book using [Bluefire Reader](http://www.bluefirereader.com/) on my phone.
And it worked. I can read the book, but I don't want to read the book on my little phone screen. So, I transferred the PDF file that Bluefire Reader downloaded to my laptop in hopes that I could open it using a simple PDF reader. Then I double click on the PDF file with a smirk on my face... and it asks me for a password.
I hope you can understand my frustration. All I want to do is read the book that I legally purchased on my laptop so that I can complete my homework and get on with my life. I tried using other eBook readers like [Calibre](http://calibre-ebook.com/) but it requires that I convert my ACSM file to EPUB using Adobe Digital Editions (which doesn't work for me). What other alternatives do I have?
|
2016/01/17
|
[
"https://superuser.com/questions/1027608",
"https://superuser.com",
"https://superuser.com/users/328397/"
] |
I created a program called [Knock](https://github.com/BentonEdmondson/knock) to convert ACSM files to DRM-free EPUB files at the command line:
```
[user@computer:~]$ knock ./example.acsm
downloading the file from Adobe...
removing DRM from the file...
DRM-free EPUB file generated at ./example.epub
```
It doesn't use Adobe Digital Editions and it doesn't use Wine. It is completely free and open-source software for native Linux.
|
The question is quite old, but people like myself still trip up on DRM locked ebooks. I assume you want to get out of the acsm a DRM-free epub. My instruction is for Ubuntu/Debian using apt-get, but the tools exist for other distros as well. I need a couple of tools in particular: the [DeDRM tool](https://github.com/apprenticeharper/DeDRM_tools/releases) for python2.7 and wine. On wine, we will install Adobe Digital Editions, python and pip for windows
1. Install wine and winetricks because we will run Adobe Digital Editions in wine. By default ubuntu19.10 intalled wine 4 on my machine. Its easier to [upgrade to wine5](https://linuxconfig.org/install-wine-on-ubuntu-20-04-focal-fossa-linux) first. ADE works so much better with wine5.
```
sudo apt-get install winehq-stable winetricks winbind
```
2. Install dotnet40
```
winetricks dotnet40
```
3. Now download [Adobe Digital Editions](https://www.adobe.com/solutions/ebook/digital-editions/download.html) for Windows and install it:
```
wine Downloads/ADE_4.5_Installer.exe
```
4. After installing and launching DigitalEditions you will need to authorize you computer or log in with your [adobe id](https://account.adobe.com/) if you don`t have one create it for free.
5. Open in ADE the acsm file. It will download the epub into your user documents folder (e.g., ~/Documents ) in sub dir "My\ Digital\ Editions". Note that the file is still DRM protected.
6. Now its time to run DeDRM from python wine. Unzip [DeDRM tool Version 6.x](https://github.com/apprenticeharper/DeDRM_tools/releases) and locate the adobekey.py file.
7. Install python, pip and pycryptodome:
```
winetricks python27 # this should also install pip
wine pip install pycryptodome
```
8. Run adobekey.py from the dedrm you downloaded before with wine python:
```
wine ~/.wine/drive_c/Python27/python.exe adobekey.py
```
9. You get the adobekey\_1.der that you need to run the other script:
```
python ineptepub.py adobekey_1.der ~/Path/to/drm_locked.epub your_drm_free_out.epub
```
For pdfs use 'ineptpdf.py' inststead of 'ineptepub.py'. If you get an [error](https://github.com/apprenticeharper/DeDRM_tools/issues/928) in this step about python, adjust the term 'python', to 'python2' or 'python3'.
10. You should get the output:
```
Successfully decrypted drm_locked.epub as your_drm_free_out.epub
```
Done. Read your epub on any epub reader, e.g., okular, readera, lithium.
To be sure, this is quite a few steps. However, ADE is not a good reader, and the reading experience using wine even worse. I disagree that removing DRM is not legal; for personal use [it's perfectly fine](https://gizmodo.com/its-perfectly-legal-to-tell-people-how-to-remove-drm-1670223538) to remove DRM from your purchased ebooks. Publishers, of course, have an interest in reducing and controlling access to the material. [EFF](https://www.eff.org/deeplinks/2017/05/book-review-end-ownership) has some interesting articles on DMCA, DRM, and copyright. Have fun reading.
|
1,027,608
|
So, I needed the [Semantics Engineering with PLT Redex](https://mitpress.mit.edu/books/semantics-engineering-plt-redex) textbook to complete a homework assignment this week. I needed it in a digital format because I'm going to [POPL 2016](http://conf.researchr.org/home/POPL-2016) tomorrow and I can't have it delivered to me. Hence, I paid $50 for the eBook so that I could complete my homework.
The problem is that I'm using [Arch Linux](https://www.archlinux.org/) and for some reason [Adobe Digital Editions](https://aur.archlinux.org/packages/adobe-digital-editions/) doesn't work for me. During installation it said that it might not work on a 64-bit system. Anyway, I tried to find an alternative solution and I learned that I could read the book using [Bluefire Reader](http://www.bluefirereader.com/) on my phone.
And it worked. I can read the book, but I don't want to read the book on my little phone screen. So, I transferred the PDF file that Bluefire Reader downloaded to my laptop in hopes that I could open it using a simple PDF reader. Then I double click on the PDF file with a smirk on my face... and it asks me for a password.
I hope you can understand my frustration. All I want to do is read the book that I legally purchased on my laptop so that I can complete my homework and get on with my life. I tried using other eBook readers like [Calibre](http://calibre-ebook.com/) but it requires that I convert my ACSM file to EPUB using Adobe Digital Editions (which doesn't work for me). What other alternatives do I have?
|
2016/01/17
|
[
"https://superuser.com/questions/1027608",
"https://superuser.com",
"https://superuser.com/users/328397/"
] |
The question is quite old, but people like myself still trip up on DRM locked ebooks. I assume you want to get out of the acsm a DRM-free epub. My instruction is for Ubuntu/Debian using apt-get, but the tools exist for other distros as well. I need a couple of tools in particular: the [DeDRM tool](https://github.com/apprenticeharper/DeDRM_tools/releases) for python2.7 and wine. On wine, we will install Adobe Digital Editions, python and pip for windows
1. Install wine and winetricks because we will run Adobe Digital Editions in wine. By default ubuntu19.10 intalled wine 4 on my machine. Its easier to [upgrade to wine5](https://linuxconfig.org/install-wine-on-ubuntu-20-04-focal-fossa-linux) first. ADE works so much better with wine5.
```
sudo apt-get install winehq-stable winetricks winbind
```
2. Install dotnet40
```
winetricks dotnet40
```
3. Now download [Adobe Digital Editions](https://www.adobe.com/solutions/ebook/digital-editions/download.html) for Windows and install it:
```
wine Downloads/ADE_4.5_Installer.exe
```
4. After installing and launching DigitalEditions you will need to authorize you computer or log in with your [adobe id](https://account.adobe.com/) if you don`t have one create it for free.
5. Open in ADE the acsm file. It will download the epub into your user documents folder (e.g., ~/Documents ) in sub dir "My\ Digital\ Editions". Note that the file is still DRM protected.
6. Now its time to run DeDRM from python wine. Unzip [DeDRM tool Version 6.x](https://github.com/apprenticeharper/DeDRM_tools/releases) and locate the adobekey.py file.
7. Install python, pip and pycryptodome:
```
winetricks python27 # this should also install pip
wine pip install pycryptodome
```
8. Run adobekey.py from the dedrm you downloaded before with wine python:
```
wine ~/.wine/drive_c/Python27/python.exe adobekey.py
```
9. You get the adobekey\_1.der that you need to run the other script:
```
python ineptepub.py adobekey_1.der ~/Path/to/drm_locked.epub your_drm_free_out.epub
```
For pdfs use 'ineptpdf.py' inststead of 'ineptepub.py'. If you get an [error](https://github.com/apprenticeharper/DeDRM_tools/issues/928) in this step about python, adjust the term 'python', to 'python2' or 'python3'.
10. You should get the output:
```
Successfully decrypted drm_locked.epub as your_drm_free_out.epub
```
Done. Read your epub on any epub reader, e.g., okular, readera, lithium.
To be sure, this is quite a few steps. However, ADE is not a good reader, and the reading experience using wine even worse. I disagree that removing DRM is not legal; for personal use [it's perfectly fine](https://gizmodo.com/its-perfectly-legal-to-tell-people-how-to-remove-drm-1670223538) to remove DRM from your purchased ebooks. Publishers, of course, have an interest in reducing and controlling access to the material. [EFF](https://www.eff.org/deeplinks/2017/05/book-review-end-ownership) has some interesting articles on DMCA, DRM, and copyright. Have fun reading.
|
I have also used release of 'knock' downloaded from Web Archive (<https://web.archive.org/web/20221020182238mp_/https://github.com/BentonEdmondson/knock/releases/download/1.3.1/knock-1.3.1-x86_64-linux>). Worked very well - thank you [@BentonEdmontson](https://superuser.com/users/1470682/bentonedmondson) !
|
1,027,608
|
So, I needed the [Semantics Engineering with PLT Redex](https://mitpress.mit.edu/books/semantics-engineering-plt-redex) textbook to complete a homework assignment this week. I needed it in a digital format because I'm going to [POPL 2016](http://conf.researchr.org/home/POPL-2016) tomorrow and I can't have it delivered to me. Hence, I paid $50 for the eBook so that I could complete my homework.
The problem is that I'm using [Arch Linux](https://www.archlinux.org/) and for some reason [Adobe Digital Editions](https://aur.archlinux.org/packages/adobe-digital-editions/) doesn't work for me. During installation it said that it might not work on a 64-bit system. Anyway, I tried to find an alternative solution and I learned that I could read the book using [Bluefire Reader](http://www.bluefirereader.com/) on my phone.
And it worked. I can read the book, but I don't want to read the book on my little phone screen. So, I transferred the PDF file that Bluefire Reader downloaded to my laptop in hopes that I could open it using a simple PDF reader. Then I double click on the PDF file with a smirk on my face... and it asks me for a password.
I hope you can understand my frustration. All I want to do is read the book that I legally purchased on my laptop so that I can complete my homework and get on with my life. I tried using other eBook readers like [Calibre](http://calibre-ebook.com/) but it requires that I convert my ACSM file to EPUB using Adobe Digital Editions (which doesn't work for me). What other alternatives do I have?
|
2016/01/17
|
[
"https://superuser.com/questions/1027608",
"https://superuser.com",
"https://superuser.com/users/328397/"
] |
I created a program called [Knock](https://github.com/BentonEdmondson/knock) to convert ACSM files to DRM-free EPUB files at the command line:
```
[user@computer:~]$ knock ./example.acsm
downloading the file from Adobe...
removing DRM from the file...
DRM-free EPUB file generated at ./example.epub
```
It doesn't use Adobe Digital Editions and it doesn't use Wine. It is completely free and open-source software for native Linux.
|
I have also used release of 'knock' downloaded from Web Archive (<https://web.archive.org/web/20221020182238mp_/https://github.com/BentonEdmondson/knock/releases/download/1.3.1/knock-1.3.1-x86_64-linux>). Worked very well - thank you [@BentonEdmontson](https://superuser.com/users/1470682/bentonedmondson) !
|
52,380,746
|
I am trying to integrate [an eBay SDK](https://github.com/davidtsadler/ebay-sdk-examples) developed by David Sadler which is in GitHub. But I got stuck on connection part itself. I am getting app token with <http://localhost/ebay-sdk-examples/oauth-tokens/01-get-app-token.php> with my production credentials.
But when I hit, <http://localhost/ebay-sdk-examples/oauth-tokens/02-get-user-token.php> it gives me this error:
```
[error] => invalid_grant
[error_description] => the provided authorization grant code is invalid or was issued to another client
```
all The codes are available in the SDK link. Incase you need here is the code snippet
```
<?php
/**
* Copyright 2017 David T. Sadler
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Include the SDK by using the autoloader from Composer.
*/
require __DIR__ . '/../vendor/autoload.php';
/**
* Include the configuration values.
*
* Ensure that you have edited the configuration.php file
* to include your application keys.
*/
$config = require __DIR__ . '/../configuration.php';
/**
* The namespaces provided by the SDK.
*/
use \DTS\eBaySDK\OAuth\Services;
use \DTS\eBaySDK\OAuth\Types;
/**
* Create the service object.
*/
$service = new Services\OAuthService([
'credentials' => $config['production']['credentials'],
'ruName' => $config['production']['ruName'],
'sandbox' => false,
]);
$token = $config['production']['testToken']; ** This is the app token I get with http://localhost/ebay-sdk-examples/oauth-tokens/01-get-app-token.php **
/**
* Create the request object.
*/
$request = new Types\GetUserTokenRestRequest();
$request->code = $token;
// $request->code = 'v^1.1#i^1#I^3#r^1#p^3#f^0#t^Ul41XzA6MkIzRjJFRjA1MENDMzZCQjlGMjVERkYyMkMxMTRBM0VfMV8xI0VeMjYw';
/**
* Send the request.
*/
$response = $service->getUserToken($request);
echo '<pre>';
print_r($response);
echo '<pre>';
exit;
/**
* Output the result of calling the service operation.
*/
printf("\nStatus Code: %s\n\n", $response->getStatusCode());
if ($response->getStatusCode() !== 200) {
printf(
"%s: %s\n\n",
$response->error,
$response->error_description
);
} else {
printf(
"%s\n%s\n%s\n%s\n\n",
$response->access_token,
$response->token_type,
$response->expires_in,
$response->refresh_token
);
}
```
If there are simple codes to without using any SDK to connect to eBay with OAuth, its what I am searching for.
|
2018/09/18
|
[
"https://Stackoverflow.com/questions/52380746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7333870/"
] |
Try this
html
```
<button type="button" (click)="check()"></button>
```
TS
```
check(){
let data = {
id: id, // custom values here
};
this._router.navigate([ 'custom-url' ], { queryParams:data });
}
```
|
To pass data from one component to another you can use query parameters.
In home component, when form submitted - navigate to table route and pass query parameters:
```js
onSubmit(): void {
this.router.navigate(['/table'], {
queryParams: { start: '2', end: '9' }
});
}
```
In xxx component (e.g. table component) read query parameters:
```js
ngOnInit(): void {
this.activatedRoute.queryParamMap.subscribe(params => {
// Get parameters
this.start = params.get('start');
this.end = params.get('end');
});
}
```
|
578,686
|
I use MAAS to make landscape openstack outopilot. I use `sudo openstack-install` but failed. This is my commands.log
```
INFO • 01-28 11:21:33 [LINE:156, FUNC:<module>] • cloudinstall • cloud-install $
DEBUG • 01-28 11:21:33 [LINE:111, FUNC:main_loop] • cloudinstall.install • loop$
INFO • 01-28 11:21:33 [LINE:71, FUNC:status_context] • cloudinstall.core • Get $
DEBUG • 01-28 11:21:33 [LINE:93, FUNC:_build_widget] • cloudinstall.ui.dialog •$
DEBUG • 01-28 11:21:39 [LINE:111, FUNC:submit] • cloudinstall.ui.dialog • Callb$
INFO • 01-28 11:21:39 [LINE:71, FUNC:status_context] • cloudinstall.core • Choo$
DEBUG • 01-28 11:21:41 [LINE:214, FUNC:submit] • cloudinstall.ui • Callback on $
INFO • 01-28 11:21:41 [LINE:71, FUNC:status_context] • cloudinstall.core • Plea$
DEBUG • 01-28 11:21:41 [LINE:93, FUNC:_build_widget] • cloudinstall.ui.dialog •$
DEBUG • 01-28 11:26:02 [LINE:111, FUNC:submit] • cloudinstall.ui.dialog • Callb$
DEBUG • 01-28 11:26:02 [LINE:81, FUNC:_save_lds_creds] • cloudinstall.landscape$
INFO • 01-28 11:26:02 [LINE:71, FUNC:status_context] • cloudinstall.core • Wait$
DEBUG • 01-28 11:27:13 [LINE:650, FUNC:ssh_genkey] • cloudinstall.utils • ssh k$
INFO • 01-28 11:27:13 [LINE:71, FUNC:status_context] • cloudinstall.core • Boot$
DEBUG • 01-28 11:27:13 [LINE:139, FUNC:do_install] • cloudinstall.multi_install$
DEBUG • 01-28 12:27:34 [LINE:145, FUNC:do_install] • cloudinstall.multi_install$
DEBUG • 01-28 12:27:34 [LINE:51, FUNC:global_exchandler] • cloudinstall.utils •$
File "/usr/share/openstack/cloudinstall/utils.py", line 66, in run
super().run()
File "/usr/lib/python3.4/threading.py", line 868, in run
self._target(*self._args, **self._kwargs)
File "/usr/share/openstack/cloudinstall/machinewait.py", line 127, in do_cont$
self.installer.do_install()
File "/usr/share/openstack/cloudinstall/multi_install.py", line 146, in do_in$
raise Exception("Problem with juju bootstrap.")
Exception: Problem with juju bootstrap.
```
How can I fix it's ?
|
2015/01/28
|
[
"https://askubuntu.com/questions/578686",
"https://askubuntu.com",
"https://askubuntu.com/users/186239/"
] |
I've seen anecdotal evidence on the juju mailing list that using juju from the juju stable ppa resolved this issue for at least one person.
Here's the [mailing list post](https://lists.ubuntu.com/archives/juju/2014-May/003849.html)
|
It could be issue like mine, described here [Failed to bootstrap during Openstack autopilot installation](https://askubuntu.com/questions/714767/faild-to-bootstrap-during-openstack-autopilot-installation)
Update your libraries with these command and start landscape installation again:
```
sudo apt-get update
sudo apt-get dist-upgrade
```
Also update your images of MAAS, through maas web ui.
|
277,053
|
According to [answers to this question](https://electronics.stackexchange.com/questions/25055/slow-blow-vs-fast-acting-fuse) there seem to be a standardized notation on fuses. For example F8AL250V means that it's a 8A fast fuse.
On the other hand there is [answers this question](https://electronics.stackexchange.com/questions/231442/how-slow-is-a-class-t-slow-blow-fuse) stating the importance of checking the datasheet for specifications on when the fuse should blow.
Pulling these answers together appears to be contradicting. While F8AL250V says 8A fast fuse you seem to have to consult the datasheet to find out what that means (which makes the notation doesn't mean anything in particular). This would also be unfortunate since it would require an end user to consult datasheets (he's not likely to understand) instead of just insisting him to use the F8AL250V fuse.
Is there a standard of requirements on fast and slow fuses regarding time-current characteristics? What does the standard say about the time before the fuse blows for various over-currents?
My specific situation is that I'm considering a power supply (Velleman FPS1320M), the load may briefely draw more than 8A. The question is if a fast 8A fuse will be adequate. For example what amount of time can I expect the fuse to withstand 16A at a minimum (I don't have the number, but I think it's just needed to last for a minute or so) and how fast can I expect it to blow (according to the PS manual it has to blow within two hours). How fast can I expect it to blow at 20 or 22A (needs to blow within 30 respectively 1 minute).
|
2016/12/27
|
[
"https://electronics.stackexchange.com/questions/277053",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/134268/"
] |
Individual manufacturers may have a consistent naming systems to identify slow, really slow, fast, turbo fast, or whatever, within their product line. Some smaller manufacturers may have copied parts of the designations from a dominant manufacturer, but you shouldn't count on that. Ultimately, only the datasheet tells you how fast or slow fast or slow really are.
End users shouldn't have to consult datasheets, and can't be counted onto understand them if they did. This is no different from any other component in a device. The way to handle this is to tell them the replacement part number explicitly.
For a common type of fuse, you can write something like "1A 250VAC" near the fuse holder, but that should be for convenience at best. Somewhere in your documentation it should say that the fuse is a Acme ICUB4UCME-1A, or equivalent. If they put in something else, the liability is now on them.
|
Slow is a relative term. Fast is a relative term. I wouldn't expect exact meanings for these two words.
More specific meanings of the words might be drawn from the context in which the term is used.
When using the **science** of electrical engineering, it is natural that the specific meaning of slow or fast should be found in a data sheet. Which would also give the conditions where the item would be slow or fast.
>
> "require an end user to consult datasheets (he's not likely to understand)"
>
>
>
Thankfully there are instructors, classes, on line help (such as EE.SE), and Books to help gain understanding.
|
277,053
|
According to [answers to this question](https://electronics.stackexchange.com/questions/25055/slow-blow-vs-fast-acting-fuse) there seem to be a standardized notation on fuses. For example F8AL250V means that it's a 8A fast fuse.
On the other hand there is [answers this question](https://electronics.stackexchange.com/questions/231442/how-slow-is-a-class-t-slow-blow-fuse) stating the importance of checking the datasheet for specifications on when the fuse should blow.
Pulling these answers together appears to be contradicting. While F8AL250V says 8A fast fuse you seem to have to consult the datasheet to find out what that means (which makes the notation doesn't mean anything in particular). This would also be unfortunate since it would require an end user to consult datasheets (he's not likely to understand) instead of just insisting him to use the F8AL250V fuse.
Is there a standard of requirements on fast and slow fuses regarding time-current characteristics? What does the standard say about the time before the fuse blows for various over-currents?
My specific situation is that I'm considering a power supply (Velleman FPS1320M), the load may briefely draw more than 8A. The question is if a fast 8A fuse will be adequate. For example what amount of time can I expect the fuse to withstand 16A at a minimum (I don't have the number, but I think it's just needed to last for a minute or so) and how fast can I expect it to blow (according to the PS manual it has to blow within two hours). How fast can I expect it to blow at 20 or 22A (needs to blow within 30 respectively 1 minute).
|
2016/12/27
|
[
"https://electronics.stackexchange.com/questions/277053",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/134268/"
] |
Every manufacturer has their own numbering system. Some numbers tell more about the products than others. It seems fairly easy to interpret that F8AL250V means an 8 amp, 250 volt fast-blowing fuse. It is a little more difficult to tell that it is a 5 X 20 mm glass tube fuse. Littelfuse shows 217008 as a replacement and Bussmann shows S500-8-R. Bussman also offers a version that has wire leads. Both Littelfuse and Bussmann give the interrupting rating as 80 amps. It appears that the F8AL250V manufacturer number is used by ShengBaiDe Electronics of China. It is customary for a product manufacturer to mark the product or provide in the instructions brand and number of the original fuse. If the end user can not find that fuse, their best alternative is to find a cross reference chart provided by another manufacturer and use the replacement recommended there. Littelfuse and Bussmann both have online cross reference search tools. They are left with some risk that the selected fuse will not protect the equipment as well as the original fuse did.
If a designer wants to find an alternative fuse, it is best to consult the datasheets. Datasheets provide curves and other information that should be used when selecting a fuse for a new design.
|
Slow is a relative term. Fast is a relative term. I wouldn't expect exact meanings for these two words.
More specific meanings of the words might be drawn from the context in which the term is used.
When using the **science** of electrical engineering, it is natural that the specific meaning of slow or fast should be found in a data sheet. Which would also give the conditions where the item would be slow or fast.
>
> "require an end user to consult datasheets (he's not likely to understand)"
>
>
>
Thankfully there are instructors, classes, on line help (such as EE.SE), and Books to help gain understanding.
|
12,579,301
|
I have three values that should in total come to 100 at all times
the user can only change one value at a time (by increments think slider it might not be single increments at a time)
when one value changes I want the others to also change to reflect the constant total, however on a pro rata basis
The larger of the other two values should increase more than the smaller value
but should decrease less than the smaller value
|
2012/09/25
|
[
"https://Stackoverflow.com/questions/12579301",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/297042/"
] |
Not sure what you mean by "but should decrease less than the smaller value" - this seems to indicate it's *not* pro-rata, especially if the ratios are maintained only in one direction.
Assuming that's a mistake, the way to pro-rata the non-moving values `b` and `c` is simply to maintain their ratio when the moving value `a` changes, something like:
```
a = 50, b = 30, c = 20 # initial values
aDelta = 10 # how much to change 'a' by
bDelta = -aDelta * b / (b + c) # bDelta <- -6
cDelta = -aDelta - bDelta # cDelta <- -4
a = a + aDelta # a <- 60
b = b + bDelta # b <- 24
c = c + cDelta # c <- 16
```
You can see there that the ratio remains the same between `b` and `c` (`30:20` and `24:16` are both `3:2`), at least until the values get small enough for rounding errors to come into play (reducing them, then increasing them may not give you back the exact values you started with).
If that's important, you could consider using floating point for the values and simply turn them into integers as a final step.
|
as B and C also need to be calculated posted here in pascal (first IDE to hand) to show complete solution
```
if inhibit then exit; { stop position changes in callback calling this! }
inhibit:=true;
if (sender=TrackBar1) then begin
aDelta:= trunc(TrackBar1.Position)-a;
bDelta:= -aDelta * b / (b + c);
cDelta:= -aDelta - bDelta;
end;
if (sender=TrackBar2) then begin
bDelta:= trunc(TrackBar2.Position)-b;
aDelta:= -bDelta * a / (a + c);
cDelta:= -bDelta - aDelta;
end;
if (sender=TrackBar3) then begin
cDelta:= trunc(TrackBar3.Position)-c;
bDelta:= -cDelta * b / (b + a);
aDelta:= -cDelta - bDelta;
end;
a:= a+aDelta;
b:= b+bDelta;
c:= c+cDelta;
TrackBar1.Position:=trunc(a);
TrackBar2.Position:=trunc(b);
TrackBar3.Position:=trunc(c);
label1.Caption:=FormatFloat('###.##',a);
label2.Caption:=FormatFloat('###.##',b);
label3.Caption:=FormatFloat('###.##',c);
label4.Caption:=FormatFloat('###.##',a+b+c);
inhibit:=false;
```
|
17,164,004
|
I have a matrix named `xs`:
```
array([[1, 1, 1, 1, 1, 0, 1, 0, 0, 2, 1],
[2, 1, 0, 0, 0, 1, 2, 1, 1, 2, 2]])
```
Now I want to replace the zeros by the nearest previous element in the same row (Assuming that the first column must be nonzero.).
The rough solution as following:
```
In [55]: row, col = xs.shape
In [56]: for r in xrange(row):
....: for c in xrange(col):
....: if xs[r, c] == 0:
....: xs[r, c] = xs[r, c-1]
....:
In [57]: xs
Out[57]:
array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1],
[2, 1, 1, 1, 1, 1, 2, 1, 1, 2, 2]])
```
Any help will be greatly appreciated.
|
2013/06/18
|
[
"https://Stackoverflow.com/questions/17164004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172677/"
] |
If you can use [pandas](http://pandas.pydata.org/), [`replace`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html) will explicitly show the replacement in one instruction:
```
import pandas as pd
import numpy as np
a = np.array([[1, 1, 1, 1, 1, 0, 1, 0, 0, 2, 1],
[2, 1, 0, 0, 0, 1, 2, 1, 1, 2, 2]])
df = pd.DataFrame(a, dtype=np.float64)
df.replace(0, method='pad', axis=1)
```
|
My version, based on step-by-step rolling and masking of initial array, no additional libraries required (except numpy):
```
import numpy as np
a = np.array([[1, 1, 1, 1, 1, 0, 1, 0, 0, 2, 1],
[2, 1, 0, 0, 0, 1, 2, 1, 1, 2, 2]])
for i in xrange(a.shape[1]):
a[a == 0] = np.roll(a,i)[a == 0]
if not (a == 0).any(): # when all of zeros
break # are filled
print a
## [[1 1 1 1 1 1 1 1 1 2 1]
## [2 1 1 1 1 1 2 1 1 2 2]]
```
|
17,164,004
|
I have a matrix named `xs`:
```
array([[1, 1, 1, 1, 1, 0, 1, 0, 0, 2, 1],
[2, 1, 0, 0, 0, 1, 2, 1, 1, 2, 2]])
```
Now I want to replace the zeros by the nearest previous element in the same row (Assuming that the first column must be nonzero.).
The rough solution as following:
```
In [55]: row, col = xs.shape
In [56]: for r in xrange(row):
....: for c in xrange(col):
....: if xs[r, c] == 0:
....: xs[r, c] = xs[r, c-1]
....:
In [57]: xs
Out[57]:
array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1],
[2, 1, 1, 1, 1, 1, 2, 1, 1, 2, 2]])
```
Any help will be greatly appreciated.
|
2013/06/18
|
[
"https://Stackoverflow.com/questions/17164004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172677/"
] |
My version, based on step-by-step rolling and masking of initial array, no additional libraries required (except numpy):
```
import numpy as np
a = np.array([[1, 1, 1, 1, 1, 0, 1, 0, 0, 2, 1],
[2, 1, 0, 0, 0, 1, 2, 1, 1, 2, 2]])
for i in xrange(a.shape[1]):
a[a == 0] = np.roll(a,i)[a == 0]
if not (a == 0).any(): # when all of zeros
break # are filled
print a
## [[1 1 1 1 1 1 1 1 1 2 1]
## [2 1 1 1 1 1 2 1 1 2 2]]
```
|
Without going crazy with complicated indexing tricks that figure out consecutive zeros, you could have a `while` loop that goes for as many iterations as consecutive zeros there are in your array:
```
zero_rows, zero_cols = np.where(xs == 0)
while zero_cols :
xs[zero_rows, zero_cols] = xs[zero_rows, zero_cols-1]
zero_rows, zero_cols = np.where(xs == 0)
```
|
17,164,004
|
I have a matrix named `xs`:
```
array([[1, 1, 1, 1, 1, 0, 1, 0, 0, 2, 1],
[2, 1, 0, 0, 0, 1, 2, 1, 1, 2, 2]])
```
Now I want to replace the zeros by the nearest previous element in the same row (Assuming that the first column must be nonzero.).
The rough solution as following:
```
In [55]: row, col = xs.shape
In [56]: for r in xrange(row):
....: for c in xrange(col):
....: if xs[r, c] == 0:
....: xs[r, c] = xs[r, c-1]
....:
In [57]: xs
Out[57]:
array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1],
[2, 1, 1, 1, 1, 1, 2, 1, 1, 2, 2]])
```
Any help will be greatly appreciated.
|
2013/06/18
|
[
"https://Stackoverflow.com/questions/17164004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/172677/"
] |
If you can use [pandas](http://pandas.pydata.org/), [`replace`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html) will explicitly show the replacement in one instruction:
```
import pandas as pd
import numpy as np
a = np.array([[1, 1, 1, 1, 1, 0, 1, 0, 0, 2, 1],
[2, 1, 0, 0, 0, 1, 2, 1, 1, 2, 2]])
df = pd.DataFrame(a, dtype=np.float64)
df.replace(0, method='pad', axis=1)
```
|
Without going crazy with complicated indexing tricks that figure out consecutive zeros, you could have a `while` loop that goes for as many iterations as consecutive zeros there are in your array:
```
zero_rows, zero_cols = np.where(xs == 0)
while zero_cols :
xs[zero_rows, zero_cols] = xs[zero_rows, zero_cols-1]
zero_rows, zero_cols = np.where(xs == 0)
```
|
34,937,273
|
I have the following JS which uses `fadeToggle()` which works fine however it does a `display:none` so the 3rd element which I always display jumps up so wondering if its possible to change to change the `opacity` to **`0`** so in theory the block is still there and nothing moves.
JS
```
$('.ty-banner__image-item.gt-banner').bind('touchstart touchend', function(e) {
$(this).find('div.image .banner-overlay').fadeToggle('fade');
$(this).find('.content h2, .content p:first-child, .content p:eq(1)').fadeToggle();
});
```
Can I toggle to set `opacity` to **`0`** on a toggle?
updated to use toggle class to add class fade which just changes `opacity: 0` but need to fade it some how.
```
// mobile touch rubbish
$('.ty-banner__image-item.gt-banner').bind('touchstart touchend', function(e) {
$(this).find('div.image .banner-overlay').toggleClass('fade');
$(this).find('.content h2, .content p:not(".button")').toggleClass('fade');
});
```
|
2016/01/22
|
[
"https://Stackoverflow.com/questions/34937273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4520308/"
] |
Because your char array isn't null-terminated and is therefore not a string. If you omit the size altogether and specify the value as a string, not individual chars, the compiler will null-terminate it for you.
|
Read [the standard library](http://www.cplusplus.com/reference/string/basic_string/operator+/) which requires the C string when used with operator+ to be null terminated: "If of type charT\*, it shall point to a null-terminated character sequence." Yours is not null terminated. Try adding an extra element at the end of the char array that is 0.
|
34,937,273
|
I have the following JS which uses `fadeToggle()` which works fine however it does a `display:none` so the 3rd element which I always display jumps up so wondering if its possible to change to change the `opacity` to **`0`** so in theory the block is still there and nothing moves.
JS
```
$('.ty-banner__image-item.gt-banner').bind('touchstart touchend', function(e) {
$(this).find('div.image .banner-overlay').fadeToggle('fade');
$(this).find('.content h2, .content p:first-child, .content p:eq(1)').fadeToggle();
});
```
Can I toggle to set `opacity` to **`0`** on a toggle?
updated to use toggle class to add class fade which just changes `opacity: 0` but need to fade it some how.
```
// mobile touch rubbish
$('.ty-banner__image-item.gt-banner').bind('touchstart touchend', function(e) {
$(this).find('div.image .banner-overlay').toggleClass('fade');
$(this).find('.content h2, .content p:not(".button")').toggleClass('fade');
});
```
|
2016/01/22
|
[
"https://Stackoverflow.com/questions/34937273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4520308/"
] |
Because your char array isn't null-terminated and is therefore not a string. If you omit the size altogether and specify the value as a string, not individual chars, the compiler will null-terminate it for you.
|
Your char array is not 0 terminated, but plain c-strings must be 0 terminated:
```
char someCharArray[7] = {'H', 'e', 'l', 'l', 'o', ' ', 0};
```
This should work.
|
586,086
|
I use a virtual server (several similar cases) set up and registered by someone else. Its IP is `10.0.0.1` and name `a.example.com` (both handled by the "someone else" above).
I manage the domain `sub.example.com` and would like to also register this server as `b.sub.example.com`.
There are two ways of doing this in my DNS: either
```
b IN CNAME a.example.com.
```
or
```
b IN A 10.0.0.1
```
Since the IP is not distributed by DHCP (it is therefore hardcoded in the server config) there will be a problem in either case if it changes without me knowing and neither solution above would help. The `PTR` will point to `a.example.com` (I do not control the IP reverse mapping)
So what is the proper way (= canonical / best practice) to do the registration on my side?
**EDIT**: since `b` is also referenced in the `NS` I will have to go for the second solution. Please see [my answer below](https://serverfault.com/a/586099/78319) for details.
I accepted [MadHatter](https://serverfault.com/users/55514/madhatter)'s answer because even though it does not address the best practices / standards for the case above (before the `NS` update which forces a solution anyway) it gives interesting insights. Thanks!
|
2014/04/02
|
[
"https://serverfault.com/questions/586086",
"https://serverfault.com",
"https://serverfault.com/users/78319/"
] |
The DNS isn't well-designed to handle changes in static IP addresses without manual intervention. There are technologies for allowing records to be propagated automatically, such as [TSIG](http://en.wikipedia.org/wiki/TSIG), but they require quite a lot of co-operative setup, and even then don't deal well with changes to PTR records.
Manual IP changes happen all the time in the real world. They have to be scheduled well in advance, and handled appropriately. That involves well-timed and thoughtful changes to the DNS, the acceptance that DNS propagation is imperfect and that there will be business effects as a result of the change, and a consequent dislike of such changes.
TomTom's comment above is right; if everyone involved does their jobs, a change will go through with the minimum of effort - but some effort **will** be needed.
|
The CNAME option will still work, as you say their infrastructure knows of the VPS's IP and they properly update their nameservers.
EDIT: About the PTR record; the only thing you can do is ask them. I myself have a few hosted VMs and all my providers except for one agreed to it. If their policy allows it you are fine.
|
586,086
|
I use a virtual server (several similar cases) set up and registered by someone else. Its IP is `10.0.0.1` and name `a.example.com` (both handled by the "someone else" above).
I manage the domain `sub.example.com` and would like to also register this server as `b.sub.example.com`.
There are two ways of doing this in my DNS: either
```
b IN CNAME a.example.com.
```
or
```
b IN A 10.0.0.1
```
Since the IP is not distributed by DHCP (it is therefore hardcoded in the server config) there will be a problem in either case if it changes without me knowing and neither solution above would help. The `PTR` will point to `a.example.com` (I do not control the IP reverse mapping)
So what is the proper way (= canonical / best practice) to do the registration on my side?
**EDIT**: since `b` is also referenced in the `NS` I will have to go for the second solution. Please see [my answer below](https://serverfault.com/a/586099/78319) for details.
I accepted [MadHatter](https://serverfault.com/users/55514/madhatter)'s answer because even though it does not address the best practices / standards for the case above (before the `NS` update which forces a solution anyway) it gives interesting insights. Thanks!
|
2014/04/02
|
[
"https://serverfault.com/questions/586086",
"https://serverfault.com",
"https://serverfault.com/users/78319/"
] |
I will finally **have** to use
```
b IN A 10.0.0.1
```
because `b` is also referenced in the `NS` record (which I did not pay attention to intially)
```
IN NS b
```
It is illegal for `b` to be a `CNAME` so there is no choice but to go with the explicit `A` record.
|
The CNAME option will still work, as you say their infrastructure knows of the VPS's IP and they properly update their nameservers.
EDIT: About the PTR record; the only thing you can do is ask them. I myself have a few hosted VMs and all my providers except for one agreed to it. If their policy allows it you are fine.
|
164,223
|
After loading the `lmroman10-regular` font in XeTeX, I can't access accents in TeX' good old ways: `\'` `\"` `\c` etc. I would need to write `Erd\H os` since because I don't have the appropriate "o" on my keyboard.
Example:
```
Before: é, \'e
\font\tenrm="[lmroman10-regular.otf]:mapping=tex-text"
\tenrm
After: é, \'e
\bye
```
Output:

How can I fix this?
|
2014/03/07
|
[
"https://tex.stackexchange.com/questions/164223",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/24686/"
] |
You should use combining characters, instead. Unfortunately, Latin Modern does not fully implement them; for instance, there's no combining cedilla, so with the code below you'd get only characters with cedilla which exist in the font.
```
Before:
\c{e}
\`{e} \'{e}
\v{e} \u{e}
\={e} \^{e}
\.{e} \H{e}
\~{e} \"{e}
\font\tenrm="[lmroman10-regular.otf]:mapping=tex-text"
\tenrm
\def\`#1{#1^^^^0300} \def\'#1{#1^^^^0301}
\def\v#1{#1^^^^030c} \def\u#1{#1^^^^0306}
\def\=#1{#1^^^^0304} \def\^#1{#1^^^^0302}
\def\.#1{#1^^^^0307} \def\H#1{#1^^^^030b}
\def\~#1{#1^^^^0303} \def\"#1{#1^^^^0308}
\def\c#1{#1^^^^0327}
After:
\c{c}
\`{e} \'{e}
\v{e} \u{e}
\={e} \^{e}
\.{e} \H{e}
\~{e} \"{e}
\bye
```
Why is this better than using `\accent`? Because the characters are *themselves*, not built-up boxes and kern combinations.

If you use `cmunrm.otf` (CMU Serif) that has the combining cedilla, you'd get also `\c{e}` (as a pair `e`+`combining cedilla`).
Note that combining characters go after the character they modify. If a combinations such as `e`+`combining acute` is defined by Unicode, the *real* U+00E8 (LATIN SMALL LETTER E WITH GRAVE) would result in the PDF file, available for copying and pasting.
|
By copying the definitions at page 356 of the TeXbook but changing the character codes, this fixes it:
```
Before:
\c{e}
\`{e} \'{e}
\v{e} \u{e}
\={e} \^{e}
\.{e} \H{e}
\~{e} \"{e}
\font\tenrm="[lmroman10-regular.otf]:mapping=tex-text"
\tenrm
\def\`#1{{\accent768 #1}} \def\'#1{{\accent180 #1}}
\def\v#1{{\accent711 #1}} \def\u#1{{\accent728 #1}}
\def\=#1{{\accent175 #1}} \def\^#1{{\accent710 #1}}
\def\.#1{{\accent729 #1}} \def\H#1{{\accent733 #1}}
\def\~#1{{\accent732 #1}} \def\"#1{{\accent168 #1}}
\def\c#1{{\setbox0=\hbox{#1}\ifdim\ht0=1ex \accent184 #1%
\else\ooalign{\unhbox0\crcr\hidewidth\char184\hidewidth}\fi}}
After:
\c{e}
\`{e} \'{e}
\v{e} \u{e}
\={e} \^{e}
\.{e} \H{e}
\~{e} \"{e}
\bye
```
Output:

|
5,075,290
|
I am trying to get the grip on the Facebook SDK and at the same time transitioning from ASP.NET forms to MVC (finally). So please bear with me ..
I have created two controller actions:
FBLogon is execetued when the user clicks on the FB login button on the form.
He is then redirected to the FB login page.
Afterwards he gets sent back to the FBAuthorize page, which is supposed to parse the returned url for the access token. I get something like:
<http://localhost:5000/account/FBAuthorize#access_token=199143326771791|827213759889396d5408fee6-100001815992604|BmYchAOMqSoZ2L0TYgCrtpoKP3M&expires_in=0>
The problem I see, is that as the access\_token is passed behind a #, asp.net cannot parse it on the server. Am I doing something fundamentaly wrong?
Code follows:
```
public ActionResult FBLogon()
{
var settings = ConfigurationManager.GetSection("facebookSettings");
IFacebookApplication current = null;
if (settings != null)
{
current = settings as IFacebookApplication;
if (current.AppId == "{app id}" || current.AppSecret == "{app secret}")
{
return View();
}
}
string[] extendedPermissions = new[] { "publish_stream", "offline_access" };
var oauth = new FacebookOAuthClient { ClientId = current.AppId, RedirectUri = new Uri("http://localhost:5000/account/FBAuthorize") };
var parameters = new Dictionary<string, object>
{
{ "response_type", "token" },
{ "display", "page" }
};
if (extendedPermissions != null && extendedPermissions.Length > 0)
{
var scope = new StringBuilder();
scope.Append(string.Join(",", extendedPermissions));
parameters["scope"] = scope.ToString();
}
var loginUrl = oauth.GetLoginUrl(parameters);
return Redirect(loginUrl.ToString());
}
public ActionResult FBAuthorize()
{
FacebookOAuthResult result;
if (FacebookOAuthResult.TryParse(Request.Url, out result))
{
if (result.IsSuccess)
{
var accesstoken = result.AccessToken;
}
else
{
var errorDescription = result.ErrorDescription;
var errorReason = result.ErrorReason;
}
}
return View();
}
```
|
2011/02/22
|
[
"https://Stackoverflow.com/questions/5075290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198402/"
] |
Ok. The facebook docs say it quite clearly:
>
> Because the access token is passed in
> an URI fragment, only client-side code
> (such as JavaScript executing in the
> browser or desktop code hosting a web
> control) can retrieve the token. App
> authentication is handled by verifying
> that the redirect\_uri is in the same
> domain as the Site URL configured in
> the Developer App
>
>
>
from <http://developers.facebook.com/docs/authentication/> ---> Client-side Flow Section.
So I'm sending the token back to my server to complete the authentication..
Update:
The sending back to the server I do using Javascript something like this:
```
var appId = "<%: Facebook.FacebookContext.Current.AppId %>";
if (window.location.hash.length > 0) {
accessToken = window.location.hash.substring(1);
var url = window.location.href.replace(/#/, '?');
window.location = url;
}
```
On the server then I have the following action. Not very nice but it works..
```
public ActionResult FBAuthorize()
{
FacebookOAuthResult result = null;
string url = Request.Url.OriginalString;
/// hack to make FacebookOuthResult accept the token..
url = url.Replace("FBAuthorize?", "FBAuthorize#");
if (FacebookOAuthResult.TryParse(url, out result))
{
if (result.IsSuccess)
{
string[] extendedPermissions = new[] { "user_about_me", "offline_access" };
var fb = new FacebookClient(result.AccessToken);
dynamic resultGet = fb.Get("/me");
var name = resultGet.name;
RegisterModel rm = new Models.RegisterModel();
rm.UserName = name;
rm.Password = "something";
rm.Email = "somethig";
rm.ConfirmPassword = "23213";
//Label1.Text = name;
//Response.Write(name);
//return RedirectToAction("register", "Account", rm);
ViewData["Register"] = rm;
return RedirectToAction("Register");
}
else
{
var errorDescription = result.ErrorDescription;
var errorReason = result.ErrorReason;
}
}
return View();
}
```
|
I am in the same spot you are at the moment.
We never get the Request.QueryString populated becasue of the "fragment" or # in the url.
Love to know if you solved this and how.
It does not look like the FacebookOAuthResult class was written to be used in web applications of any sort.
you can change the response type in you scope paramas to be "code" then it will send back a code in the querystring in which you can swap for a token.
|
5,075,290
|
I am trying to get the grip on the Facebook SDK and at the same time transitioning from ASP.NET forms to MVC (finally). So please bear with me ..
I have created two controller actions:
FBLogon is execetued when the user clicks on the FB login button on the form.
He is then redirected to the FB login page.
Afterwards he gets sent back to the FBAuthorize page, which is supposed to parse the returned url for the access token. I get something like:
<http://localhost:5000/account/FBAuthorize#access_token=199143326771791|827213759889396d5408fee6-100001815992604|BmYchAOMqSoZ2L0TYgCrtpoKP3M&expires_in=0>
The problem I see, is that as the access\_token is passed behind a #, asp.net cannot parse it on the server. Am I doing something fundamentaly wrong?
Code follows:
```
public ActionResult FBLogon()
{
var settings = ConfigurationManager.GetSection("facebookSettings");
IFacebookApplication current = null;
if (settings != null)
{
current = settings as IFacebookApplication;
if (current.AppId == "{app id}" || current.AppSecret == "{app secret}")
{
return View();
}
}
string[] extendedPermissions = new[] { "publish_stream", "offline_access" };
var oauth = new FacebookOAuthClient { ClientId = current.AppId, RedirectUri = new Uri("http://localhost:5000/account/FBAuthorize") };
var parameters = new Dictionary<string, object>
{
{ "response_type", "token" },
{ "display", "page" }
};
if (extendedPermissions != null && extendedPermissions.Length > 0)
{
var scope = new StringBuilder();
scope.Append(string.Join(",", extendedPermissions));
parameters["scope"] = scope.ToString();
}
var loginUrl = oauth.GetLoginUrl(parameters);
return Redirect(loginUrl.ToString());
}
public ActionResult FBAuthorize()
{
FacebookOAuthResult result;
if (FacebookOAuthResult.TryParse(Request.Url, out result))
{
if (result.IsSuccess)
{
var accesstoken = result.AccessToken;
}
else
{
var errorDescription = result.ErrorDescription;
var errorReason = result.ErrorReason;
}
}
return View();
}
```
|
2011/02/22
|
[
"https://Stackoverflow.com/questions/5075290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/198402/"
] |
I found this post <http://facebooksdk.codeplex.com/discussions/244568> on codeplex. I think this is what you need.
Note that instead of using the client-side flow, you need to use the server-side flow.
This is what you should do
Create a login link for server-side flow. After Authorization, facebook will return an url containing a code instead of a access token.
Then you request for a token from facebook using the code. this is my example
```
public ActionResult FBAuthorize()
{
FacebookOAuthClient cl = new FacebookOAuthClient(FacebookContext.Current);
FacebookOAuthResult result = null;
string url = Request.Url.OriginalString;
// verify that there is a code in the url
if (FacebookOAuthResult.TryParse(url, out result))
{
if (result.IsSuccess)
{
string code = result.Code;
// this line is necessary till they fix a bug *see details below
cl.RedirectUri = new UriBuilder("http://localhost:5000/account/FBAuthorize").Uri;
var parameters = new Dictionary<string, object>();
//parameters.Add("permissions", "offline_access");
Dictionary<String, Object> dict = (Dictionary<String, Object>)cl.ExchangeCodeForAccessToken(code, new Dictionary<string, object> { { "redirect_uri", "http://localhost:5000/account/FBAuthorize" } });
Object Token = dict.Values.ElementAt(0);
TempData["accessToken"] = Token.ToString();
return RedirectToAction ("ShowUser");
}
else
{
var errorDescription = result.ErrorDescription;
}
}
else
{
// TODO: handle error
}
return View();
}
```
\*There is bug when using IIS in localhost, see the original post for details (the redirect uri when asking for the token must be the same as the one used asking for the code)
It is highly recommended to use IIS and not visual studio web server. There are many things that wont work in visual studio web server.
|
I am in the same spot you are at the moment.
We never get the Request.QueryString populated becasue of the "fragment" or # in the url.
Love to know if you solved this and how.
It does not look like the FacebookOAuthResult class was written to be used in web applications of any sort.
you can change the response type in you scope paramas to be "code" then it will send back a code in the querystring in which you can swap for a token.
|
26,014
|
According to MDBG and Ichiba, 后位 could mean after/post-something, so what's the difference of '之后' and '后位'?
Which one is correct:
- 葬礼之后
- 葬礼后位
Does 后位 have to follow a noun?
|
2017/08/15
|
[
"https://chinese.stackexchange.com/questions/26014",
"https://chinese.stackexchange.com",
"https://chinese.stackexchange.com/users/17496/"
] |
...之后 is a normal term to express "after...". So, 葬礼之后 is correct in this context.
后位 is short for 后面的位置. It refers to positioning, not timing sequence. It is only used in some particular areas. Someone had given enough examples above.
后位 could also be understood as:
皇后之位 in 宫廷剧 (Chinese royal opera);
Another 后卫: the back (defense position) in sports: soccer, American football, and etc.
|
“后位” is not a common term in daily usage, we barely hear it. As Dan described, it can mean the position of Queen. “之后” and “后面” is commonly mistaken, “之后” is usually used when something happens after something. “后面” is used when something is behind something.
|
69,218,591
|
I have seen a similar example with loops continuing after the last element to reset to first, which is great. However, I am unable to figure out how to add that PLUS start iterating from a specified index of the `IList` object.
Assume we have this `IList` object with a count of 6. (To simplify I'm only using indices below instead of the full objects.)
`[1, 2, 3, 4, 5, 6]`
Now assume we need to iterate over this `IList` 10 times.
`=> Iterate 10 times`
The expected output based on the above should be:
`=> 1, 2, 3, 4, 5, 6, 1, 2, 3, 4`
However I'd like to start iterating from #4 for example, so the expected output should now be:
`=> 4, 5, 6, 1, 2, 3, 4, 5, 6, 1`
(All the numbers above represent **the position** of the elements in the collection, not the actual objects as ints)
Any ideas on how this is possible with LINQ and C#? Please keep in mind that we're working with an `IList`.
|
2021/09/17
|
[
"https://Stackoverflow.com/questions/69218591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1027620/"
] |
You could write the following extension method:
```
public static class Extensions
{
public static IEnumerable<T> Iterate<T>(this IList<T> input, int from, int length)
{
for(int i = from; i < from + length; i++)
{
yield return input[i % input.Count];
}
}
}
```
The modulo division makes sure that you start at 0 again if your index is bigger than the size of the list.
Online demo: <https://dotnetfiddle.net/Geqslv>
|
You can use `Skip` to skip required number of first elements.
For example:
```
public IEnumerable<T> GetRolledItems<T>(IList<T> source, int count, int startIndex)
{
return Enumerable.Repeat(source, (count + startIndex) / source.Count() + 1)
.SelectMany(a => a)
.Skip(startIndex)
.Take(count);
}
```
|
69,218,591
|
I have seen a similar example with loops continuing after the last element to reset to first, which is great. However, I am unable to figure out how to add that PLUS start iterating from a specified index of the `IList` object.
Assume we have this `IList` object with a count of 6. (To simplify I'm only using indices below instead of the full objects.)
`[1, 2, 3, 4, 5, 6]`
Now assume we need to iterate over this `IList` 10 times.
`=> Iterate 10 times`
The expected output based on the above should be:
`=> 1, 2, 3, 4, 5, 6, 1, 2, 3, 4`
However I'd like to start iterating from #4 for example, so the expected output should now be:
`=> 4, 5, 6, 1, 2, 3, 4, 5, 6, 1`
(All the numbers above represent **the position** of the elements in the collection, not the actual objects as ints)
Any ideas on how this is possible with LINQ and C#? Please keep in mind that we're working with an `IList`.
|
2021/09/17
|
[
"https://Stackoverflow.com/questions/69218591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1027620/"
] |
I suggest implementing an *extension method* for looping again and again:
```
// Let it be general case with IEnumerable<T>
public static class EnumerableExtensions {
public static IEnumerable<T> Loop<T>(this IEnumerable<T> source) {
if (null == source)
throw new ArgumentNullException(name(source));
List<T> list = new List<T>();
foreach (var item in source) {
yield return item;
list.Add(item);
}
// ist.Count > 0 - we can't loop (again and again) over empty list
for (int i = 0; list.Count > 0; i = (i + 1) % list.Count)
yield return list[i];
}
}
```
Then you can put
```
List<int> myList = ...
// we start looping infinitely - Loop()
// but take first 10 items only - Take(10)
foreach (var item in myList.Loop().Take(10)) {
...
}
// we start looping infinitely - Loop()
// skip first 4 items - Skip(4)
// then take 11 items only - Take(11)
foreach (var item in myList.Loop().Skip(4).Take(11)) {
...
}
```
|
You can use `Skip` to skip required number of first elements.
For example:
```
public IEnumerable<T> GetRolledItems<T>(IList<T> source, int count, int startIndex)
{
return Enumerable.Repeat(source, (count + startIndex) / source.Count() + 1)
.SelectMany(a => a)
.Skip(startIndex)
.Take(count);
}
```
|
27,403,397
|
I am trying to rework a query that is based on cursors.
The query calculates certain stats based on multiple values. In the snippet below the first, second and third `CASE` works out the happiness of `Unit1`. Any of these fields are 0 (they can never be `NULL`) I will get a `Divide by Zero` error. I could just add 1 to each field `(Unit2 + 1) / (Unit1 + 1)` and that will stop the error. However, it seems like a bodge and it will potentially give the incorrect result. ie. `Unit1` needs the same amount of `Unit2` to keep them happy. If I have one `Unit1` and no `Unit2` this bodge will give 100% happy for that check. So my first problem is how do I prevent the divide by zero but not distort the results. Each `CASE` gives me a `%` happy
```
Select
CASE WHEN ((Unit2 / Unit1) * 100) > 100 Then 100 Else ((Unit2 / Unit1) * 100) END Unit1Happy1,
CASE WHEN ((Stock3 / (Unit1 * 2)) * 100) > 100 Then 100 Else ((Stock3 / (Unit1 * 2)) * 100) END Unit1Happy2,
CASE WHEN (((Drug3 + (Drug1 / 2)) / Unit1) * 100) > 100 Then 100 Else (((Drug3 + (Drug1 / 2)) / Unit1) * 100) END Unit1Happy3,
CASE WHEN (((Weapon6 + Weapon7 + Weapon8 + Weapon9) / Unit2) * 100) > 100 Then 100 ELSE (((Weapon6 + Weapon7 + Weapon8 + Weapon9) / Unit2) * 100) END Unit2Happ1,
CASE WHEN (((Stock2 + (Stock1 / 2)) / Unit2) * 100) > 100 Then 100 Else (((Stock2 + (Stock1 / 2)) / Unit2) * 100) END Unit2Happ2
FROM tblUserFiles
```
My next problem is that I need to take to lowest value for each UnitHappiness and store that value in the table. So in `tblUserFiles` are 5 fields `Unit1Happ`, `Unit2Happ` .... `Unit5Happ`. Looking at the above query if `Unit1Happy1` is the lowest figure I store that figure into `Unit1Happ`, If `Unit2Happy` is the lowest I store that etc.
My record Identifier is `UserId` and I need to run this for a given `UserId` or for the whole table.
What I am basically asking is:
* What is the best method to identify the lowest value of each Unit
calculation?
* What is the best way to prevent the divide by zero
error?
* Can I approach this problem in a better way?
**Update**
I am working through the suggestions posted in the answers below. As this is just a training exercise it may take a while. I do have a working query that gives the results I am looking for I am just not sure if the suggested answers would be more efficient.
```
Update tblUserFiles Set Unit1Happ = happyvals.Unit1Happiness, Unit2Happ = happyvals.Unit2Happiness, Unit3Happ = happyvals.Unit3Happiness, Unit4Happ = happyvals.Unit4Happiness, Unit5Happ = happyvals.Unit5Happiness FROM
(SELECT ch.UserId,
Case When ch.Unit1Happy1 < ch.Unit1Happy2 And ch.Unit1Happy1 < ch.Unit1Happy3 Then ch.Unit1Happy1
When ch.Unit1Happy2 < ch.Unit1Happy1 And ch.Unit1Happy2 < ch.Unit1Happy3 Then ch.Unit1Happy2
Else ch.Unit1Happy3
End As Unit1Happiness,
CASE WHEN ch.Unit2Happy1 > ch.Unit2Happy2 THEN ch.Unit2Happy1
ELSE ch.Unit2Happy2
END AS Unit2Happiness,
ch.Unit3Happy1 AS Unit3Happiness,
ch.Unit4Happy1 AS Unit4Happiness,
ch.Unit5Happy1 AS Unit5Happiness
FROM
(
Select
UserId,
CASE WHEN Unit2 = 0 OR Unit1 = 0 THEN 0
WHEN ((Unit2 / Unit1) * 100) > 100 Then 100
ELSE ((Unit2 / Unit1) * 100)
END Unit1Happy1,
CASE WHEN Stock3 = 0 OR Unit1 = 0 THEN 0
WHEN ((Stock3 / (Unit1 * 2)) * 100) > 100 THEN 100
ELSE ((Stock3 / (Unit1 * 2)) * 100)
END Unit1Happy2,
CASE WHEN Unit1 = 0 THEN 0
WHEN Drug3 = 0 AND Drug1 = 0 THEN 0
WHEN Drug1 = 0 THEN
CASE WHEN (Drug3 / Unit1) * 100 > 100 THEN 100
ELSE (Drug3 / Unit1) * 100
END
WHEN Drug3 = 0 THEN
CASE WHEN (Drug1 / 2) / Unit1 > 100 THEN 100
ELSE (Drug1 / 2) / Unit1
END
ELSE
CASE WHEN (((Drug3 + (Drug1 / 2)) / Unit1) * 100) > 100 THEN 100
ELSE (((Drug3 + (Drug1 / 2)) / Unit1) * 100)
END
END Unit1Happy3,
CASE WHEN Unit2 = 0 THEN 0
WHEN (Weapon6 + Weapon7 + Weapon8 + Weapon9) = 0 THEN 0
WHEN (((Weapon6 + Weapon7 + Weapon8 + Weapon9) / Unit2) * 100) > 100 THEN 100
ELSE (((Weapon6 + Weapon7 + Weapon8 + Weapon9) / Unit2) * 100)
END Unit2Happy1,
CASE WHEN Unit2 = 0 THEN 0
WHEN Stock1 = 0 AND Stock2 = 0 THEN 0
WHEN Stock1 = 0 THEN
CASE WHEN ((Stock2 / Unit2) * 100) > 100 THEN 100
ELSE ((Stock2 / Unit2) * 100)
END
WHEN Stock2 = 0 THEN
CASE WHEN (((Stock1 / 2) / Unit2) * 100) > 100 THEN 100
ELSE (((Stock1 / 2) / Unit2) * 100)
END
WHEN (((Stock2 + (Stock1 / 2)) / Unit2) * 100) > 100 THEN 100
ELSE (((Stock2 + (Stock1 / 2)) / Unit2) * 100)
END Unit2Happy2,
CASE WHEN Unit2 = 0 OR Unit3 = 0 THEN 0
WHEN ((Unit2 / Unit3) * 100) > 100 THEN 100
ELSE ((Unit2 / Unit3) * 100)
END Unit3Happy1,
CASE WHEN Unit2 = 0 OR Unit4 = 0 THEN 0
WHEN ((Unit2 / Unit4) * 100) > 100 THEN 100
ELSE ((Unit2 / Unit4) * 100)
END Unit4Happy1,
CASE WHEN Unit2 = 0 OR Unit5 = 0 THEN 0
WHEN ((Unit2 / Unit5) * 100) > 100 THEN 100
ELSE ((Unit2 / Unit5) * 100)
END Unit5Happy1
FROM tblUserFiles) ch) happyvals
Join tblUserFiles ON tblUserFiles.UserID = happyvals.UserID
```
|
2014/12/10
|
[
"https://Stackoverflow.com/questions/27403397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1562451/"
] |
put a `nullif(Unit1, 0)` around every divide by group ?
|
Something like this.
The idea is to wrap your division in a UDF (scalar user defined function)....and use the "Max(v)" trick.
The code below may not be perfect, I've supplying the idea.
Cursors are horrible performers, 99.9% of the time. Try to solve this without cursors.
```
/* or Create */
ALTER FUNCTION dbo.udfSafeDivision (@num float , @denom float)
RETURNS float
AS
BEGIN
declare @returnValue float
select @returnValue = 0
if(isnull(@denom,0) != 0)
BEGIN
select @returnValue = convert(float, convert(float, @num)/convert(float, @denom))
END
return @returnValue
END
GO
IF OBJECT_ID('tempdb..#TableOne') IS NOT NULL
begin
drop table #TableOne
end
CREATE TABLE #TableOne
(
SurrogateKey int IDENTITY(1001, 1),
Unit1 int ,
Unit2 int ,
Stock1 int ,
Stock2 int ,
Stock3 int ,
Drug1 int ,
Drug3 int ,
Weapon6 int , Weapon7 int , Weapon8 int , Weapon9 int
)
Insert into #TableOne (Unit1, Unit2, Stock1, Stock2 , Stock3 , Drug1, Drug3 , Weapon6 , Weapon7 , Weapon8 , Weapon9)
select 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0
UNION ALL select 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0
UNION ALL select 1 , 2 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0
UNION ALL select 1 , 2 , 3 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0
UNION ALL select 1 , 2 , 3 , 4 , 0 , 0 , 0 , 0 , 0 , 0 , 0
UNION ALL select 1 , 2 , 3 , 4 , 5 , 0 , 0 , 0 , 0 , 0 , 0
UNION ALL select 1 , 2 , 3 , 4 , 5 , 6 , 0 , 0 , 0 , 0 , 0
UNION ALL select 1 , 2 , 3 , 4 , 5 , 6 , 7 , 0 , 0 , 0 , 0
UNION ALL select 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 0 , 0 , 0
UNION ALL select 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 0 , 0
UNION ALL select 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 0
UNION ALL select 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11
UNION ALL select 5 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0
UNION ALL select 5 , 0 , 0 , 0 , 5 , 0 , 0 , 0 , 0 , 0 , 0
UNION ALL select 10 , 0 , 0 , 0 , 0 , 5 , 10 , 0 , 0 , 0 , 0
UNION ALL select 0 , 1 , 0 , 0 , 0 , 5 , 10 , 10 , 20 , 30 , 40
UNION ALL select 0 , 50 , 20 , 10 , 0 , 0 , 0 , 0 , 0 , 0 , 0
SELECT
(SELECT Max(v)
FROM (VALUES (Unit1Happy1), (Unit1Happy2), (Unit1Happy3), (Unit2Happ1), (Unit2Happ2)) AS value(v)) as [MaxValue]
, '--------' as Sep1
, derived1.*
FROM
(
Select
CASE WHEN ((dbo.udfSafeDivision(Unit2 , Unit1)) * 100) > 100 Then 100 Else (dbo.udfSafeDivision(Unit2 , Unit1) * 100) END Unit1Happy1,
CASE WHEN (dbo.udfSafeDivision(Stock3 , (Unit1 * 2)) * 100) > 100 Then 100 Else (dbo.udfSafeDivision(Stock3 , (Unit1 * 2)) * 100) END Unit1Happy2,
CASE WHEN (dbo.udfSafeDivision((Drug3 + (Drug1 / 2)) , Unit1) * 100) > 100 Then 100 Else (dbo.udfSafeDivision((Drug3 + (Drug1 / 2)) , Unit1) * 100) END Unit1Happy3,
CASE WHEN (dbo.udfSafeDivision((Weapon6 + Weapon7 + Weapon8 + Weapon9) , Unit2) * 100) > 100 Then 100 ELSE (dbo.udfSafeDivision((Weapon6 + Weapon7 + Weapon8 + Weapon9) , Unit2) * 100) END Unit2Happ1,
CASE WHEN (dbo.udfSafeDivision((Stock2 + (Stock1 / 2)) , Unit2) * 100) > 100 Then 100 Else (dbo.udfSafeDivision((Stock2 + (Stock1 / 2)) , Unit2) * 100) END Unit2Happ2
/* the below is to debug */
, '--' as Sep1
, Unit1, Unit2, Stock1, Stock2 , Stock3 , Drug1, Drug3 , Weapon6 , Weapon7 , Weapon8 , Weapon9
, dbo.udfSafeDivision(Unit2 , Unit1) as Div1
, dbo.udfSafeDivision(Stock3 , (Unit1 * 2)) as Div3
FROM #TableOne
) as derived1
IF OBJECT_ID('tempdb..#TableOne') IS NOT NULL
begin
drop table #TableOne
end
```
|
2,194,630
|
I have tried the question with $Rolle's$ theorem...
Let the equation have $2$ unequal real roots
$f'(x)= 4ax^3-4ax+1=0$
But cannot proceed after this.
|
2017/03/20
|
[
"https://math.stackexchange.com/questions/2194630",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/427385/"
] |
**Hint:** Note that the equation can be factorised as $(x^2 + x - a)(x^2 - x + 1 -a)$, which reduces it to the condition for two standard quadratics to have real roots.
|
we can write above equation as $x^4-2ax^2+x+a^2-a=0$ as $a^2-(2x^2+1)a+x^4+x=0$
So $$\displaystyle a= \frac{(2x^2+1)\pm\sqrt{(2x^2+1)^2-4(x^4+x)}}{2}=\frac{(2x^2+1)\pm (2x-1)}{2}$$
So $x^2+x-a=0$ or $x^2-x+1-a=0$
So for real roots , $1+4a\geq 0$ and $1-4(1-a)\geq 0 $
|
279,422
|
I am building a power source for my astro-imaging gear using a 12V marine deep-cycle battery (120 amp-hours) stored in a battery box. The battery is supposed to power the [telescope mount](https://starizona.com/acb/Advanced-VX-Mount-P3550C761.aspx) (requires 12V DC, 3.5A) and my laptop (requires 19V, 2.4A). Later, I might also add dew heaters for which I would use this [controller](http://www.kendrickastro.com/dew_controllers.html#Standard%20Dual%20Channel%20Controller).
I want to add three 12V cigarette lighter sockets and a fuse.
My main questions are:
1. Where to add the fuse in the circuit and why?
2. What rating should the fuse have?
3. Should I also add a fuse in front of each cigarette lighter socket?
I read that the loads in a circuit will only take the amps the need.
4. Can a marine deep-cycle battery also actually "push" current into my devices and blow them? Or are voltage fluctuations more of a problem?
For the laptop, I am planning on using a power inverter. I know it's not as efficient as a DC to DC power adapter but I think the battery has enough power to handle this inefficiency no problem and it's also more convenient in case I want to add a different laptop with different power supply specs.
|
2017/01/10
|
[
"https://electronics.stackexchange.com/questions/279422",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/133974/"
] |
A deep cycle battery is a good choice for this it will not "push" extra current to your loads. That does not happen unless the voltage is too high.
Each cigar lighter plug should already have its own fuse this will be rated to protect the wire to the device and the device.
For fuses in your box you are protecting the wiring in your box. Wires have an "ampacity" this can be found on the web. This is the amount of current it is safe to push through a wire of that size. In fault situations a lead acid battery can push very large currents and this is what you need to protect against. A single fuse **at the battery** rated at the ampacity of all your wire will adequately protect your box. If you need more current than this fuse will supply instead use a similarly sized fuse in each of the feeders to the cigar lighters again at the battery.
Why do we fuse at the power source, the battery. Taking a pessimistic view of the world a fault can develop anywhere along the wire. If this point is before the fuse it can result in a fire. From a safety point of view therefore it is good to get into the habit of fusing at the source.
|
Please do research before posting, [Can a fuse be placed after a load?](https://electronics.stackexchange.com/questions/77958/can-a-fuse-be-placed-after-a-load/194473#194473) for the first fuse question.
This for the second question: [Fuse rating and safety](https://electronics.stackexchange.com/questions/169818/fuse-rating-and-safety)
Fuse each load you want to protect from shorting out. Do not fuse circuits that dont have a risk of shorting. If you think one circuit might short and you want the others to stay on, then fuse each one.
Study up on how voltage works, current flows from high voltage to low voltage.
|
25,940,396
|
How do I export a security certificate from Chrome v37 on a Mac?
Previously I could click on the little lock icon next to the URL, select "Connection," select the certificate, and an "Export" button would appear.
Not so anymore!
|
2014/09/19
|
[
"https://Stackoverflow.com/questions/25940396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1526115/"
] |
Just found out this does not work on Chrome Version 105.0.5195.125 on MacOS.
The certificate viewer looks like this now:


I haven't found a way how to save a certificate, but if you want to access the page just type the following while the focus is on the page:
* ### thisisunsafe
and the page will load instantly.
found the information here: <https://www.rffuste.com/tag/neterr_cert_invalid/>
|
You could use Firefox or Safari instead of Chrome.
### Steps for Firefox
1. Click the lock icon
2. More information
3. View Certificate
4. In next screen each cert in chain can be exported as PEM
[](https://i.stack.imgur.com/Qazbk.png)
[](https://i.stack.imgur.com/9eb0r.png)
|
25,940,396
|
How do I export a security certificate from Chrome v37 on a Mac?
Previously I could click on the little lock icon next to the URL, select "Connection," select the certificate, and an "Export" button would appear.
Not so anymore!
|
2014/09/19
|
[
"https://Stackoverflow.com/questions/25940396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1526115/"
] |
I found a workaround and tested by Chrome Version 73.0.3683.103 (Official Build) (64-bit) on Macos 10.14.3.
When open the site with unsafe certificate, Chrome will show an error page 'Your connection is not private', follow the below steps:
1. Click the text 'NET::ERR\_CERT\_AUTHORITY\_INVALID', the content of the certificate will be shown.
2. Copy the content from the line '-----BEGIN CERTIFICATE-----' to '-----END CERTIFICATE-----'.
3. Paste them into a text editor, and save as a .crt file with plain text format.
4. Import the .crt file into Keychain Access.
|
You could use Firefox or Safari instead of Chrome.
### Steps for Firefox
1. Click the lock icon
2. More information
3. View Certificate
4. In next screen each cert in chain can be exported as PEM
[](https://i.stack.imgur.com/Qazbk.png)
[](https://i.stack.imgur.com/9eb0r.png)
|
25,940,396
|
How do I export a security certificate from Chrome v37 on a Mac?
Previously I could click on the little lock icon next to the URL, select "Connection," select the certificate, and an "Export" button would appear.
Not so anymore!
|
2014/09/19
|
[
"https://Stackoverflow.com/questions/25940396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1526115/"
] |
Edit 4/3/19: I have found a workaround. This is tested on Chrome for Mac 73.0.3686.86 64-bit, platform: macOS 10.14.4:
1. Open a new TextEdit document.
2. In TextEdit, click Format | Make Plain Text.
3. Arrange windows so that the TextEdit window and the Chrome window are both visible.
4. In Chrome, click the icon to the left of the URL in the address bar.
5. In the dropdown list, click Certificate.
6. Hold down Option and drag from the large certificate icon to the body of the TextEdit document. Note: If you did not follow the steps above in exactly the order stated, you may need to first single-click within the Chrome window so that TextEdit doesn't become hidden when you Option-click.
7. Save the TextEdit document with a .pem extension.
If you don't hold down Option when you drag, then you will instead get the certificate contents in human-readable form, which can also be handy.
(Edited 2/24/19: @RichardTopchiy is correct, this no longer works. Testing on Chrome 72.0.3626.119 64-bit. I don't know of any workaround at the present.)
(Edited 2/10/17: I have added a more up-to-date answer in a comment: [How to Export Certificate from Chrome on a Mac?](https://stackoverflow.com/questions/25940396/how-to-export-certificate-from-chrome-on-a-mac/30177897#comment71501487_30177897))
1. Click the icon to the left of the URL.
2. In the box that pops up, click the Connection tab.
3. Click the Certificate Information link.
4. A box pops up showing information about the certificate. Drag the large certificate icon to a Finder window. A .cer file will be created in the location you drag it to.
This is based on Chrome 42.0.2311.135 (64-bit) for Mac.
|
You should make flowing steps,
show certificate detail on chrome browser on macOS

drag big certificate icon on certificate detail window

drop the icon to desktop and ta-ta!
created the domain certificate `.cer` file on the desktop

|
25,940,396
|
How do I export a security certificate from Chrome v37 on a Mac?
Previously I could click on the little lock icon next to the URL, select "Connection," select the certificate, and an "Export" button would appear.
Not so anymore!
|
2014/09/19
|
[
"https://Stackoverflow.com/questions/25940396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1526115/"
] |
Edit 4/3/19: I have found a workaround. This is tested on Chrome for Mac 73.0.3686.86 64-bit, platform: macOS 10.14.4:
1. Open a new TextEdit document.
2. In TextEdit, click Format | Make Plain Text.
3. Arrange windows so that the TextEdit window and the Chrome window are both visible.
4. In Chrome, click the icon to the left of the URL in the address bar.
5. In the dropdown list, click Certificate.
6. Hold down Option and drag from the large certificate icon to the body of the TextEdit document. Note: If you did not follow the steps above in exactly the order stated, you may need to first single-click within the Chrome window so that TextEdit doesn't become hidden when you Option-click.
7. Save the TextEdit document with a .pem extension.
If you don't hold down Option when you drag, then you will instead get the certificate contents in human-readable form, which can also be handy.
(Edited 2/24/19: @RichardTopchiy is correct, this no longer works. Testing on Chrome 72.0.3626.119 64-bit. I don't know of any workaround at the present.)
(Edited 2/10/17: I have added a more up-to-date answer in a comment: [How to Export Certificate from Chrome on a Mac?](https://stackoverflow.com/questions/25940396/how-to-export-certificate-from-chrome-on-a-mac/30177897#comment71501487_30177897))
1. Click the icon to the left of the URL.
2. In the box that pops up, click the Connection tab.
3. Click the Certificate Information link.
4. A box pops up showing information about the certificate. Drag the large certificate icon to a Finder window. A .cer file will be created in the location you drag it to.
This is based on Chrome 42.0.2311.135 (64-bit) for Mac.
|
Just found out this does not work on Chrome Version 105.0.5195.125 on MacOS.
The certificate viewer looks like this now:


I haven't found a way how to save a certificate, but if you want to access the page just type the following while the focus is on the page:
* ### thisisunsafe
and the page will load instantly.
found the information here: <https://www.rffuste.com/tag/neterr_cert_invalid/>
|
25,940,396
|
How do I export a security certificate from Chrome v37 on a Mac?
Previously I could click on the little lock icon next to the URL, select "Connection," select the certificate, and an "Export" button would appear.
Not so anymore!
|
2014/09/19
|
[
"https://Stackoverflow.com/questions/25940396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1526115/"
] |
@Simon Zuckerbraun's answer is correct. My workaround is almost the same as Simon's. But don't need to use Text Editor, just drag the certificate to the Desktop Window then the certificate will be created immediately. Follow these steps :
1. Open Google Chrome, go to the site.
2. Click the icon to the left of the URL in the address bar.
3. Click Certificate
4. Arrange windows so that the Chrome window and the Desktop window are both visible.
5. If you want to get a .cer certificate, drag from the large certificate icon to the desktop. If you want to get a .pem certificate, hold down option, and drag from the large certificate icon to the desktop.
[Click here](https://estucode.blogspot.com/2020/08/how-to-export-certificate-public-key-chrome-mac.html) for more details
|
You could use Firefox or Safari instead of Chrome.
### Steps for Firefox
1. Click the lock icon
2. More information
3. View Certificate
4. In next screen each cert in chain can be exported as PEM
[](https://i.stack.imgur.com/Qazbk.png)
[](https://i.stack.imgur.com/9eb0r.png)
|
25,940,396
|
How do I export a security certificate from Chrome v37 on a Mac?
Previously I could click on the little lock icon next to the URL, select "Connection," select the certificate, and an "Export" button would appear.
Not so anymore!
|
2014/09/19
|
[
"https://Stackoverflow.com/questions/25940396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1526115/"
] |
You should make flowing steps,
show certificate detail on chrome browser on macOS

drag big certificate icon on certificate detail window

drop the icon to desktop and ta-ta!
created the domain certificate `.cer` file on the desktop

|
As of Chrome 72 the certificate icon cannot be dragged/exported from Chrome as @RichardTopchiy stated in his comments.
However Safari **does still allow the certificate icon to be dragged** from the browser.
So the easiest way to export the certificate from Chrome is... to use a different browser to export the SSL certificate. Once the certificate is trusted, it will work on any browser on that device's user account. You're just using Safari to export the certificate easily.
|
25,940,396
|
How do I export a security certificate from Chrome v37 on a Mac?
Previously I could click on the little lock icon next to the URL, select "Connection," select the certificate, and an "Export" button would appear.
Not so anymore!
|
2014/09/19
|
[
"https://Stackoverflow.com/questions/25940396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1526115/"
] |
Edit 4/3/19: I have found a workaround. This is tested on Chrome for Mac 73.0.3686.86 64-bit, platform: macOS 10.14.4:
1. Open a new TextEdit document.
2. In TextEdit, click Format | Make Plain Text.
3. Arrange windows so that the TextEdit window and the Chrome window are both visible.
4. In Chrome, click the icon to the left of the URL in the address bar.
5. In the dropdown list, click Certificate.
6. Hold down Option and drag from the large certificate icon to the body of the TextEdit document. Note: If you did not follow the steps above in exactly the order stated, you may need to first single-click within the Chrome window so that TextEdit doesn't become hidden when you Option-click.
7. Save the TextEdit document with a .pem extension.
If you don't hold down Option when you drag, then you will instead get the certificate contents in human-readable form, which can also be handy.
(Edited 2/24/19: @RichardTopchiy is correct, this no longer works. Testing on Chrome 72.0.3626.119 64-bit. I don't know of any workaround at the present.)
(Edited 2/10/17: I have added a more up-to-date answer in a comment: [How to Export Certificate from Chrome on a Mac?](https://stackoverflow.com/questions/25940396/how-to-export-certificate-from-chrome-on-a-mac/30177897#comment71501487_30177897))
1. Click the icon to the left of the URL.
2. In the box that pops up, click the Connection tab.
3. Click the Certificate Information link.
4. A box pops up showing information about the certificate. Drag the large certificate icon to a Finder window. A .cer file will be created in the location you drag it to.
This is based on Chrome 42.0.2311.135 (64-bit) for Mac.
|
New browsers process is different. Please follow the below steps
Inspect the chrome browser-> You can find **Security** tab -> Click on the **View Ceritificate** button then i will open the popup
[Click on the details tab and press Copy to file button](https://i.stack.imgur.com/M3ex0.png)
Then press the buttton Next->Next->Browse->Save the file in your local directory. The file will save with .cer extension.
|
25,940,396
|
How do I export a security certificate from Chrome v37 on a Mac?
Previously I could click on the little lock icon next to the URL, select "Connection," select the certificate, and an "Export" button would appear.
Not so anymore!
|
2014/09/19
|
[
"https://Stackoverflow.com/questions/25940396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1526115/"
] |
Edit 4/3/19: I have found a workaround. This is tested on Chrome for Mac 73.0.3686.86 64-bit, platform: macOS 10.14.4:
1. Open a new TextEdit document.
2. In TextEdit, click Format | Make Plain Text.
3. Arrange windows so that the TextEdit window and the Chrome window are both visible.
4. In Chrome, click the icon to the left of the URL in the address bar.
5. In the dropdown list, click Certificate.
6. Hold down Option and drag from the large certificate icon to the body of the TextEdit document. Note: If you did not follow the steps above in exactly the order stated, you may need to first single-click within the Chrome window so that TextEdit doesn't become hidden when you Option-click.
7. Save the TextEdit document with a .pem extension.
If you don't hold down Option when you drag, then you will instead get the certificate contents in human-readable form, which can also be handy.
(Edited 2/24/19: @RichardTopchiy is correct, this no longer works. Testing on Chrome 72.0.3626.119 64-bit. I don't know of any workaround at the present.)
(Edited 2/10/17: I have added a more up-to-date answer in a comment: [How to Export Certificate from Chrome on a Mac?](https://stackoverflow.com/questions/25940396/how-to-export-certificate-from-chrome-on-a-mac/30177897#comment71501487_30177897))
1. Click the icon to the left of the URL.
2. In the box that pops up, click the Connection tab.
3. Click the Certificate Information link.
4. A box pops up showing information about the certificate. Drag the large certificate icon to a Finder window. A .cer file will be created in the location you drag it to.
This is based on Chrome 42.0.2311.135 (64-bit) for Mac.
|
I was able to start it with --ignore-certificate-errors --incognito.
Incognito so that it doesn't use any open sessions.
|
25,940,396
|
How do I export a security certificate from Chrome v37 on a Mac?
Previously I could click on the little lock icon next to the URL, select "Connection," select the certificate, and an "Export" button would appear.
Not so anymore!
|
2014/09/19
|
[
"https://Stackoverflow.com/questions/25940396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1526115/"
] |
You should make flowing steps,
show certificate detail on chrome browser on macOS

drag big certificate icon on certificate detail window

drop the icon to desktop and ta-ta!
created the domain certificate `.cer` file on the desktop

|
New browsers process is different. Please follow the below steps
Inspect the chrome browser-> You can find **Security** tab -> Click on the **View Ceritificate** button then i will open the popup
[Click on the details tab and press Copy to file button](https://i.stack.imgur.com/M3ex0.png)
Then press the buttton Next->Next->Browse->Save the file in your local directory. The file will save with .cer extension.
|
25,940,396
|
How do I export a security certificate from Chrome v37 on a Mac?
Previously I could click on the little lock icon next to the URL, select "Connection," select the certificate, and an "Export" button would appear.
Not so anymore!
|
2014/09/19
|
[
"https://Stackoverflow.com/questions/25940396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1526115/"
] |
Just found out this does not work on Chrome Version 105.0.5195.125 on MacOS.
The certificate viewer looks like this now:


I haven't found a way how to save a certificate, but if you want to access the page just type the following while the focus is on the page:
* ### thisisunsafe
and the page will load instantly.
found the information here: <https://www.rffuste.com/tag/neterr_cert_invalid/>
|
I was able to start it with --ignore-certificate-errors --incognito.
Incognito so that it doesn't use any open sessions.
|
39,037,671
|
I have a simple node.js server and some app running on it, that should connect to Oracle database. For that reason I decided to use `node-oracledb` driver, but I'm having some problems with installation. I followed instructions on [Oracle webpage](https://community.oracle.com/docs/DOC-931127) and those on [github](https://github.com/oracle/node-oracledb/blob/master/INSTALL.md#instwin), but I still get an error below.
My environment configuration:
* Windows 8.1 Pro 64 bit
* node.js v6.4.0
* npm v3.10.3
* MS Visual Studio 2013 Community edition
* Python v2.7.12
* Oracle Instant Client (basic + SDK) v12.1.0.2.0
Node, Python and Oracle Instant Client folders are included in PATH variable. OCI\_LIB\_DIR and OCI\_INC\_DIR are also set according to github instructions.
Here's the problem: when I execute command `npm install oracledb -g`, the following error occurs:
```
> oracledb@1.11.0 install C:\Users\pr\AppData\Roaming\npm\node_modules\ora
cledb
> node-gyp rebuild
C:\Users\pr\AppData\Roaming\npm\node_modules\oracledb>if not defined npm_c
onfig_node_gyp (node "C:\Program Files\nodejs\node_modules\npm\bin\node-gyp-bin\
\..\..\node_modules\node-gyp\bin\node-gyp.js" rebuild ) else (node "" rebuild )
Building the projects in this solution one at a time. To enable parallel build,
please add the "/m" switch.
C:\Users\pr\AppData\Roaming\npm\node_modules\oracledb\build\oracledb.vcxp
roj(20,3): error MSB4019: The imported project "C:\Microsoft.Cpp.Default.props"
was not found. Confirm that the path in the <Import> declaration is correct, a
nd that the file exists on disk.
gyp ERR! build error
gyp ERR! stack Error: `msbuild` failed with exit code: 1
gyp ERR! stack at ChildProcess.onExit (C:\Program Files\nodejs\node_modules\
npm\node_modules\node-gyp\lib\build.js:276:23)
gyp ERR! stack at emitTwo (events.js:106:13)
gyp ERR! stack at ChildProcess.emit (events.js:191:7)
gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_proces
s.js:204:12)
gyp ERR! System Windows_NT 6.3.9600
gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodej
s\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
gyp ERR! cwd C:\Users\pr\AppData\Roaming\npm\node_modules\oracledb
gyp ERR! node -v v6.4.0
gyp ERR! node-gyp -v v3.3.1
gyp ERR! not ok
npm ERR! Windows_NT 6.3.9600
npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\
node_modules\\npm\\bin\\npm-cli.js" "install" "oracledb" "-g"
npm ERR! node v6.4.0
npm ERR! npm v3.10.3
npm ERR! code ELIFECYCLE
npm ERR! oracledb@1.11.0 install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the oracledb@1.11.0 install script 'node-gyp rebuild'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the oracledb package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node-gyp rebuild
npm ERR! You can get information on how to open an issue for this project with:
npm ERR! npm bugs oracledb
npm ERR! Or if that isn't available, you can get their info via:
npm ERR! npm owner ls oracledb
npm ERR! There is likely additional logging output above.
npm ERR! Please include the following file with any support request:
npm ERR! C:\Users\pr\Development\Visual Studio 2013\npm-debug.log
```
I don't really know where to look at for a solution. What could cause that error? Are there any known incompatibilities between node/oracle client/python?
One more thing: github instructions say:
>
> Make sure the Microsoft Visual Studio environment variables are set
> appropriately. Use set PATH and verify it contains your Visual Studio
> paths. If they are not set, use vcvars64.bat (or vcvars.bat if you
> building with 32-bit binaries) to set the environment.
>
>
>
Which VS environment variables should be set and which VS paths should be contained in PATH exactly?
|
2016/08/19
|
[
"https://Stackoverflow.com/questions/39037671",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394223/"
] |
Modules like oracledb or node-oracledb needs compilations. Compilation requires software like C compiler, Python etc.
I was facing the same issue with oracldb module. follow below instructions and it works like charm.
<https://community.oracle.com/docs/DOC-931127>
|
try updating npm to the latest version:
```
npm install -g npm
```
if it still doesn't work, try including your VS version like so:
```
npm install oracledb --msvs_version=2013
```
|
74,289,527
|
I wanted to host a API in WPF. I have tried implementing Self hosted api using below article.
<https://learn.microsoft.com/en-us/aspnet/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api>
When i have done the implementation for Console application. I was able to verify with PostMan tool to verify get API and it works fine.
But if i implement the same in WPF like below:
MainWindow() in WPF:
```
string baseAddress = "http://localhost:4444/";
public MainWindow()
{
InitializeComponent();
WebApp.Start<StartUp>(baseAddress);
GetCall();
}
```
StartUp class:
```
using Owin;
using System.Web.Http;
namespace WpfApp3
{
public class StartUp
{
// This code configures Web API. The Startup class is specified as a type
// parameter in the WebApp.Start method.
public void Configuration(IAppBuilder appBuilder)
{
// Configure Web API for self-host.
HttpConfiguration config = new HttpConfiguration();
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.MapHttpAttributeRoutes();
appBuilder.UseWebApi(config);
Owin.CorsExtensions.UseCors(appBuilder,
Microsoft.Owin.Cors.CorsOptions.AllowAll);
}
}
}
```
GET API implementation like below.
```
string baseAddress = "http://localhost:4444/";
HttpClient client = new HttpClient();
var res = await client.GetStringAsync(baseAddress + "api/demo");
```
After Get API called: I got below exception.
Exception :System.Threading.Tasks.TaskCanceledException: 'The request was canceled due to the configured HttpClient.Timeout of 100 seconds elapsing.'
Four Inner Exceptions:
* TimeoutException: The operation was canceled.
* TaskCanceledException: The operation was canceled.
* IOException: Unable to read data from the transport connection: The
I/O operation has been aborted because of either a thread exit or an
application request..
* SocketException: The I/O operation has been aborted because of either
a thread exit or an application request.
So, I am struggling to find a solution for this. Please provide a solution on this. am i going in the right way or not.
Or Is there any other solution for WPF to host api which will help a lot.
|
2022/11/02
|
[
"https://Stackoverflow.com/questions/74289527",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8070342/"
] |
Do you have a `DemoController`? If you copied the `ValuesController` class from the example, the URI should be "api/**values**" and nothing else:
```
string baseAddress = "http://localhost:4444/";
HttpClient client = new HttpClient();
var res = await client.GetStringAsync(baseAddress + "api/values");
```
|
I got a solution from this article.
<https://blog.codeinside.eu/2015/09/29/wpf-chrome-embedded-and-webapi-selfhosting/>
Now i am able to host api in WPF.
|
52,323,898
|
I have to create a calculated column in a query (T2) based in a corresponding record in other table(T1) that attends to a certain condition, like this:
**T1** - Contracts:
[T1.Id]
[T1.Conclusion]
**T2** - Financial Entries:
[T2.Id]
[T2.ContractId]
[**CALCULATED COLUMN** returning "ok" if a record exists in T1 where ([T1.Id]=[T2.ContractId] and [T1.Conclusion] <= TODAY)]
Thank´s!
|
2018/09/14
|
[
"https://Stackoverflow.com/questions/52323898",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10361224/"
] |
You can use a correlated subquery and `EXISTS` in a `CASE` expression.
```
SELECT t2.id,
t2.contractid,
CASE
WHEN EXISTS (SELECT *
FROM t1
WHERE t1.id = t2.contractid
AND t1.conclusion <= curdate()) THEN
'ok'
END
FROM t2;
```
|
You can go ahead with simple LEFT join using below Query:
```
SELECT DISTINCT T2.*, T1.id
FROM T2
LEFT JOIN T1 ON T1.Id = T2.ContractId AND T1.Conclusion <= TODAY
```
If you get NULL in T1.id then not data exists else "OK".
|
23,126,460
|
Problem with the order of retrieving rows. I have a table called documentfiles in that i have three columns filename filepath num i have a query which retrieves filename and filepath with respect to the num
here is my query
```
rs=s.executeQuery("SELECT filename from
documentfiles
where num in
(2167, 2156,
1677, 2149,
1946,1511
) "
);
```
the problem here i am facing is the query retrieving rows in the ascending order of num that is retrieving in this order
>
> `1511 1677 1946 2149 2151 2156 2167 2526 2527 2612 2887 2890 2894 2895 3665 6254 6258 6920 7001 7013 7071 7072 7074 7100`
>
>
>
but i want in this order
>
> `2167, 2156, 1677, 7074, 2149, 7100, 7072, 2890, 2527, 2526, 1946, 1511, 7071, 7013, 7001, 6920, 6258, 6254, 3665, 2895, 2894, 2887, 2612, 2151`
>
>
>
well i have stored num with values in ascending order
`1511 1677 1946 2149 2151 2156 2167 2526 2527 2612 2887 2890 2894 2895 3665 6254 6258 6920 7001 7013 7071 7072 7074 7100`
not in this order
>
> 2167, 2156, 1677, 2149, 1946, 1511
>
>
>
so how do i achieve this is that possible,
any help would be greatly appreciated
thanks in advance
|
2014/04/17
|
[
"https://Stackoverflow.com/questions/23126460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2318813/"
] |
Adapt the query to:
```
SELECT filename
from documentfiles
where num in (2167, 2156, 1677,2149,1946,1511)
order by case when num = 2167 then 1
when num = 2156 then 2
when num = 1677 then 3
when num = 2149 then 4
when num = 1946 then 5
when num = 1511 then 6
end
```
If it is a generated script you don't care how many you put, as it will be fairly simple to construct your query. If it is not generated, then you have to put it by hand.
I also might suggest that you make a sp out of it, and call it with a TVP (table valued parameter) with 2 columns (num,crt). So your query will change like:
```
SELECT filename
from documentfiles df
join tvp
on df.num=tvp.num
order by crt
```
|
```
CREATE TABLE numbers
(
ID int identity(1,1) primary key,
number int
)
CREATE PROCEDURE insertnumbers
@number int
AS BEGIN
INSERT INTO numbers VALUES (@number);
END
```
Now you add comma on beginning
```
,2167, 2156, 1677, 7074, 2149, 7100,
7072, 2890, 2527, 2526, 1946, 1511,
7071, 7013, 7001, 6920, 6258, 6254,
3665, 2895, 2894, 2887, 2612, 2151
```
and then you use notepad and SEARCH AND REPLACE
search: `,`
replace: `; EXEC insertnumbers`
Then you remove first `;` and you can insert numbers. Then you INNER JOIN table filename with table numbers ON filename.filenumber = numbers.number and ORDER BY numbers.ID.
|
23,126,460
|
Problem with the order of retrieving rows. I have a table called documentfiles in that i have three columns filename filepath num i have a query which retrieves filename and filepath with respect to the num
here is my query
```
rs=s.executeQuery("SELECT filename from
documentfiles
where num in
(2167, 2156,
1677, 2149,
1946,1511
) "
);
```
the problem here i am facing is the query retrieving rows in the ascending order of num that is retrieving in this order
>
> `1511 1677 1946 2149 2151 2156 2167 2526 2527 2612 2887 2890 2894 2895 3665 6254 6258 6920 7001 7013 7071 7072 7074 7100`
>
>
>
but i want in this order
>
> `2167, 2156, 1677, 7074, 2149, 7100, 7072, 2890, 2527, 2526, 1946, 1511, 7071, 7013, 7001, 6920, 6258, 6254, 3665, 2895, 2894, 2887, 2612, 2151`
>
>
>
well i have stored num with values in ascending order
`1511 1677 1946 2149 2151 2156 2167 2526 2527 2612 2887 2890 2894 2895 3665 6254 6258 6920 7001 7013 7071 7072 7074 7100`
not in this order
>
> 2167, 2156, 1677, 2149, 1946, 1511
>
>
>
so how do i achieve this is that possible,
any help would be greatly appreciated
thanks in advance
|
2014/04/17
|
[
"https://Stackoverflow.com/questions/23126460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2318813/"
] |
You didn't state your DBMS so this is ANSI SQL:
```
with numbers (num, sort_order) as (
values (2167,1), (2156,2), (1677,3), (2149,4), (1946,5), (1511, 6)
)
select filename
from documentfiles d
join numbers n on d.num = n.num
order by n.sort_order
```
|
```
CREATE TABLE numbers
(
ID int identity(1,1) primary key,
number int
)
CREATE PROCEDURE insertnumbers
@number int
AS BEGIN
INSERT INTO numbers VALUES (@number);
END
```
Now you add comma on beginning
```
,2167, 2156, 1677, 7074, 2149, 7100,
7072, 2890, 2527, 2526, 1946, 1511,
7071, 7013, 7001, 6920, 6258, 6254,
3665, 2895, 2894, 2887, 2612, 2151
```
and then you use notepad and SEARCH AND REPLACE
search: `,`
replace: `; EXEC insertnumbers`
Then you remove first `;` and you can insert numbers. Then you INNER JOIN table filename with table numbers ON filename.filenumber = numbers.number and ORDER BY numbers.ID.
|
265,994
|
Hello I have this function that looks for nested value 3 levels deep currently
```
// This handle nested data to be applied to filter option which comes from filterProps.prop values
// This is currently chained 3 level deep I.E clock.props.children to add more just keep chaineding
const handleNestFilterProp = (prop: any, item: any, trim?: boolean) => {
return trim
? prop.length === 1
? item[prop[0]] && item[prop[0]].trim().length > 0
: prop.length === 2
? item[prop[0]][prop[1]].trim().length > 0
: prop.length === 3 && item[prop[0]][prop[1]][prop[2]].trim().length > 0
: prop.length === 1
? item[prop[0]] && item[prop[0]]
: prop.length === 2
? item[prop[0]][prop[1]]
: prop.length === 3 && item[prop[0]][prop[1]][prop[2]];
};
```
I'm trying to figure out a way to reduce the logic and make it simpler.
I thinking if it would be a good idea to use get from Lodash
<https://lodash.com/docs/4.17.15#get>
###### UPDATE added lodash get to simplify
```
const handleNestFilterProp = (prop: any, item: any, trim?: boolean) => {
const L1 = _.get(item, prop[0]);
const L2 = _.get(item, [prop[0], prop[1]]);
const L3 = _.get(item, [prop[0], prop[1], prop[2]]);
return trim
? prop.length === 1
? L1 && L1.trim().length > 0
: prop.length === 2
? L2 && L2.trim().length > 0
: prop.length === 3 && L3.trim().length > 0
: prop.length === 1
? L1
: prop.length === 2
? L2
: prop.length === 3 && L3;
};
```
###### UPDATE 2
```
const handleNestFilterProp = (prop: any, item: any, trim?: boolean) => {
const L1 = _.get(item, prop[0]);
const L2 = _.get(item, [prop[0], prop[1]]);
const L3 = _.get(item, [prop[0], prop[1], prop[2]]);
return prop.length === 1
? trim
? L1.trim().length > 0
: L1
: prop.length === 2
? trim
? L2.trim().length > 0
: L2
: prop.length === 3 && trim
? L3.trim().length > 0
: L3;
};
```
###### UPDATE 3
```
const handleNestFilterProp = (prop: any, item: any, trim?: boolean) => {
const nest = [prop[0], prop[1], prop[2]];
const L1 = _.get(item, nest.slice(0, 1));
const L2 = _.get(item, nest.slice(0, 2));
const L3 = _.get(item, nest);
return prop.length === 1
? trim
? L1.trim().length > 0
: L1
: prop.length === 2
? trim
? L2.trim().length > 0
: L2
: prop.length === 3 && trim
? L3.trim().length > 0
: L3;
};
```
|
2021/08/12
|
[
"https://codereview.stackexchange.com/questions/265994",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/244349/"
] |
```
const handleNestFilterProp = (prop: string, item: any, trim?: boolean) => {
return trim ? _.get(item, prop).trim().length > 0 : _.get(item, prop);
};
```
\_.get just takes 'props.clock.children' and goes deep no matter how deep
|
For me, using nested conditional expression makes the code very hard to understand, I think you should use `if` and `switch` statements for readability. It's difficult to understand what your code returns in each case so I only write the structure of the code.
```javascript
const handleNestFilterProp = (prop: any, item: any, trim?: boolean) => {
if (trim) {
switch (prop.length) {
case 1:
break;
case 2:
break;
case 3:
break;
}
} else {
switch (prop.length) {
switch (prop.length) {
case 1:
break;
case 2:
break;
case 3:
break;
}
}
}
};
```
```
|
265,994
|
Hello I have this function that looks for nested value 3 levels deep currently
```
// This handle nested data to be applied to filter option which comes from filterProps.prop values
// This is currently chained 3 level deep I.E clock.props.children to add more just keep chaineding
const handleNestFilterProp = (prop: any, item: any, trim?: boolean) => {
return trim
? prop.length === 1
? item[prop[0]] && item[prop[0]].trim().length > 0
: prop.length === 2
? item[prop[0]][prop[1]].trim().length > 0
: prop.length === 3 && item[prop[0]][prop[1]][prop[2]].trim().length > 0
: prop.length === 1
? item[prop[0]] && item[prop[0]]
: prop.length === 2
? item[prop[0]][prop[1]]
: prop.length === 3 && item[prop[0]][prop[1]][prop[2]];
};
```
I'm trying to figure out a way to reduce the logic and make it simpler.
I thinking if it would be a good idea to use get from Lodash
<https://lodash.com/docs/4.17.15#get>
###### UPDATE added lodash get to simplify
```
const handleNestFilterProp = (prop: any, item: any, trim?: boolean) => {
const L1 = _.get(item, prop[0]);
const L2 = _.get(item, [prop[0], prop[1]]);
const L3 = _.get(item, [prop[0], prop[1], prop[2]]);
return trim
? prop.length === 1
? L1 && L1.trim().length > 0
: prop.length === 2
? L2 && L2.trim().length > 0
: prop.length === 3 && L3.trim().length > 0
: prop.length === 1
? L1
: prop.length === 2
? L2
: prop.length === 3 && L3;
};
```
###### UPDATE 2
```
const handleNestFilterProp = (prop: any, item: any, trim?: boolean) => {
const L1 = _.get(item, prop[0]);
const L2 = _.get(item, [prop[0], prop[1]]);
const L3 = _.get(item, [prop[0], prop[1], prop[2]]);
return prop.length === 1
? trim
? L1.trim().length > 0
: L1
: prop.length === 2
? trim
? L2.trim().length > 0
: L2
: prop.length === 3 && trim
? L3.trim().length > 0
: L3;
};
```
###### UPDATE 3
```
const handleNestFilterProp = (prop: any, item: any, trim?: boolean) => {
const nest = [prop[0], prop[1], prop[2]];
const L1 = _.get(item, nest.slice(0, 1));
const L2 = _.get(item, nest.slice(0, 2));
const L3 = _.get(item, nest);
return prop.length === 1
? trim
? L1.trim().length > 0
: L1
: prop.length === 2
? trim
? L2.trim().length > 0
: L2
: prop.length === 3 && trim
? L3.trim().length > 0
: L3;
};
```
|
2021/08/12
|
[
"https://codereview.stackexchange.com/questions/265994",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/244349/"
] |
Undefined
---------
Information is missing in regard to the function's possible inputs. I will make a guess as to what the possibilities are in the rewrites
TypeScript
----------
To use TypeScript and gain any benefit you need to define the types of all variables. Using `any` is just lazy and degrades the code quality as type syntax just becomes noise.
I will treat the code as if its JavaScript
Names
-----
You are using some poor names. This means one must decipher their content by reading the code. Names should provide the information needed to understand their content and how they are used.
Looking at the line...
```
const handleNestFilterProp = (prop: any, item: any, trim?: boolean) => {
```
... here are some suggest improvements
* `handleNestFilterProp` can be `trimAtPath`,
or if `trim` is always `false` `traversePath`
or if `trim` is always `true` `pathStrHasLength`
See second rewrite for how the last two names can be used.
* `prop` Is an array so the name should be a plural `props`.
Yes they are property names but they are used as directions to the property we are after. It is common to call this type of array usage a `path`
* `item` Is OK but rather generic. It is the starting point (root) of the object you are traversing so the name `rootObj` or just `root` would be more informative.
* `trim` is a good name. But really should not be part of the function (see second rewrite)
So the line becomes
```
const traversePath = (path, root, trim) => {
```
Your question
-------------
Taking from
>
> *"...for nested value 3 levels deep currently"*
>
>
>
with *"currently"* meaning you want to handle any depth.
Rather than statically check the depth to find the linked object, the function can step along the path using a loop. You assign the root the next object on the path to the variable that holds the current root.
You don't need to slow down your page with a bulky library (like lodash) as the this is very easy to do in JavaScript or TypeScript
Rewrite
-------
We can greatly simplify the function using the above points, however there are some caveats regarding the inputs.
* Assumes path has 1 or more items
* Assumes root can be indexed or has properties
* Assumes the path is valid
Thus we get the function below.
```
function trimAtPath(path, root, trim) {
var i = 0;
while (i < path.length) { root = root[path[i++]] }
return trim ? root.trim().length > 0 : root;
}
```
The above is still not right as the return is not evident in the call. We can break it into two functions.
**Note** I have swapped the argument order of `root` and `path`
**Note** traversing the path can be done using [Array.reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce "MDN JavaScript global objects reference. Array reduce")
```
const traversePath = (root, path) => path.reduce((root, key) => root[key], root);
const pathStrHasLen = (root, path) => traversePath(root, path).trim().length > 0;
```
To test the trimmed string length is made when calling the function using a ternary to select the correct function.
```
const result = (trim ? pathStrHasLen : traversePath)(root, path);
```
Alternative
-----------
You can also write the `traversePath` function to have the same signature as `lodash.get` using [... (rest parameters)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters "MDN JavaScript Functions rest parameters")
```
const traversePath = (root, ...path) => path.reduce((root, key) => root[key], root);
// called using
traversePath(root, ...path);
// or
traversePath(root, path[0], path[1], path[2]);
```
|
For me, using nested conditional expression makes the code very hard to understand, I think you should use `if` and `switch` statements for readability. It's difficult to understand what your code returns in each case so I only write the structure of the code.
```javascript
const handleNestFilterProp = (prop: any, item: any, trim?: boolean) => {
if (trim) {
switch (prop.length) {
case 1:
break;
case 2:
break;
case 3:
break;
}
} else {
switch (prop.length) {
switch (prop.length) {
case 1:
break;
case 2:
break;
case 3:
break;
}
}
}
};
```
```
|
265,994
|
Hello I have this function that looks for nested value 3 levels deep currently
```
// This handle nested data to be applied to filter option which comes from filterProps.prop values
// This is currently chained 3 level deep I.E clock.props.children to add more just keep chaineding
const handleNestFilterProp = (prop: any, item: any, trim?: boolean) => {
return trim
? prop.length === 1
? item[prop[0]] && item[prop[0]].trim().length > 0
: prop.length === 2
? item[prop[0]][prop[1]].trim().length > 0
: prop.length === 3 && item[prop[0]][prop[1]][prop[2]].trim().length > 0
: prop.length === 1
? item[prop[0]] && item[prop[0]]
: prop.length === 2
? item[prop[0]][prop[1]]
: prop.length === 3 && item[prop[0]][prop[1]][prop[2]];
};
```
I'm trying to figure out a way to reduce the logic and make it simpler.
I thinking if it would be a good idea to use get from Lodash
<https://lodash.com/docs/4.17.15#get>
###### UPDATE added lodash get to simplify
```
const handleNestFilterProp = (prop: any, item: any, trim?: boolean) => {
const L1 = _.get(item, prop[0]);
const L2 = _.get(item, [prop[0], prop[1]]);
const L3 = _.get(item, [prop[0], prop[1], prop[2]]);
return trim
? prop.length === 1
? L1 && L1.trim().length > 0
: prop.length === 2
? L2 && L2.trim().length > 0
: prop.length === 3 && L3.trim().length > 0
: prop.length === 1
? L1
: prop.length === 2
? L2
: prop.length === 3 && L3;
};
```
###### UPDATE 2
```
const handleNestFilterProp = (prop: any, item: any, trim?: boolean) => {
const L1 = _.get(item, prop[0]);
const L2 = _.get(item, [prop[0], prop[1]]);
const L3 = _.get(item, [prop[0], prop[1], prop[2]]);
return prop.length === 1
? trim
? L1.trim().length > 0
: L1
: prop.length === 2
? trim
? L2.trim().length > 0
: L2
: prop.length === 3 && trim
? L3.trim().length > 0
: L3;
};
```
###### UPDATE 3
```
const handleNestFilterProp = (prop: any, item: any, trim?: boolean) => {
const nest = [prop[0], prop[1], prop[2]];
const L1 = _.get(item, nest.slice(0, 1));
const L2 = _.get(item, nest.slice(0, 2));
const L3 = _.get(item, nest);
return prop.length === 1
? trim
? L1.trim().length > 0
: L1
: prop.length === 2
? trim
? L2.trim().length > 0
: L2
: prop.length === 3 && trim
? L3.trim().length > 0
: L3;
};
```
|
2021/08/12
|
[
"https://codereview.stackexchange.com/questions/265994",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/244349/"
] |
Undefined
---------
Information is missing in regard to the function's possible inputs. I will make a guess as to what the possibilities are in the rewrites
TypeScript
----------
To use TypeScript and gain any benefit you need to define the types of all variables. Using `any` is just lazy and degrades the code quality as type syntax just becomes noise.
I will treat the code as if its JavaScript
Names
-----
You are using some poor names. This means one must decipher their content by reading the code. Names should provide the information needed to understand their content and how they are used.
Looking at the line...
```
const handleNestFilterProp = (prop: any, item: any, trim?: boolean) => {
```
... here are some suggest improvements
* `handleNestFilterProp` can be `trimAtPath`,
or if `trim` is always `false` `traversePath`
or if `trim` is always `true` `pathStrHasLength`
See second rewrite for how the last two names can be used.
* `prop` Is an array so the name should be a plural `props`.
Yes they are property names but they are used as directions to the property we are after. It is common to call this type of array usage a `path`
* `item` Is OK but rather generic. It is the starting point (root) of the object you are traversing so the name `rootObj` or just `root` would be more informative.
* `trim` is a good name. But really should not be part of the function (see second rewrite)
So the line becomes
```
const traversePath = (path, root, trim) => {
```
Your question
-------------
Taking from
>
> *"...for nested value 3 levels deep currently"*
>
>
>
with *"currently"* meaning you want to handle any depth.
Rather than statically check the depth to find the linked object, the function can step along the path using a loop. You assign the root the next object on the path to the variable that holds the current root.
You don't need to slow down your page with a bulky library (like lodash) as the this is very easy to do in JavaScript or TypeScript
Rewrite
-------
We can greatly simplify the function using the above points, however there are some caveats regarding the inputs.
* Assumes path has 1 or more items
* Assumes root can be indexed or has properties
* Assumes the path is valid
Thus we get the function below.
```
function trimAtPath(path, root, trim) {
var i = 0;
while (i < path.length) { root = root[path[i++]] }
return trim ? root.trim().length > 0 : root;
}
```
The above is still not right as the return is not evident in the call. We can break it into two functions.
**Note** I have swapped the argument order of `root` and `path`
**Note** traversing the path can be done using [Array.reduce](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce "MDN JavaScript global objects reference. Array reduce")
```
const traversePath = (root, path) => path.reduce((root, key) => root[key], root);
const pathStrHasLen = (root, path) => traversePath(root, path).trim().length > 0;
```
To test the trimmed string length is made when calling the function using a ternary to select the correct function.
```
const result = (trim ? pathStrHasLen : traversePath)(root, path);
```
Alternative
-----------
You can also write the `traversePath` function to have the same signature as `lodash.get` using [... (rest parameters)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters "MDN JavaScript Functions rest parameters")
```
const traversePath = (root, ...path) => path.reduce((root, key) => root[key], root);
// called using
traversePath(root, ...path);
// or
traversePath(root, path[0], path[1], path[2]);
```
|
```
const handleNestFilterProp = (prop: string, item: any, trim?: boolean) => {
return trim ? _.get(item, prop).trim().length > 0 : _.get(item, prop);
};
```
\_.get just takes 'props.clock.children' and goes deep no matter how deep
|
14,102,055
|
I am in need for some design help.
I have a class, let's call it a spaceship which can implement several behaviors.
I've defined an interface to declare the operations each behavior supports.
Until now this is the classic strategy pattern.
However, the implemented strategies need to be able to call actions and methods on the context class. I've been thinking of passing along the context as an interface itself to the encapsulated algorithms.
Is this the best approach? If not, what would you recommend?

|
2012/12/31
|
[
"https://Stackoverflow.com/questions/14102055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/126015/"
] |
What you are planning to do seems fine to me. One thing to hold into account is to not pass in too much to the method(s) of your behaviour class(es). For instance, if your spaceship has an `engine behaviour`, only pass it your `fuel tank` and `drive unit`, not the whole spaceship.
|
Depending on what your strategies need the context for, you could consider making it event-based using the Observer pattern as well so that your strategies not coupled to the context.
An example could be if your strategies cause something in your context to change, these could be events that some intermediary (or your context itself) subscribe to.
|
990,710
|
It is known that after exceeding amount of write procedures to a particular SSD sector this sector dies and is replaced with another one from reserved ones. Please, correct me if I'm wrong.
I suppose it might be unsafe to use SSD disc for very long time. But I would like to know how much damaged is my disc, how many damaged sectors it has? How to get such info? Is there any useful software to check it?
|
2015/10/23
|
[
"https://superuser.com/questions/990710",
"https://superuser.com",
"https://superuser.com/users/178137/"
] |
The idea that SSDs are fragile snowflakes that will melt under the white heat of data is a bit of a mistake.
Many tests have been done where drives have been torture tested - tech report did one [with last generation drives](http://techreport.com/review/27909/the-ssd-endurance-experiment-theyre-all-dead) and basically its PRETTY hard to kill a modern SSD by excessive writes.
Bit of a disclaimer. SMART needs careful interpretation and will tell you something *can* go wrong. Not that it will. SSDs may have different smart attributes based on brand. Look up the documentation for your drive. I primarily own samsungs at the moment, so my answer references the drives I have and the software for them.
People have put SSDs through workloads *significantly* worse than what they have been rated for and they have survived. *Treat them like any other storage*. Back them up, of course, but they arn't typically going to die that fast.
There's a few factors to SSD endurance - process size (the larger the better but not always), bits per cell (slc is better than mlc is better than tlc) and so on. However most modern drive have *impressive* endurance,
However, most drives have a certain amount of 'spare' cells (aka overprovisioning) that should help mitigate dead/worn out nand. Amusingly, the best drives (enterprise class SLC) and worst consumer level TLC drives *both* have a lot of this. In short, the drive handles this so you don't have to.
Interestingly SSDs use the same SMART standards as any other drive, and either your manufacturers tools or your favourite SMART information tool will tell you the raw values. However the *attributes may differ*.
[](https://i.stack.imgur.com/3RHsX.png)
Annoyingly these standards are not *too* standard and interpretation is as much as art as a science. I just tend to rely on the little green health status label to tell me everything's fine. That said, [samsung has a rough guide on interpreting the values](http://www.samsung.com/global/business/semiconductor/minisite/SSD/global/html/whitepaper/whitepaper07.html) and suggest except for total LBA's written, the raw values should be indicative of what's going on. Check your specific manufacturer to be sure,
Practically speaking, unless you're hitting the bathtub curve of premature death, or a wierd bug, your drive is at least going to live as long as the warranty.
|
>
> But I would like to know how deadly is my disc, how many damaged sectors it has? How to get such info?
>
>
>
This information is commonly available from [SMART](https://en.wikipedia.org/wiki/S.M.A.R.T.) data. Disk vendors often provide tools that will show this information in a reasonably user-friendly manner, or you can use generic tools that will simply display the data and leave the interpretation to you.
As an example, my Intel 530 SSD (after nearly two years of use) reports the value of the `Media_Wearout_Indicator` SMART attribute as `098` (it started out at `100`, and is a percentage; this is documented by Intel in some specification somewhere...), with a "threshold" of `000`. The "threshold" value is when the vendor feels the media has outlived its useful life and/or failure is imminent. The exact physical processes that map to these values differ between drives, which is why the normalized value is useful for telling the current state of the drive. *Other SSDs are probably slightly different, but the principle is the same.*
>
> It is known that after exceeding write procedure to particular SSD sector count this sector dies and is replaced with another one from reserved ones. Please, correct me if I'm wrong.
>
>
>
Your understanding is wrong. SSDs use a combination of several techniques to spread the writes, and the most relevant here is probably [wear leveling](https://en.wikipedia.org/wiki/Wear_leveling). This is done to prolong the life of each flash block proactively, rather than simply react to failing writes after the fact. Also, flash memory is rated to a certain number of writes per block (not sector; "sector" is an artefact of rotational storage), but that doesn't mean that the memory will instantly fail once that number of writes has been reached, just that the flash memory manufacturer doesn't guarantee that it will keep working after that point.
And like Journeyman Geek said, **backups!** We get questions all the time from people on how to recover data from a failed storage device which held the only copy of the data. Make regular backups (ideally, make the backups fully automated); you will save yourself a *lot* of grief. [SSDs aren't *particularly* fragile](https://serverfault.com/a/507536/58408), but they still fail from time to time just like any other device.
|
6,968,523
|
I am working on a 3d game engine for the iPhone and Im currently working out how Im going to be handling all of my 3D objects. I have a class that holds information pertaining to each 3D object such as vertexdata, texture information, etc.
I also have a method that is called once every x milleseconds that handles rendering the 3d scene.
Inside of this method, I would like to loop through all of my 3D objects to get access to their render data.
I realize I could store pointers to all of my 3D objects in an array and iterate through this array, but before venturing down this possibly unnecessary road I was wondering if there was away to simply iterate through all instances of a given class (ie my 3d object class), as this would solve my problem.
Pseduo:
For (obj in AEobject3D){
render obj
}
Is something like this possible? If so please excuse the ignorance, I cant seem to find information in the docs / internet, and Im still learning my way through Objective C.
Thanks,
- Adam Eisfeld
|
2011/08/06
|
[
"https://Stackoverflow.com/questions/6968523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/882151/"
] |
No, there's no built-in way to do this. If you wanted to implement it yourself, you'd still have to use an array to keep track of the objects. So I suggest you just use an array in the first place.
|
Just make an array and be some with it. For instance, UIKit uses the concept of subviews too, which are arrays in arrays.
|
922,766
|
Let $f$ be a not decreasing, Lebesgue integrable function with finite integral over $[0,+\infty)$.
It seems obvious to me that $\lim\_{b\rightarrow\infty}\int\_b^{\infty}f(x)\,dx=0$ then.
But how can one very formally show it?
And assumption about monotonicity is crucial here, yes?
|
2014/09/07
|
[
"https://math.stackexchange.com/questions/922766",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/121568/"
] |
Be
$$F = \int\_0^\infty f(x)\,\mathrm dx.$$
We have from the general rules of integration:
$$F = \int\_0^\infty f(x)\,\mathrm dx = \int\_0^b f(x) \,\mathrm dx
+ \int\_b^\infty f(x) \,\mathrm dx.$$
Therefore
$$\int\_b^\infty f(x) \,\mathrm dx = F - \int\_0^b f(x) \,\mathrm dx$$
and thus
$$\lim\_{b\to\infty} \int\_b^\infty f(x) \,\mathrm dx = F - \lim\_{b\to\infty}\int\_0^b f(x) \,\mathrm dx = F - \int\_0^\infty f(x)\,\mathrm dx = F - F = 0.$$
|
Lebesgue dominated convergence theorem.
|
73,991,129
|
I have integrated the stripe Api in my website to process payments and It is working fine. The only problem is that after the a successfull payment, i don't get any response or an object to know if the payment is successful or not.
Stripe does process the payment and everything is fine but the question is how would I know that it is successful after stripe redirects the client to the success url ?
|
2022/10/07
|
[
"https://Stackoverflow.com/questions/73991129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19535558/"
] |
You can implement webhook in your application. After a payment is completed stripe will call webhook/callback of your application with the payment\_status and other details. Have a look at documentation here [Triggering actions with webhooks](https://stripe.com/docs/payments/handling-payment-events)
|
Using webhooks and events is definitely the right way to go. You can listen for successful payments, failed payments, and other event types, then add some server code to take some action based on those events.
There's a mention of webhooks in Stripe's custom payments quickstart guide: <https://stripe.com/docs/payments/quickstart#use-webhook>
They also have a standalone webhooks guide: <https://stripe.com/docs/webhooks/quickstart>
|
445,604
|
Since Flash 10 was introduced, many of the popular 'copy to clipboard' scripts out there have stopped working due to new security restrictions. There is a Flash-only solution here:
<http://cfruss.blogspot.com/2009/01/copy-to-clipboard-swf-button-cross.html>
...though I'm looking for the ability to trigger the copy function via JS, rather than relying on the user to click on a Flash object to trigger.
For an example of what we currently employ, see:
<http://snipt.net/public>
Any of the 'copy' links use jQuery's copy plugin here:
<http://plugins.jquery.com/project/copy>
UPDATE: OK, so I tried ZeroClipboard. At first glance, it looked great. However, the amount of [redundant code needed to enable multiple clipboard bindings](http://bowser.macminicolo.net/~jhuckaby/zeroclipboard/multiple.php) is unacceptable. In some cases, there will be 40+ instances of text that each have their own 'copy' link. Still looking for a better solution...
|
2009/01/15
|
[
"https://Stackoverflow.com/questions/445604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22468/"
] |
That's terrible news, I hadn't even noticed. I use the Flash trick extensively too. As far as I know that was the only way to get copy to work without having to install some other plugin (besides the ubiquitous Flash) due to browser security concerns.
Update: After much panic, and a few google searches, I stumbled on <http://code.google.com/p/zeroclipboard/> which provides a Flash 10 compatible trick to get the copy to work once again. Now to go around updating websites...
|
This solution only works for keystrokes that would invoke the desired operation. It works by moving the user's cursor into a textarea element before the user finishes the relevant keystroke. It only works for text input. I've got this working in firefox and chrome. IE can use the clipboardData object (which is preferable to this hack).
In your html somewhere you should create a textarea element with arbitrarily large rows and cols attributes. The '**clipboard-textarea**' element will be the holding area for the pasted and copied data. I hide the element using some style attributes.
The script:
```
var desiredClipboardContents = 'It works';
function onCopyKeyPressed() {
// The trick here is to populate the textarea with
// the text you want copied before the user releases
// the copy keystroke.
var textarea = document.getElementById('clipboard-textarea');
textarea.value = desiredClipboardContents;
textarea.focus();
textarea.select();
}
function onPasteKeyPressed() {
var textarea = document.getElementById('clipboard-textarea');
textarea.value = '';
textarea.focus();
// The trick here is to delay slurping the content
// that arrives in the textarea element until after
// the paste keystroke is completed. The 750 ms timeout
// provides the necessary delay.
setTimeout("finishedPasting", 750);
}
function finishedPasting() {
var textarea = document.getElementById('clipboard-textarea');
alert("Received from clipboard-paste: " + textarea.value);
}
```
|
38,904
|
Warum muss man immer auch das weibliche Wort nennen, wenn man von einer bestimmten Gruppe von Menschen, Beruf usw. spricht? Wäre es denn nicht leichter bloß "Schüler" zu sagen?
Und was hat es mit dieser Schreibweise "SchülerIn" auf sich? Ist sie korrekt oder nur umgangssprachlich verwendet?
|
2017/09/05
|
[
"https://german.stackexchange.com/questions/38904",
"https://german.stackexchange.com",
"https://german.stackexchange.com/users/29020/"
] |
Man muss durchaus nicht immer eine männliche und eine weibliche Form parallel nennen. In der Belletristik - einem Roman etwa - wirst du diese Verwendung auch nie finden, und im etablierten Journalismus nur selten. Das pärchenweise Aufführen männlicher und weiblicher Formen hat sich jedoch in den letzten Jahren im behördlichen, geschäftlichen und teils auch akademischen Schriftverkehr weitgehend druchgesetzt. Treibender Faktor ist hier die gesellschaftliche Diskussion zur Gleichberechtigung von Männern und Frauen.
Viele Leute sehen in der Verwendung der männlichen Formen (Beamter, Schüler, Lehrer, Sportler, man) eine latente Benachteiligung oder Unterdrückung von Frauen. Um dem entgegenzuwirken, fügt man im behördlichen oder auch geschäftsmäßigen Schriftverkehr in der Regel darum die weibliche Form hinzu (Beamtin, Schülerin, Sportlerin, seltener auch: frau).
Alternativ werden auch Kombinationsformen verwendet:
>
> Schüler/in, Angestellte/r (mit Schrägstrich)
>
>
> SchülerIn, ParteigenossIn (mit großem Binnen-i)
>
>
>
Daneben gibt es auch Bestrebungen, schriftliche Ausdrucksformen für noch weitere Geschlechteridentitäten (jenseits von nur Mann und Frau) zu finden, etwa mit einem Sternchen oder Unterstrich: Lehrer\*in - was die Möglichkeit anzeigen soll, dass man sich auch anders definiert, zum Beispiel als beides, gar nichts davon oder auch als etwas Drittes.
Es gibt auch Versuche, die als Grundform historisch gebräuchliche (oder eben auch nicht mehr durchgängig gebräuchliche) männliche Form ganz durch die weibliche zu ersetzen. Bekannt wurde die Universität Leipzig, die in der Neufassung ihrer Statuten ("Grundordnung") ausschließlich die weibliche Form verwendet (Professorin), wobei damit aber wiederum stets auch Professoren (männlicher Art) mitgemeint sein sollen ("generisches Femininum").
Für deinen eigenen Gebrauch musst du selber entscheiden, wie du schreibst. Dabei wird der Kontext deines Schreibens den Ausschlag geben. Schreibst du einen Roman, wirst du kaum
>
> Lehrerinnen und Lehrer machen mit Schülerinnen und Schülern einen Ausflug
>
>
>
schreiben (außer es wäre ironisch) sondern kurz und simpel
>
> Lehrer und Schüler machen zusammen einen Ausflug,
>
>
>
denn im Roman kommt es dir weniger auf *political correctness* an als auf gute, saubere, umstandsfreie Sprache.
Schreibst du einen Zeitungsartikel, wirst du auf die Gender-Dopplung verzichten und nur von
>
> Politikern aller Parteien
>
>
>
sprechen, kaum je von
>
> Politikerinnen und Politikern aller Parteien
>
>
>
oder von
>
> Bewohnern und Bewohnerinnen dieses abgelegenen Landstrichs
>
>
>
schon weil du auf der Zeitungsseite nicht so viel Platz hast und den Leser (huch!) nicht nerven willst.
Veröffentlichst du eine Stellenanzeige, wirst du aber in der Regel einen Platz für
>
> eine/n Mechatroniker/in
>
>
>
oder
>
> eine Reinigungsfachkraft (m/w)
>
>
>
anbieten, denn du möchtest der Welt signalisieren, dass Frauen in deiner Firma nicht benachteiligt werden (auch wenn das vielleicht nur schöne Worte sind).
Eine spaßige Beobachtung am Rande: Im Eifer des Gefechts für Gender-Gleichberechtigung versteigen sich Laienschreiber/Laienschreiberinnen manchmal auch ins Absurde. Bekannt wurden Texte aus dem Vereinsumfeld, in denen
>
> Unsere Mitglieder und Mitgliederinnen
>
>
>
zur Jahreshauptversammlung und
>
> Liebe Kinder und Kinderinnen
>
>
>
zur Faschingsfeier eingeladen wurden. Das mag aus übergroßer Furcht geschehen, bei nachlässiger Gender-Dopplung von Eiferern und/oder Eiferinnen eins auf die Mütze zu bekommen. Vielleicht kann man es als Zeichen sehen für die versteckte Vehemenz der zugrundeliegenden Diskussion.
|
Versuch einer knappen Erklärung, was hier die Intention einer [geschlechtergerechten Sprache](https://de.wikipedia.org/wiki/Geschlechtergerechte_Sprache) ist.
In meinem Kopf enstehen nämlich beim Lesen geschlechterspezifische Bilder.
Schüler
=======
>
> [](https://i.stack.imgur.com/TuLGn.png)
>
>
>
Schülerin
=========
>
> [](https://i.stack.imgur.com/yIxhj.png)
>
>
>
Ähnliche Bilder kommen auch bei Arzt und Ärztin oder bei Bauer und Bäurin.
Mit einer geschlechtergerechten Sprache soll erreicht werden, dass nicht mehr nur ein Geschlecht automatisch im Kopf erscheint, sondern keines oder beide.
Wer Schüler/in (oder irgendeine andere gängige Variante) schreibt, möchte also zeigen, dass das biologische Geschlecht hier keine Rolle spielt. Nicht mehr, aber auch nicht weniger. Nicht nur staatliche Einrichtungen, sondern auch Privatunternehmen (inklusive StackExchange) bringen dies heute mit Umsetzen einer geschlechtergerechten Sprache zum Ausdruck.
|
1,589,791
|
Looking for a simple diagram showing the constituent parts of the Flash player like AVM1,AVM2,graphics renderer, text layout engine, video player, etc. Can anyone help me out? Thanks.
|
2009/10/19
|
[
"https://Stackoverflow.com/questions/1589791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/146543/"
] |
The easiest option would be to just make your UserControl expose a click event, and pass through your Button's click event.
In MyButton's xaml:
```
<Button Width="Auto" HorizontalAlignment="Center" Click="onButtonClick">
```
In MyButton's code:
```
public event RoutedEventHandler Click;
void onButtonClick(object sender, RoutedEventArgs e)
{
if (this.Click != null)
{
this.Click(this, e);
}
}
```
You can then leave your "implementation" code as-is.
|
The answer really depends on what your goals are for the control. You may be able to get away with not creating a user or custom control if you can manipulate the data that you are binding to. If all you want to do is display a dynamic image and text, then you could create an ImageText object that contains two properties. You could then bind the default Button control's Content property to this object and use a DataTemplate to define the layout of the content.
If you cannot control the data type that you are binding to, or if you're really set on the idea of creating a control then I would recommend creating a custom control. Custom controls allow you to utilize the built-in capabilities of a standard button. Generally you would only want to create a User Control if you wanted to hide or encapsulate the default functionality of the visual controls contained within the control.
Good luck.
|
31,201,454
|
Solved, thanks. It's base64 and this works.
```
System.Convert.FromBase64String(columns[6]);
```
Thanks again.
I got a TSV file, and inside this file there're audio stored as original string and related wave info. One wave and its info per line. What I need to do is to read each line, get the audio, and save them as separated wave files.
One sample of wave string is like this:
>
> UklGRpgiAABXQVZFZm10ICwAAACUAgEAgD4AAPAKAAA4AAAAGgABAA8AKACOAgEAgD4AANAHAAAoAAAAAgBAAWRhdGFYIgAAQMQKQPQTQTQSQTQSQTQUQYNBVBNBJBJBJBNBJBRBRKFEE0EkE0FEFEE0FEFUFQAAAAAAAAAAAADACOmRY92lbj7+7kGhMFC3V9I3qMyjX2G8vAclkKFxUlD26mS+1qCRMV4OuVCxXf/IxrFBj///9sAG0iRqqUOIIRKT/4vqBtdWJF6pI/mWgPFx6JlUIFUPm6gofbyf93hJ6NCbgja88uTflydp///
>
>
>
And I tried to read this line and use:
```
byte[] waveContext = Encoding.Default.GetBytes(columns[6]);
File.WriteAllBytes(waveFullPath, waveContext);
```
But the output file contains just the same string.
Does anybody got ideas on how to handle this?
Many thanks.
|
2015/07/03
|
[
"https://Stackoverflow.com/questions/31201454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4238769/"
] |
There are quite a few redundancies with your code.
```
double average, count, orig = (double) 0;
```
can be written as:
```
double average, count, orig = 0.0d;
```
(you should consider checking float and decide which suits you better - doesn't really matter here)
Since java 1.7, you can declare lists in a shorter manner (search "diamond expression").
```
ArrayList<Double> list = new ArrayList<>();
```
In the line
```
double e = average.get(average.size() - 1);
```
you probably ment `list` instead of average, which should fix the error in the title.
Right now your code is printing average multiple times and only the last time is the real average of list items. Consider moving printing command of average out of for loop.
try this:
```
for (Double x: list)
{
all += x;
}
average = all/count;
System.out.println(average);
```
|
You cannot call size() method on primitive data type.It can be called on `java.util.List` ,etc. So your `double e = average.get(average.size() - 1);` makes no sense.
You can directly write:
```
average = all/count;
```
|
31,201,454
|
Solved, thanks. It's base64 and this works.
```
System.Convert.FromBase64String(columns[6]);
```
Thanks again.
I got a TSV file, and inside this file there're audio stored as original string and related wave info. One wave and its info per line. What I need to do is to read each line, get the audio, and save them as separated wave files.
One sample of wave string is like this:
>
> UklGRpgiAABXQVZFZm10ICwAAACUAgEAgD4AAPAKAAA4AAAAGgABAA8AKACOAgEAgD4AANAHAAAoAAAAAgBAAWRhdGFYIgAAQMQKQPQTQTQSQTQSQTQUQYNBVBNBJBJBJBNBJBRBRKFEE0EkE0FEFEE0FEFUFQAAAAAAAAAAAADACOmRY92lbj7+7kGhMFC3V9I3qMyjX2G8vAclkKFxUlD26mS+1qCRMV4OuVCxXf/IxrFBj///9sAG0iRqqUOIIRKT/4vqBtdWJF6pI/mWgPFx6JlUIFUPm6gofbyf93hJ6NCbgja88uTflydp///
>
>
>
And I tried to read this line and use:
```
byte[] waveContext = Encoding.Default.GetBytes(columns[6]);
File.WriteAllBytes(waveFullPath, waveContext);
```
But the output file contains just the same string.
Does anybody got ideas on how to handle this?
Many thanks.
|
2015/07/03
|
[
"https://Stackoverflow.com/questions/31201454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4238769/"
] |
There are quite a few redundancies with your code.
```
double average, count, orig = (double) 0;
```
can be written as:
```
double average, count, orig = 0.0d;
```
(you should consider checking float and decide which suits you better - doesn't really matter here)
Since java 1.7, you can declare lists in a shorter manner (search "diamond expression").
```
ArrayList<Double> list = new ArrayList<>();
```
In the line
```
double e = average.get(average.size() - 1);
```
you probably ment `list` instead of average, which should fix the error in the title.
Right now your code is printing average multiple times and only the last time is the real average of list items. Consider moving printing command of average out of for loop.
try this:
```
for (Double x: list)
{
all += x;
}
average = all/count;
System.out.println(average);
```
|
You are keeping too much code in the loop.
While you iterate over the list of doubles, you only need to keep a running total. Afterwards, you should then compute the average as the sum of doubles divided by the size of the list.
Here is how to fix the loop:
```
for (Double x: list)
{
all += x;
}
average = all/count;
System.out.println(average);
//These lines are not useful, so they are commented out.
//double e = average.get(average.size() - 1);
// System.out.println(e);
```
|
31,201,454
|
Solved, thanks. It's base64 and this works.
```
System.Convert.FromBase64String(columns[6]);
```
Thanks again.
I got a TSV file, and inside this file there're audio stored as original string and related wave info. One wave and its info per line. What I need to do is to read each line, get the audio, and save them as separated wave files.
One sample of wave string is like this:
>
> UklGRpgiAABXQVZFZm10ICwAAACUAgEAgD4AAPAKAAA4AAAAGgABAA8AKACOAgEAgD4AANAHAAAoAAAAAgBAAWRhdGFYIgAAQMQKQPQTQTQSQTQSQTQUQYNBVBNBJBJBJBNBJBRBRKFEE0EkE0FEFEE0FEFUFQAAAAAAAAAAAADACOmRY92lbj7+7kGhMFC3V9I3qMyjX2G8vAclkKFxUlD26mS+1qCRMV4OuVCxXf/IxrFBj///9sAG0iRqqUOIIRKT/4vqBtdWJF6pI/mWgPFx6JlUIFUPm6gofbyf93hJ6NCbgja88uTflydp///
>
>
>
And I tried to read this line and use:
```
byte[] waveContext = Encoding.Default.GetBytes(columns[6]);
File.WriteAllBytes(waveFullPath, waveContext);
```
But the output file contains just the same string.
Does anybody got ideas on how to handle this?
Many thanks.
|
2015/07/03
|
[
"https://Stackoverflow.com/questions/31201454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4238769/"
] |
You cannot call size() method on primitive data type.It can be called on `java.util.List` ,etc. So your `double e = average.get(average.size() - 1);` makes no sense.
You can directly write:
```
average = all/count;
```
|
You are keeping too much code in the loop.
While you iterate over the list of doubles, you only need to keep a running total. Afterwards, you should then compute the average as the sum of doubles divided by the size of the list.
Here is how to fix the loop:
```
for (Double x: list)
{
all += x;
}
average = all/count;
System.out.println(average);
//These lines are not useful, so they are commented out.
//double e = average.get(average.size() - 1);
// System.out.println(e);
```
|
62,307,237
|
I included Vuejs in my existing project but now it is affecting my original theme JavaScript files.
Without app.js on my homepage, everything works fine. But when I include it, All UI effects and functionalities on my original theme js file including sliders, canvas, carousels, and dropdowns all stops working.
How do I stop Vue from colliding with my theme js and causing it to break
|
2020/06/10
|
[
"https://Stackoverflow.com/questions/62307237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10367781/"
] |
regarding CSS collisions...
---------------------------
You can solve by making sure all your css is getting scoped.
instead of
```html
<style>
/* global styles */
</style>
```
use
```html
<style scoped>
/* local styles */
</style>
```
Vue will then compile your css to have generated is like `h1[data-v-f3f3eg9]` that will prevent other elements on the page from being formatted by your vue code. It will not, however, prevent your page code from affecting the vue components unless you add css resets to you components.
### regarding JS code...
it's hard to tell without seeing what the collisions are. AFAIK There's no magical setting for that.
|
I found the solution for this collision
Put your `app.js` at the top of your script links like:
```
<script src="{{ asset('js/app.js') }}"></script>
```
Then
```
<script> $.noConflict(); /script>
```
After that put your other JavaScript it will work fine.
|
60,129,814
|
Below is a reproducible example, but you will need a google API to help. Here is a quick example of the behavior I am seeing.
Given the following code:
```
test.1 <- data.frame(rbind("02908", "98144"), c("60612", "60612"),
stringsAsFactors = FALSE)
colnames(test.1) <- c("from", "to")
library(ggmap)
Distance <- mapdist(from = test.1$from,
to = test.1$to,
mode = "driving",
output = "simple")
Distance
```
Yields the following output:
```
> Distance
# A tibble: 2 x 9
from to m km miles seconds minutes hours mode
<chr> <chr> <int> <dbl> <dbl> <int> <dbl> <dbl> <chr>
1 02908 60612 3321774 3322. 2064. 109087 1818. 30.3 driving
2 98144 60612 1562693 1563. 971. 53819 897. 14.9 driving
```
But when I manually do a search, using the following:
```
mapdist(from = "02908",
to = "60612",
mode = "driving",
output = "simple")
mapdist(from = "98144",
to = "60612",
mode = "driving",
output = "simple")
```
I get the following output for each:
```
# A tibble: 1 x 9
from to m km miles seconds minutes hours mode
<chr> <chr> <int> <dbl> <dbl> <int> <dbl> <dbl> <chr>
1 02908 60612 1562693 1563. 971. 53819 897. 14.9 driving
```
and
```
# A tibble: 1 x 9
from to m km miles seconds minutes hours mode
<chr> <chr> <int> <dbl> <dbl> <int> <dbl> <dbl> <chr>
1 98144 60612 3321774 3322. 2064. 109087 1818. 30.3 driving
```
As you can see, when I make the call for each "from/to" separately, it's exactly flipped from when I make the call from a dataframe. Or, more to the point, the distance from "02908" to "60612" = 971 miles when I make the request directly, but 2064 miles when the call comes from a dataframe. Worse, it appears the individual call is correct, but the call from the dataframe is wrong. And of course I want to do this for a lot of "from/to" pairs.
Any help would be ever so much appreciated.
|
2020/02/08
|
[
"https://Stackoverflow.com/questions/60129814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12864391/"
] |
You can use [`number_format`](https://www.php.net/manual/en/function.number-format.php) for this.
```
echo number_format($item->price,2);
```
**Demo:** <https://3v4l.org/NnZlb>
Just a side note that `number_format` also [`rounds silently`](https://www.php.net/manual/en/function.number-format.php#88424).
|
Try this:
```
$item->price= sprintf("%.2f", $item->price);
```
The underlying problem is that the original number cannot be represented as an exact floating point number on the system it was generated on. It was probably a floating point number that was converted to a string as part of JSON encoding.
A number of functions in languages handle this for you by doing silently rounding the insignificant digits to zero. Whatever produced the original JSON did not.
Since you don't need the value as a number you can use the sprintf() function to convert it to a 2 decimal point string representation of the number.
|
5,898,911
|
how can we log spring Transaction mechanism. i am showing below example shown in [Spring Doc sec 10.5.2](http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/transaction.html#tx-decl-explained).if i want to logging upto this level how to do that
i am using Spring,Hibernate and Log4j.
```
<!-- the Spring container is starting up... -->
[AspectJInvocationContextExposingAdvisorAutoProxyCreator] - Creating implicit proxy
for bean 'fooService' with 0 common interceptors and 1 specific interceptors
<!-- the DefaultFooService is actually proxied -->
[JdkDynamicAopProxy] - Creating JDK dynamic proxy for [x.y.service.DefaultFooService]
<!-- ... the insertFoo(..) method is now being invoked on the proxy -->
[TransactionInterceptor] - Getting transaction for x.y.service.FooService.insertFoo
<!-- the transactional advice kicks in here... -->
[DataSourceTransactionManager] - Creating new transaction with name [x.y.service.FooService.insertFoo]
[DataSourceTransactionManager] - Acquired Connection
[org.apache.commons.dbcp.PoolableConnection@a53de4] for JDBC transaction
<!-- the insertFoo(..) method from DefaultFooService throws an exception... -->
[RuleBasedTransactionAttribute] - Applying rules to determine whether transaction should
rollback on java.lang.UnsupportedOperationException
[TransactionInterceptor] - Invoking rollback for transaction on x.y.service.FooService.insertFoo
due to throwable [java.lang.UnsupportedOperationException]
<!-- and the transaction is rolled back (by default, RuntimeException instances cause rollback) -->
[DataSourceTransactionManager] - Rolling back JDBC transaction on Connection
[org.apache.commons.dbcp.PoolableConnection@a53de4]
[DataSourceTransactionManager] - Releasing JDBC Connection after transaction
[DataSourceUtils] - Returning JDBC Connection to DataSource
Exception in thread "main" java.lang.UnsupportedOperationException
at x.y.service.DefaultFooService.insertFoo(DefaultFooService.java:14)
<!-- AOP infrastructure stack trace elements removed for clarity -->
at $Proxy0.insertFoo(Unknown Source)
```
Logging File..
```
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.rootLogger=info, stdout
log4j.category.org.springframework.transactions=DEBUG
```
|
2011/05/05
|
[
"https://Stackoverflow.com/questions/5898911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/692692/"
] |
There's [a section about Logging](http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/overview.html#d0e743) in the Spring Reference.
It shows how to configure different logging frameworks, among them [log4j](http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/overview.html#d0e826)
In your case the last line of the config would be:
```
log4j.logger.org.springframework.transaction=DEBUG
```
|
If you're just willing to set the log level of spring transaction support, try adding the following logger to your log4j.xml :
```
<logger name="org.springframework.transaction">
<level value="DEBUG" />
</logger>
```
|
12,686,490
|
I want to enumerate colors and use Color instances. Therefore I have created an
enum with a private field and a get-function, but using it is cumbersome because
of the need to call `getColor()`.
Is there a better approach at directly using the enumeration constant without calling `getColor()`?
```
public class ColorListTest {
public enum ColorList
{
WHITE(new Color(255, 255, 255)),
BLACK(new Color(255, 255, 255)),
;
private Color color;
private ColorList(Color color) { this.color = color; }
public Color getColor() { return color; }
}
public static void main(String[] args)
{
Color color = ColorList.WHITE.getColor();
// I'd rather have something similar to:
// Color color = WHITE;
// Color color = ColorList.WHITE;
}
}
```
The answer to [Using enums as key for map](https://stackoverflow.com/questions/12669497/using-enum-as-key-for-map)
question suggests to use a map, which also needs to call get().
Another option is to use a list of constants, which is less type safe since there is no
enum anymore:
```
static public class ColorList
{
static final Color WHITE = new Color(null, 255, 255, 255);
static final Color BLACK = new Color(null, 0, 0, 0);
}
```
(The other posts I found seem to deal with string conversions a lot.)
So do you have a recommendation on a nice to use enum?
|
2012/10/02
|
[
"https://Stackoverflow.com/questions/12686490",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1671066/"
] |
The only thing you can do which might be nicer is to use a static import.
```
import static mypackage.ColourList.*;
public static void main(String[] args) {
Color color = WHITE.getColor();
}
```
|
Use enumerators to define constants that you want to use.
You can define the enumarator in a different class file and directly call the constants rather than defining it inside a class.
|
23,983,276
|
i have MainActivty and MyLocationListener classes.
MyLocationListener extends AsyncTask implements LocationListener..
Here is code of the Location Listener Class:
private class MyLocationListener extends AsyncTask implements LocationListener {
```
@Override
public void onLocationChanged(Location location) {
// convert coords from double to string
String lat = Double.toString(location.getLatitude());
String lon = Double.toString(location.getLongitude());
Log.i(AppHelper.APP_LOG_NAMESPACE, "lat " + lat);
Log.i(AppHelper.APP_LOG_NAMESPACE, "lon " + lon);
// save actual position into shared preferences storage
_appPrefs = new AppPreferences(activityContext);
_appPrefs.saveSomeString("lat", lat);
_appPrefs.saveSomeString("lon", lon);
getAddressByCoords(location.getLatitude(),
location.getLongitude());
setPositionToView(activityContext, mView);
}
/**
* Method get string representation of the place in given coords
*
* @param lat
* double
* @param lon
* double
* @return List <Address>
* @throws Exception
*/
public List<Address> getAddressByCoords(double lat, double lon) {
Geocoder gCoder = new Geocoder(activityContext);
try {
addresses = gCoder.getFromLocation(lat, lon, 1);
if (addresses != null && addresses.size() > 0) {
Log.d("APP",
"LOCATION " + addresses.get(0).getAddressLine(0));
Log.d("APP",
"LOCATION " + addresses.get(0).getAddressLine(1));
Log.d("APP",
"LOCATION " + addresses.get(0).getAddressLine(2));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return addresses;
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(MainActivity.this,
provider + "'s status changed to " + status + "!",
Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderEnabled(String provider) {
Toast.makeText(MainActivity.this,
"Provider " + provider + " enabled!", Toast.LENGTH_SHORT)
.show();
}
@Override
public void onProviderDisabled(String provider) {
Toast.makeText(MainActivity.this,
"Provider " + provider + " disabled!", Toast.LENGTH_SHORT)
.show();
}
@Override
protected Object doInBackground(Object... params) {
try {
// Define the criteria how to select the location provider
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE); // default
criteria.setCostAllowed(false);
// get the best provider depending on the criteria
provider = locationManager.getBestProvider(criteria, false);
// the last known location of this provider
Location location = locationManager
.getLastKnownLocation(provider);
// request single update
this.onLocationChanged(location);
} catch (Exception e) {
Log.e(AppHelper.APP_LOG_NAMESPACE,
"doInBackground method cannot be processed", e);
e.printStackTrace();
}
return null;
}
}
```
If i'm trying to get GPS coords using the:
```
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mView = view;
boolean isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// get values from user settings
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this);
Boolean prefferNativeGPs = sharedPrefs.getBoolean(
"prefNativeGps", false);
Log.i("APP", "GPS enabled " + isGPSEnabled); // false
Log.i("APP", "NETWORK enabled " + isNetworkEnabled); // true
Log.i("APP", "USE native " + prefferNativeGPs); // true
// blink textview
TextView stateTv = (TextView) findViewById(R.id.state);
stateTv.setTextColor(getResources().getColor(R.color.black));
startBlinkText();
Log.i("APP", "GPS POSITION USING GPS_PROVIDER");
Toast.makeText(this,R.string.parking_car_using_gps_it_can_take_more_time,
Toast.LENGTH_LONG).show();
// calling doInBackground
new MyLocationListener().execute("");
```
I got following exception in doInBackground:
*cannot create handler inside thread that has not called looper.prepare*
I would like to ask, how to modify my code to do processing correctly?
Many thanks for any help.
|
2014/06/01
|
[
"https://Stackoverflow.com/questions/23983276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/535556/"
] |
Change this:
```
for ( var i in images) {
code += '<img src="' + i + '" alt="image not available">';
}
```
To this:
```
for ( var i = 0; i < images.length; i++) {
code += '<img src="' + images[i] + '" alt="image not available">';
}
```
The `for ( var foo in bar )` construct doesn't do what you think it does. It iterates the *properties* of the object, which in the case of the array are unordered array indices, not array values.
Note: Several answers suggest you keep the `for...in` syntax and index your array properly. This will probably work in the basic case, but it is not recommended for two reasons:
1. Iterting an array in this way is not guaranteed to go in index order. So if you want your images in the same order as they appear in the array, you could get burned.
2. The `for...in` syntax iterates all properties of the array, not just elements in the array. A base array like you have here, with no magic in play from third party libraries, etc..., does not have any additional properties. But it might, and then your code would break.
The **right** way to iterate an array is with a standard `for` loop. See [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) which says:
>
> for..in should not be used to iterate over an Array where index order is important. Array indexes are just enumerable properties with integer names and are otherwise identical to general Object properties. There is no guarantee that for...in will return the indexes in any particular order and it will return all enumerable properties, including those with non–integer names and those that are inherited.
>
>
> Because the order of iteration is implementation dependent, iterating over an array may not visit elements in a consistent order. Therefore it is better to use a for loop with a numeric index (or Array.forEach or the non-standard for...of loop) when iterating over arrays where the order of access is important.
>
>
>
|
When you use `for (var i in images)`, `i` becomes the *index*, not the element itself. Try:
```
for (var i in images) {
code += '<img src="' + images[i] + '" alt="image not available">';
}
```
|
23,983,276
|
i have MainActivty and MyLocationListener classes.
MyLocationListener extends AsyncTask implements LocationListener..
Here is code of the Location Listener Class:
private class MyLocationListener extends AsyncTask implements LocationListener {
```
@Override
public void onLocationChanged(Location location) {
// convert coords from double to string
String lat = Double.toString(location.getLatitude());
String lon = Double.toString(location.getLongitude());
Log.i(AppHelper.APP_LOG_NAMESPACE, "lat " + lat);
Log.i(AppHelper.APP_LOG_NAMESPACE, "lon " + lon);
// save actual position into shared preferences storage
_appPrefs = new AppPreferences(activityContext);
_appPrefs.saveSomeString("lat", lat);
_appPrefs.saveSomeString("lon", lon);
getAddressByCoords(location.getLatitude(),
location.getLongitude());
setPositionToView(activityContext, mView);
}
/**
* Method get string representation of the place in given coords
*
* @param lat
* double
* @param lon
* double
* @return List <Address>
* @throws Exception
*/
public List<Address> getAddressByCoords(double lat, double lon) {
Geocoder gCoder = new Geocoder(activityContext);
try {
addresses = gCoder.getFromLocation(lat, lon, 1);
if (addresses != null && addresses.size() > 0) {
Log.d("APP",
"LOCATION " + addresses.get(0).getAddressLine(0));
Log.d("APP",
"LOCATION " + addresses.get(0).getAddressLine(1));
Log.d("APP",
"LOCATION " + addresses.get(0).getAddressLine(2));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return addresses;
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(MainActivity.this,
provider + "'s status changed to " + status + "!",
Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderEnabled(String provider) {
Toast.makeText(MainActivity.this,
"Provider " + provider + " enabled!", Toast.LENGTH_SHORT)
.show();
}
@Override
public void onProviderDisabled(String provider) {
Toast.makeText(MainActivity.this,
"Provider " + provider + " disabled!", Toast.LENGTH_SHORT)
.show();
}
@Override
protected Object doInBackground(Object... params) {
try {
// Define the criteria how to select the location provider
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE); // default
criteria.setCostAllowed(false);
// get the best provider depending on the criteria
provider = locationManager.getBestProvider(criteria, false);
// the last known location of this provider
Location location = locationManager
.getLastKnownLocation(provider);
// request single update
this.onLocationChanged(location);
} catch (Exception e) {
Log.e(AppHelper.APP_LOG_NAMESPACE,
"doInBackground method cannot be processed", e);
e.printStackTrace();
}
return null;
}
}
```
If i'm trying to get GPS coords using the:
```
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mView = view;
boolean isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// get values from user settings
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this);
Boolean prefferNativeGPs = sharedPrefs.getBoolean(
"prefNativeGps", false);
Log.i("APP", "GPS enabled " + isGPSEnabled); // false
Log.i("APP", "NETWORK enabled " + isNetworkEnabled); // true
Log.i("APP", "USE native " + prefferNativeGPs); // true
// blink textview
TextView stateTv = (TextView) findViewById(R.id.state);
stateTv.setTextColor(getResources().getColor(R.color.black));
startBlinkText();
Log.i("APP", "GPS POSITION USING GPS_PROVIDER");
Toast.makeText(this,R.string.parking_car_using_gps_it_can_take_more_time,
Toast.LENGTH_LONG).show();
// calling doInBackground
new MyLocationListener().execute("");
```
I got following exception in doInBackground:
*cannot create handler inside thread that has not called looper.prepare*
I would like to ask, how to modify my code to do processing correctly?
Many thanks for any help.
|
2014/06/01
|
[
"https://Stackoverflow.com/questions/23983276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/535556/"
] |
When you use `for (var i in images)`, `i` becomes the *index*, not the element itself. Try:
```
for (var i in images) {
code += '<img src="' + images[i] + '" alt="image not available">';
}
```
|
Use the developer tools that come with the browser to further investigate - sometimes the paths get messed up depending on the url of the file loading the javascript. I would put the full URL to the pictures in the array - that way there isnt confusion.
|
23,983,276
|
i have MainActivty and MyLocationListener classes.
MyLocationListener extends AsyncTask implements LocationListener..
Here is code of the Location Listener Class:
private class MyLocationListener extends AsyncTask implements LocationListener {
```
@Override
public void onLocationChanged(Location location) {
// convert coords from double to string
String lat = Double.toString(location.getLatitude());
String lon = Double.toString(location.getLongitude());
Log.i(AppHelper.APP_LOG_NAMESPACE, "lat " + lat);
Log.i(AppHelper.APP_LOG_NAMESPACE, "lon " + lon);
// save actual position into shared preferences storage
_appPrefs = new AppPreferences(activityContext);
_appPrefs.saveSomeString("lat", lat);
_appPrefs.saveSomeString("lon", lon);
getAddressByCoords(location.getLatitude(),
location.getLongitude());
setPositionToView(activityContext, mView);
}
/**
* Method get string representation of the place in given coords
*
* @param lat
* double
* @param lon
* double
* @return List <Address>
* @throws Exception
*/
public List<Address> getAddressByCoords(double lat, double lon) {
Geocoder gCoder = new Geocoder(activityContext);
try {
addresses = gCoder.getFromLocation(lat, lon, 1);
if (addresses != null && addresses.size() > 0) {
Log.d("APP",
"LOCATION " + addresses.get(0).getAddressLine(0));
Log.d("APP",
"LOCATION " + addresses.get(0).getAddressLine(1));
Log.d("APP",
"LOCATION " + addresses.get(0).getAddressLine(2));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return addresses;
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(MainActivity.this,
provider + "'s status changed to " + status + "!",
Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderEnabled(String provider) {
Toast.makeText(MainActivity.this,
"Provider " + provider + " enabled!", Toast.LENGTH_SHORT)
.show();
}
@Override
public void onProviderDisabled(String provider) {
Toast.makeText(MainActivity.this,
"Provider " + provider + " disabled!", Toast.LENGTH_SHORT)
.show();
}
@Override
protected Object doInBackground(Object... params) {
try {
// Define the criteria how to select the location provider
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE); // default
criteria.setCostAllowed(false);
// get the best provider depending on the criteria
provider = locationManager.getBestProvider(criteria, false);
// the last known location of this provider
Location location = locationManager
.getLastKnownLocation(provider);
// request single update
this.onLocationChanged(location);
} catch (Exception e) {
Log.e(AppHelper.APP_LOG_NAMESPACE,
"doInBackground method cannot be processed", e);
e.printStackTrace();
}
return null;
}
}
```
If i'm trying to get GPS coords using the:
```
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mView = view;
boolean isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// get values from user settings
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this);
Boolean prefferNativeGPs = sharedPrefs.getBoolean(
"prefNativeGps", false);
Log.i("APP", "GPS enabled " + isGPSEnabled); // false
Log.i("APP", "NETWORK enabled " + isNetworkEnabled); // true
Log.i("APP", "USE native " + prefferNativeGPs); // true
// blink textview
TextView stateTv = (TextView) findViewById(R.id.state);
stateTv.setTextColor(getResources().getColor(R.color.black));
startBlinkText();
Log.i("APP", "GPS POSITION USING GPS_PROVIDER");
Toast.makeText(this,R.string.parking_car_using_gps_it_can_take_more_time,
Toast.LENGTH_LONG).show();
// calling doInBackground
new MyLocationListener().execute("");
```
I got following exception in doInBackground:
*cannot create handler inside thread that has not called looper.prepare*
I would like to ask, how to modify my code to do processing correctly?
Many thanks for any help.
|
2014/06/01
|
[
"https://Stackoverflow.com/questions/23983276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/535556/"
] |
Change this:
```
for ( var i in images) {
code += '<img src="' + i + '" alt="image not available">';
}
```
To this:
```
for ( var i = 0; i < images.length; i++) {
code += '<img src="' + images[i] + '" alt="image not available">';
}
```
The `for ( var foo in bar )` construct doesn't do what you think it does. It iterates the *properties* of the object, which in the case of the array are unordered array indices, not array values.
Note: Several answers suggest you keep the `for...in` syntax and index your array properly. This will probably work in the basic case, but it is not recommended for two reasons:
1. Iterting an array in this way is not guaranteed to go in index order. So if you want your images in the same order as they appear in the array, you could get burned.
2. The `for...in` syntax iterates all properties of the array, not just elements in the array. A base array like you have here, with no magic in play from third party libraries, etc..., does not have any additional properties. But it might, and then your code would break.
The **right** way to iterate an array is with a standard `for` loop. See [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) which says:
>
> for..in should not be used to iterate over an Array where index order is important. Array indexes are just enumerable properties with integer names and are otherwise identical to general Object properties. There is no guarantee that for...in will return the indexes in any particular order and it will return all enumerable properties, including those with non–integer names and those that are inherited.
>
>
> Because the order of iteration is implementation dependent, iterating over an array may not visit elements in a consistent order. Therefore it is better to use a for loop with a numeric index (or Array.forEach or the non-standard for...of loop) when iterating over arrays where the order of access is important.
>
>
>
|
Just Change:
```
for ( var i in images) {
code += '<img src="' + i + '" alt="image not available">';
}
```
to
```
for ( var i in images) {
code += '<img src="' + images[i] + '" alt="image not available">';
}
```
|
23,983,276
|
i have MainActivty and MyLocationListener classes.
MyLocationListener extends AsyncTask implements LocationListener..
Here is code of the Location Listener Class:
private class MyLocationListener extends AsyncTask implements LocationListener {
```
@Override
public void onLocationChanged(Location location) {
// convert coords from double to string
String lat = Double.toString(location.getLatitude());
String lon = Double.toString(location.getLongitude());
Log.i(AppHelper.APP_LOG_NAMESPACE, "lat " + lat);
Log.i(AppHelper.APP_LOG_NAMESPACE, "lon " + lon);
// save actual position into shared preferences storage
_appPrefs = new AppPreferences(activityContext);
_appPrefs.saveSomeString("lat", lat);
_appPrefs.saveSomeString("lon", lon);
getAddressByCoords(location.getLatitude(),
location.getLongitude());
setPositionToView(activityContext, mView);
}
/**
* Method get string representation of the place in given coords
*
* @param lat
* double
* @param lon
* double
* @return List <Address>
* @throws Exception
*/
public List<Address> getAddressByCoords(double lat, double lon) {
Geocoder gCoder = new Geocoder(activityContext);
try {
addresses = gCoder.getFromLocation(lat, lon, 1);
if (addresses != null && addresses.size() > 0) {
Log.d("APP",
"LOCATION " + addresses.get(0).getAddressLine(0));
Log.d("APP",
"LOCATION " + addresses.get(0).getAddressLine(1));
Log.d("APP",
"LOCATION " + addresses.get(0).getAddressLine(2));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return addresses;
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(MainActivity.this,
provider + "'s status changed to " + status + "!",
Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderEnabled(String provider) {
Toast.makeText(MainActivity.this,
"Provider " + provider + " enabled!", Toast.LENGTH_SHORT)
.show();
}
@Override
public void onProviderDisabled(String provider) {
Toast.makeText(MainActivity.this,
"Provider " + provider + " disabled!", Toast.LENGTH_SHORT)
.show();
}
@Override
protected Object doInBackground(Object... params) {
try {
// Define the criteria how to select the location provider
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE); // default
criteria.setCostAllowed(false);
// get the best provider depending on the criteria
provider = locationManager.getBestProvider(criteria, false);
// the last known location of this provider
Location location = locationManager
.getLastKnownLocation(provider);
// request single update
this.onLocationChanged(location);
} catch (Exception e) {
Log.e(AppHelper.APP_LOG_NAMESPACE,
"doInBackground method cannot be processed", e);
e.printStackTrace();
}
return null;
}
}
```
If i'm trying to get GPS coords using the:
```
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mView = view;
boolean isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// get values from user settings
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this);
Boolean prefferNativeGPs = sharedPrefs.getBoolean(
"prefNativeGps", false);
Log.i("APP", "GPS enabled " + isGPSEnabled); // false
Log.i("APP", "NETWORK enabled " + isNetworkEnabled); // true
Log.i("APP", "USE native " + prefferNativeGPs); // true
// blink textview
TextView stateTv = (TextView) findViewById(R.id.state);
stateTv.setTextColor(getResources().getColor(R.color.black));
startBlinkText();
Log.i("APP", "GPS POSITION USING GPS_PROVIDER");
Toast.makeText(this,R.string.parking_car_using_gps_it_can_take_more_time,
Toast.LENGTH_LONG).show();
// calling doInBackground
new MyLocationListener().execute("");
```
I got following exception in doInBackground:
*cannot create handler inside thread that has not called looper.prepare*
I would like to ask, how to modify my code to do processing correctly?
Many thanks for any help.
|
2014/06/01
|
[
"https://Stackoverflow.com/questions/23983276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/535556/"
] |
Change this:
```
for ( var i in images) {
code += '<img src="' + i + '" alt="image not available">';
}
```
To this:
```
for ( var i = 0; i < images.length; i++) {
code += '<img src="' + images[i] + '" alt="image not available">';
}
```
The `for ( var foo in bar )` construct doesn't do what you think it does. It iterates the *properties* of the object, which in the case of the array are unordered array indices, not array values.
Note: Several answers suggest you keep the `for...in` syntax and index your array properly. This will probably work in the basic case, but it is not recommended for two reasons:
1. Iterting an array in this way is not guaranteed to go in index order. So if you want your images in the same order as they appear in the array, you could get burned.
2. The `for...in` syntax iterates all properties of the array, not just elements in the array. A base array like you have here, with no magic in play from third party libraries, etc..., does not have any additional properties. But it might, and then your code would break.
The **right** way to iterate an array is with a standard `for` loop. See [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) which says:
>
> for..in should not be used to iterate over an Array where index order is important. Array indexes are just enumerable properties with integer names and are otherwise identical to general Object properties. There is no guarantee that for...in will return the indexes in any particular order and it will return all enumerable properties, including those with non–integer names and those that are inherited.
>
>
> Because the order of iteration is implementation dependent, iterating over an array may not visit elements in a consistent order. Therefore it is better to use a for loop with a numeric index (or Array.forEach or the non-standard for...of loop) when iterating over arrays where the order of access is important.
>
>
>
|
Use the developer tools that come with the browser to further investigate - sometimes the paths get messed up depending on the url of the file loading the javascript. I would put the full URL to the pictures in the array - that way there isnt confusion.
|
23,983,276
|
i have MainActivty and MyLocationListener classes.
MyLocationListener extends AsyncTask implements LocationListener..
Here is code of the Location Listener Class:
private class MyLocationListener extends AsyncTask implements LocationListener {
```
@Override
public void onLocationChanged(Location location) {
// convert coords from double to string
String lat = Double.toString(location.getLatitude());
String lon = Double.toString(location.getLongitude());
Log.i(AppHelper.APP_LOG_NAMESPACE, "lat " + lat);
Log.i(AppHelper.APP_LOG_NAMESPACE, "lon " + lon);
// save actual position into shared preferences storage
_appPrefs = new AppPreferences(activityContext);
_appPrefs.saveSomeString("lat", lat);
_appPrefs.saveSomeString("lon", lon);
getAddressByCoords(location.getLatitude(),
location.getLongitude());
setPositionToView(activityContext, mView);
}
/**
* Method get string representation of the place in given coords
*
* @param lat
* double
* @param lon
* double
* @return List <Address>
* @throws Exception
*/
public List<Address> getAddressByCoords(double lat, double lon) {
Geocoder gCoder = new Geocoder(activityContext);
try {
addresses = gCoder.getFromLocation(lat, lon, 1);
if (addresses != null && addresses.size() > 0) {
Log.d("APP",
"LOCATION " + addresses.get(0).getAddressLine(0));
Log.d("APP",
"LOCATION " + addresses.get(0).getAddressLine(1));
Log.d("APP",
"LOCATION " + addresses.get(0).getAddressLine(2));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return addresses;
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(MainActivity.this,
provider + "'s status changed to " + status + "!",
Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderEnabled(String provider) {
Toast.makeText(MainActivity.this,
"Provider " + provider + " enabled!", Toast.LENGTH_SHORT)
.show();
}
@Override
public void onProviderDisabled(String provider) {
Toast.makeText(MainActivity.this,
"Provider " + provider + " disabled!", Toast.LENGTH_SHORT)
.show();
}
@Override
protected Object doInBackground(Object... params) {
try {
// Define the criteria how to select the location provider
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE); // default
criteria.setCostAllowed(false);
// get the best provider depending on the criteria
provider = locationManager.getBestProvider(criteria, false);
// the last known location of this provider
Location location = locationManager
.getLastKnownLocation(provider);
// request single update
this.onLocationChanged(location);
} catch (Exception e) {
Log.e(AppHelper.APP_LOG_NAMESPACE,
"doInBackground method cannot be processed", e);
e.printStackTrace();
}
return null;
}
}
```
If i'm trying to get GPS coords using the:
```
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mView = view;
boolean isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// get values from user settings
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this);
Boolean prefferNativeGPs = sharedPrefs.getBoolean(
"prefNativeGps", false);
Log.i("APP", "GPS enabled " + isGPSEnabled); // false
Log.i("APP", "NETWORK enabled " + isNetworkEnabled); // true
Log.i("APP", "USE native " + prefferNativeGPs); // true
// blink textview
TextView stateTv = (TextView) findViewById(R.id.state);
stateTv.setTextColor(getResources().getColor(R.color.black));
startBlinkText();
Log.i("APP", "GPS POSITION USING GPS_PROVIDER");
Toast.makeText(this,R.string.parking_car_using_gps_it_can_take_more_time,
Toast.LENGTH_LONG).show();
// calling doInBackground
new MyLocationListener().execute("");
```
I got following exception in doInBackground:
*cannot create handler inside thread that has not called looper.prepare*
I would like to ask, how to modify my code to do processing correctly?
Many thanks for any help.
|
2014/06/01
|
[
"https://Stackoverflow.com/questions/23983276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/535556/"
] |
Just Change:
```
for ( var i in images) {
code += '<img src="' + i + '" alt="image not available">';
}
```
to
```
for ( var i in images) {
code += '<img src="' + images[i] + '" alt="image not available">';
}
```
|
Use the developer tools that come with the browser to further investigate - sometimes the paths get messed up depending on the url of the file loading the javascript. I would put the full URL to the pictures in the array - that way there isnt confusion.
|
58,302,969
|
I have created a matrix of binary digits from reading in a pgm file using the R package pixmap but I am trying to inverse the binary digits (making all 0s become 1s and all 1s become 0s) and outputting the matrix again. Is there an efficient way of doing this?
|
2019/10/09
|
[
"https://Stackoverflow.com/questions/58302969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12168692/"
] |
If you have matrix with 1 and 0's and want to change 1's with 0's and vice versa you can do
```
+(mat == 0)
# [,1] [,2] [,3] [,4]
#[1,] 1 1 1 0
#[2,] 1 0 1 1
#[3,] 1 0 0 0
#[4,] 0 0 0 1
```
**data**
where original `mat` was :
```
set.seed(123)
mat <- matrix(sample(0:1, 16, replace = TRUE), 4)
mat
# [,1] [,2] [,3] [,4]
#[1,] 0 0 0 1
#[2,] 0 1 0 0
#[3,] 0 1 1 1
#[4,] 1 1 1 0
```
|
You could try
```
indOnes <- matrix == 1
indZeros <- matrix == 0
matrix[indOnes] <- 0
matrix[indZeros] <- 1
```
|
58,302,969
|
I have created a matrix of binary digits from reading in a pgm file using the R package pixmap but I am trying to inverse the binary digits (making all 0s become 1s and all 1s become 0s) and outputting the matrix again. Is there an efficient way of doing this?
|
2019/10/09
|
[
"https://Stackoverflow.com/questions/58302969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12168692/"
] |
```
matrix <- +(!matrix)
```
The `!` coerces it into a logical matrix and switches the 0s and 1s to TRUE and FALSE. The `+` coerces it back to 0s and 1s.
|
You could try
```
indOnes <- matrix == 1
indZeros <- matrix == 0
matrix[indOnes] <- 0
matrix[indZeros] <- 1
```
|
58,302,969
|
I have created a matrix of binary digits from reading in a pgm file using the R package pixmap but I am trying to inverse the binary digits (making all 0s become 1s and all 1s become 0s) and outputting the matrix again. Is there an efficient way of doing this?
|
2019/10/09
|
[
"https://Stackoverflow.com/questions/58302969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12168692/"
] |
If you have matrix with 1 and 0's and want to change 1's with 0's and vice versa you can do
```
+(mat == 0)
# [,1] [,2] [,3] [,4]
#[1,] 1 1 1 0
#[2,] 1 0 1 1
#[3,] 1 0 0 0
#[4,] 0 0 0 1
```
**data**
where original `mat` was :
```
set.seed(123)
mat <- matrix(sample(0:1, 16, replace = TRUE), 4)
mat
# [,1] [,2] [,3] [,4]
#[1,] 0 0 0 1
#[2,] 0 1 0 0
#[3,] 0 1 1 1
#[4,] 1 1 1 0
```
|
You can try `abs(1-your_matrix)`
```
mat <- matrix(as.numeric(runif(6) > 0.5), 3, 2)
mat
# [,1] [,2] [,3]
#[1,] 1 0 1
#[2,] 1 0 1
abs(1-mat)
# [,1] [,2] [,3]
#[1,] 0 1 0
#[2,] 0 1 0
```
|
58,302,969
|
I have created a matrix of binary digits from reading in a pgm file using the R package pixmap but I am trying to inverse the binary digits (making all 0s become 1s and all 1s become 0s) and outputting the matrix again. Is there an efficient way of doing this?
|
2019/10/09
|
[
"https://Stackoverflow.com/questions/58302969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12168692/"
] |
```
matrix <- +(!matrix)
```
The `!` coerces it into a logical matrix and switches the 0s and 1s to TRUE and FALSE. The `+` coerces it back to 0s and 1s.
|
If you have matrix with 1 and 0's and want to change 1's with 0's and vice versa you can do
```
+(mat == 0)
# [,1] [,2] [,3] [,4]
#[1,] 1 1 1 0
#[2,] 1 0 1 1
#[3,] 1 0 0 0
#[4,] 0 0 0 1
```
**data**
where original `mat` was :
```
set.seed(123)
mat <- matrix(sample(0:1, 16, replace = TRUE), 4)
mat
# [,1] [,2] [,3] [,4]
#[1,] 0 0 0 1
#[2,] 0 1 0 0
#[3,] 0 1 1 1
#[4,] 1 1 1 0
```
|
58,302,969
|
I have created a matrix of binary digits from reading in a pgm file using the R package pixmap but I am trying to inverse the binary digits (making all 0s become 1s and all 1s become 0s) and outputting the matrix again. Is there an efficient way of doing this?
|
2019/10/09
|
[
"https://Stackoverflow.com/questions/58302969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12168692/"
] |
If you have matrix with 1 and 0's and want to change 1's with 0's and vice versa you can do
```
+(mat == 0)
# [,1] [,2] [,3] [,4]
#[1,] 1 1 1 0
#[2,] 1 0 1 1
#[3,] 1 0 0 0
#[4,] 0 0 0 1
```
**data**
where original `mat` was :
```
set.seed(123)
mat <- matrix(sample(0:1, 16, replace = TRUE), 4)
mat
# [,1] [,2] [,3] [,4]
#[1,] 0 0 0 1
#[2,] 0 1 0 0
#[3,] 0 1 1 1
#[4,] 1 1 1 0
```
|
We can negate the `mat` to return a logical matrix and use `+` to coerce it to binary
```
+!(mat)
# [,1] [,2] [,3] [,4]
#[1,] 1 1 1 0
#[2,] 1 0 1 1
#[3,] 1 0 0 0
#[4,] 0 0 0 1
```
### data
set.seed(123)
mat <- matrix(sample(0:1, 16, replace = TRUE), 4)
|
58,302,969
|
I have created a matrix of binary digits from reading in a pgm file using the R package pixmap but I am trying to inverse the binary digits (making all 0s become 1s and all 1s become 0s) and outputting the matrix again. Is there an efficient way of doing this?
|
2019/10/09
|
[
"https://Stackoverflow.com/questions/58302969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12168692/"
] |
```
matrix <- +(!matrix)
```
The `!` coerces it into a logical matrix and switches the 0s and 1s to TRUE and FALSE. The `+` coerces it back to 0s and 1s.
|
You can try `abs(1-your_matrix)`
```
mat <- matrix(as.numeric(runif(6) > 0.5), 3, 2)
mat
# [,1] [,2] [,3]
#[1,] 1 0 1
#[2,] 1 0 1
abs(1-mat)
# [,1] [,2] [,3]
#[1,] 0 1 0
#[2,] 0 1 0
```
|
58,302,969
|
I have created a matrix of binary digits from reading in a pgm file using the R package pixmap but I am trying to inverse the binary digits (making all 0s become 1s and all 1s become 0s) and outputting the matrix again. Is there an efficient way of doing this?
|
2019/10/09
|
[
"https://Stackoverflow.com/questions/58302969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12168692/"
] |
```
matrix <- +(!matrix)
```
The `!` coerces it into a logical matrix and switches the 0s and 1s to TRUE and FALSE. The `+` coerces it back to 0s and 1s.
|
We can negate the `mat` to return a logical matrix and use `+` to coerce it to binary
```
+!(mat)
# [,1] [,2] [,3] [,4]
#[1,] 1 1 1 0
#[2,] 1 0 1 1
#[3,] 1 0 0 0
#[4,] 0 0 0 1
```
### data
set.seed(123)
mat <- matrix(sample(0:1, 16, replace = TRUE), 4)
|
43,628
|
Sorry for my bad english.
I have WP 3.3.1 & wp-e-commerce.3.8.7.6.2. On the products page (which use wpsc-products\_page.php template) I have list of products. I want to group this products by category. For example:
*\**\*Cat1
Product 1
Product 2
\**\** Cat2
Product 1
Product 2
\**\** Cat3
Product 1
Product 2
I try to use this method, but it`s does not work
```
add_filter('posts_join', create_function('$a', 'global $wpdb; return $a . " INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id) ";'));
add_filter('posts_where', create_function('$a', 'global $wpdb; return $a . " AND $wpdb->term_taxonomy.taxonomy = \'wpsc_product_category\'";'));
add_filter('posts_orderby', create_function('$a','global $wpdb; return "$wpdb->term_taxonomy.term_id DESC";'));
query_posts('');
```
Thank you all in advance for your reply!
|
2012/02/27
|
[
"https://wordpress.stackexchange.com/questions/43628",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/13568/"
] |
You are very close. I had the same problem a while ago, and [blogged about it](http://snippets.webaware.com.au/snippets/sort-wp-e-commerce-products-by-category-and-product-title/). Your join is missing one more join table, wp\_terms, which has the term you want to sort on.
Here is the code I used:
```
class OrderWpscProducts {
// flag for when a shop products post query is being created
private $isProductQuery = false;
public function __construct() {
// hooks for altering order of product pages
add_filter('parse_query', array($this, 'filterProductQueryMark'), 20);
add_filter('posts_join', array($this, 'filterProductQueryJoins'), 20);
add_filter('posts_orderby', array($this, 'filterProductQueryOrderBy'), 20);
}
/**
* detect a posts query that should return a list of shop products,
* and mark it for later filters
* @param WP_Query $query
* @return WP_Query
*/
public function filterProductQueryMark($query) {
$this->isProductQuery = false;
if (!is_admin() && (wpsc_is_in_category() || !empty($query->query_vars['wpsc_wine_style']))) {
$this->isProductQuery = true;
}
}
/**
* if the posts query is for a list of shop products,
* then add some tables to the join so that we can sort by category name
* @param string $joins
* @return string
*/
public function filterProductQueryJoins($joins) {
global $wpdb;
if ($this->isProductQuery) {
$joins .= "
INNER JOIN $wpdb->term_relationships wpsc_cat_rel ON wp_posts.ID = wpsc_cat_rel.object_id
INNER JOIN $wpdb->term_taxonomy wpsc_cat_tax ON wpsc_cat_tax.term_taxonomy_id = wpsc_cat_rel.term_taxonomy_id
and wpsc_cat_tax.taxonomy = 'wpsc_product_category'
INNER JOIN $wpdb->terms wpsc_cat ON wpsc_cat.term_id = wpsc_cat_tax.term_id
";
}
return $joins;
}
/**
* if the posts query is for a list of shop products, then sort by category name and product title
* @param string $orderby
* @return string
*/
public function filterProductQueryOrderBy($orderby) {
if ($this->isProductQuery) {
$orderby = 'wpsc_cat.name ASC, wp_posts.post_title ASC';
}
return $orderby;
}
}
// create instance, will be kept alive by hooks
new OrderWpscProducts();
```
|
Here you can find a solution : <http://subharanjan.in/category-wise-products-display-in-wp-e-commerce/>
I am not sure if this will solve your problem.
Thanks!
|
9,873,954
|
I am trying to debug a large (1.1Gb) SQL dump file. The file says there was an error on line 14718. I have tried opening the file in VIM and gedit but the file was too big to load. Is there a quick way to get a small piece of the file so that I can correct the error and save the file?
|
2012/03/26
|
[
"https://Stackoverflow.com/questions/9873954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/726543/"
] |
Nick, not sure if this will, help, but I always end up using `less`.
Give this a try and let me know if it helps:
```
less +j14718 -N aFile.txt
```
|
I'm using Geany to parse very large files. (like your sql dump)
It runs under Linux, FreeBSD, NetBSD, OpenBSD, MacOS X, AIX, Solaris Express and Windows.
And it's GPL: <http://www.geany.org/>
(you may find it in most linux distribuitions as an IDE)
|
358,885
|
I was working on my home server remotely and wanted to make some changes to my .htaccess. I could not see this file using my FTP(filezilla) and thought there was none there. I decided to upload one I had in my computer to my server in public\_html and edit it.Although the upload was successful per FZ, this file is not listed anywhere, even when I physically access the server.
It looks like it is being hidden. The main problem is that after this, now I get the following error message and cannot access my test site:
```
You don't have permission to access / on this server.
```
If I access my server and DISABLE SELINUX or make it PERMISSIVE, my pages start working as normal. If I make it ENFORCING my webpage becomes unavailable and I see the error listed above.
Questions:
1. First of all, how can I make this .htaccess visible in a CentOS 5.6 system?
2. Will I run into Security Risks if I leave my server setup as PERMISSIVE?
Thank you all,
|
2012/02/10
|
[
"https://serverfault.com/questions/358885",
"https://serverfault.com",
"https://serverfault.com/users/110237/"
] |
actually my own previous post wouldn't have worked. this works (and doesn't require 3rd party products):
```
$user = get-aduser jdoe
Set-ADObject $user -Replace @{telephoneNumber=12345}
```
|
A room mailbox has an associated user that sets these properties. Using the Quest AD cmdlets, available [here](http://www.quest.com/powershell/activeroles-server.aspx), you could run the following -
```
Set-QADUser -Identity $RoomMailboxUser -Office "Location here" -PhoneNumber "Phone number here"
```
|
36,204,222
|
I am making a website in 2 languages. Is it possible to check it in which country the user is, so that I can switch the language automatically for the user? I also have a switch option in my menu with a \_GET. I have this piece of code in the beginning:
```
if (isset($_GET['taal'])) {
$taal = $_GET['taal'];
} else {
$taal = 'ENG';
}
switch ($taal) {
case 'NL':
include('NL.php');
break;
case 'ENG':
include('ENG.php');
break;
default:
include('ENG.php');
break;
}
```
|
2016/03/24
|
[
"https://Stackoverflow.com/questions/36204222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5585845/"
] |
Found the solution. Following posts helped me in that:
[Sailsjs view caching (bug ?)](https://stackoverflow.com/questions/28294429/sailsjs-view-caching-bug?rq=1)
<https://github.com/balderdashy/sails/issues/3513>
<http://expressjs.com/en/api.html>
The reason is, express was cashing views in production mode, so on disabling that it worked.
```
sails.hooks.http.app.disable('view cache');
console.log("view-cache-disabled: " + sails.hooks.http.app.disabled("view cache"));
```
|
You have to use a watcher like forever, nodemon, or something else...
Install forever by running:
```
sudo npm install -g forever
```
Run it:
```
forever -w start app.js
```
|
48,632,583
|
**Laravel 5.5**
I have a search view where users can type in the `text input` fields to search a table. The request goes to GET variables onto the results blade.
Inside the results blade, there is a Laravel ajax table. <https://datatables.yajrabox.com/>
I can't figure out how to get pass the GET variables in the URL to the search Laravel ajax request.
Ultimately, I want to be able to pass `$_GET` lead\_name, lead\_phone, etc to this ajax request. How can I accomplish that?
Here is my datatables script at the bottom of the page:
```
<script>
$(function() {
$('.datatable').DataTable({
processing: true,
serverSide: true,
ajax: {
url: '{{ route('SearchResults') }}',
method: 'GET'
},
columns: [
{ data: 'lead_name', name: 'leads.lead_name' },
{ data: 'lead_merchant_id', name: 'leads.lead_merchant_id'},
{ data: 'lead_address_city', name: 'leads.lead_address_city' },
{ data: 'lead_address_state', name: 'leads.lead_address_state' },
{ data: 'accountstatus_description', name: 'accountstatus.accountstatus_description' },
{ data: 'firstlast_name', name: 'name' }
],
rowReorder: {
selector: 'td:nth-child(0)'
},
responsive: true
});
});
```
If I run a dd on my searchresults route:
```
public function SearchResults(request $request) {
dd($request);
}
```
it doesn't return any of the previous GET data.
|
2018/02/05
|
[
"https://Stackoverflow.com/questions/48632583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5254224/"
] |
No need to send by GET method , You can easily use the POST method in the following way :
You should have a form on your page with the POST method and unique ID
```
<form method="POST" id="search-form" role="form">
{{csrf_field()}}
<input type="text" name="lead_phone">
</form>
```
On your page, write this jquery code that runs this code when you submit the form
```
$(document).ready(function(){
$('#search-form').on('submit', function(e) {
table.draw();
e.preventDefault();
});
});
```
Then use the following code for your DataTable section
```
$(function() {
var table = $('.datatable').DataTable({
processing: true,
serverSide: true,
ajax: {
url: '{{ route('SearchResults') }}',
type: "post",
data: function (d) {
d.lead_phone = $('input[name=visited]').val();
d._token = _token;
},
},
columns: [
{ data: 'lead_name', name: 'leads.lead_name' },
{ data: 'lead_merchant_id', name: 'leads.lead_merchant_id'},
{ data: 'lead_address_city', name: 'leads.lead_address_city' },
{ data: 'lead_address_state', name: 'leads.lead_address_state' },
{ data: 'accountstatus_description', name: 'accountstatus.accountstatus_description' },
{ data: 'firstlast_name', name: 'name' }
],
rowReorder: {
selector: 'td:nth-child(0)'
},
responsive: true
});
});
```
If the data is sent by Query String, there's no need for a jquery code and form, just write down the following code in your DataTable section
```
$(function() {
var table = $('.datatable').DataTable({
processing: true,
serverSide: true,
ajax: {
url: '{{ route('SearchResults') }}',
type: "post",
data: function (d) {
d.lead_phone = '{{$_GET['lead_phone']}}';
d._token = '{{csrf_token()}}';
},
},
columns: [
{ data: 'lead_name', name: 'leads.lead_name' },
{ data: 'lead_merchant_id', name: 'leads.lead_merchant_id'},
{ data: 'lead_address_city', name: 'leads.lead_address_city' },
{ data: 'lead_address_state', name: 'leads.lead_address_state' },
{ data: 'accountstatus_description', name: 'accountstatus.accountstatus_description' },
{ data: 'firstlast_name', name: 'name' }
],
rowReorder: {
selector: 'td:nth-child(0)'
},
responsive: true
});
});
```
And then get the data you send to controller
```
public function DataTable(Request $request)
{
$lead_phone = $request->get('lead_phone');
.
.
.
}
```
|
Please specify the `method` of sending data.
```
<script>
$(function() {
$('.datatable').DataTable({
processing: true,
serverSide: true,
method: post,
ajax: '{{ route('SearchResults') }}',
columns: [
{ data: 'lead_name', name: 'leads.lead_name' },
{ data: 'lead_merchant_id', name: 'leads.lead_merchant_id'},
{ data: 'lead_address_city', name: 'leads.lead_address_city' },
{ data: 'lead_address_state', name: 'leads.lead_address_state' },
{ data: 'accountstatus_description', name: 'accountstatus.accountstatus_description' },
{ data: 'firstlast_name', name: 'name' }
],
rowReorder: {
selector: 'td:nth-child(0)'
},
responsive: true
});
});
```
|
472,119
|
Hope someone can help me with this. It's like this, my husband trying to be an IT, basically he's not and honestly I'm not too, installed MBAM anti malware to his Windows PC. It's the anti malware his company is using. Because of whatever reason he has, he installed it. After installing and running a PC scan, he can't open his PC because it's asking a license key. Thanks God his PC is in dual boot. He installed Ubuntu a month ago. All his CAD files are in windows and he needs a revision of his project he is working on. Can he uninstall MBAM installed in windows using ubuntu? or any other way he can use XP again? Need help on this.
Thank u..
|
2014/05/25
|
[
"https://askubuntu.com/questions/472119",
"https://askubuntu.com",
"https://askubuntu.com/users/285272/"
] |
Install Tweak Tool:
<https://apps.ubuntu.com/cat/applications/gnome-tweak-tool/>
then open it and go to Appearance and set the icons to Ubuntu-mono-dark (Ambiance) or Ubuntu-mono-light (Radiance).

|
If you didn't uninstall unity, just log out, choose unity session from the login screen and it should be there. If you did uninstall unity, just do `sudo apt-get install unity*` then it should install it for you. To be honest you if you like the unity icons, you can just go to the theme settings and change it to the unity ones. I think they're either called ambiance or radiance.
|
42,179,392
|
I have made the following code in order to create something like a piano. When you click on a button (`#start_img`) each `.piano` div should get the `press` class and after a short break it should be removed from it again.
Then the function should loop to the next `.piano` div and repeat the same actions there. Doesn't sound too difficult, only problem is that it isn't working. Can anyone explain to me what's wrong with the code?
```js
$('#start_img').on('click', function() {
$('.piano').each(function(index) {
$(this).addClass('press').delay(900).removeClass('press');
});
});
```
```css
.press {
background-color: silver;
}
.piano {
border: 1px solid black;
display: inline-block;
width: 20px;
height: 60px;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='start_img'>Start</button>
<div id='page'>
<div class='piano'></div>
<div class='piano'></div>
<div class='piano'></div>
<div class='piano'></div>
<div class='piano'></div>
<div class='piano'></div>
<div class='piano'></div>
<div class='piano'></div>
<div class='piano'></div>
</div>
```
|
2017/02/11
|
[
"https://Stackoverflow.com/questions/42179392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7548524/"
] |
Two reasons.
1. delay() will only work for methods that use the animation queue internally
2. The loop will run instantaneously and therefore add same delay to each instance making them all activate simultaneously
You could do something like
```
piano.each(function(index){
var $el = $(this);
setTimeout(function(){
$el.addClass('press');
setTimeout(function(){
$el.removeClass('press');
}, 880);
}, (index+1) * 900);// multiply delay by index to increment each one
});
```
|
You can use setTimeout with a delay at the particular index.
```
start.on('click', function() {
var piano = $('.piano');
piano.each(function(index) {
var _this = $(this);
_this.addClass('press');
setTimeout(function() {
_this.removeClass('press');
}, 900 * index);
});
});
```
|
37,318
|
I have a database called `example.mdf` with a total size of 1GB which suffers from performance issues. I checked the allocated hardware and it is higher than required, I double checked the design and every thing looks normal, when I look at the `.mdf` files in their physical location (`C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\example.mdf`) I found that the database is split into multiple files `example_1.mdf`, `example_2.mdf`, `example_3.mdf`, up to `example_7.mdf`.
I have another database file on the same SQL Server that has the same issue.
Why does this happen? Does this affect the performance? How can I prevent or stop SQL Server from splitting my `.mdf` files? Moreover I need to combine back the already split files.
|
2013/03/22
|
[
"https://dba.stackexchange.com/questions/37318",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/-1/"
] |
Who ever created the database did this on purpose. Assuming that all the database files are part of the same file group (the database properties will tell you this) then all you need to do is do a DBCC SHRINKFILE any use the EMPTYFILE parameter.
```
DBCC SHRINKFILE (Example_1, EMPTYFILE)
GO
ALTER DATABASE MyDatabase REMOVE FILE Example_1
GO
```
Do that for each of the files and all the data will be put back into a single file. You can then delete the extra files.
Now odds are this isn't hurting your performance any, so you'll need to continue investigating why you are having performance problems.
|
The .mdf extensions doesn't really matter and the same case with .ndf/.ldf extensions as well.
Primary file/secondary file/log file can have any extension (something like .xyz)
And NO it is not SQL Server that created multiple data files.
For further clarity please refer here:
[Can a Database have more than one mdf File?](http://sqlserverzest.com/2011/11/23/can-a-database-have-more-than-one-primary-data-mdf-file/)
If you want to delete the extra data files/log files, please refer this post: [How to Best Remove Extra TempDB Data Files and Log Files](http://sqlserverzest.com/2013/05/06/how-to-remove-extra-tempdb-data-files-and-log-files/)
|
37,318
|
I have a database called `example.mdf` with a total size of 1GB which suffers from performance issues. I checked the allocated hardware and it is higher than required, I double checked the design and every thing looks normal, when I look at the `.mdf` files in their physical location (`C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\example.mdf`) I found that the database is split into multiple files `example_1.mdf`, `example_2.mdf`, `example_3.mdf`, up to `example_7.mdf`.
I have another database file on the same SQL Server that has the same issue.
Why does this happen? Does this affect the performance? How can I prevent or stop SQL Server from splitting my `.mdf` files? Moreover I need to combine back the already split files.
|
2013/03/22
|
[
"https://dba.stackexchange.com/questions/37318",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/-1/"
] |
Who ever created the database did this on purpose. Assuming that all the database files are part of the same file group (the database properties will tell you this) then all you need to do is do a DBCC SHRINKFILE any use the EMPTYFILE parameter.
```
DBCC SHRINKFILE (Example_1, EMPTYFILE)
GO
ALTER DATABASE MyDatabase REMOVE FILE Example_1
GO
```
Do that for each of the files and all the data will be put back into a single file. You can then delete the extra files.
Now odds are this isn't hurting your performance any, so you'll need to continue investigating why you are having performance problems.
|
There are couple of things to check
1. Why is the database on System drive (C:\ ) ? Dont you have any other
storage / SAN attached to the server ?
2. Where is the log location ?
3. How is the database being used - no of concurrent users, load on the server, RAM on the server, no of cpu's on the server ?
4. Why is a 1 GB database split up into 7 files ? Do you really need the database having multiple files ? Also, note that you can have 1 primary filegroup(.mdf) and then rest are secondary filegroups (.\**n*\*df).
5. When you say "performance issues" what is actually happening - what
is slow or not working ? Did you ran a short trace during the period
when performance is degraded ?
|
37,318
|
I have a database called `example.mdf` with a total size of 1GB which suffers from performance issues. I checked the allocated hardware and it is higher than required, I double checked the design and every thing looks normal, when I look at the `.mdf` files in their physical location (`C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\example.mdf`) I found that the database is split into multiple files `example_1.mdf`, `example_2.mdf`, `example_3.mdf`, up to `example_7.mdf`.
I have another database file on the same SQL Server that has the same issue.
Why does this happen? Does this affect the performance? How can I prevent or stop SQL Server from splitting my `.mdf` files? Moreover I need to combine back the already split files.
|
2013/03/22
|
[
"https://dba.stackexchange.com/questions/37318",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/-1/"
] |
These mdf files can also be of other databases...
to check your database files use script:
```
USE [DatabaseName]
GO
SELECT name, physical_name
FROM sys.database_files
GO
```
|
The .mdf extensions doesn't really matter and the same case with .ndf/.ldf extensions as well.
Primary file/secondary file/log file can have any extension (something like .xyz)
And NO it is not SQL Server that created multiple data files.
For further clarity please refer here:
[Can a Database have more than one mdf File?](http://sqlserverzest.com/2011/11/23/can-a-database-have-more-than-one-primary-data-mdf-file/)
If you want to delete the extra data files/log files, please refer this post: [How to Best Remove Extra TempDB Data Files and Log Files](http://sqlserverzest.com/2013/05/06/how-to-remove-extra-tempdb-data-files-and-log-files/)
|
37,318
|
I have a database called `example.mdf` with a total size of 1GB which suffers from performance issues. I checked the allocated hardware and it is higher than required, I double checked the design and every thing looks normal, when I look at the `.mdf` files in their physical location (`C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\example.mdf`) I found that the database is split into multiple files `example_1.mdf`, `example_2.mdf`, `example_3.mdf`, up to `example_7.mdf`.
I have another database file on the same SQL Server that has the same issue.
Why does this happen? Does this affect the performance? How can I prevent or stop SQL Server from splitting my `.mdf` files? Moreover I need to combine back the already split files.
|
2013/03/22
|
[
"https://dba.stackexchange.com/questions/37318",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/-1/"
] |
These mdf files can also be of other databases...
to check your database files use script:
```
USE [DatabaseName]
GO
SELECT name, physical_name
FROM sys.database_files
GO
```
|
There are couple of things to check
1. Why is the database on System drive (C:\ ) ? Dont you have any other
storage / SAN attached to the server ?
2. Where is the log location ?
3. How is the database being used - no of concurrent users, load on the server, RAM on the server, no of cpu's on the server ?
4. Why is a 1 GB database split up into 7 files ? Do you really need the database having multiple files ? Also, note that you can have 1 primary filegroup(.mdf) and then rest are secondary filegroups (.\**n*\*df).
5. When you say "performance issues" what is actually happening - what
is slow or not working ? Did you ran a short trace during the period
when performance is degraded ?
|
37,318
|
I have a database called `example.mdf` with a total size of 1GB which suffers from performance issues. I checked the allocated hardware and it is higher than required, I double checked the design and every thing looks normal, when I look at the `.mdf` files in their physical location (`C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\example.mdf`) I found that the database is split into multiple files `example_1.mdf`, `example_2.mdf`, `example_3.mdf`, up to `example_7.mdf`.
I have another database file on the same SQL Server that has the same issue.
Why does this happen? Does this affect the performance? How can I prevent or stop SQL Server from splitting my `.mdf` files? Moreover I need to combine back the already split files.
|
2013/03/22
|
[
"https://dba.stackexchange.com/questions/37318",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/-1/"
] |
Who ever created the database did this on purpose. Assuming that all the database files are part of the same file group (the database properties will tell you this) then all you need to do is do a DBCC SHRINKFILE any use the EMPTYFILE parameter.
```
DBCC SHRINKFILE (Example_1, EMPTYFILE)
GO
ALTER DATABASE MyDatabase REMOVE FILE Example_1
GO
```
Do that for each of the files and all the data will be put back into a single file. You can then delete the extra files.
Now odds are this isn't hurting your performance any, so you'll need to continue investigating why you are having performance problems.
|
Not sure if you can merge files in existing database but you can create new database and then use some of the third party database comparison tools to migrate data and structure to new database. Just be careful when migrating schema not to migrate the part that tells SQL Server to split files ;)
|
37,318
|
I have a database called `example.mdf` with a total size of 1GB which suffers from performance issues. I checked the allocated hardware and it is higher than required, I double checked the design and every thing looks normal, when I look at the `.mdf` files in their physical location (`C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\example.mdf`) I found that the database is split into multiple files `example_1.mdf`, `example_2.mdf`, `example_3.mdf`, up to `example_7.mdf`.
I have another database file on the same SQL Server that has the same issue.
Why does this happen? Does this affect the performance? How can I prevent or stop SQL Server from splitting my `.mdf` files? Moreover I need to combine back the already split files.
|
2013/03/22
|
[
"https://dba.stackexchange.com/questions/37318",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/-1/"
] |
These mdf files can also be of other databases...
to check your database files use script:
```
USE [DatabaseName]
GO
SELECT name, physical_name
FROM sys.database_files
GO
```
|
Not sure if you can merge files in existing database but you can create new database and then use some of the third party database comparison tools to migrate data and structure to new database. Just be careful when migrating schema not to migrate the part that tells SQL Server to split files ;)
|
37,318
|
I have a database called `example.mdf` with a total size of 1GB which suffers from performance issues. I checked the allocated hardware and it is higher than required, I double checked the design and every thing looks normal, when I look at the `.mdf` files in their physical location (`C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\example.mdf`) I found that the database is split into multiple files `example_1.mdf`, `example_2.mdf`, `example_3.mdf`, up to `example_7.mdf`.
I have another database file on the same SQL Server that has the same issue.
Why does this happen? Does this affect the performance? How can I prevent or stop SQL Server from splitting my `.mdf` files? Moreover I need to combine back the already split files.
|
2013/03/22
|
[
"https://dba.stackexchange.com/questions/37318",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/-1/"
] |
You want to recombine the files because you think that is the cause of your performance issue. Do you have any proof that it actually is?
It is a lot more likely that the problem is somewhere else, as distributing a database across multiple files actually increases performance in many cases.
Things to look at first:
1. do you have appropriate indexes
2. are you using cursors in your queries
3. are your queries written in a way that would prevent index usage
4. is your server actually big enough to handle the load. However, this is a very small database, so it is likely that your hardware is not the problem.
If you looked at all that and you still think that the splitt file is your problem, you can follow these steps:
1. Add a new file big enough to hold the entirety of the data.
2. set all original files to not autogrow.
3. shrink each original file 1 at a time with "release unused space"
4. shrink each original file 1 at a time with "empty file and migrate data" and then drop the file before shrinking the next.
5. Run an index rebuild on every index in the database to reduce fragmentation caused by the migration.
However, make sure you do not need the files. Someone might have created file groups to allow for partitioning. In that case you cannot combine the files without first moving all table and partitions from the other filegroups to the primary filegroup.
|
There are couple of things to check
1. Why is the database on System drive (C:\ ) ? Dont you have any other
storage / SAN attached to the server ?
2. Where is the log location ?
3. How is the database being used - no of concurrent users, load on the server, RAM on the server, no of cpu's on the server ?
4. Why is a 1 GB database split up into 7 files ? Do you really need the database having multiple files ? Also, note that you can have 1 primary filegroup(.mdf) and then rest are secondary filegroups (.\**n*\*df).
5. When you say "performance issues" what is actually happening - what
is slow or not working ? Did you ran a short trace during the period
when performance is degraded ?
|
37,318
|
I have a database called `example.mdf` with a total size of 1GB which suffers from performance issues. I checked the allocated hardware and it is higher than required, I double checked the design and every thing looks normal, when I look at the `.mdf` files in their physical location (`C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\example.mdf`) I found that the database is split into multiple files `example_1.mdf`, `example_2.mdf`, `example_3.mdf`, up to `example_7.mdf`.
I have another database file on the same SQL Server that has the same issue.
Why does this happen? Does this affect the performance? How can I prevent or stop SQL Server from splitting my `.mdf` files? Moreover I need to combine back the already split files.
|
2013/03/22
|
[
"https://dba.stackexchange.com/questions/37318",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/-1/"
] |
The .mdf extensions doesn't really matter and the same case with .ndf/.ldf extensions as well.
Primary file/secondary file/log file can have any extension (something like .xyz)
And NO it is not SQL Server that created multiple data files.
For further clarity please refer here:
[Can a Database have more than one mdf File?](http://sqlserverzest.com/2011/11/23/can-a-database-have-more-than-one-primary-data-mdf-file/)
If you want to delete the extra data files/log files, please refer this post: [How to Best Remove Extra TempDB Data Files and Log Files](http://sqlserverzest.com/2013/05/06/how-to-remove-extra-tempdb-data-files-and-log-files/)
|
Not sure if you can merge files in existing database but you can create new database and then use some of the third party database comparison tools to migrate data and structure to new database. Just be careful when migrating schema not to migrate the part that tells SQL Server to split files ;)
|
37,318
|
I have a database called `example.mdf` with a total size of 1GB which suffers from performance issues. I checked the allocated hardware and it is higher than required, I double checked the design and every thing looks normal, when I look at the `.mdf` files in their physical location (`C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\example.mdf`) I found that the database is split into multiple files `example_1.mdf`, `example_2.mdf`, `example_3.mdf`, up to `example_7.mdf`.
I have another database file on the same SQL Server that has the same issue.
Why does this happen? Does this affect the performance? How can I prevent or stop SQL Server from splitting my `.mdf` files? Moreover I need to combine back the already split files.
|
2013/03/22
|
[
"https://dba.stackexchange.com/questions/37318",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/-1/"
] |
Who ever created the database did this on purpose. Assuming that all the database files are part of the same file group (the database properties will tell you this) then all you need to do is do a DBCC SHRINKFILE any use the EMPTYFILE parameter.
```
DBCC SHRINKFILE (Example_1, EMPTYFILE)
GO
ALTER DATABASE MyDatabase REMOVE FILE Example_1
GO
```
Do that for each of the files and all the data will be put back into a single file. You can then delete the extra files.
Now odds are this isn't hurting your performance any, so you'll need to continue investigating why you are having performance problems.
|
You want to recombine the files because you think that is the cause of your performance issue. Do you have any proof that it actually is?
It is a lot more likely that the problem is somewhere else, as distributing a database across multiple files actually increases performance in many cases.
Things to look at first:
1. do you have appropriate indexes
2. are you using cursors in your queries
3. are your queries written in a way that would prevent index usage
4. is your server actually big enough to handle the load. However, this is a very small database, so it is likely that your hardware is not the problem.
If you looked at all that and you still think that the splitt file is your problem, you can follow these steps:
1. Add a new file big enough to hold the entirety of the data.
2. set all original files to not autogrow.
3. shrink each original file 1 at a time with "release unused space"
4. shrink each original file 1 at a time with "empty file and migrate data" and then drop the file before shrinking the next.
5. Run an index rebuild on every index in the database to reduce fragmentation caused by the migration.
However, make sure you do not need the files. Someone might have created file groups to allow for partitioning. In that case you cannot combine the files without first moving all table and partitions from the other filegroups to the primary filegroup.
|
37,318
|
I have a database called `example.mdf` with a total size of 1GB which suffers from performance issues. I checked the allocated hardware and it is higher than required, I double checked the design and every thing looks normal, when I look at the `.mdf` files in their physical location (`C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\example.mdf`) I found that the database is split into multiple files `example_1.mdf`, `example_2.mdf`, `example_3.mdf`, up to `example_7.mdf`.
I have another database file on the same SQL Server that has the same issue.
Why does this happen? Does this affect the performance? How can I prevent or stop SQL Server from splitting my `.mdf` files? Moreover I need to combine back the already split files.
|
2013/03/22
|
[
"https://dba.stackexchange.com/questions/37318",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/-1/"
] |
There are couple of things to check
1. Why is the database on System drive (C:\ ) ? Dont you have any other
storage / SAN attached to the server ?
2. Where is the log location ?
3. How is the database being used - no of concurrent users, load on the server, RAM on the server, no of cpu's on the server ?
4. Why is a 1 GB database split up into 7 files ? Do you really need the database having multiple files ? Also, note that you can have 1 primary filegroup(.mdf) and then rest are secondary filegroups (.\**n*\*df).
5. When you say "performance issues" what is actually happening - what
is slow or not working ? Did you ran a short trace during the period
when performance is degraded ?
|
Not sure if you can merge files in existing database but you can create new database and then use some of the third party database comparison tools to migrate data and structure to new database. Just be careful when migrating schema not to migrate the part that tells SQL Server to split files ;)
|
34,472
|
I work as a sound designer. Sometimes I do dialogue recording for short films. But honestly, I never use a field mixer or portable mic preamp. I only ever use a handheld (Zoom H4n or Tascam DR) and a shotgun mic (Rode NTG 1).
I've recently done a lot of research on the internet about field mixers, and I'm starting to understand basically how they work.
But I'm finding it difficult to learn about gain control when using 2 or 3 shotgun mics.
That's why we use a mixer isn't it...? to mix 2 or more dialogue tracks down to 1 track?
So I'm thinking there must be some technique to control the gain
* Which mic should be louder?
* Which mic should be softer?
* What are the standards used to decide it?
Can anyone help with information... links, references?
|
2015/02/11
|
[
"https://sound.stackexchange.com/questions/34472",
"https://sound.stackexchange.com",
"https://sound.stackexchange.com/users/12962/"
] |
A mixer will have multiple channels for your multiple inputs.
Each channel will have a trim pot (gain knob) for adjusting the input level.
(Sidenote: some channels may not have a trim, those are line-level inputs, not mic-level inputs, and they are meant for things that already at "line-level")
You set your gain as you need to for each channel, nothing more or less. The only real standard is "don't clip the channel." (Unless it sounds good... but really, for what you're doing, don't clip anything)
You generally don't want to be making crucial mix decisions in the field. Ideally, you will be using direct-outs from the mixer, but you can also utilize the various bussing options (auxes, sub-groups, matrices, left and right channels, etc.) to isolate your signals as much as possible.
Those outputs are then generally sent to a multi-track recorder which captures the individual sources for use later. The actual mix is postponed, just as the video edit isn't done on the fly.
That said, you absolutely can (and may have to), make some final choices while shooting. This may be because you have a limited number of recording inputs, or because your mixer doesn't have enough outputs. Whatever the reason, it means you'll have to do some mixing in the field.
In those situations, you just do the best you can. Use your ears and mix the signals in the best way you know how. Consider not only what you are hearing, but the tools that can be used later as well, along with what you think the finished product should sound like. Hopefully you're only having to mix a couple tracks together, so you'll only need to worry about the balance of say, two things, as opposed to thirty things. Just consider that small piece in the broader perspective of the full puzzle.
|
The use of a field mixer is not restricted to mixing several sources into one track. It is often used to send individual sources to individual tracks.
When you need to mix several sources into one track in a live dialogue recording situation, you have to dynamically deal with each of the sources as the shot goes by. Having sevral microphones continuously open usually leads to poor results.
Example 1 : one shotgun on a boom and several lavalier microphones. You will have to deal with opening and closing smoothly each of the lavalier when the character it is used for is speaking/not speaking, and deal with the ratio of boom you want to add on top. A common use case is using a stereo mixer, where you would send the boom on one side and a mix of lavalier on the other side.
Example 2 : one main microphone on a boom and others microphones hidden on set for particular parts of the scene. You will also have to deal with opening the hiden microphones only when they are useful, unless you want a lot of undesirable artifacts on your sound take.
There are today several manufacturer of multitracks field recorder that allow to record each individual source on it's own track and deal with the mix at the post-production stage. This technique can prevent unfortunate choices on stage and offer a wider choice when dub mixing. But it can also make the post-production workflow more complex.
To sum it up : there's no theoretical technique to set up the gain (apart from not overloading your channel and recorder) but a lot of practice and know-how to be able to deal with live mixing of several sources.
|
7,696,988
|
I am trying to show a border on the left side, but it doesn't show after the first div(breadCrumb). The HTML code is following :-
```
<div class="contentHolder">
<div class="breadCrumb">
<a href="http://www.pricetag.com">Store </a>>> Electronics
</div>
<div class="contentMainDiv">
<div class="leftDiv"><p>orem ipsume Lorem ipsume Lorem ipsume Lorem ipsume</p>
</div>
<div class="rightDiv">
</div>
</div>
</div>
```
The CSS code is following :
>
> .contentHolder { padding: 10px 0 0 10px; border-left: 1px solid #CCC; }
>
>
> .contentHolder div.breadCrumb { font-size:12px; }
>
>
> .contentHolder div.breadCrumb a {color:#408080; text-decoration:none; }
>
>
> .contentHolder div.breadCrumb a:hover {text-decoration:underline; }
>
>
> .contentHolder div.leftDiv{ float:left; width: 150px; }
>
>
> .contentHolder div.rightDiv { float:left;}
>
>
>
**Below is Image for the Error Page** : -
---

|
2011/10/08
|
[
"https://Stackoverflow.com/questions/7696988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/570928/"
] |
You need to [clear/contain the floated elements](http://www.quirksmode.org/css/clearing.html) in `.contentMainDiv`.
One way to do that is to add `overflow: hidden`.
|
```
.contentHolder div.leftDiv{ float:left; width: 150px; }
```
remove float: left or use clearfix <http://perishablepress.com/press/2009/12/06/new-clearfix-hack/> for contentHolder class
preview <http://jsfiddle.net/TrePF/>
```css
.clearfix:after {
visibility: hidden;
display: block;
font-size: 0;
content: " ";
clear: both;
height: 0;
}
.clearfix { display: inline-table; }
/* Hides from IE-mac \*/
* html .clearfix { height: 1%; }
.clearfix { display: block; }
/* End hide from IE-mac */
.contentHolder { padding: 10px 0 0 10px; border-left: 1px solid #CCC; }
.contentHolder div.breadCrumb { font-size:12px; }
.contentHolder div.breadCrumb a {color:#408080; text-decoration:none; }
.contentHolder div.breadCrumb a:hover {text-decoration:underline; }
.contentHolder div.leftDiv{ float:left; width: 150px; }
.contentHolder div.rightDiv { float:left;}
```
```html
<div class="contentHolder clearfix">
<div class="breadCrumb">
<a href="http://www.pricetag.com">Store </a>>> Electronics
</div>
<div class="contentMainDiv">
<div class="leftDiv"><p>orem ipsume Lorem ipsume Lorem ipsume Lorem ipsume</p>
</div>
<div class="rightDiv">
</div>
</div>
</div>
```
|
7,696,988
|
I am trying to show a border on the left side, but it doesn't show after the first div(breadCrumb). The HTML code is following :-
```
<div class="contentHolder">
<div class="breadCrumb">
<a href="http://www.pricetag.com">Store </a>>> Electronics
</div>
<div class="contentMainDiv">
<div class="leftDiv"><p>orem ipsume Lorem ipsume Lorem ipsume Lorem ipsume</p>
</div>
<div class="rightDiv">
</div>
</div>
</div>
```
The CSS code is following :
>
> .contentHolder { padding: 10px 0 0 10px; border-left: 1px solid #CCC; }
>
>
> .contentHolder div.breadCrumb { font-size:12px; }
>
>
> .contentHolder div.breadCrumb a {color:#408080; text-decoration:none; }
>
>
> .contentHolder div.breadCrumb a:hover {text-decoration:underline; }
>
>
> .contentHolder div.leftDiv{ float:left; width: 150px; }
>
>
> .contentHolder div.rightDiv { float:left;}
>
>
>
**Below is Image for the Error Page** : -
---

|
2011/10/08
|
[
"https://Stackoverflow.com/questions/7696988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/570928/"
] |
You need to [clear/contain the floated elements](http://www.quirksmode.org/css/clearing.html) in `.contentMainDiv`.
One way to do that is to add `overflow: hidden`.
|
You can add `float: left;` or `display: inline-block;` to `.contentHolder`
```
.contentHolder {
padding: 10px 0 0 10px;
border-left: 1px solid #CCC;
float: left;
}
```
Either should work.
|
7,696,988
|
I am trying to show a border on the left side, but it doesn't show after the first div(breadCrumb). The HTML code is following :-
```
<div class="contentHolder">
<div class="breadCrumb">
<a href="http://www.pricetag.com">Store </a>>> Electronics
</div>
<div class="contentMainDiv">
<div class="leftDiv"><p>orem ipsume Lorem ipsume Lorem ipsume Lorem ipsume</p>
</div>
<div class="rightDiv">
</div>
</div>
</div>
```
The CSS code is following :
>
> .contentHolder { padding: 10px 0 0 10px; border-left: 1px solid #CCC; }
>
>
> .contentHolder div.breadCrumb { font-size:12px; }
>
>
> .contentHolder div.breadCrumb a {color:#408080; text-decoration:none; }
>
>
> .contentHolder div.breadCrumb a:hover {text-decoration:underline; }
>
>
> .contentHolder div.leftDiv{ float:left; width: 150px; }
>
>
> .contentHolder div.rightDiv { float:left;}
>
>
>
**Below is Image for the Error Page** : -
---

|
2011/10/08
|
[
"https://Stackoverflow.com/questions/7696988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/570928/"
] |
```
.contentHolder div.leftDiv{ float:left; width: 150px; }
```
remove float: left or use clearfix <http://perishablepress.com/press/2009/12/06/new-clearfix-hack/> for contentHolder class
preview <http://jsfiddle.net/TrePF/>
```css
.clearfix:after {
visibility: hidden;
display: block;
font-size: 0;
content: " ";
clear: both;
height: 0;
}
.clearfix { display: inline-table; }
/* Hides from IE-mac \*/
* html .clearfix { height: 1%; }
.clearfix { display: block; }
/* End hide from IE-mac */
.contentHolder { padding: 10px 0 0 10px; border-left: 1px solid #CCC; }
.contentHolder div.breadCrumb { font-size:12px; }
.contentHolder div.breadCrumb a {color:#408080; text-decoration:none; }
.contentHolder div.breadCrumb a:hover {text-decoration:underline; }
.contentHolder div.leftDiv{ float:left; width: 150px; }
.contentHolder div.rightDiv { float:left;}
```
```html
<div class="contentHolder clearfix">
<div class="breadCrumb">
<a href="http://www.pricetag.com">Store </a>>> Electronics
</div>
<div class="contentMainDiv">
<div class="leftDiv"><p>orem ipsume Lorem ipsume Lorem ipsume Lorem ipsume</p>
</div>
<div class="rightDiv">
</div>
</div>
</div>
```
|
You can add `float: left;` or `display: inline-block;` to `.contentHolder`
```
.contentHolder {
padding: 10px 0 0 10px;
border-left: 1px solid #CCC;
float: left;
}
```
Either should work.
|
37,862,419
|
I'm building an app which shows data from **firebase database** in `ListView` adapter, but the listview doesn't fill with data. Database works. I tried this with `textview.setText` method on specially created layout.
```
public class MainActivityListFragment extends ListFragment {
private ArrayList<typ> typy;
private typAdapter typAdapter;
String tytul1, rodzaj1, godzina1, typ1, kurs1;
DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference mmecz1 = mRootRef.child("mecz1");
DatabaseReference mtytul1 = mmecz1.child("tytul1");
DatabaseReference mrodzaj1 = mmecz1.child("rodzaj1");
DatabaseReference mgodzina1 = mmecz1.child("godzina1");
DatabaseReference mtyp1 = mmecz1.child("typ1");
DatabaseReference mkurs1 = mmecz1.child("kurs1");
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
typy = new ArrayList<typ>();
typy.add(new typ(tytul1, rodzaj1, godzina1, typ1, kurs1));
typy.add(new typ("Portugalia - Islandia", "wygrana drużyny", "21:00", "1", "1.50"));
typAdapter = new typAdapter(getActivity(), typy);
setListAdapter(typAdapter);
getListView().setDivider(ContextCompat.getDrawable(getActivity(), android.R.color.black));
getListView().setDividerHeight(0);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
}
@Override
public void onStart() {
super.onStart();
mtytul1.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String text1 = dataSnapshot.getValue(String.class);
tytul1 = text1;
}
@Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(getActivity(),"No internet connection",Toast.LENGTH_SHORT).show();
}
});
mrodzaj1.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String text2 = dataSnapshot.getValue(String.class);
rodzaj1=text2;
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
mgodzina1.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String text3 = dataSnapshot.getValue(String.class);
godzina1 = text3;
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
mtyp1.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String text4 = dataSnapshot.getValue(String.class);
typ1 = text4;
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
mkurs1.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String text5 = dataSnapshot.getValue(String.class);
kurs1 = text5;
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
```
|
2016/06/16
|
[
"https://Stackoverflow.com/questions/37862419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6475203/"
] |
If I understand your question right - you looking for "how to set config param", then you can use `Config::set($key, $value)`
|
Correct answer is above
```
Config::set($key, $value)
```
Example
```
//Not forget to add namespace using class.
use Config;
//Example to set config. (configFile.key)
Config::set('auth.enable_verification', false);
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.