qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
477,504 | I got a local repository in `/var/www/html/centos/7` directory. In here, all rpm packages from centos are downloaded.
I will create a crontab for updating my local repository every 1 week or sth.
I want to learn that does `repocreate --update` do this? Or should I download all the packages from centos repo again?
If I should download the packages from centos repo, is there a way to skip the downloaded packages (they're in `/centos/7` directory as I mentioned) and download just the new (updated) packages from centos?
UPDATE
I have found the solution but it's not working for me. I created a new directory centos7/repo and download some files to check if the rsync --ignore-existing will work. But whenever I run the below command, I got an error
```
failed to connect to ftp.linux.org.tr (193.140.100.100): Connection timed out (110)
rsync: failed to connect to ftp.linux.org.tr (2001:a98:11::100): Network is unreachable (101)
rsync error: error in socket IO (code 10) at clientserver.c(125) [Receiver=3.1.2]
```
The command is:
```
rsync -avz --ignore-existing rsync://ftp.linux.org.tr/centos/7/os/x86_64/ /var/www/html/centos7/repo/
```
I tried other mirrors as well from <https://centos.org/download/mirrors/> (there are rsync location in this site as well). But none of them worked. Can anybody validate that rsync mirrors does work? Probably I can't go through firewall with port 873.
Is there anyway that I can use this rsync through port 80 or is there another way to accomplish this task? (I tried zsync but it needs a zsync file.) | 2018/10/24 | [
"https://unix.stackexchange.com/questions/477504",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/317026/"
] | If you have problems with rsync, then you can use [reposync](https://linux.die.net/man/1/reposync). It is able to download all packages (or --newest-only| -n) from repo, configured in the system.
So final commands in script looks like:
```
/usr/bin/reposync --repoid=updates --download_path=/var/www/html/centos7/repo/updates --newest-only
/usr/bin/createrepo /var/www/html/centos7/repo/updates
``` | repoquery queries every package in repository that you configured for your system and after that give the list to xargs to download all packages (new ones not existing ones)with repotrack to your server.
```
repoquery -a | xargs repotrack -a x86_64 -p .
```
The rsync solution also works if you haven't got any firewall rules that restrict the rsync daemon port.
```
rsync -avz --ignore-existing rsync://ftp.linux.org.tr/centos/7/os/x86_64/ /var/www/html/centos7/repo/
``` |
1,016,204 | I have an existing project that I was working on, and I recently decided to update my iPhone SDK and updated to the latest 3.0 SDK.
I update my SDK and go to open my existing project. Sure enough, there are some problems including some certificate problems and so on. Anyway, google and I were able to solve most of them, but I haven't had any luck on what I hope to be the last of my problems.
When running my program in the simulator, I now get
>
> dyld: Library not loaded:
> /System/Library/Frameworks/UIKit.framework/UIKit
> Referenced from:
> /Developer/iGameLib/iGameLib/build/Debug-iphonesimulator/iGameLib.app/iGameLib Reason: image not found
>
>
>
Now, I discovered the UIKit has moved to
>
> /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.0sdk/
> System/Library/FrameWorks/UIKit
>
>
>
and I have updated my target and project settings to point to that new framework location, but still when I build it, no luck.
I have also tried clearing out the simulator's applications and settings, still no luck.
The referencing .app is cleared when I run the "clean" menuitem, I have confirmed this, so clearly something in my project settings are still pointing to use the old UIKit location.
**Where should I be looking?**
I've gone as far as I can to help myself but I'm afraid I'm at a loss here. I don't see it under the target settings, or the project settings, or the plist, or any of the other files within my project. | 2009/06/19 | [
"https://Stackoverflow.com/questions/1016204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | 1. Check your target settings
Make sure you're actually linking to all of those frameworks in the Target (check under "link binary with libraries")
2. Make sure you've chosen the 3.0 sdk as your base SDK
3. Create a blank project and add your frameworks as before; if you still have issues, probably a borked SDK install
BTW, you shouldn't have to re-add sdk frameworks, as the paths are relative to the current SDK
Just trying to be helpful… not sure I can debug from here :) | I had the same problem using Xcode 3.2.1 but it was solved in an easier manner. I realized I had recently disabled my target's environment variables, specifically ones to do with memory debugging (NSDebugEnabled, NSZombieEnabled, NSAutoreleaseFreedObjectCheckEnabled, MallocStackLogging, MallocStackLoggingNoCompact). The app ran once in the simulator after removing the environment variables but never again after that.
Quitting Xcode, the Simulator, restarting Xcode and doing a complete clean of the target (including it's dependencies off course) brought me back to a good state. |
1,016,204 | I have an existing project that I was working on, and I recently decided to update my iPhone SDK and updated to the latest 3.0 SDK.
I update my SDK and go to open my existing project. Sure enough, there are some problems including some certificate problems and so on. Anyway, google and I were able to solve most of them, but I haven't had any luck on what I hope to be the last of my problems.
When running my program in the simulator, I now get
>
> dyld: Library not loaded:
> /System/Library/Frameworks/UIKit.framework/UIKit
> Referenced from:
> /Developer/iGameLib/iGameLib/build/Debug-iphonesimulator/iGameLib.app/iGameLib Reason: image not found
>
>
>
Now, I discovered the UIKit has moved to
>
> /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.0sdk/
> System/Library/FrameWorks/UIKit
>
>
>
and I have updated my target and project settings to point to that new framework location, but still when I build it, no luck.
I have also tried clearing out the simulator's applications and settings, still no luck.
The referencing .app is cleared when I run the "clean" menuitem, I have confirmed this, so clearly something in my project settings are still pointing to use the old UIKit location.
**Where should I be looking?**
I've gone as far as I can to help myself but I'm afraid I'm at a loss here. I don't see it under the target settings, or the project settings, or the plist, or any of the other files within my project. | 2009/06/19 | [
"https://Stackoverflow.com/questions/1016204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I just deleted the UIKit.framework from the 'Frameworks' folder, right-clicked and added it back again.
Clean build, and no problem.. | I had the same problem using Xcode 3.2.1 but it was solved in an easier manner. I realized I had recently disabled my target's environment variables, specifically ones to do with memory debugging (NSDebugEnabled, NSZombieEnabled, NSAutoreleaseFreedObjectCheckEnabled, MallocStackLogging, MallocStackLoggingNoCompact). The app ran once in the simulator after removing the environment variables but never again after that.
Quitting Xcode, the Simulator, restarting Xcode and doing a complete clean of the target (including it's dependencies off course) brought me back to a good state. |
1,016,204 | I have an existing project that I was working on, and I recently decided to update my iPhone SDK and updated to the latest 3.0 SDK.
I update my SDK and go to open my existing project. Sure enough, there are some problems including some certificate problems and so on. Anyway, google and I were able to solve most of them, but I haven't had any luck on what I hope to be the last of my problems.
When running my program in the simulator, I now get
>
> dyld: Library not loaded:
> /System/Library/Frameworks/UIKit.framework/UIKit
> Referenced from:
> /Developer/iGameLib/iGameLib/build/Debug-iphonesimulator/iGameLib.app/iGameLib Reason: image not found
>
>
>
Now, I discovered the UIKit has moved to
>
> /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.0sdk/
> System/Library/FrameWorks/UIKit
>
>
>
and I have updated my target and project settings to point to that new framework location, but still when I build it, no luck.
I have also tried clearing out the simulator's applications and settings, still no luck.
The referencing .app is cleared when I run the "clean" menuitem, I have confirmed this, so clearly something in my project settings are still pointing to use the old UIKit location.
**Where should I be looking?**
I've gone as far as I can to help myself but I'm afraid I'm at a loss here. I don't see it under the target settings, or the project settings, or the plist, or any of the other files within my project. | 2009/06/19 | [
"https://Stackoverflow.com/questions/1016204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | OK, SO I HAVE THE ANSWER!!!
Quite simply, Xcode is not changing all of the variables correctly in the actual .xcodeproj file. So, here are the steps I took.
Get out of Xcode, you've got to do this job at the terminal. Bring up a terminal and go to where your project is. Find your .xcodeproj and go into it as if it were a directory. It looks like an actual file in finder, but it is one of those package directories.
Now, I couldn't get textedit to allow me to edit it, but you can go into nano, so like I did
sudo nano project.pbxproj which is under my .xcodeproj file/folder/package/whatever.
In this file, you need to find where the SDKROOT is set. Chances are there are a few places it is referenced, but you're looking for SDKROOT = iphoneos2.2.1 or something similar. Change ALL OF THESE (there are a few) to SDKROOT = iphoneos3.0
Now, you're half way there. do ctrl x and save the file. Next you're going to do ls and find out what the .pbxuser file is. Mine is myname.pbxuser. run the same command of
sudo nano myname.pbxuser
In this file, there are a HUGE number of references to the 2.1 iphone sdk directory. Do a search/replace of iPhoneSimulatorOLDVERSION.sdk, in my case it was iPhoneSimulator2.1.sdk
and change the 2.1 to 3.0. Be very careful with this though, I wouldn't want to know what happens when you mess this file up.
Save it and open xcode. CLEAN the project and build and run. Presto! | I have had some similar problems with Xcode that seem to have no apparent cause. The fact of the matter is that Xcode does still have bugs here and there and sometimes you WILL run into a wall.
**My Experience:** Similar to your situation somewhat, on one particular occasion, an Xcode project I was working just stopped building for whatever mysterious reason, and no amount of cleaning, googling or SO-ing provided me any answers. So I simply created a FRESH, NEW project and filled the source-code from my corrupt project into that of the new project. The new project used the SAME source, libraries, resources, settings, mind you -- and yet it built with no problems. It took about 20-25 minutes to make the transfer but considering that I had spent several HOURS trying to address a bug that would not reveal itself in the corrupt project, the time was well worth it.
So, I'd suggest doing what I did: Maybe try creating a fresh project and transfer your old source and resources over.
Good Luck |
1,016,204 | I have an existing project that I was working on, and I recently decided to update my iPhone SDK and updated to the latest 3.0 SDK.
I update my SDK and go to open my existing project. Sure enough, there are some problems including some certificate problems and so on. Anyway, google and I were able to solve most of them, but I haven't had any luck on what I hope to be the last of my problems.
When running my program in the simulator, I now get
>
> dyld: Library not loaded:
> /System/Library/Frameworks/UIKit.framework/UIKit
> Referenced from:
> /Developer/iGameLib/iGameLib/build/Debug-iphonesimulator/iGameLib.app/iGameLib Reason: image not found
>
>
>
Now, I discovered the UIKit has moved to
>
> /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.0sdk/
> System/Library/FrameWorks/UIKit
>
>
>
and I have updated my target and project settings to point to that new framework location, but still when I build it, no luck.
I have also tried clearing out the simulator's applications and settings, still no luck.
The referencing .app is cleared when I run the "clean" menuitem, I have confirmed this, so clearly something in my project settings are still pointing to use the old UIKit location.
**Where should I be looking?**
I've gone as far as I can to help myself but I'm afraid I'm at a loss here. I don't see it under the target settings, or the project settings, or the plist, or any of the other files within my project. | 2009/06/19 | [
"https://Stackoverflow.com/questions/1016204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I was getting the same error
dyld: Library not loaded: /System/Library/Frameworks/UIKit.framework/UIKit
The solution on my case was simply quit Xcode and try again. | I have had some similar problems with Xcode that seem to have no apparent cause. The fact of the matter is that Xcode does still have bugs here and there and sometimes you WILL run into a wall.
**My Experience:** Similar to your situation somewhat, on one particular occasion, an Xcode project I was working just stopped building for whatever mysterious reason, and no amount of cleaning, googling or SO-ing provided me any answers. So I simply created a FRESH, NEW project and filled the source-code from my corrupt project into that of the new project. The new project used the SAME source, libraries, resources, settings, mind you -- and yet it built with no problems. It took about 20-25 minutes to make the transfer but considering that I had spent several HOURS trying to address a bug that would not reveal itself in the corrupt project, the time was well worth it.
So, I'd suggest doing what I did: Maybe try creating a fresh project and transfer your old source and resources over.
Good Luck |
1,016,204 | I have an existing project that I was working on, and I recently decided to update my iPhone SDK and updated to the latest 3.0 SDK.
I update my SDK and go to open my existing project. Sure enough, there are some problems including some certificate problems and so on. Anyway, google and I were able to solve most of them, but I haven't had any luck on what I hope to be the last of my problems.
When running my program in the simulator, I now get
>
> dyld: Library not loaded:
> /System/Library/Frameworks/UIKit.framework/UIKit
> Referenced from:
> /Developer/iGameLib/iGameLib/build/Debug-iphonesimulator/iGameLib.app/iGameLib Reason: image not found
>
>
>
Now, I discovered the UIKit has moved to
>
> /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.0sdk/
> System/Library/FrameWorks/UIKit
>
>
>
and I have updated my target and project settings to point to that new framework location, but still when I build it, no luck.
I have also tried clearing out the simulator's applications and settings, still no luck.
The referencing .app is cleared when I run the "clean" menuitem, I have confirmed this, so clearly something in my project settings are still pointing to use the old UIKit location.
**Where should I be looking?**
I've gone as far as I can to help myself but I'm afraid I'm at a loss here. I don't see it under the target settings, or the project settings, or the plist, or any of the other files within my project. | 2009/06/19 | [
"https://Stackoverflow.com/questions/1016204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | 1. Check your target settings
Make sure you're actually linking to all of those frameworks in the Target (check under "link binary with libraries")
2. Make sure you've chosen the 3.0 sdk as your base SDK
3. Create a blank project and add your frameworks as before; if you still have issues, probably a borked SDK install
BTW, you shouldn't have to re-add sdk frameworks, as the paths are relative to the current SDK
Just trying to be helpful… not sure I can debug from here :) | Same problem when launching my application without debugging.
In my experience the produced binary does not seem to be the culprit.
I created an app from the xcode wizard which does launch OK in the simulator (let's call it testApp, my application being called myApp), I tried to figure out where is the difference with my app.
`otool -L myApp`
gives correct (relative paths) to the frameworks, same as testApp
`ps -E`
DYLD\_ROOT\_PATH, DYLD\_FALLBACK\_FRAMEWORK\_PATH, DYLD\_FRAMEWORK\_PATH, DYLD\_LIBRARY\_PATH environment variables needed by ld to locate the framework
are OK for myApp compared to the values of these variables when testApp is launched
I suspect that the problem lies somewhere in the communicartion between XCode and the simulator once the app is launched ... altough I can't find what's wrong ...
The solution that worked (at least for me) have certainly some big side effects but here it is :
quit xcode
browse the content of the package myApp.xcodeproj
unlock .model1v3 and .pbxuser for modification (the lock in the information panel (cmd-I on the file))
delete these two files
start xcode and retry to launch your application from there |
1,016,204 | I have an existing project that I was working on, and I recently decided to update my iPhone SDK and updated to the latest 3.0 SDK.
I update my SDK and go to open my existing project. Sure enough, there are some problems including some certificate problems and so on. Anyway, google and I were able to solve most of them, but I haven't had any luck on what I hope to be the last of my problems.
When running my program in the simulator, I now get
>
> dyld: Library not loaded:
> /System/Library/Frameworks/UIKit.framework/UIKit
> Referenced from:
> /Developer/iGameLib/iGameLib/build/Debug-iphonesimulator/iGameLib.app/iGameLib Reason: image not found
>
>
>
Now, I discovered the UIKit has moved to
>
> /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.0sdk/
> System/Library/FrameWorks/UIKit
>
>
>
and I have updated my target and project settings to point to that new framework location, but still when I build it, no luck.
I have also tried clearing out the simulator's applications and settings, still no luck.
The referencing .app is cleared when I run the "clean" menuitem, I have confirmed this, so clearly something in my project settings are still pointing to use the old UIKit location.
**Where should I be looking?**
I've gone as far as I can to help myself but I'm afraid I'm at a loss here. I don't see it under the target settings, or the project settings, or the plist, or any of the other files within my project. | 2009/06/19 | [
"https://Stackoverflow.com/questions/1016204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I was getting the same error
dyld: Library not loaded: /System/Library/Frameworks/UIKit.framework/UIKit
The solution on my case was simply quit Xcode and try again. | Same problem when launching my application without debugging.
In my experience the produced binary does not seem to be the culprit.
I created an app from the xcode wizard which does launch OK in the simulator (let's call it testApp, my application being called myApp), I tried to figure out where is the difference with my app.
`otool -L myApp`
gives correct (relative paths) to the frameworks, same as testApp
`ps -E`
DYLD\_ROOT\_PATH, DYLD\_FALLBACK\_FRAMEWORK\_PATH, DYLD\_FRAMEWORK\_PATH, DYLD\_LIBRARY\_PATH environment variables needed by ld to locate the framework
are OK for myApp compared to the values of these variables when testApp is launched
I suspect that the problem lies somewhere in the communicartion between XCode and the simulator once the app is launched ... altough I can't find what's wrong ...
The solution that worked (at least for me) have certainly some big side effects but here it is :
quit xcode
browse the content of the package myApp.xcodeproj
unlock .model1v3 and .pbxuser for modification (the lock in the information panel (cmd-I on the file))
delete these two files
start xcode and retry to launch your application from there |
1,016,204 | I have an existing project that I was working on, and I recently decided to update my iPhone SDK and updated to the latest 3.0 SDK.
I update my SDK and go to open my existing project. Sure enough, there are some problems including some certificate problems and so on. Anyway, google and I were able to solve most of them, but I haven't had any luck on what I hope to be the last of my problems.
When running my program in the simulator, I now get
>
> dyld: Library not loaded:
> /System/Library/Frameworks/UIKit.framework/UIKit
> Referenced from:
> /Developer/iGameLib/iGameLib/build/Debug-iphonesimulator/iGameLib.app/iGameLib Reason: image not found
>
>
>
Now, I discovered the UIKit has moved to
>
> /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.0sdk/
> System/Library/FrameWorks/UIKit
>
>
>
and I have updated my target and project settings to point to that new framework location, but still when I build it, no luck.
I have also tried clearing out the simulator's applications and settings, still no luck.
The referencing .app is cleared when I run the "clean" menuitem, I have confirmed this, so clearly something in my project settings are still pointing to use the old UIKit location.
**Where should I be looking?**
I've gone as far as I can to help myself but I'm afraid I'm at a loss here. I don't see it under the target settings, or the project settings, or the plist, or any of the other files within my project. | 2009/06/19 | [
"https://Stackoverflow.com/questions/1016204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | 1. Check your target settings
Make sure you're actually linking to all of those frameworks in the Target (check under "link binary with libraries")
2. Make sure you've chosen the 3.0 sdk as your base SDK
3. Create a blank project and add your frameworks as before; if you still have issues, probably a borked SDK install
BTW, you shouldn't have to re-add sdk frameworks, as the paths are relative to the current SDK
Just trying to be helpful… not sure I can debug from here :) | I have had some similar problems with Xcode that seem to have no apparent cause. The fact of the matter is that Xcode does still have bugs here and there and sometimes you WILL run into a wall.
**My Experience:** Similar to your situation somewhat, on one particular occasion, an Xcode project I was working just stopped building for whatever mysterious reason, and no amount of cleaning, googling or SO-ing provided me any answers. So I simply created a FRESH, NEW project and filled the source-code from my corrupt project into that of the new project. The new project used the SAME source, libraries, resources, settings, mind you -- and yet it built with no problems. It took about 20-25 minutes to make the transfer but considering that I had spent several HOURS trying to address a bug that would not reveal itself in the corrupt project, the time was well worth it.
So, I'd suggest doing what I did: Maybe try creating a fresh project and transfer your old source and resources over.
Good Luck |
1,016,204 | I have an existing project that I was working on, and I recently decided to update my iPhone SDK and updated to the latest 3.0 SDK.
I update my SDK and go to open my existing project. Sure enough, there are some problems including some certificate problems and so on. Anyway, google and I were able to solve most of them, but I haven't had any luck on what I hope to be the last of my problems.
When running my program in the simulator, I now get
>
> dyld: Library not loaded:
> /System/Library/Frameworks/UIKit.framework/UIKit
> Referenced from:
> /Developer/iGameLib/iGameLib/build/Debug-iphonesimulator/iGameLib.app/iGameLib Reason: image not found
>
>
>
Now, I discovered the UIKit has moved to
>
> /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.0sdk/
> System/Library/FrameWorks/UIKit
>
>
>
and I have updated my target and project settings to point to that new framework location, but still when I build it, no luck.
I have also tried clearing out the simulator's applications and settings, still no luck.
The referencing .app is cleared when I run the "clean" menuitem, I have confirmed this, so clearly something in my project settings are still pointing to use the old UIKit location.
**Where should I be looking?**
I've gone as far as I can to help myself but I'm afraid I'm at a loss here. I don't see it under the target settings, or the project settings, or the plist, or any of the other files within my project. | 2009/06/19 | [
"https://Stackoverflow.com/questions/1016204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | OK, SO I HAVE THE ANSWER!!!
Quite simply, Xcode is not changing all of the variables correctly in the actual .xcodeproj file. So, here are the steps I took.
Get out of Xcode, you've got to do this job at the terminal. Bring up a terminal and go to where your project is. Find your .xcodeproj and go into it as if it were a directory. It looks like an actual file in finder, but it is one of those package directories.
Now, I couldn't get textedit to allow me to edit it, but you can go into nano, so like I did
sudo nano project.pbxproj which is under my .xcodeproj file/folder/package/whatever.
In this file, you need to find where the SDKROOT is set. Chances are there are a few places it is referenced, but you're looking for SDKROOT = iphoneos2.2.1 or something similar. Change ALL OF THESE (there are a few) to SDKROOT = iphoneos3.0
Now, you're half way there. do ctrl x and save the file. Next you're going to do ls and find out what the .pbxuser file is. Mine is myname.pbxuser. run the same command of
sudo nano myname.pbxuser
In this file, there are a HUGE number of references to the 2.1 iphone sdk directory. Do a search/replace of iPhoneSimulatorOLDVERSION.sdk, in my case it was iPhoneSimulator2.1.sdk
and change the 2.1 to 3.0. Be very careful with this though, I wouldn't want to know what happens when you mess this file up.
Save it and open xcode. CLEAN the project and build and run. Presto! | I just deleted the UIKit.framework from the 'Frameworks' folder, right-clicked and added it back again.
Clean build, and no problem.. |
1,016,204 | I have an existing project that I was working on, and I recently decided to update my iPhone SDK and updated to the latest 3.0 SDK.
I update my SDK and go to open my existing project. Sure enough, there are some problems including some certificate problems and so on. Anyway, google and I were able to solve most of them, but I haven't had any luck on what I hope to be the last of my problems.
When running my program in the simulator, I now get
>
> dyld: Library not loaded:
> /System/Library/Frameworks/UIKit.framework/UIKit
> Referenced from:
> /Developer/iGameLib/iGameLib/build/Debug-iphonesimulator/iGameLib.app/iGameLib Reason: image not found
>
>
>
Now, I discovered the UIKit has moved to
>
> /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.0sdk/
> System/Library/FrameWorks/UIKit
>
>
>
and I have updated my target and project settings to point to that new framework location, but still when I build it, no luck.
I have also tried clearing out the simulator's applications and settings, still no luck.
The referencing .app is cleared when I run the "clean" menuitem, I have confirmed this, so clearly something in my project settings are still pointing to use the old UIKit location.
**Where should I be looking?**
I've gone as far as I can to help myself but I'm afraid I'm at a loss here. I don't see it under the target settings, or the project settings, or the plist, or any of the other files within my project. | 2009/06/19 | [
"https://Stackoverflow.com/questions/1016204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | OK, SO I HAVE THE ANSWER!!!
Quite simply, Xcode is not changing all of the variables correctly in the actual .xcodeproj file. So, here are the steps I took.
Get out of Xcode, you've got to do this job at the terminal. Bring up a terminal and go to where your project is. Find your .xcodeproj and go into it as if it were a directory. It looks like an actual file in finder, but it is one of those package directories.
Now, I couldn't get textedit to allow me to edit it, but you can go into nano, so like I did
sudo nano project.pbxproj which is under my .xcodeproj file/folder/package/whatever.
In this file, you need to find where the SDKROOT is set. Chances are there are a few places it is referenced, but you're looking for SDKROOT = iphoneos2.2.1 or something similar. Change ALL OF THESE (there are a few) to SDKROOT = iphoneos3.0
Now, you're half way there. do ctrl x and save the file. Next you're going to do ls and find out what the .pbxuser file is. Mine is myname.pbxuser. run the same command of
sudo nano myname.pbxuser
In this file, there are a HUGE number of references to the 2.1 iphone sdk directory. Do a search/replace of iPhoneSimulatorOLDVERSION.sdk, in my case it was iPhoneSimulator2.1.sdk
and change the 2.1 to 3.0. Be very careful with this though, I wouldn't want to know what happens when you mess this file up.
Save it and open xcode. CLEAN the project and build and run. Presto! | I had the same problem using Xcode 3.2.1 but it was solved in an easier manner. I realized I had recently disabled my target's environment variables, specifically ones to do with memory debugging (NSDebugEnabled, NSZombieEnabled, NSAutoreleaseFreedObjectCheckEnabled, MallocStackLogging, MallocStackLoggingNoCompact). The app ran once in the simulator after removing the environment variables but never again after that.
Quitting Xcode, the Simulator, restarting Xcode and doing a complete clean of the target (including it's dependencies off course) brought me back to a good state. |
1,016,204 | I have an existing project that I was working on, and I recently decided to update my iPhone SDK and updated to the latest 3.0 SDK.
I update my SDK and go to open my existing project. Sure enough, there are some problems including some certificate problems and so on. Anyway, google and I were able to solve most of them, but I haven't had any luck on what I hope to be the last of my problems.
When running my program in the simulator, I now get
>
> dyld: Library not loaded:
> /System/Library/Frameworks/UIKit.framework/UIKit
> Referenced from:
> /Developer/iGameLib/iGameLib/build/Debug-iphonesimulator/iGameLib.app/iGameLib Reason: image not found
>
>
>
Now, I discovered the UIKit has moved to
>
> /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator3.0sdk/
> System/Library/FrameWorks/UIKit
>
>
>
and I have updated my target and project settings to point to that new framework location, but still when I build it, no luck.
I have also tried clearing out the simulator's applications and settings, still no luck.
The referencing .app is cleared when I run the "clean" menuitem, I have confirmed this, so clearly something in my project settings are still pointing to use the old UIKit location.
**Where should I be looking?**
I've gone as far as I can to help myself but I'm afraid I'm at a loss here. I don't see it under the target settings, or the project settings, or the plist, or any of the other files within my project. | 2009/06/19 | [
"https://Stackoverflow.com/questions/1016204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I was getting the same error
dyld: Library not loaded: /System/Library/Frameworks/UIKit.framework/UIKit
The solution on my case was simply quit Xcode and try again. | I had the same problem using Xcode 3.2.1 but it was solved in an easier manner. I realized I had recently disabled my target's environment variables, specifically ones to do with memory debugging (NSDebugEnabled, NSZombieEnabled, NSAutoreleaseFreedObjectCheckEnabled, MallocStackLogging, MallocStackLoggingNoCompact). The app ran once in the simulator after removing the environment variables but never again after that.
Quitting Xcode, the Simulator, restarting Xcode and doing a complete clean of the target (including it's dependencies off course) brought me back to a good state. |
64,040,215 | I made this code that creates a scatter chart and allows me to change the color of a node on the plot when I click/select it.
```
package com.jpc.javafx.charttest;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.ScatterChart;
import javafx.scene.chart.XYChart;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class CreateChart extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
//-------Create Chart--------------
NumberAxis xAxis = new NumberAxis();
NumberAxis yAxis = new NumberAxis();
XYChart.Series<Number,Number> dataSeries1 = new XYChart.Series();
ScatterChart chart = new ScatterChart(xAxis,yAxis);
dataSeries1.getData().add(new XYChart.Data( 1, 567));
dataSeries1.getData().add(new XYChart.Data( 5, 612));
dataSeries1.getData().add(new XYChart.Data(10, 800));
chart.getData().add(dataSeries1);
//-----Select node and change color -----
for(final XYChart.Data<Number,Number> data : dataSeries1.getData()) {
data.getNode().setOnMouseClicked(e-> {
//dataSeries1.getNode().lookup(".chart-symbol").setStyle("-fx-background-color: red"); that does not work
data.getNode().setStyle("-fx-background-color: blue" );
});
}
VBox vbox = new VBox(chart);
Scene scene = new Scene(vbox, 400, 200);
primaryStage.setScene(scene);
primaryStage.setHeight(300);
primaryStage.setWidth(1200);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
```
The problem is that when I select another point the previous one stays blue. So I need to reset all the nodes to the default color before I change the selected point's color.
I tried to add this:
`dataSeries1.getNode().lookup(".chart-symbol").setStyle("-fx-background-color: red");`
but I get:
>
> Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
>
>
> | 2020/09/24 | [
"https://Stackoverflow.com/questions/64040215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14127900/"
] | To summarize your requirement:
* a visual property of a chart-symbol should be marked on user interaction
* there should be only one such marked symbol
Sounds like a kind of selection mechanism - which is not supported for chart symbols out of the box, application code must take care of it. The task is
* keep track of the (last) selected symbol
* guarantee that at any time only a single symbol is selected
* keep the visual state of un/selected as needed
The most simple implementation for the logic (the first two bullets) would be to keep a reference to the current selected and update it on user interaction. An appropriate instrument for the latter would be a PseudoClass: can be defined in the css and de/activated along with the logic.
Code snippets (to be inserted into your example)
```
// Pseudo-class
private PseudoClass selected = PseudoClass.getPseudoClass("selected");
// selected logic
private Node selectedSymbol;
protected void setSelectedSymbol(Node symbol) {
if (selectedSymbol != null) {
selectedSymbol.pseudoClassStateChanged(selected, false);
}
selectedSymbol = symbol;
if (selectedSymbol != null) {
selectedSymbol.pseudoClassStateChanged(selected, true);
}
}
// event handler on every symbol
data.getNode().setOnXX(e -> setSelectedSymbol(data.getNode()));
```
css example, to be loaded via a style-sheet f.i.:
```
.chart-symbol:selected {
-fx-background-color: blue;
}
``` | One thing you can do is loop through the data and change the color for the one clicked and set all the other to `null`
```
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.ScatterChart;
import javafx.scene.chart.XYChart;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class CreateChart extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
//-------Create Chart--------------
NumberAxis xAxis = new NumberAxis();
NumberAxis yAxis = new NumberAxis();
XYChart.Series<Number,Number> dataSeries1 = new XYChart.Series();
ScatterChart chart = new ScatterChart(xAxis,yAxis);
dataSeries1.getData().add(new XYChart.Data( 1, 567));
dataSeries1.getData().add(new XYChart.Data( 5, 612));
dataSeries1.getData().add(new XYChart.Data(10, 800));
chart.getData().add(dataSeries1);
//-----Select node and change color -----
for(final XYChart.Data<Number,Number> data : dataSeries1.getData()) {
data.getNode().setOnMouseClicked(e-> {
for(final XYChart.Data<Number,Number> data2 : dataSeries1.getData()) {
if(data == data2)
{
data2.getNode().setStyle("-fx-background-color: blue" );
}
else
{
data2.getNode().setStyle(null);
}
}
});
}
VBox vbox = new VBox(chart);
Scene scene = new Scene(vbox, 400, 200);
primaryStage.setScene(scene);
primaryStage.setHeight(300);
primaryStage.setWidth(1200);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
``` |
14,241,389 | I am getting a "Specified cast is not valid" valid when doing only a release build from MSBuild 4.0. I tested this out in using a release build from Visual Studio 2012 and didn't get this issue. I also tested this out using a debug build from MSBuild 4.0 and didn't get this issue.
Exception: 
Code
```
public abstract class CachedSessionBase : ISessionObject
{
protected Dictionary<MethodBase, Object> _getAndSetCache = new Dictionary<MethodBase, object>();
protected TResult SetAndGet<TResult>(ObjectFactory factory, Func<TResult> func)
{
StackTrace stackTrace = new StackTrace();
var methodBase = stackTrace.GetFrame(1).GetMethod();
if (!_getAndSetCache.ContainsKey(methodBase))
{
_getAndSetCache[methodBase] = func.Invoke();
}
return (TResult)_getAndSetCache[methodBase];
}
```
The error is being thrown on this line
```
return (TResult)_getAndSetCache[methodBase];
``` | 2013/01/09 | [
"https://Stackoverflow.com/questions/14241389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/463469/"
] | It is likely that the call stack is different than what you are expecting it to be. Your method may be getting inlined, then `GetFrame(1)` is retrieving the caller's caller. When the value is retrieved from the dictionary, it is of a different type because it is for a different method.
You could try adding the attribute `[MethodImpl(MethodImplOptions.NoInlining]` to `SetAndGet` to prevent the inlining optimization for the method. | I had the same problem when running `nuget pack` which invoked
>
> MSBuild auto-detection: using msbuild version '15.0'...
>
>
>
but the problem was solved by running `dotnet pack` which invoked
>
> Microsoft (R) Build Engine version 15.3.409.57025 for .NET Core
>
>
> |
56,666,430 | hi m trying to download db data in excel format,,, but when I click on download then it says: Call to undefined method Maatwebsite\Excel\Excel::create()
code of controller:
```
function excel()
{
$pdf_data = DB::table('importpdfs')->get()->toArray();
$pdf_array[] = array('Battery', 'No_of_questions_attempted', 'SAS', 'NPR', 'ST', 'GR');
foreach($pdf_data as $pdf)
{
$pdf_array[] = array(
'Battery' => $pdf->Battery,
'No_of_questions_attempted' => $pdf->No_of_questions_attempted,
'SAS' => $pdf->SAS,
'NPR' => $pdf->NPR,
'ST' => $pdf->ST,
'GR' => $pdf->GR
);
}
Excel::create('Pdf Data', function($excel) use ($pdf_array){
$excel->setTitle('Pdf Data');
$excel->sheet('Pdf Data', function($sheet) use ($pdf_array){
$sheet->fromArray($pdf_array, null, 'A1', false, false);
});
})->download('xlsx');
}
``` | 2019/06/19 | [
"https://Stackoverflow.com/questions/56666430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10896655/"
] | The create method was removed with `laravel-excel` version `3.0`.
From the [upgrade guide](https://docs.laravel-excel.com/3.1/getting-started/upgrade.html#upgrading-to-3-from-2-1):
>
> Excel::create() is removed and replaced by
> Excel::download/Excel::store($yourExport)
>
>
>
I would use the [quickstart guide](https://docs.laravel-excel.com/3.1/exports/) from their documentation. | You are probably not using the Facade and using the file directly, make sure you are using
```
use Maatwebsite\Excel\Facades\Excel;
```
and not
```
use Maatwebsite\Excel\Excel;
``` |
56,666,430 | hi m trying to download db data in excel format,,, but when I click on download then it says: Call to undefined method Maatwebsite\Excel\Excel::create()
code of controller:
```
function excel()
{
$pdf_data = DB::table('importpdfs')->get()->toArray();
$pdf_array[] = array('Battery', 'No_of_questions_attempted', 'SAS', 'NPR', 'ST', 'GR');
foreach($pdf_data as $pdf)
{
$pdf_array[] = array(
'Battery' => $pdf->Battery,
'No_of_questions_attempted' => $pdf->No_of_questions_attempted,
'SAS' => $pdf->SAS,
'NPR' => $pdf->NPR,
'ST' => $pdf->ST,
'GR' => $pdf->GR
);
}
Excel::create('Pdf Data', function($excel) use ($pdf_array){
$excel->setTitle('Pdf Data');
$excel->sheet('Pdf Data', function($sheet) use ($pdf_array){
$sheet->fromArray($pdf_array, null, 'A1', false, false);
});
})->download('xlsx');
}
``` | 2019/06/19 | [
"https://Stackoverflow.com/questions/56666430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10896655/"
] | If you previously updated your `"maatwebsite/excel"` package to 3.\*. version, the method `Excel::create($yourExport)` is removed. Instead you should use `Excel::download/Excel::store($yourExport)`.
Example how it should be used with new version:
```
use App\Exports\UsersExport;
use Maatwebsite\Excel\Facades\Excel;
use App\Http\Controllers\Controller;
class UsersController extends Controller
{
public function export()
{
return Excel::download(new UsersExport, 'users.xlsx');
}
}
```
Where `UsersExport` is a new class created by using the `make:export` command.
**UsersExport.php:**
```
<?php
namespace App\Exports;
use App\User;
use Maatwebsite\Excel\Concerns\FromCollection;
class UsersExport implements FromCollection
{
public function collection()
{
return User::all();
}
}
```
Here you can find official [Upgrade guide](https://docs.laravel-excel.com/3.1/getting-started/upgrade.html) to a new version. | You are probably not using the Facade and using the file directly, make sure you are using
```
use Maatwebsite\Excel\Facades\Excel;
```
and not
```
use Maatwebsite\Excel\Excel;
``` |
238,223 | I would like to create a view that uses aggregation on an entity to display the count and the sum by date. But it should be grouped by date only without time even the original date value has time values. I.e.
Entity:
processedTime | amount | value | ...
01/01/2017 08:00:00 | 10 | 1 | ...
01/01/2017 08:18:10 | 10 | 1 | ...
01/01/2017 10:00:00 | 10 | 1 | ...
01/02/2017 08:00:00 | 10 | 1 | ...
01/02/2017 09:30:00 | 10 | 1 | ...
...
the view should output
01/01/2017 | 30 | 3 | ...
01/02/2017 | 20 | 2 | ...
If I create a view with aggregation grouped by the date field, the view also evaluates the time and tries to group by the entire value of the date field. How can I group only by year, month and day without time? | 2017/06/11 | [
"https://drupal.stackexchange.com/questions/238223",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/76493/"
] | @kiamlaluno described the technical details. This is the background why the `DependencySerializationTrait` was introduced:
This was the situation before:
>
> * Any class that receives injected dependencies (whether by
> constructor injection or setter injection) typically keeps a reference
> to its dependencies in class members. That's how dependency injection
> works.
> * Drupal being Drupal, it serializes stuff in several
> places:
> + Anything that is in a $form / $form\_state : the FormInterface object, but also any object whose methods are used by
> FAPI #callbacks ('#pre\_render' = array($some\_object,
> 'someSubmit')).
> + Anything that gets cached, stored in state(), or more generally in the k/v stores...
> * When an object is serialized, all the objects it references get serialized as well, and recursively, all the
> dependencies of those objects...
> * This leads to a
> serialization chain of hell: [#1909418] hit a case where serializing
> the form controller meant serializing the EntityManager -> the
> Container -> (among many other things) the DrupalKernel. This got
> fixed by making sure the kernel was serializable - which is just
> insane :-).
>
>
>
And this was the proposed solution:
>
> The answer for "DIC-friendly serialization" seems to be: * On
> serialize, do not serialize dependencies.
> * On unserialize,
> re-pull them from the container. Granted, this breaks mocking, but
> serialization/unserialization is not something you typically do in
> unit tests, so I don't see this as a real problem.
>
>
>
> How to do this might not be too simple though. Two approaches come to
> mind:
>
>
> 1. Classes that want to be "DIC-friendly serialized" need to
> implement an unserialize() method that hardcodes the services ids of
> its dependencies. That means doing something similar to the create()
> factory method that is currently used at instantiation time in a
> couple places in core (controllers, some plugins). Hardcoding service
> ids in more and more classes is not a joyful perspective, though.
> 2. Crazy idea:
> * Modify the DIC so that each time a service gets instantiated, the service id by which it got instantiated gets placed
> in a public \_\_serviceId (or something) property on the object.
> * Classes that want to be "DIC-friendly serialized" do:
>
> * On serialize() : foreach member, if (!empty($this->member->\_\_serviceId)) {just serialize the \_\_serviceId
> string instead of the whole object});
> * On unserialize() : $this->member = \Drupal::service($service\_id)
>
>
>
Quoted from [Injected dependencies and serialization hell](https://www.drupal.org/node/2004282) | [`DependencySerializationTrait`](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21DependencyInjection%21DependencySerializationTrait.php/trait/DependencySerializationTrait/8.9.x) is used from classes that are serialized and that have services in their properties. For those classes, the trait replaces the service with its service ID, so that when an object of those classes is restored after being serialized, those service properties get a fresh object, as said in the code comment.
>
> If a class member was instantiated by the dependency injection container, only store its ID so it can be used to get a fresh object on unserialization.
>
>
>
For example, a class that just saves arrays in its properties would not have much use of that trait, especially if it's not going to be serialized.
If then the class stores the dependency injection container, the trait replaces it with the string *service\_container*. |
3,178,361 | Finding $$\int^{6}\_{0}x(x-1)(x-2)(x-3)(x-4)(x-6)dx$$
My progress so far
$$x(x-4)(x-6)(x-1)(x-2)(x-3)=\bigg(x^3-10x^2+24x\bigg)\bigg(x^3-6x^2+11x-6\bigg)$$
How can I find solution Help me | 2019/04/07 | [
"https://math.stackexchange.com/questions/3178361",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/661425/"
] | Well, you can certainly proceed as you are now, and continue expanding until you get the polynomial into standard form, then integrate. We could go about it in a bit of a different way, though.
Let $f(x)=x(x-1)(x-2)(x-3)(x-4)(x-6).$ Then we have $$\int\_0^6f(x)dx=\int\_0^3f(x)dx+\int\_3^6f(x)dx,$$ and making the substitution $x\mapsto 6-x$ (so $3\mapsto 3,$ $6\mapsto 0,$ and $dx\mapsto-dx$) in the rightmost integral gets us
\begin{eqnarray}\int\_0^6f(x)dx &=& \int\_0^3f(x)dx-\int\_3^0f(6-x)dx\\ &=& \int\_0^3f(x)dx+\int\_0^3f(6-x)dx\\ &=& \int\_0^3\bigl(f(x)+f(6-x)\bigr)dx.\end{eqnarray}
Now, note that
\begin{eqnarray}f(6-x) &=& (6-x)(5-x)(4-x)(3-x)(2-x)(0-x)\\ &=& (-1)^6(x-6)(x-5)(x-4)(x-3)(x-2)(x-0)\\ &=& x(x-2)(x-3)(x-4)(x-5)(x-6),\end{eqnarray}
so that, remembering our difference of squares formula $(u+v)(u-v)=u^2-v^2,$ we can see that
\begin{eqnarray}f(x)+f(6-x) &=& x(x-2)(x-3)(x-4)(x-6)\bigl((x-1)+(x-5)\bigr)\\ &=& x(x-2)(x-3)(x-4)(x-6)(2x-6)\\ &=& 2x(x-2)(x-3)^2(x-4)(x-6)\\ &=& 2x(x-6)(x-2)(x-4)(x-3)^2\\ &=& 2\bigl((x-3)+3\bigr)\bigl((x-3)-3\bigr)\bigl((x-3)+1\bigr)\bigl((x-3)-1\bigr)(x-3)^2\\ &=& 2\left((x-3)^2-9\right)\left((x-3)^2-1\right)(x-3)^2\\ &=& 2\left((x-3)^4-10(x-3)^2+9\right)(x-3)^2\\ &=& 2\left((x-3)^6-10(x-3)^4+9(x-3)^2\right).\end{eqnarray}
Thus, we have $$\int\_0^6f(x)dx=2\int\_0^3\left((x-3)^6-10(x-3)^4+9(x-3)^2\right)dx,$$ and making the substitution $x\mapsto 3-x$ (so that $0\mapsto 3,$ $3\mapsto 0,$ and $x\mapsto-dx$) on the right-hand side, we get
\begin{eqnarray}f(6-x) &=& -2\int\_3^0\left((-x)^6-10(-x)^4+9(-x)^2\right)dx\\ &=& -2\int\_3^0\left(x^6-10x^4+9x^2\right)dx\\ &=& 2\int\_0^3\left(x^6-10x^4+9x^2\right)dx,\end{eqnarray}
which is a much nicer integral to evaluate. Still, that's a lot of work to go through just to avoid a few more polynomial expansions. | Hint: Expanding the Integrand we get $$x^6-16 x^5+95 x^4-260 x^3+324 x^2-144 x$$ |
3,178,361 | Finding $$\int^{6}\_{0}x(x-1)(x-2)(x-3)(x-4)(x-6)dx$$
My progress so far
$$x(x-4)(x-6)(x-1)(x-2)(x-3)=\bigg(x^3-10x^2+24x\bigg)\bigg(x^3-6x^2+11x-6\bigg)$$
How can I find solution Help me | 2019/04/07 | [
"https://math.stackexchange.com/questions/3178361",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/661425/"
] | Well, you can certainly proceed as you are now, and continue expanding until you get the polynomial into standard form, then integrate. We could go about it in a bit of a different way, though.
Let $f(x)=x(x-1)(x-2)(x-3)(x-4)(x-6).$ Then we have $$\int\_0^6f(x)dx=\int\_0^3f(x)dx+\int\_3^6f(x)dx,$$ and making the substitution $x\mapsto 6-x$ (so $3\mapsto 3,$ $6\mapsto 0,$ and $dx\mapsto-dx$) in the rightmost integral gets us
\begin{eqnarray}\int\_0^6f(x)dx &=& \int\_0^3f(x)dx-\int\_3^0f(6-x)dx\\ &=& \int\_0^3f(x)dx+\int\_0^3f(6-x)dx\\ &=& \int\_0^3\bigl(f(x)+f(6-x)\bigr)dx.\end{eqnarray}
Now, note that
\begin{eqnarray}f(6-x) &=& (6-x)(5-x)(4-x)(3-x)(2-x)(0-x)\\ &=& (-1)^6(x-6)(x-5)(x-4)(x-3)(x-2)(x-0)\\ &=& x(x-2)(x-3)(x-4)(x-5)(x-6),\end{eqnarray}
so that, remembering our difference of squares formula $(u+v)(u-v)=u^2-v^2,$ we can see that
\begin{eqnarray}f(x)+f(6-x) &=& x(x-2)(x-3)(x-4)(x-6)\bigl((x-1)+(x-5)\bigr)\\ &=& x(x-2)(x-3)(x-4)(x-6)(2x-6)\\ &=& 2x(x-2)(x-3)^2(x-4)(x-6)\\ &=& 2x(x-6)(x-2)(x-4)(x-3)^2\\ &=& 2\bigl((x-3)+3\bigr)\bigl((x-3)-3\bigr)\bigl((x-3)+1\bigr)\bigl((x-3)-1\bigr)(x-3)^2\\ &=& 2\left((x-3)^2-9\right)\left((x-3)^2-1\right)(x-3)^2\\ &=& 2\left((x-3)^4-10(x-3)^2+9\right)(x-3)^2\\ &=& 2\left((x-3)^6-10(x-3)^4+9(x-3)^2\right).\end{eqnarray}
Thus, we have $$\int\_0^6f(x)dx=2\int\_0^3\left((x-3)^6-10(x-3)^4+9(x-3)^2\right)dx,$$ and making the substitution $x\mapsto 3-x$ (so that $0\mapsto 3,$ $3\mapsto 0,$ and $x\mapsto-dx$) on the right-hand side, we get
\begin{eqnarray}f(6-x) &=& -2\int\_3^0\left((-x)^6-10(-x)^4+9(-x)^2\right)dx\\ &=& -2\int\_3^0\left(x^6-10x^4+9x^2\right)dx\\ &=& 2\int\_0^3\left(x^6-10x^4+9x^2\right)dx,\end{eqnarray}
which is a much nicer integral to evaluate. Still, that's a lot of work to go through just to avoid a few more polynomial expansions. | If you just perform all the multiplication you get an integral of a sum of powers. The integral of a sum is the sum of the itegrals of each term, which will be of the formg $c\int \! \mathrm{d}x \; x^{\alpha} = c\;\frac{x^{\alpha+1}}{\alpha+1}$ |
1,748,908 | I am using sugarCRM at my localhost.
For no apparent reason firefox is viewing the page in Quirks mode (the login page). This is completely messing up the page, here is a sample of the data shown:
>
> ��������Z�n7�-}v�fd4��q�Z�·8�ڱa�-�
> f(�
> 5�rf��<�b���y�=��ftwRw�@"����m�<�2��^?}�
> -��Ӌ�s���w|�#��Wo����U��'���a�n�{2��f0f1�E��~K���
> fA\�$♞)�ioDU���]�U�;�$�`��krp@�XKE|I�p&k������C[rP��!��?�tH��9�j�p=
>
>
>
I thought this might be the server's fault (apache) but if I use Epiphany I can see the page perfectly. When I see the pages info, I see that the render mode is in quirks mode.
Is there any way to force it to use the Standards compliance mode?
I am on ubuntu 9.10 using Firefox 3.5 (I also tried 3.0.15, same thing happened) I disabled all the extension and I still got the same page. A friend tried viewing it with Chrome and the same thing happened :( | 2009/11/17 | [
"https://Stackoverflow.com/questions/1748908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8715/"
] | To get Firefox to render a page in standards-compliant mode, add a DOCTYPE to your HTML. For example, if you're using HTML (as opposed to XHTML), use:
```
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/DTD/strict.dtd">
```
You might find this Wikipedia link helpful - [triggering different rendering modes](http://en.wikipedia.org/wiki/Quirks_mode#Triggering_different_rendering_modes). | Are you using PHP 5.3? It may be the reason.
What is your Sugar version? |
1,748,908 | I am using sugarCRM at my localhost.
For no apparent reason firefox is viewing the page in Quirks mode (the login page). This is completely messing up the page, here is a sample of the data shown:
>
> ��������Z�n7�-}v�fd4��q�Z�·8�ڱa�-�
> f(�
> 5�rf��<�b���y�=��ftwRw�@"����m�<�2��^?}�
> -��Ӌ�s���w|�#��Wo����U��'���a�n�{2��f0f1�E��~K���
> fA\�$♞)�ioDU���]�U�;�$�`��krp@�XKE|I�p&k������C[rP��!��?�tH��9�j�p=
>
>
>
I thought this might be the server's fault (apache) but if I use Epiphany I can see the page perfectly. When I see the pages info, I see that the render mode is in quirks mode.
Is there any way to force it to use the Standards compliance mode?
I am on ubuntu 9.10 using Firefox 3.5 (I also tried 3.0.15, same thing happened) I disabled all the extension and I still got the same page. A friend tried viewing it with Chrome and the same thing happened :( | 2009/11/17 | [
"https://Stackoverflow.com/questions/1748908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8715/"
] | Couldn't it be an encoding issue? E.g., your Apache sends
```
Content-Type: text/html; charset=Big5
```
but your HTML page is simply ASCII. Then you get gibberish as that. If you know your HTML encoding, try "View" -> "Character Encoding" in FF and switch back and forth a bit.
Alternatively, look at Apache's httpd.conf and search for the
```
AddDefaultCharset
```
setting. | Are you using PHP 5.3? It may be the reason.
What is your Sugar version? |
1,748,908 | I am using sugarCRM at my localhost.
For no apparent reason firefox is viewing the page in Quirks mode (the login page). This is completely messing up the page, here is a sample of the data shown:
>
> ��������Z�n7�-}v�fd4��q�Z�·8�ڱa�-�
> f(�
> 5�rf��<�b���y�=��ftwRw�@"����m�<�2��^?}�
> -��Ӌ�s���w|�#��Wo����U��'���a�n�{2��f0f1�E��~K���
> fA\�$♞)�ioDU���]�U�;�$�`��krp@�XKE|I�p&k������C[rP��!��?�tH��9�j�p=
>
>
>
I thought this might be the server's fault (apache) but if I use Epiphany I can see the page perfectly. When I see the pages info, I see that the render mode is in quirks mode.
Is there any way to force it to use the Standards compliance mode?
I am on ubuntu 9.10 using Firefox 3.5 (I also tried 3.0.15, same thing happened) I disabled all the extension and I still got the same page. A friend tried viewing it with Chrome and the same thing happened :( | 2009/11/17 | [
"https://Stackoverflow.com/questions/1748908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8715/"
] | The screwed up data you posted suggests that the character encoding your document uses and the character encoding that Firefox thinks it uses does not match.
1. Pick a character encoding
2. Make sure you use it in your document
3. Make sure your Content-Type header specifies that encoding
<http://www.w3.org/International/tutorials/tutorial-char-enc/> is a useful guide. | Are you using PHP 5.3? It may be the reason.
What is your Sugar version? |
2,030,910 | I am sending a status code via the header function, such as `header('HTTP/1.1 403');`, and would like to in another area of my code detect what status code is to be sent (in particular if I have sent an error code of some nature). As has been mentioned [elsewhere](https://stackoverflow.com/questions/1798353/determine-the-http-status-that-will-be-sent-in-php), `headers_list()` does not return this particular item, and it's unclear to me if it actually counts as a header, as neither Firebug nor Fiddler2 treat it with the headers. So - how can a PHP script detect which status code is about to be sent to the browser?
I would rather not use a wrapper function (or object) around the header method, or otherwise set some global variable along with the sending of the status code. I'd also rather not call my code from itself using curl or the like, due to performance concerns. Please let me know what you think. | 2010/01/08 | [
"https://Stackoverflow.com/questions/2030910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/118153/"
] | Consider setting a constant:
```
define('HTTP_STATUS', 403);
```
and using the `defined` function later on:
```
if(defined('HTTP_STATUS') && HTTP_STATUS == 403) // ...or whatever you're looking to do
```
Actually peeking back at the headers themselves is kind of a hack in itself as it's simply too slow: you're dealing with strings and arrays and all sorts of other messy data. Set for yourself a simple constant: it's blazing fast, it does the same thing, and it doesn't create any "true" global variables. | It's another call, but as a last resort you could use this rather than curl. If you have php 5.0, What about [get\_headers()](http://us.php.net/manual/en/function.get-headers.php)? |
2,030,910 | I am sending a status code via the header function, such as `header('HTTP/1.1 403');`, and would like to in another area of my code detect what status code is to be sent (in particular if I have sent an error code of some nature). As has been mentioned [elsewhere](https://stackoverflow.com/questions/1798353/determine-the-http-status-that-will-be-sent-in-php), `headers_list()` does not return this particular item, and it's unclear to me if it actually counts as a header, as neither Firebug nor Fiddler2 treat it with the headers. So - how can a PHP script detect which status code is about to be sent to the browser?
I would rather not use a wrapper function (or object) around the header method, or otherwise set some global variable along with the sending of the status code. I'd also rather not call my code from itself using curl or the like, due to performance concerns. Please let me know what you think. | 2010/01/08 | [
"https://Stackoverflow.com/questions/2030910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/118153/"
] | [`http_response_code()`](http://php.net/manual/en/function.http-response-code.php) in PHP 5.4 does this now. | It's another call, but as a last resort you could use this rather than curl. If you have php 5.0, What about [get\_headers()](http://us.php.net/manual/en/function.get-headers.php)? |
2,030,910 | I am sending a status code via the header function, such as `header('HTTP/1.1 403');`, and would like to in another area of my code detect what status code is to be sent (in particular if I have sent an error code of some nature). As has been mentioned [elsewhere](https://stackoverflow.com/questions/1798353/determine-the-http-status-that-will-be-sent-in-php), `headers_list()` does not return this particular item, and it's unclear to me if it actually counts as a header, as neither Firebug nor Fiddler2 treat it with the headers. So - how can a PHP script detect which status code is about to be sent to the browser?
I would rather not use a wrapper function (or object) around the header method, or otherwise set some global variable along with the sending of the status code. I'd also rather not call my code from itself using curl or the like, due to performance concerns. Please let me know what you think. | 2010/01/08 | [
"https://Stackoverflow.com/questions/2030910",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/118153/"
] | Consider setting a constant:
```
define('HTTP_STATUS', 403);
```
and using the `defined` function later on:
```
if(defined('HTTP_STATUS') && HTTP_STATUS == 403) // ...or whatever you're looking to do
```
Actually peeking back at the headers themselves is kind of a hack in itself as it's simply too slow: you're dealing with strings and arrays and all sorts of other messy data. Set for yourself a simple constant: it's blazing fast, it does the same thing, and it doesn't create any "true" global variables. | [`http_response_code()`](http://php.net/manual/en/function.http-response-code.php) in PHP 5.4 does this now. |
696,208 | learning QM and just have a few questions regarding normalizing wavefunctions.
1. Thus far, every initial wavefunction that we've normalized has had an undefined constant explicitly put out front (i.e., something like $\Psi (x,0) = A(a - x^{2})$, as an example) I was recently asked to normalize a wavefunction that didn't have any undetermined constant out front of the function involving x. Now it's okay for me to multiply the undefined constant, say $A$, to the wavefunction? Since, of course, the purpose of normalizing the wavefunction is finding a form such that the probability is 1 over all space.
2. If I'm given a complete wavefunction (i.e., a solution to the time dependent Schrodinger equation - $\Psi(x,t) = \psi(x)\phi(t)$ I can just perform the normalization at $t=0$ right? In other words, normalize the initial wavefunction $\Psi(x,0) = \psi(x)\phi(0)$. Since once a wavefunction is normalized, it remains normalized for all time, correct? Or do I need to perform the normalization at arbitrary time $t$ if given the complete wavefunction?
3. If I've just normalized a wavefunction and am determining the constant $A$ but have $|A|^{2}$ = $K$ where $K$ is just some constant then I necessarily have $A$ = $\pm\sqrt{K}$ but the problem makes no mention of the nature of the constant (i.e., doesn't say anything like "where $A,a,b,$ etc... are all positive real constants) then how am I to determine the sign of $A$? Does it even matter? I imagine it wouldn't in the verification of the normalization but it would change the sign of the wavefunction, so it must have some importance?
4. If I get a wavefunction such that $|\Psi(x,0)|^{2} = 1$ would that tell me that this wavefunction is non-normalizable? Since the integral doesn't converge. | 2022/02/23 | [
"https://physics.stackexchange.com/questions/696208",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/152819/"
] | 1. Yes. Normalizing the wavefunction means multiplying it by whatever constant you need to in order to make its norm equal to $1$.
2. Yes, because time evolution in quantum mechanics is *unitary* - in other words, you can write $\psi(t) = \hat U(t) \psi(0)$ for a unitary operator $\hat U(t)$ called the *propagator*, and $\Vert \hat U \psi\Vert = \Vert \psi\Vert $ for all unitary operators $\hat U$. Caveat: this is no longer true if you perform a measurement, in which case your wavefunction will undergo (non-unitary) projective evolution and you may need to renormalize afterward.
3. If $|A|^2 = K$, then $A=e^{i\theta} \sqrt{K}$ for any arbitrary phase angle $\theta\in[0,2\pi)$. You may make any choice you want, and it will not impact any physically meaningful predictions of the theory. Perhaps you could check to see whether multiplying the wave function by some $e^{i\theta}$ changes e.g. the probabilities of any measurement outcomes. | 1. yes
2. yes
3. the constant is determined up to an arbitrary phase. Remember that this is also the case for the wave function. |
696,208 | learning QM and just have a few questions regarding normalizing wavefunctions.
1. Thus far, every initial wavefunction that we've normalized has had an undefined constant explicitly put out front (i.e., something like $\Psi (x,0) = A(a - x^{2})$, as an example) I was recently asked to normalize a wavefunction that didn't have any undetermined constant out front of the function involving x. Now it's okay for me to multiply the undefined constant, say $A$, to the wavefunction? Since, of course, the purpose of normalizing the wavefunction is finding a form such that the probability is 1 over all space.
2. If I'm given a complete wavefunction (i.e., a solution to the time dependent Schrodinger equation - $\Psi(x,t) = \psi(x)\phi(t)$ I can just perform the normalization at $t=0$ right? In other words, normalize the initial wavefunction $\Psi(x,0) = \psi(x)\phi(0)$. Since once a wavefunction is normalized, it remains normalized for all time, correct? Or do I need to perform the normalization at arbitrary time $t$ if given the complete wavefunction?
3. If I've just normalized a wavefunction and am determining the constant $A$ but have $|A|^{2}$ = $K$ where $K$ is just some constant then I necessarily have $A$ = $\pm\sqrt{K}$ but the problem makes no mention of the nature of the constant (i.e., doesn't say anything like "where $A,a,b,$ etc... are all positive real constants) then how am I to determine the sign of $A$? Does it even matter? I imagine it wouldn't in the verification of the normalization but it would change the sign of the wavefunction, so it must have some importance?
4. If I get a wavefunction such that $|\Psi(x,0)|^{2} = 1$ would that tell me that this wavefunction is non-normalizable? Since the integral doesn't converge. | 2022/02/23 | [
"https://physics.stackexchange.com/questions/696208",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/152819/"
] | 1. yes
2. yes
3. the constant is determined up to an arbitrary phase. Remember that this is also the case for the wave function. | Since people had already answered correctly questions 1 and 2, I'd like to answer/point some details as for 3 and 4:
3. It is a postulate in quantum mechanics that the states of a (quantum) dynamical system are in one-to-one correspondence with some complex projective Hilbert space, then yes, the sign of your normalization doesn't matter, nor a complex phase (a unit modulus complex number), not even you need to normalize the wavefunction at first place (this would mean you have to take the adequate care when computing things such as operator's expectation values, projected states after measurement/collapse etc.). The reason why one computes normalizations is because it makes further calculations "cleaner".
4. The complex projective Hilbert space after which we usually model our (quantum) dynamical system is the projective space of $L^2(V)$, where $V \subseteq \mathbb{R}$ (in order to allow every momenta value to be a possible eigenstate of the Hamiltonian). So, if for any reason $V$ happens to be compact, then your function is square-integrable. |
696,208 | learning QM and just have a few questions regarding normalizing wavefunctions.
1. Thus far, every initial wavefunction that we've normalized has had an undefined constant explicitly put out front (i.e., something like $\Psi (x,0) = A(a - x^{2})$, as an example) I was recently asked to normalize a wavefunction that didn't have any undetermined constant out front of the function involving x. Now it's okay for me to multiply the undefined constant, say $A$, to the wavefunction? Since, of course, the purpose of normalizing the wavefunction is finding a form such that the probability is 1 over all space.
2. If I'm given a complete wavefunction (i.e., a solution to the time dependent Schrodinger equation - $\Psi(x,t) = \psi(x)\phi(t)$ I can just perform the normalization at $t=0$ right? In other words, normalize the initial wavefunction $\Psi(x,0) = \psi(x)\phi(0)$. Since once a wavefunction is normalized, it remains normalized for all time, correct? Or do I need to perform the normalization at arbitrary time $t$ if given the complete wavefunction?
3. If I've just normalized a wavefunction and am determining the constant $A$ but have $|A|^{2}$ = $K$ where $K$ is just some constant then I necessarily have $A$ = $\pm\sqrt{K}$ but the problem makes no mention of the nature of the constant (i.e., doesn't say anything like "where $A,a,b,$ etc... are all positive real constants) then how am I to determine the sign of $A$? Does it even matter? I imagine it wouldn't in the verification of the normalization but it would change the sign of the wavefunction, so it must have some importance?
4. If I get a wavefunction such that $|\Psi(x,0)|^{2} = 1$ would that tell me that this wavefunction is non-normalizable? Since the integral doesn't converge. | 2022/02/23 | [
"https://physics.stackexchange.com/questions/696208",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/152819/"
] | 1. Yes. Normalizing the wavefunction means multiplying it by whatever constant you need to in order to make its norm equal to $1$.
2. Yes, because time evolution in quantum mechanics is *unitary* - in other words, you can write $\psi(t) = \hat U(t) \psi(0)$ for a unitary operator $\hat U(t)$ called the *propagator*, and $\Vert \hat U \psi\Vert = \Vert \psi\Vert $ for all unitary operators $\hat U$. Caveat: this is no longer true if you perform a measurement, in which case your wavefunction will undergo (non-unitary) projective evolution and you may need to renormalize afterward.
3. If $|A|^2 = K$, then $A=e^{i\theta} \sqrt{K}$ for any arbitrary phase angle $\theta\in[0,2\pi)$. You may make any choice you want, and it will not impact any physically meaningful predictions of the theory. Perhaps you could check to see whether multiplying the wave function by some $e^{i\theta}$ changes e.g. the probabilities of any measurement outcomes. | Since people had already answered correctly questions 1 and 2, I'd like to answer/point some details as for 3 and 4:
3. It is a postulate in quantum mechanics that the states of a (quantum) dynamical system are in one-to-one correspondence with some complex projective Hilbert space, then yes, the sign of your normalization doesn't matter, nor a complex phase (a unit modulus complex number), not even you need to normalize the wavefunction at first place (this would mean you have to take the adequate care when computing things such as operator's expectation values, projected states after measurement/collapse etc.). The reason why one computes normalizations is because it makes further calculations "cleaner".
4. The complex projective Hilbert space after which we usually model our (quantum) dynamical system is the projective space of $L^2(V)$, where $V \subseteq \mathbb{R}$ (in order to allow every momenta value to be a possible eigenstate of the Hamiltonian). So, if for any reason $V$ happens to be compact, then your function is square-integrable. |
16,049,330 | I am attempting to store css files inside database and call them in the most effective wa using PHP. I know I can include a style.php file and just do a query to get the data; however, not sure if that is the best way or not. I'd prefer to not have
```
<style>
#blah { }
#blah 2 { }
etc.
</style>
```
show up on every page. I am attempting to make this work similar to how a typical css file would work where it is just a link similar to the way it is below. I have read about people using
html page:
```
<link rel="stylesheet" type="text/css" href="style.php" />
```
style.php page:
```
header("Content-Type: text/css");
```
however, have also seen that that doesn't work well with IE.
So does anyone have any recommendations on how I can do this in the best way for all browsers? | 2013/04/17 | [
"https://Stackoverflow.com/questions/16049330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2200549/"
] | I'd probably write a tiny wrapper class for each:
```
template <class T>
class read_only {
T volatile *addr;
public:
read_only(int address) : addr((T *)address) {}
operator T() volatile const { return *addr; }
};
template <class T>
class write_only {
T volatile *addr;
public:
write_only(int address) : addr ((T *)address) {}
// chaining not allowed since it's write only.
void operator=(T const &t) volatile { *addr = t; }
};
```
At least assuming your system has a reasonable compiler, I'd expect both of these to be optimized so the generated code was indistinguishable from using a raw pointer. Usage:
```
read_only<unsigned char> x(0x1234);
write_only<unsigned char> y(0x1235);
y = x + 1; // No problem
x = y; // won't compile
``` | I would use a combination of structs to rappresent the register and a pair of functions to handle them.
In a `fpga_register.h` you would have something like
```
#define FPGA_READ = 1;
#define FPGA_WRITE = 2;
typedef struct register_t {
char permissions;
} FPGARegister;
FPGARegister* fpga_init(void* address, char permissions);
int fpga_write(FPGARegister* register, void* value);
int fpga_read(FPGARegister* register, void* value);
```
with READ and WRITE in xor to express permissions.
Than in the `fpga_register.c` you would define a new struct
```
typedef struct register_t2 {
char permissions;
void * address;
} FPGARegisterReal;
```
so that you returns a pointer to it instead of a pointer to `FPGARegister` on `fpga_init`.
Then, on `fpga_read` and `fpga_write` you check the permissions and
* if the operetion is allowed, cast back the `FPGARegister` from the argument to a `FPGARegisterReal`, execute the desired action (set or read the value) and return a success code
* if the operation is not allowed, just return an error code
This way, no one including the header file will be able to access the `FPGARegisterReal` structure, and thus it will not have direct access to the register address. Obviously, one could hack it, but I'm quite sure that such intentional hacks are not your actual concerns. |
16,049,330 | I am attempting to store css files inside database and call them in the most effective wa using PHP. I know I can include a style.php file and just do a query to get the data; however, not sure if that is the best way or not. I'd prefer to not have
```
<style>
#blah { }
#blah 2 { }
etc.
</style>
```
show up on every page. I am attempting to make this work similar to how a typical css file would work where it is just a link similar to the way it is below. I have read about people using
html page:
```
<link rel="stylesheet" type="text/css" href="style.php" />
```
style.php page:
```
header("Content-Type: text/css");
```
however, have also seen that that doesn't work well with IE.
So does anyone have any recommendations on how I can do this in the best way for all browsers? | 2013/04/17 | [
"https://Stackoverflow.com/questions/16049330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2200549/"
] | I'd probably write a tiny wrapper class for each:
```
template <class T>
class read_only {
T volatile *addr;
public:
read_only(int address) : addr((T *)address) {}
operator T() volatile const { return *addr; }
};
template <class T>
class write_only {
T volatile *addr;
public:
write_only(int address) : addr ((T *)address) {}
// chaining not allowed since it's write only.
void operator=(T const &t) volatile { *addr = t; }
};
```
At least assuming your system has a reasonable compiler, I'd expect both of these to be optimized so the generated code was indistinguishable from using a raw pointer. Usage:
```
read_only<unsigned char> x(0x1234);
write_only<unsigned char> y(0x1235);
y = x + 1; // No problem
x = y; // won't compile
``` | I've worked with a lot of hardware, and some of which has "read only" or "write only" registers (or different functions depending on whether you read or write to the register, which makes for fun when someone decides to do "reg |= 4;" instead of remembering the value it should have, set bit 2 and write the new value, like you should. Nothing like trying to debug hardware that has random bits appearing and disappearing from registers you can't read! ;) I have so far not seen any attempts of actually blocking reads from a write-only register, or writes to read-only registers.
By the way, did I say that having registers that are "write only" is a REALLY bad idea, because you can't read back to check if the software has set the register correctly, which makes debugging really hard - and people writing drivers don't like debugging hard problems that could be made really easy by two lines of VHDL or Verilog code.
If you have some control over the register layout, I would suggest that you put "readonly" registers at a 4KB-aligned address, and "writeonly" registers in another 4KB-aligned address [more than 4KB is fine]. Then you can program the memory controller of the hardware to prevent the access.
Or, let the hardware produce an interrupt if registers that aren't supposed to be read are being read, or registers that aren't supposed to be written are written. I presume the hardware does produce interrupts for other purposes?
The other suggestions made using various C++ solutions are fine, but it doesn't really stop someone who is intent on using the registers directly, so if it's really a safety concern (rather than "let's make it awkward"), then you should have hardware to protect against the misuse of the hardware. |
16,049,330 | I am attempting to store css files inside database and call them in the most effective wa using PHP. I know I can include a style.php file and just do a query to get the data; however, not sure if that is the best way or not. I'd prefer to not have
```
<style>
#blah { }
#blah 2 { }
etc.
</style>
```
show up on every page. I am attempting to make this work similar to how a typical css file would work where it is just a link similar to the way it is below. I have read about people using
html page:
```
<link rel="stylesheet" type="text/css" href="style.php" />
```
style.php page:
```
header("Content-Type: text/css");
```
however, have also seen that that doesn't work well with IE.
So does anyone have any recommendations on how I can do this in the best way for all browsers? | 2013/04/17 | [
"https://Stackoverflow.com/questions/16049330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2200549/"
] | I'd probably write a tiny wrapper class for each:
```
template <class T>
class read_only {
T volatile *addr;
public:
read_only(int address) : addr((T *)address) {}
operator T() volatile const { return *addr; }
};
template <class T>
class write_only {
T volatile *addr;
public:
write_only(int address) : addr ((T *)address) {}
// chaining not allowed since it's write only.
void operator=(T const &t) volatile { *addr = t; }
};
```
At least assuming your system has a reasonable compiler, I'd expect both of these to be optimized so the generated code was indistinguishable from using a raw pointer. Usage:
```
read_only<unsigned char> x(0x1234);
write_only<unsigned char> y(0x1235);
y = x + 1; // No problem
x = y; // won't compile
``` | I see no elegant way of doing it in C. I do however see a way of doing it:
```
#define DEREF_PTR(type, ptr) type ptr; \
typedef char ptr ## _DEREF_PTR;
#define NO_DEREF_PTR(type, ptr) type ptr; \
#define DEREFERENCE(ptr) \
*ptr; \
{ptr ## _DEREF_PTR \
attempt_to_dereference_pointer_ ## ptr;}
int main(int argc, char *argv[]) {
DEREF_PTR(int*, x)
NO_DEREF_PTR(int*, y);
DEREFERENCE(x);
DEREFERENCE(y); // will throw an error
}
```
This has the benefit of giving you static error checking. Of course, using this method, you'll have to go out and modify all of your pointer declarations to use macros, which is probably not a whole lot of fun.
**Edit:**
As described in the comments.
```
#define READABLE_PTR(type, ptr) type ptr; \
typedef char ptr ## _READABLE_PTR;
#define NON_READABLE_PTR(type, ptr) type ptr; \
#define GET(ptr) \
*ptr; \
{ptr ## _READABLE_PTR \
attempt_to_dereference_non_readable_pointer_ ## ptr;}
#define SET(ptr, value) \
*ptr = value;
int main(int argc, char *argv[]) {
READABLE_PTR(int*, x)
NON_READABLE_PTR(int*, y);
SET(x, 1);
SET(y, 1);
int foo = GET(x);
int bar = GET(y); // error
}
``` |
16,049,330 | I am attempting to store css files inside database and call them in the most effective wa using PHP. I know I can include a style.php file and just do a query to get the data; however, not sure if that is the best way or not. I'd prefer to not have
```
<style>
#blah { }
#blah 2 { }
etc.
</style>
```
show up on every page. I am attempting to make this work similar to how a typical css file would work where it is just a link similar to the way it is below. I have read about people using
html page:
```
<link rel="stylesheet" type="text/css" href="style.php" />
```
style.php page:
```
header("Content-Type: text/css");
```
however, have also seen that that doesn't work well with IE.
So does anyone have any recommendations on how I can do this in the best way for all browsers? | 2013/04/17 | [
"https://Stackoverflow.com/questions/16049330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2200549/"
] | I'd probably write a tiny wrapper class for each:
```
template <class T>
class read_only {
T volatile *addr;
public:
read_only(int address) : addr((T *)address) {}
operator T() volatile const { return *addr; }
};
template <class T>
class write_only {
T volatile *addr;
public:
write_only(int address) : addr ((T *)address) {}
// chaining not allowed since it's write only.
void operator=(T const &t) volatile { *addr = t; }
};
```
At least assuming your system has a reasonable compiler, I'd expect both of these to be optimized so the generated code was indistinguishable from using a raw pointer. Usage:
```
read_only<unsigned char> x(0x1234);
write_only<unsigned char> y(0x1235);
y = x + 1; // No problem
x = y; // won't compile
``` | In C, you can use pointers to incomplete types to prevent all dereferencing:
---
```
/* writeonly.h */
typedef struct writeonly *wo_ptr_t;
```
---
```
/* writeonly.c */
#include "writeonly.h"
struct writeonly {
int value
};
/*...*/
FOO_REGISTER->value = 42;
```
---
```
/* someother.c */
#include "writeonly.h"
/*...*/
int x = FOO_REGISTER->value; /* error: deref'ing pointer to incomplete type */
```
---
Only `writeonly.c`, or in general any code that has a definition `struct writeonly`, can dereference the pointer. That code, of course, can accidentally read the value also, but at least all other code is prevented from dereferencing the pointers all together, while being able to pass those pointers around and store them in variables, arrays and structures.
`writeonly.[ch]` could provide a function for writing a value. |
16,049,330 | I am attempting to store css files inside database and call them in the most effective wa using PHP. I know I can include a style.php file and just do a query to get the data; however, not sure if that is the best way or not. I'd prefer to not have
```
<style>
#blah { }
#blah 2 { }
etc.
</style>
```
show up on every page. I am attempting to make this work similar to how a typical css file would work where it is just a link similar to the way it is below. I have read about people using
html page:
```
<link rel="stylesheet" type="text/css" href="style.php" />
```
style.php page:
```
header("Content-Type: text/css");
```
however, have also seen that that doesn't work well with IE.
So does anyone have any recommendations on how I can do this in the best way for all browsers? | 2013/04/17 | [
"https://Stackoverflow.com/questions/16049330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2200549/"
] | I'd probably write a tiny wrapper class for each:
```
template <class T>
class read_only {
T volatile *addr;
public:
read_only(int address) : addr((T *)address) {}
operator T() volatile const { return *addr; }
};
template <class T>
class write_only {
T volatile *addr;
public:
write_only(int address) : addr ((T *)address) {}
// chaining not allowed since it's write only.
void operator=(T const &t) volatile { *addr = t; }
};
```
At least assuming your system has a reasonable compiler, I'd expect both of these to be optimized so the generated code was indistinguishable from using a raw pointer. Usage:
```
read_only<unsigned char> x(0x1234);
write_only<unsigned char> y(0x1235);
y = x + 1; // No problem
x = y; // won't compile
``` | Dan Saks has a Youtube presentation, that I couldn't, find where he introduces write-only registers for embedded devices.
Fortunately he wrote an article, that was easier to search, here: <https://www.embedded.com/how-to-enforce-write-only-access/>
This is the code from the article, updated for C++11
```
class write_only_T{
public:
write_only_T(){}
write_only_T(T const& v) : m(v){}
write_only_T(T&& v) : m(std::move(v)){}
write_only_T& operator=(T const& v){
m = v;
return *this;
}
write_only_T& operator=(T&& v){
m = std::move(v);
return *this;
}
write_only_T(write_only_T const&) = delete;
write_only_T(write_only_T&&) = delete;
write_only_T& operator=(write_only_T const&) = delete;
write_only_T& operator=(write_only_T&&) = delete;
private:
T m;
};
```
I don't think you need a special pointer type if you used this because write-only is a property of the value, but I can imagine a synthetic pointer-type that skips the value type.
Likely you will need to introduce a write-only reference-type and so on. |
16,049,330 | I am attempting to store css files inside database and call them in the most effective wa using PHP. I know I can include a style.php file and just do a query to get the data; however, not sure if that is the best way or not. I'd prefer to not have
```
<style>
#blah { }
#blah 2 { }
etc.
</style>
```
show up on every page. I am attempting to make this work similar to how a typical css file would work where it is just a link similar to the way it is below. I have read about people using
html page:
```
<link rel="stylesheet" type="text/css" href="style.php" />
```
style.php page:
```
header("Content-Type: text/css");
```
however, have also seen that that doesn't work well with IE.
So does anyone have any recommendations on how I can do this in the best way for all browsers? | 2013/04/17 | [
"https://Stackoverflow.com/questions/16049330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2200549/"
] | I would use a combination of structs to rappresent the register and a pair of functions to handle them.
In a `fpga_register.h` you would have something like
```
#define FPGA_READ = 1;
#define FPGA_WRITE = 2;
typedef struct register_t {
char permissions;
} FPGARegister;
FPGARegister* fpga_init(void* address, char permissions);
int fpga_write(FPGARegister* register, void* value);
int fpga_read(FPGARegister* register, void* value);
```
with READ and WRITE in xor to express permissions.
Than in the `fpga_register.c` you would define a new struct
```
typedef struct register_t2 {
char permissions;
void * address;
} FPGARegisterReal;
```
so that you returns a pointer to it instead of a pointer to `FPGARegister` on `fpga_init`.
Then, on `fpga_read` and `fpga_write` you check the permissions and
* if the operetion is allowed, cast back the `FPGARegister` from the argument to a `FPGARegisterReal`, execute the desired action (set or read the value) and return a success code
* if the operation is not allowed, just return an error code
This way, no one including the header file will be able to access the `FPGARegisterReal` structure, and thus it will not have direct access to the register address. Obviously, one could hack it, but I'm quite sure that such intentional hacks are not your actual concerns. | Dan Saks has a Youtube presentation, that I couldn't, find where he introduces write-only registers for embedded devices.
Fortunately he wrote an article, that was easier to search, here: <https://www.embedded.com/how-to-enforce-write-only-access/>
This is the code from the article, updated for C++11
```
class write_only_T{
public:
write_only_T(){}
write_only_T(T const& v) : m(v){}
write_only_T(T&& v) : m(std::move(v)){}
write_only_T& operator=(T const& v){
m = v;
return *this;
}
write_only_T& operator=(T&& v){
m = std::move(v);
return *this;
}
write_only_T(write_only_T const&) = delete;
write_only_T(write_only_T&&) = delete;
write_only_T& operator=(write_only_T const&) = delete;
write_only_T& operator=(write_only_T&&) = delete;
private:
T m;
};
```
I don't think you need a special pointer type if you used this because write-only is a property of the value, but I can imagine a synthetic pointer-type that skips the value type.
Likely you will need to introduce a write-only reference-type and so on. |
16,049,330 | I am attempting to store css files inside database and call them in the most effective wa using PHP. I know I can include a style.php file and just do a query to get the data; however, not sure if that is the best way or not. I'd prefer to not have
```
<style>
#blah { }
#blah 2 { }
etc.
</style>
```
show up on every page. I am attempting to make this work similar to how a typical css file would work where it is just a link similar to the way it is below. I have read about people using
html page:
```
<link rel="stylesheet" type="text/css" href="style.php" />
```
style.php page:
```
header("Content-Type: text/css");
```
however, have also seen that that doesn't work well with IE.
So does anyone have any recommendations on how I can do this in the best way for all browsers? | 2013/04/17 | [
"https://Stackoverflow.com/questions/16049330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2200549/"
] | I've worked with a lot of hardware, and some of which has "read only" or "write only" registers (or different functions depending on whether you read or write to the register, which makes for fun when someone decides to do "reg |= 4;" instead of remembering the value it should have, set bit 2 and write the new value, like you should. Nothing like trying to debug hardware that has random bits appearing and disappearing from registers you can't read! ;) I have so far not seen any attempts of actually blocking reads from a write-only register, or writes to read-only registers.
By the way, did I say that having registers that are "write only" is a REALLY bad idea, because you can't read back to check if the software has set the register correctly, which makes debugging really hard - and people writing drivers don't like debugging hard problems that could be made really easy by two lines of VHDL or Verilog code.
If you have some control over the register layout, I would suggest that you put "readonly" registers at a 4KB-aligned address, and "writeonly" registers in another 4KB-aligned address [more than 4KB is fine]. Then you can program the memory controller of the hardware to prevent the access.
Or, let the hardware produce an interrupt if registers that aren't supposed to be read are being read, or registers that aren't supposed to be written are written. I presume the hardware does produce interrupts for other purposes?
The other suggestions made using various C++ solutions are fine, but it doesn't really stop someone who is intent on using the registers directly, so if it's really a safety concern (rather than "let's make it awkward"), then you should have hardware to protect against the misuse of the hardware. | Dan Saks has a Youtube presentation, that I couldn't, find where he introduces write-only registers for embedded devices.
Fortunately he wrote an article, that was easier to search, here: <https://www.embedded.com/how-to-enforce-write-only-access/>
This is the code from the article, updated for C++11
```
class write_only_T{
public:
write_only_T(){}
write_only_T(T const& v) : m(v){}
write_only_T(T&& v) : m(std::move(v)){}
write_only_T& operator=(T const& v){
m = v;
return *this;
}
write_only_T& operator=(T&& v){
m = std::move(v);
return *this;
}
write_only_T(write_only_T const&) = delete;
write_only_T(write_only_T&&) = delete;
write_only_T& operator=(write_only_T const&) = delete;
write_only_T& operator=(write_only_T&&) = delete;
private:
T m;
};
```
I don't think you need a special pointer type if you used this because write-only is a property of the value, but I can imagine a synthetic pointer-type that skips the value type.
Likely you will need to introduce a write-only reference-type and so on. |
16,049,330 | I am attempting to store css files inside database and call them in the most effective wa using PHP. I know I can include a style.php file and just do a query to get the data; however, not sure if that is the best way or not. I'd prefer to not have
```
<style>
#blah { }
#blah 2 { }
etc.
</style>
```
show up on every page. I am attempting to make this work similar to how a typical css file would work where it is just a link similar to the way it is below. I have read about people using
html page:
```
<link rel="stylesheet" type="text/css" href="style.php" />
```
style.php page:
```
header("Content-Type: text/css");
```
however, have also seen that that doesn't work well with IE.
So does anyone have any recommendations on how I can do this in the best way for all browsers? | 2013/04/17 | [
"https://Stackoverflow.com/questions/16049330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2200549/"
] | I see no elegant way of doing it in C. I do however see a way of doing it:
```
#define DEREF_PTR(type, ptr) type ptr; \
typedef char ptr ## _DEREF_PTR;
#define NO_DEREF_PTR(type, ptr) type ptr; \
#define DEREFERENCE(ptr) \
*ptr; \
{ptr ## _DEREF_PTR \
attempt_to_dereference_pointer_ ## ptr;}
int main(int argc, char *argv[]) {
DEREF_PTR(int*, x)
NO_DEREF_PTR(int*, y);
DEREFERENCE(x);
DEREFERENCE(y); // will throw an error
}
```
This has the benefit of giving you static error checking. Of course, using this method, you'll have to go out and modify all of your pointer declarations to use macros, which is probably not a whole lot of fun.
**Edit:**
As described in the comments.
```
#define READABLE_PTR(type, ptr) type ptr; \
typedef char ptr ## _READABLE_PTR;
#define NON_READABLE_PTR(type, ptr) type ptr; \
#define GET(ptr) \
*ptr; \
{ptr ## _READABLE_PTR \
attempt_to_dereference_non_readable_pointer_ ## ptr;}
#define SET(ptr, value) \
*ptr = value;
int main(int argc, char *argv[]) {
READABLE_PTR(int*, x)
NON_READABLE_PTR(int*, y);
SET(x, 1);
SET(y, 1);
int foo = GET(x);
int bar = GET(y); // error
}
``` | Dan Saks has a Youtube presentation, that I couldn't, find where he introduces write-only registers for embedded devices.
Fortunately he wrote an article, that was easier to search, here: <https://www.embedded.com/how-to-enforce-write-only-access/>
This is the code from the article, updated for C++11
```
class write_only_T{
public:
write_only_T(){}
write_only_T(T const& v) : m(v){}
write_only_T(T&& v) : m(std::move(v)){}
write_only_T& operator=(T const& v){
m = v;
return *this;
}
write_only_T& operator=(T&& v){
m = std::move(v);
return *this;
}
write_only_T(write_only_T const&) = delete;
write_only_T(write_only_T&&) = delete;
write_only_T& operator=(write_only_T const&) = delete;
write_only_T& operator=(write_only_T&&) = delete;
private:
T m;
};
```
I don't think you need a special pointer type if you used this because write-only is a property of the value, but I can imagine a synthetic pointer-type that skips the value type.
Likely you will need to introduce a write-only reference-type and so on. |
16,049,330 | I am attempting to store css files inside database and call them in the most effective wa using PHP. I know I can include a style.php file and just do a query to get the data; however, not sure if that is the best way or not. I'd prefer to not have
```
<style>
#blah { }
#blah 2 { }
etc.
</style>
```
show up on every page. I am attempting to make this work similar to how a typical css file would work where it is just a link similar to the way it is below. I have read about people using
html page:
```
<link rel="stylesheet" type="text/css" href="style.php" />
```
style.php page:
```
header("Content-Type: text/css");
```
however, have also seen that that doesn't work well with IE.
So does anyone have any recommendations on how I can do this in the best way for all browsers? | 2013/04/17 | [
"https://Stackoverflow.com/questions/16049330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2200549/"
] | In C, you can use pointers to incomplete types to prevent all dereferencing:
---
```
/* writeonly.h */
typedef struct writeonly *wo_ptr_t;
```
---
```
/* writeonly.c */
#include "writeonly.h"
struct writeonly {
int value
};
/*...*/
FOO_REGISTER->value = 42;
```
---
```
/* someother.c */
#include "writeonly.h"
/*...*/
int x = FOO_REGISTER->value; /* error: deref'ing pointer to incomplete type */
```
---
Only `writeonly.c`, or in general any code that has a definition `struct writeonly`, can dereference the pointer. That code, of course, can accidentally read the value also, but at least all other code is prevented from dereferencing the pointers all together, while being able to pass those pointers around and store them in variables, arrays and structures.
`writeonly.[ch]` could provide a function for writing a value. | Dan Saks has a Youtube presentation, that I couldn't, find where he introduces write-only registers for embedded devices.
Fortunately he wrote an article, that was easier to search, here: <https://www.embedded.com/how-to-enforce-write-only-access/>
This is the code from the article, updated for C++11
```
class write_only_T{
public:
write_only_T(){}
write_only_T(T const& v) : m(v){}
write_only_T(T&& v) : m(std::move(v)){}
write_only_T& operator=(T const& v){
m = v;
return *this;
}
write_only_T& operator=(T&& v){
m = std::move(v);
return *this;
}
write_only_T(write_only_T const&) = delete;
write_only_T(write_only_T&&) = delete;
write_only_T& operator=(write_only_T const&) = delete;
write_only_T& operator=(write_only_T&&) = delete;
private:
T m;
};
```
I don't think you need a special pointer type if you used this because write-only is a property of the value, but I can imagine a synthetic pointer-type that skips the value type.
Likely you will need to introduce a write-only reference-type and so on. |
17,316,183 | I want to start and stop service when device in action call, so i use TelephonyManager and my class extends flagment. i Tried this code
```
TelephonyManager tm = (TelephonyManager)getActivity().getSystemService(Context.TELEPHONY_SERVICE);
tm.listen(mPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
private PhoneStateListener mPhoneListener = new PhoneStateListener() {
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
getActivity().stopService(new Intent(getActivity(),LockScreenService.class));
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
getActivity().stopService(new Intent(getActivity(),LockScreenService.class));
break;
case TelephonyManager.CALL_STATE_IDLE:
getActivity().startService(new Intent(getActivity(),LockScreenService.class));
break;
}
}
}
;
```
but it does not work. Please give me some advises. Thanks so much | 2013/06/26 | [
"https://Stackoverflow.com/questions/17316183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2503313/"
] | Try this code:
```
telephonyManager = ( TelephonyManager )getActivity.getSystemService( Context.TELEPHONY_SERVICE );
imeistring = telephonyManager.getDeviceId();
``` | use Telephony manager inside your oncreate view |
693,174 | I know its possible to integrate jQuery within Firefox addons, but are we able to manipulate (animate, move, adjust transparency, etc) XUL elements themselves?
From what I understand, the Firefox addon can use jQuery to manipulate HTML/DOM elements, but not sure about XUL elements. | 2009/03/28 | [
"https://Stackoverflow.com/questions/693174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/84047/"
] | I was wondering this myself recently. Obviously the DHTML doesn't make sense, but the basic syntactic sugar and things are rumored to work.
* There is this [jQuery on XUL](http://groups.google.com/group/jquery-dev/browse_thread/thread/4545040bf26c6eea?pli=1) discussion from the jQuery group which indicates that it loads up with some exceptions.
* Also see this slightly more recent blog post about [jQuery and DHTML in XUL](http://digitalmihailo.blogspot.com/2008/05/jquery-and-dynamic-html-in-xul.html). That person is going after the HTML within the XUL which is not exactly what you need but he does have good information. | The answer right now is "mostly".
Basic stuff works, including selecting, deleting and finding. I use 1.5.2 pretty heavily both inside an extension and on content pages from the extension.
$.ready() also doesn't work because jQuery assumes and waits for a body. This is the [commit](https://github.com/jquery/jquery/commit/262fcf7b7b919da1564509f621cf7480a5d5572b) that broke it.
Some stuff doesn't work because, as @Daniel describes, jQuery's doesn't properly detect what it can and can't do in XUL (more background below). From stepping through jQuery code I have have found you need at least the following lines in your own code.
```
// Workarounds for jQuery not properly testing support in XUL environment
// These are done at jQuery init
// This is actually critical, otherwise elements are not properly removed from the cache and you get a cache[id] is undefined
crowdmash.$.support.deleteExpando = true;
// These are done at ready(), but jQuery never fires ready in XUL
// XUL doesn't seem to support offsetWidth and offsetHeight (without this :hidden is broken which breaks fadeIn)
crowdmash.$.support.reliableHiddenOffsets = false;
crowdmash.$.support.opacity = true;
```
If you want to use jQuery on a content page from an extension, see my [tips](http://forums.mozillazine.org/viewtopic.php?f=19&t=2105087).
[jquery-xul](https://github.com/ilyakharlamov/jquery-xul/wiki) modifies 1.4.4 to better work with XUL. I have not tried it yet, but from looking at its changes it does look like fixes the ready issue. I don't know if it fixes the support issue .
As background on the $.support issue. The problem is that jQuery's feature detection creates a and then populates it using innerHTML. XUL divs do not support innerHTML, so the support code fails marking nothing as supported. There is actually a ticket on this that is open and being discussed for 1.7 - <http://bugs.jquery.com/ticket/5206>. |
693,174 | I know its possible to integrate jQuery within Firefox addons, but are we able to manipulate (animate, move, adjust transparency, etc) XUL elements themselves?
From what I understand, the Firefox addon can use jQuery to manipulate HTML/DOM elements, but not sure about XUL elements. | 2009/03/28 | [
"https://Stackoverflow.com/questions/693174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/84047/"
] | ***Short answer:*** Yes
***Long Answer:***
I experimented with it myself. I could only use it in a limited way. Manipulation of XUL elements is possible. But I am having a hard time observing events, since I am pretty new to jQuery - I don't know how to tweak it to observe events at Firefox/XUL level - I don't even know whether tweaking is required :D
***Example:***
**overlay.xul**
```
<?xml version="1.0"?>
<?xml-stylesheet href="chrome://testaddon/content/overlay.css" type="text/css"?>
<overlay id="testaddon_overlay"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
xmlns:html="http://www.w3.org/1999/xhtml">
<script type="application/x-javascript" src="chrome://testaddon/content/jquery-1.4.2.js" />
<script type="application/x-javascript" src="chrome://testaddon/content/overlay.js" />
<toolbox id="navigator-toolbox">
<toolbar toolbarname="TestAddonToolbar" class="chromeclass-toolbar">
<toolbaritem>
<toolbarbutton id="btnHide" label="HideMe" onclick="hideMe();" />
</toolbaritem>
</toolbar>
</toolbox>
</overlay>
```
**overlay.js**
```
function hideMe()
{
$('#btnHide').hide();
}
```
Above code will hide the button when you click on it - basic XUL manipulation with jQuery!
But as I said, try to observe document load and other such events and it gets complicated very quickly (or I don't know much :D).
**Update:** I tried some effects. Effects.fadeIn() works - but since the transparency properties are set differently in XUL when compared to HTML, the button stays there and in the end, it abruptly disappears. Now it is becoming clear to what extent we can (can't) use jQuery to manipulate XUL. | The answer right now is "mostly".
Basic stuff works, including selecting, deleting and finding. I use 1.5.2 pretty heavily both inside an extension and on content pages from the extension.
$.ready() also doesn't work because jQuery assumes and waits for a body. This is the [commit](https://github.com/jquery/jquery/commit/262fcf7b7b919da1564509f621cf7480a5d5572b) that broke it.
Some stuff doesn't work because, as @Daniel describes, jQuery's doesn't properly detect what it can and can't do in XUL (more background below). From stepping through jQuery code I have have found you need at least the following lines in your own code.
```
// Workarounds for jQuery not properly testing support in XUL environment
// These are done at jQuery init
// This is actually critical, otherwise elements are not properly removed from the cache and you get a cache[id] is undefined
crowdmash.$.support.deleteExpando = true;
// These are done at ready(), but jQuery never fires ready in XUL
// XUL doesn't seem to support offsetWidth and offsetHeight (without this :hidden is broken which breaks fadeIn)
crowdmash.$.support.reliableHiddenOffsets = false;
crowdmash.$.support.opacity = true;
```
If you want to use jQuery on a content page from an extension, see my [tips](http://forums.mozillazine.org/viewtopic.php?f=19&t=2105087).
[jquery-xul](https://github.com/ilyakharlamov/jquery-xul/wiki) modifies 1.4.4 to better work with XUL. I have not tried it yet, but from looking at its changes it does look like fixes the ready issue. I don't know if it fixes the support issue .
As background on the $.support issue. The problem is that jQuery's feature detection creates a and then populates it using innerHTML. XUL divs do not support innerHTML, so the support code fails marking nothing as supported. There is actually a ticket on this that is open and being discussed for 1.7 - <http://bugs.jquery.com/ticket/5206>. |
693,174 | I know its possible to integrate jQuery within Firefox addons, but are we able to manipulate (animate, move, adjust transparency, etc) XUL elements themselves?
From what I understand, the Firefox addon can use jQuery to manipulate HTML/DOM elements, but not sure about XUL elements. | 2009/03/28 | [
"https://Stackoverflow.com/questions/693174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/84047/"
] | I was wondering this myself recently. Obviously the DHTML doesn't make sense, but the basic syntactic sugar and things are rumored to work.
* There is this [jQuery on XUL](http://groups.google.com/group/jquery-dev/browse_thread/thread/4545040bf26c6eea?pli=1) discussion from the jQuery group which indicates that it loads up with some exceptions.
* Also see this slightly more recent blog post about [jQuery and DHTML in XUL](http://digitalmihailo.blogspot.com/2008/05/jquery-and-dynamic-html-in-xul.html). That person is going after the HTML within the XUL which is not exactly what you need but he does have good information. | Unfortunately, jQuery fails to initialize in XUL because of the HTML-specific functions like `document.body` that exist for HTML pages only. However there is a special branch called [jQuery-xul](https://github.com/ilyakharlamov/jquery-xul) that it optimized for use in FireFox extensions. I have checked, it works fine. |
693,174 | I know its possible to integrate jQuery within Firefox addons, but are we able to manipulate (animate, move, adjust transparency, etc) XUL elements themselves?
From what I understand, the Firefox addon can use jQuery to manipulate HTML/DOM elements, but not sure about XUL elements. | 2009/03/28 | [
"https://Stackoverflow.com/questions/693174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/84047/"
] | XUL and HTML actually deal with opacity the exact same way, and it is jQuery that incorrectly detects what the browser can do. jQuery thinks it's in a different browser when it's living inside XUL, and so opacity effects are handled differently - by jQuery. Since it IS in Firefox, and it should deal with opacity normally, you can override this like so:
jQuery.support.opacity = true
Do this right after jQuery is loaded.
There is probably a whole category of similar fixes that can be post-applied to jQuery to make it behave better, but I haven't looked in to it. | The answer right now is "mostly".
Basic stuff works, including selecting, deleting and finding. I use 1.5.2 pretty heavily both inside an extension and on content pages from the extension.
$.ready() also doesn't work because jQuery assumes and waits for a body. This is the [commit](https://github.com/jquery/jquery/commit/262fcf7b7b919da1564509f621cf7480a5d5572b) that broke it.
Some stuff doesn't work because, as @Daniel describes, jQuery's doesn't properly detect what it can and can't do in XUL (more background below). From stepping through jQuery code I have have found you need at least the following lines in your own code.
```
// Workarounds for jQuery not properly testing support in XUL environment
// These are done at jQuery init
// This is actually critical, otherwise elements are not properly removed from the cache and you get a cache[id] is undefined
crowdmash.$.support.deleteExpando = true;
// These are done at ready(), but jQuery never fires ready in XUL
// XUL doesn't seem to support offsetWidth and offsetHeight (without this :hidden is broken which breaks fadeIn)
crowdmash.$.support.reliableHiddenOffsets = false;
crowdmash.$.support.opacity = true;
```
If you want to use jQuery on a content page from an extension, see my [tips](http://forums.mozillazine.org/viewtopic.php?f=19&t=2105087).
[jquery-xul](https://github.com/ilyakharlamov/jquery-xul/wiki) modifies 1.4.4 to better work with XUL. I have not tried it yet, but from looking at its changes it does look like fixes the ready issue. I don't know if it fixes the support issue .
As background on the $.support issue. The problem is that jQuery's feature detection creates a and then populates it using innerHTML. XUL divs do not support innerHTML, so the support code fails marking nothing as supported. There is actually a ticket on this that is open and being discussed for 1.7 - <http://bugs.jquery.com/ticket/5206>. |
693,174 | I know its possible to integrate jQuery within Firefox addons, but are we able to manipulate (animate, move, adjust transparency, etc) XUL elements themselves?
From what I understand, the Firefox addon can use jQuery to manipulate HTML/DOM elements, but not sure about XUL elements. | 2009/03/28 | [
"https://Stackoverflow.com/questions/693174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/84047/"
] | The answer right now is "mostly".
Basic stuff works, including selecting, deleting and finding. I use 1.5.2 pretty heavily both inside an extension and on content pages from the extension.
$.ready() also doesn't work because jQuery assumes and waits for a body. This is the [commit](https://github.com/jquery/jquery/commit/262fcf7b7b919da1564509f621cf7480a5d5572b) that broke it.
Some stuff doesn't work because, as @Daniel describes, jQuery's doesn't properly detect what it can and can't do in XUL (more background below). From stepping through jQuery code I have have found you need at least the following lines in your own code.
```
// Workarounds for jQuery not properly testing support in XUL environment
// These are done at jQuery init
// This is actually critical, otherwise elements are not properly removed from the cache and you get a cache[id] is undefined
crowdmash.$.support.deleteExpando = true;
// These are done at ready(), but jQuery never fires ready in XUL
// XUL doesn't seem to support offsetWidth and offsetHeight (without this :hidden is broken which breaks fadeIn)
crowdmash.$.support.reliableHiddenOffsets = false;
crowdmash.$.support.opacity = true;
```
If you want to use jQuery on a content page from an extension, see my [tips](http://forums.mozillazine.org/viewtopic.php?f=19&t=2105087).
[jquery-xul](https://github.com/ilyakharlamov/jquery-xul/wiki) modifies 1.4.4 to better work with XUL. I have not tried it yet, but from looking at its changes it does look like fixes the ready issue. I don't know if it fixes the support issue .
As background on the $.support issue. The problem is that jQuery's feature detection creates a and then populates it using innerHTML. XUL divs do not support innerHTML, so the support code fails marking nothing as supported. There is actually a ticket on this that is open and being discussed for 1.7 - <http://bugs.jquery.com/ticket/5206>. | Unfortunately, jQuery fails to initialize in XUL because of the HTML-specific functions like `document.body` that exist for HTML pages only. However there is a special branch called [jQuery-xul](https://github.com/ilyakharlamov/jquery-xul) that it optimized for use in FireFox extensions. I have checked, it works fine. |
693,174 | I know its possible to integrate jQuery within Firefox addons, but are we able to manipulate (animate, move, adjust transparency, etc) XUL elements themselves?
From what I understand, the Firefox addon can use jQuery to manipulate HTML/DOM elements, but not sure about XUL elements. | 2009/03/28 | [
"https://Stackoverflow.com/questions/693174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/84047/"
] | My explanation refers to jQuery 1.7.1.
My goal was to perform a fade animation within the XUL context, but errors were being thrown because jQuery wrongly assumes it is dealing with IE if jQuery.support.opacity is falsy.
The logic that populates the **support** Object was prematurely returning an empty Object due to the inability to interact with a DOM element created via **document.createElement( "div" )**. My problem was solved by using **document.createElementNS**:
```
createElementNS("http://www.w3.org/1999/xhtml", "div");
```
I searched the jQuery bug tracker after coming up with this solution and found the following related ticket: <http://bugs.jquery.com/ticket/5206>
jQuery isn't advertised as working within the XUL context and therefore the team has no plans of addressing the issue, though they should address the issue of the IE false positive. I am content with manually making this one line change in the source code for my application.
Cheers,
Andy | Unfortunately, jQuery fails to initialize in XUL because of the HTML-specific functions like `document.body` that exist for HTML pages only. However there is a special branch called [jQuery-xul](https://github.com/ilyakharlamov/jquery-xul) that it optimized for use in FireFox extensions. I have checked, it works fine. |
693,174 | I know its possible to integrate jQuery within Firefox addons, but are we able to manipulate (animate, move, adjust transparency, etc) XUL elements themselves?
From what I understand, the Firefox addon can use jQuery to manipulate HTML/DOM elements, but not sure about XUL elements. | 2009/03/28 | [
"https://Stackoverflow.com/questions/693174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/84047/"
] | I was wondering this myself recently. Obviously the DHTML doesn't make sense, but the basic syntactic sugar and things are rumored to work.
* There is this [jQuery on XUL](http://groups.google.com/group/jquery-dev/browse_thread/thread/4545040bf26c6eea?pli=1) discussion from the jQuery group which indicates that it loads up with some exceptions.
* Also see this slightly more recent blog post about [jQuery and DHTML in XUL](http://digitalmihailo.blogspot.com/2008/05/jquery-and-dynamic-html-in-xul.html). That person is going after the HTML within the XUL which is not exactly what you need but he does have good information. | My explanation refers to jQuery 1.7.1.
My goal was to perform a fade animation within the XUL context, but errors were being thrown because jQuery wrongly assumes it is dealing with IE if jQuery.support.opacity is falsy.
The logic that populates the **support** Object was prematurely returning an empty Object due to the inability to interact with a DOM element created via **document.createElement( "div" )**. My problem was solved by using **document.createElementNS**:
```
createElementNS("http://www.w3.org/1999/xhtml", "div");
```
I searched the jQuery bug tracker after coming up with this solution and found the following related ticket: <http://bugs.jquery.com/ticket/5206>
jQuery isn't advertised as working within the XUL context and therefore the team has no plans of addressing the issue, though they should address the issue of the IE false positive. I am content with manually making this one line change in the source code for my application.
Cheers,
Andy |
693,174 | I know its possible to integrate jQuery within Firefox addons, but are we able to manipulate (animate, move, adjust transparency, etc) XUL elements themselves?
From what I understand, the Firefox addon can use jQuery to manipulate HTML/DOM elements, but not sure about XUL elements. | 2009/03/28 | [
"https://Stackoverflow.com/questions/693174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/84047/"
] | ***Short answer:*** Yes
***Long Answer:***
I experimented with it myself. I could only use it in a limited way. Manipulation of XUL elements is possible. But I am having a hard time observing events, since I am pretty new to jQuery - I don't know how to tweak it to observe events at Firefox/XUL level - I don't even know whether tweaking is required :D
***Example:***
**overlay.xul**
```
<?xml version="1.0"?>
<?xml-stylesheet href="chrome://testaddon/content/overlay.css" type="text/css"?>
<overlay id="testaddon_overlay"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
xmlns:html="http://www.w3.org/1999/xhtml">
<script type="application/x-javascript" src="chrome://testaddon/content/jquery-1.4.2.js" />
<script type="application/x-javascript" src="chrome://testaddon/content/overlay.js" />
<toolbox id="navigator-toolbox">
<toolbar toolbarname="TestAddonToolbar" class="chromeclass-toolbar">
<toolbaritem>
<toolbarbutton id="btnHide" label="HideMe" onclick="hideMe();" />
</toolbaritem>
</toolbar>
</toolbox>
</overlay>
```
**overlay.js**
```
function hideMe()
{
$('#btnHide').hide();
}
```
Above code will hide the button when you click on it - basic XUL manipulation with jQuery!
But as I said, try to observe document load and other such events and it gets complicated very quickly (or I don't know much :D).
**Update:** I tried some effects. Effects.fadeIn() works - but since the transparency properties are set differently in XUL when compared to HTML, the button stays there and in the end, it abruptly disappears. Now it is becoming clear to what extent we can (can't) use jQuery to manipulate XUL. | Unfortunately, jQuery fails to initialize in XUL because of the HTML-specific functions like `document.body` that exist for HTML pages only. However there is a special branch called [jQuery-xul](https://github.com/ilyakharlamov/jquery-xul) that it optimized for use in FireFox extensions. I have checked, it works fine. |
693,174 | I know its possible to integrate jQuery within Firefox addons, but are we able to manipulate (animate, move, adjust transparency, etc) XUL elements themselves?
From what I understand, the Firefox addon can use jQuery to manipulate HTML/DOM elements, but not sure about XUL elements. | 2009/03/28 | [
"https://Stackoverflow.com/questions/693174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/84047/"
] | ***Short answer:*** Yes
***Long Answer:***
I experimented with it myself. I could only use it in a limited way. Manipulation of XUL elements is possible. But I am having a hard time observing events, since I am pretty new to jQuery - I don't know how to tweak it to observe events at Firefox/XUL level - I don't even know whether tweaking is required :D
***Example:***
**overlay.xul**
```
<?xml version="1.0"?>
<?xml-stylesheet href="chrome://testaddon/content/overlay.css" type="text/css"?>
<overlay id="testaddon_overlay"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
xmlns:html="http://www.w3.org/1999/xhtml">
<script type="application/x-javascript" src="chrome://testaddon/content/jquery-1.4.2.js" />
<script type="application/x-javascript" src="chrome://testaddon/content/overlay.js" />
<toolbox id="navigator-toolbox">
<toolbar toolbarname="TestAddonToolbar" class="chromeclass-toolbar">
<toolbaritem>
<toolbarbutton id="btnHide" label="HideMe" onclick="hideMe();" />
</toolbaritem>
</toolbar>
</toolbox>
</overlay>
```
**overlay.js**
```
function hideMe()
{
$('#btnHide').hide();
}
```
Above code will hide the button when you click on it - basic XUL manipulation with jQuery!
But as I said, try to observe document load and other such events and it gets complicated very quickly (or I don't know much :D).
**Update:** I tried some effects. Effects.fadeIn() works - but since the transparency properties are set differently in XUL when compared to HTML, the button stays there and in the end, it abruptly disappears. Now it is becoming clear to what extent we can (can't) use jQuery to manipulate XUL. | My explanation refers to jQuery 1.7.1.
My goal was to perform a fade animation within the XUL context, but errors were being thrown because jQuery wrongly assumes it is dealing with IE if jQuery.support.opacity is falsy.
The logic that populates the **support** Object was prematurely returning an empty Object due to the inability to interact with a DOM element created via **document.createElement( "div" )**. My problem was solved by using **document.createElementNS**:
```
createElementNS("http://www.w3.org/1999/xhtml", "div");
```
I searched the jQuery bug tracker after coming up with this solution and found the following related ticket: <http://bugs.jquery.com/ticket/5206>
jQuery isn't advertised as working within the XUL context and therefore the team has no plans of addressing the issue, though they should address the issue of the IE false positive. I am content with manually making this one line change in the source code for my application.
Cheers,
Andy |
693,174 | I know its possible to integrate jQuery within Firefox addons, but are we able to manipulate (animate, move, adjust transparency, etc) XUL elements themselves?
From what I understand, the Firefox addon can use jQuery to manipulate HTML/DOM elements, but not sure about XUL elements. | 2009/03/28 | [
"https://Stackoverflow.com/questions/693174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/84047/"
] | XUL and HTML actually deal with opacity the exact same way, and it is jQuery that incorrectly detects what the browser can do. jQuery thinks it's in a different browser when it's living inside XUL, and so opacity effects are handled differently - by jQuery. Since it IS in Firefox, and it should deal with opacity normally, you can override this like so:
jQuery.support.opacity = true
Do this right after jQuery is loaded.
There is probably a whole category of similar fixes that can be post-applied to jQuery to make it behave better, but I haven't looked in to it. | Unfortunately, jQuery fails to initialize in XUL because of the HTML-specific functions like `document.body` that exist for HTML pages only. However there is a special branch called [jQuery-xul](https://github.com/ilyakharlamov/jquery-xul) that it optimized for use in FireFox extensions. I have checked, it works fine. |
59,534,983 | I have the following code (full example):
```
import React, { useState, useEffect } from 'react';
import { SafeAreaView, View, Button, StyleSheet, Animated } from 'react-native';
import { PanGestureHandler, State } from 'react-native-gesture-handler';
const App = () => {
const [blocks, setBlocks] = useState([]);
const CreateBlockHandler = () => {
let array = blocks;
array.push({
x: new Animated.Value(0),
y: new Animated.Value(0)
});
setBlocks(array);
RenderBlocks();
};
const MoveBlockHandler = (index, event) => {
Animated.spring(blocks[index].x, { toValue: event.nativeEvent.x }).start();
Animated.spring(blocks[index].y, { toValue: event.nativeEvent.y }).start();
};
const RenderBlocks = () => {
return blocks.map((item, index) => {
return (
<PanGestureHandler key={index} onGestureEvent={event => MoveBlockHandler(index,event)}>
<Animated.View style={[styles.block, {
transform: [
{ translateX: item.x },
{ translateY: item.y }
]
}]} />
</PanGestureHandler>
)
});
};
return (
<SafeAreaView style={styles.container}>
<View style={styles.pancontainer}>
<RenderBlocks />
</View>
<Button title="Add block" onPress={CreateBlockHandler} />
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
},
pancontainer: {
width: '95%',
height:'75%',
borderWidth: 1,
borderColor: 'black'
},
block: {
width: 50,
height: 50,
backgroundColor: 'black'
}
});
export default App;
```
What does this code do? It's a big square, and a button below it. When I click on the button, a new black square (50x50) is made in the big square. I do this by creating a new array element (the array = blocks). This is done in the function **CreateBlockHandler**. This does not work correctly!
The function **MoveBlockHandler** makes the little squares movable. This works!
What does not work? When I create a new black square, the black square is not rendered on the screen. Only when I refresh, the square is rendered. The square is created through CreateBlockHandler, because when I do a console.log(blocks) in that function, I can see that a new array element is added.
How can I force this code to do a full re-render with all the array elements? I tried to wrap the render of the square in a separate function (**RenderBlocks**) and I'm calling this function every time a new square is made (last line in CreateBlockHandler). The function is called (I can check this with a console.log()) but no squares are rendered. | 2019/12/30 | [
"https://Stackoverflow.com/questions/59534983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12496104/"
] | When you assign `blocks` to `array` the reference gete copied which mutates the state, so it doesn't re-render on `setState`.
```
const CreateBlockHandler = () => {
let array = [...blocks];
array.push({
x: new Animated.Value(0),
y: new Animated.Value(0)
});
setBlocks(array);
RenderBlocks
``` | There are multiple issues with your code.
As kooskoos pointed out, your state remains referentially equal (it's the same array, only the elements change). This will not trigger re-render.
Also, you are manipulating state of the `App` component. `RenderBlocks` component's props and state remain unchanged which implies that they don't need to be re-rendered. Since the component is an anonymous function and is recreated during every render of `App`, it probably gets re-rendered anyways.
In addition, you are directly calling `RenderBlocks`, which looks like a component. That is unnecessary and will do nothing here, but if it had any hooks, it would cause problems.
You should probably also conform to the convention that components are PascalCase capitalised and callbacks snakeCase capitalised. |
61,118,659 | Tried extracting the href from:
```
<a lang="en" class="new class" href="/abc/stack.com"
tabindex="-1" data-type="itemTitles"><span><mark>Scott</mark>, CC042<br></span></a>
```
using `elems = driver.find_elements_by_css_selector(".new class [href]")` , but doesn't seem to work.
Also tried [Python Selenium - get href value](https://stackoverflow.com/questions/54862426/python-selenium-get-href-value), but it returned an empty list.
So I want to extract all the href elements of class = "new class" as mentioned above and append them in a list
Thanks!! | 2020/04/09 | [
"https://Stackoverflow.com/questions/61118659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13016237/"
] | Use `.get_attribute('href')`.
`by_css_selector`:
```
elems = driver.find_elements_by_css_selector('.new.class')
for elem in elems:
print(elem.get_attribute('href'))
```
Or `by_xpath`:
```
elems = driver.find_elements_by_xpath('//a[@class="new class"]')
``` | Just change it to
```
elems = driver.find_elements_by_css_selector(".new.class[href]")
```
OR
```
elems = driver.find_elements_by_css_selector("[class='new class'][href]")
``` |
431,878 | I have files with naming convention of this pattern:
```
bond_7.LEU.CA.1.dat
bond_7.LEU.CA.2.dat
bond_7.LEU.CA.3.dat
bond_12.ALA.CB.1.dat
bond_12.ALA.CB.2.dat
bond_12.ALA.CB.3.dat
...
```
I want to concatenate all files of the same group into a single one. For example:
```
cat bond_7.LEU.CA.*.dat > ../bondvalues/bond_7.LEU.CA.1_3.dat
```
There's large number of these files. How can achieve this with a bash script? | 2012/06/02 | [
"https://superuser.com/questions/431878",
"https://superuser.com",
"https://superuser.com/users/137717/"
] | Assuming that the example you provide reflects all of your files the following should do the trick:
```
for f in *.1.dat
do
cat ${f%%1.dat}* > ${f%%1.dat}1_3.dat
done
```
This requires that each group contains a file with the .1.dat extension. | ```
printf "%s\n" * | cut -d. -f1-3 | sort -u | while read prefix; do
files=(${prefix}*)
first=$(cut -d. -f4 <<< "${files[0]}")
last=$(cut -d. -f4 <<< "${files[${#files[@]}-1]}")
newfile=$(printf "../bondvalues/%s.%s_%s.dat" "$prefix" "$first" "$last")
cat "${files[@]}" > "$newfile"
done
``` |
7,640,177 | I'm defining a javascript object and setting its properties and methods like this:
```
function MyObject()
{
this.prop1 = 1;
this.prop2 = 2;
this.meth1=meth1;
}
function meth1()
{
// do soemthing
}
```
All is fine. My question is how can i have an object be a property of MyObject? I actually want an 'associative array' as a property something along these lines:
```
function MyObject()
{
this.obj['x'] = 'val1';
this.obj['y'= = 'val2';
this.prop1 = 1;
this.prop2 = 2;
this.meth1=meth1;
}
```
I have tried declaring obj in MyObject like this: `obj = new Object`; with no luck, obj is not being interpreted as a property.
Any clues as to what i'm doing wrong?
thanks | 2011/10/03 | [
"https://Stackoverflow.com/questions/7640177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/550116/"
] | Do you mean:
```
function MyObject() {
this.obj = {'x': 'val1', 'y': 'val2'};
this.prop1 = 1;
this.prop2 = 2;
this.meth1=meth1;
}
```
?
Now you can say:
```
new MyObject().obj.x //`val1`
```
Alternative syntax:
```
this.obj = {};
this.obj.x = 'val1';
this.obj.y = 'val2';
``` | It's often easiest to use the object literal notation:
```
function MyObject()
{
// obj as an object literal
this.obj = {
x: "val1",
y: "val2",
z: "val3"
};
this.prop1 = 1;
this.prop2 = 2;
this.meth1=meth1;
}
``` |
41,764,618 | ```
$("selector").data("name", null);
console.log($("selector").data("name"));
```
This prints `undefined`.
Is there anyway to instantiate a `null` item in the jQuery data object of an element, not an undefined one? | 2017/01/20 | [
"https://Stackoverflow.com/questions/41764618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3380611/"
] | Yes and Your code works fine, You should check if your `$("selector")` exists | Your code works well as @Sebastian Krysiak stated, check if the selector exists. See working snippet below:
```js
console.log("before: " + $(".selector").data("name"));
$(".selector").data("name", null);
console.log("after: " + $(".selector").data("name"));
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='selector' data-name='test'></div>
```
An example to demonstrate what happens if the selector does not exist, like in your case, it returns `undefined` (maybe you should say what is the type of the selector e.g. `class` - `.selector` or `id` - `#selector`):
```js
console.log("before: " + $("selector").data("name"));
$("selector").data("name", null);
console.log("after: " + $("selector").data("name"));
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='selector' data-name='test'></div>
``` |
41,764,618 | ```
$("selector").data("name", null);
console.log($("selector").data("name"));
```
This prints `undefined`.
Is there anyway to instantiate a `null` item in the jQuery data object of an element, not an undefined one? | 2017/01/20 | [
"https://Stackoverflow.com/questions/41764618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3380611/"
] | Yes and Your code works fine, You should check if your `$("selector")` exists | ```
$("#selector").data("name", null);
console.log($("#selector").data("name"));
```
Works just fine as is, your selector might not exist.
Here's a fiddle <https://jsfiddle.net/eo32jjay/> |
41,764,618 | ```
$("selector").data("name", null);
console.log($("selector").data("name"));
```
This prints `undefined`.
Is there anyway to instantiate a `null` item in the jQuery data object of an element, not an undefined one? | 2017/01/20 | [
"https://Stackoverflow.com/questions/41764618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3380611/"
] | Yes and Your code works fine, You should check if your `$("selector")` exists | What about this?
```js
$(document).ready(function() {
var aVariableValue = null;
$("#myDiv").data("name", aVariableValue);
console.log($("#myDiv").data("name"));
});
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="myDiv"></div>
``` |
41,764,618 | ```
$("selector").data("name", null);
console.log($("selector").data("name"));
```
This prints `undefined`.
Is there anyway to instantiate a `null` item in the jQuery data object of an element, not an undefined one? | 2017/01/20 | [
"https://Stackoverflow.com/questions/41764618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3380611/"
] | Yes and Your code works fine, You should check if your `$("selector")` exists | It looks like your method should work, tho the element you are selecting must exists.
Look at [this fiddle](https://jsfiddle.net/hsukrk9b/) to see it in action.
```
// Before
alert($('#elem').data('foo'));
$('#elem').data('foo', null);
// After
alert($('#elem').data('foo'));
``` |
5,019,360 | I have made a webapp for my android phone where I can check the sales at my store when I'm not there.
I would like to have notifications on my phone whenever a sale is made.
What is the best way of doing this? Any existing android apps that I can configure to check a php-script every 2 minutes or something? | 2011/02/16 | [
"https://Stackoverflow.com/questions/5019360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/348776/"
] | Try using XMPP to send a message to yourself, which you can receive via gtalk on the phone. Alternatively, an email, SMS, etc. | Could you rig up an RSS feed and use a feed reader to notify you? |
5,507,754 | I have an html form that sends data to .cgi page. Here is the html:
```
<HTML>
<BODY BGCOLOR="#FFFFFF">
<FORM METHOD="post" ACTION="test.cgi">
<B>Write to me below:</B><P>
<TEXTAREA NAME="feedback" ROWS=10 COLS=50></TEXTAREA><P>
<CENTER>
<INPUT TYPE=submit VALUE="SEND">
<INPUT TYPE=reset VALUE="CLEAR">
</CENTER>
</FORM>
</BODY>
</HTML>
```
Here is the perl script for test.cgi:
```
#!/usr/bin/perl
use utf8;
use encoding('utf8');
require Encode;
require CGI;
# The following accepts the data from the form and puts it in %FORM
if ($ENV{'REQUEST_METHOD'} eq 'POST') {
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
@pairs = split(/&/, $buffer);
foreach $pair (@pairs) {
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}
# The following generates the html for the page
print "Content-type: text/html\n\n";
print "<HTML>\n";
print "<HEAD>\n";
print "<TITLE>Thank You!</TITLE>\n";
print "</HEAD>\n";
print "<BODY BGCOLOR=#FFFFCC TEXT=#000000>\n";
print "<H1>Thank You!</H1>\n";
print "<P>\n";
print "<H3>Your feedback is greatly appreciated.</h3><BR>\n";
print "<P>\n<P>\n";
print "The user wrote:\n\n";
print "<P>\n";
# This is print statement A
print "$FORM{'feedback'}<br>\n";
$FORM{'feedback'}=~s/(\w)/ $1/g;
# This is print statement B
print "$FORM{'feedback'}\n";
print "</BODY>\n";
print "</HTML>\n";
exit(0);
}
```
This all works the way it's supposed to if the user enters English text. However, this will eventually be used in a product where the user will enter Chinese text. So here's an example of the problem. If the user enters "中文" into the form, then Print Statement A prints "中文." However, Print Statement B (which prints $value after the regex has been run) prints "&# 2 0 0 1 3;&# 2 5 9 9 1; ". What I want it to print however is "中 文". If you want to see this, go to <http://thedeandp.com/chinese/input.html> and try it yourself.
So basically, what I've figured out is that when perl reads in the form, it's just treating each byte as a character, so the regex adds a space between each byte. Chinese characters use unicode, so it's multiple bytes to a character. That means the regex breaks up the unicode with a space between the bytes, and that is what produces the output seen in Print Statement B. I've tried methods like $value = Encode::decode\_utf8($value) to get perl to treat it as unicode, but nothing has worked so far. | 2011/03/31 | [
"https://Stackoverflow.com/questions/5507754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/686620/"
] | That [CGI](http://search.cpan.org/perldoc?CGI) style could be improved while fixing your encoding decoding issue. Try this–
```
use strict;
use warnings;
use Encode;
use CGI ":standard";
use HTML::Entities;
print
header("text/html; charset=utf-8"),
start_html("Thank you!"),
h1("Thank You!"),
h3("Your feedback is greatly appreciated.");
if ( my $feedback = decode_utf8( param("feedback") ) )
{
print
p("The user wrote:"),
blockquote( encode_utf8( encode_entities($feedback) ) );
}
print end_html();
```
Proper encoding and decoding between octets/bytes and utf-8 is necessary to avoid surprises and allow the Perl to behave as you’d expect.
For example, you can drop this in–
```
h4("Which capitalizes as:"),
blockquote( encode_utf8( uc $feedback ) );
```
And see character conversions work like so: å™ç∂®r£ ➟ Å™Ç∂®R£
Update: added `encode_entities`. NEVER print user input back without escaping the HTML. Update to update: which actually will end up escaping the utf-8 depending on the setup (you can have it only escape ['"<>] for example)… | What version of Perl are you using? This works for me with v5.10.1 on i686-cygwin-thread-multi-64int:
```
perl -E 'use utf8; use encoding("utf8"); $_="中文"; say; s/(\w)/$1 /g; say'
```
Output:
>
> 中文
>
> 中 文
>
>
>
I'm sure you've read [perlunicode](http://perldoc.perl.org/perlunicode.html)? |
5,507,754 | I have an html form that sends data to .cgi page. Here is the html:
```
<HTML>
<BODY BGCOLOR="#FFFFFF">
<FORM METHOD="post" ACTION="test.cgi">
<B>Write to me below:</B><P>
<TEXTAREA NAME="feedback" ROWS=10 COLS=50></TEXTAREA><P>
<CENTER>
<INPUT TYPE=submit VALUE="SEND">
<INPUT TYPE=reset VALUE="CLEAR">
</CENTER>
</FORM>
</BODY>
</HTML>
```
Here is the perl script for test.cgi:
```
#!/usr/bin/perl
use utf8;
use encoding('utf8');
require Encode;
require CGI;
# The following accepts the data from the form and puts it in %FORM
if ($ENV{'REQUEST_METHOD'} eq 'POST') {
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
@pairs = split(/&/, $buffer);
foreach $pair (@pairs) {
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}
# The following generates the html for the page
print "Content-type: text/html\n\n";
print "<HTML>\n";
print "<HEAD>\n";
print "<TITLE>Thank You!</TITLE>\n";
print "</HEAD>\n";
print "<BODY BGCOLOR=#FFFFCC TEXT=#000000>\n";
print "<H1>Thank You!</H1>\n";
print "<P>\n";
print "<H3>Your feedback is greatly appreciated.</h3><BR>\n";
print "<P>\n<P>\n";
print "The user wrote:\n\n";
print "<P>\n";
# This is print statement A
print "$FORM{'feedback'}<br>\n";
$FORM{'feedback'}=~s/(\w)/ $1/g;
# This is print statement B
print "$FORM{'feedback'}\n";
print "</BODY>\n";
print "</HTML>\n";
exit(0);
}
```
This all works the way it's supposed to if the user enters English text. However, this will eventually be used in a product where the user will enter Chinese text. So here's an example of the problem. If the user enters "中文" into the form, then Print Statement A prints "中文." However, Print Statement B (which prints $value after the regex has been run) prints "&# 2 0 0 1 3;&# 2 5 9 9 1; ". What I want it to print however is "中 文". If you want to see this, go to <http://thedeandp.com/chinese/input.html> and try it yourself.
So basically, what I've figured out is that when perl reads in the form, it's just treating each byte as a character, so the regex adds a space between each byte. Chinese characters use unicode, so it's multiple bytes to a character. That means the regex breaks up the unicode with a space between the bytes, and that is what produces the output seen in Print Statement B. I've tried methods like $value = Encode::decode\_utf8($value) to get perl to treat it as unicode, but nothing has worked so far. | 2011/03/31 | [
"https://Stackoverflow.com/questions/5507754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/686620/"
] | That [CGI](http://search.cpan.org/perldoc?CGI) style could be improved while fixing your encoding decoding issue. Try this–
```
use strict;
use warnings;
use Encode;
use CGI ":standard";
use HTML::Entities;
print
header("text/html; charset=utf-8"),
start_html("Thank you!"),
h1("Thank You!"),
h3("Your feedback is greatly appreciated.");
if ( my $feedback = decode_utf8( param("feedback") ) )
{
print
p("The user wrote:"),
blockquote( encode_utf8( encode_entities($feedback) ) );
}
print end_html();
```
Proper encoding and decoding between octets/bytes and utf-8 is necessary to avoid surprises and allow the Perl to behave as you’d expect.
For example, you can drop this in–
```
h4("Which capitalizes as:"),
blockquote( encode_utf8( uc $feedback ) );
```
And see character conversions work like so: å™ç∂®r£ ➟ Å™Ç∂®R£
Update: added `encode_entities`. NEVER print user input back without escaping the HTML. Update to update: which actually will end up escaping the utf-8 depending on the setup (you can have it only escape ['"<>] for example)… | If you look at the source for the thank you page, the content is:
```
中文<br>
&# 2 0 0 1 3;&# 2 5 9 9 1;
```
So it seems like `$FORM{'feedback'}` is arriving as HTML entities rather than as UTF-8. You probably need to convert those entities to real UTF-8 characters before working on the data, I'm not sure the best way to do that. |
31,946,407 | I have a C# application using Oracle database and Entity Framework 5. Oracle client is version 12c R1. My application uses database first approach. I'm trying to run the app using Visual Studio Enterprise 2015. When I access the edmx file and I try to update the model from the database, it gives me the following error:
>
> An exception of type 'System.ArgumentException' occurred while attempting to update from the database. The exception message is: 'Unable to convert runtime connection string to its design-time equivalent. The libraries required to enable Visual Studio to communicate with the database for design purposes (DDEX provider) are not installed for provider 'Oracle.DataAccess.Client'. Connection string: XXXXX.
>
>
>
This error does not occur when I use Visual Studio Ultimate 2013. Only on Visual Studio Enterprise 2015.
Is there any known incompatibility issue with the new one? | 2015/08/11 | [
"https://Stackoverflow.com/questions/31946407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4791851/"
] | I believe it is because not yet out ODT version compatible with Visual Studio 2015. Wait or will have no choice for now?
[Oracle Developer Tools](http://www.oracle.com/technetwork/developer-tools/visual-studio/overview/index.html) | I installed the Oracle Developer Tools for 2015 but still could not get this to work. When I would attempt to do an Update Model from Database with Entity Framework, I encountered this error below.
[](https://i.stack.imgur.com/tKQM6.jpg)
So I did as instructed and removed all references to Oracle from the GAC, even following advice here [Oracle .Net Developer's Guide](https://docs.oracle.com/cd/E11882_01/win.112/e23174/InstallODP.htm#ODPNT152), but it still didn't work. Being that I'm on a tight schedule and don't have time to fool with this, I opened my solution in VS2012, did my Entity Framework changes, and then reopened the solution in VS2015, and that worked fine. Irritating, but at least I have a workaround for now. |
440,571 | I'm trying to build some unit tests for testing my Rails helpers, but I can never remember how to access them. Annoying. Suggestions? | 2009/01/13 | [
"https://Stackoverflow.com/questions/440571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4322/"
] | You can do the same in RSpec as:
```
require File.dirname(__FILE__) + '/../spec_helper'
describe FoosHelper do
it "should do something" do
helper.some_helper_method.should == @something
end
end
``` | Stolen from here: <http://joakimandersson.se/archives/2006/10/05/test-your-rails-helpers/>
```
require File.dirname(__FILE__) + ‘/../test_helper’
require ‘user_helper’
class UserHelperTest < Test::Unit::TestCase
include UserHelper
def test_a_user_helper_method_here
end
end
```
[Stolen from Matt Darby, who also wrote in this thread.] You can do the same in RSpec as:
```
require File.dirname(__FILE__) + '/../spec_helper'
describe FoosHelper do
it "should do something" do
helper.some_helper_method.should == @something
end
end
``` |
440,571 | I'm trying to build some unit tests for testing my Rails helpers, but I can never remember how to access them. Annoying. Suggestions? | 2009/01/13 | [
"https://Stackoverflow.com/questions/440571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4322/"
] | In rails 3 you can do this (and in fact it's what the generator creates):
```
require 'test_helper'
class YourHelperTest < ActionView::TestCase
test "should work" do
assert_equal "result", your_helper_method
end
end
```
And of course [the rspec variant by Matt Darby](https://stackoverflow.com/a/441298/1152564) works in rails 3 too | Stolen from here: <http://joakimandersson.se/archives/2006/10/05/test-your-rails-helpers/>
```
require File.dirname(__FILE__) + ‘/../test_helper’
require ‘user_helper’
class UserHelperTest < Test::Unit::TestCase
include UserHelper
def test_a_user_helper_method_here
end
end
```
[Stolen from Matt Darby, who also wrote in this thread.] You can do the same in RSpec as:
```
require File.dirname(__FILE__) + '/../spec_helper'
describe FoosHelper do
it "should do something" do
helper.some_helper_method.should == @something
end
end
``` |
440,571 | I'm trying to build some unit tests for testing my Rails helpers, but I can never remember how to access them. Annoying. Suggestions? | 2009/01/13 | [
"https://Stackoverflow.com/questions/440571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4322/"
] | Stolen from here: <http://joakimandersson.se/archives/2006/10/05/test-your-rails-helpers/>
```
require File.dirname(__FILE__) + ‘/../test_helper’
require ‘user_helper’
class UserHelperTest < Test::Unit::TestCase
include UserHelper
def test_a_user_helper_method_here
end
end
```
[Stolen from Matt Darby, who also wrote in this thread.] You can do the same in RSpec as:
```
require File.dirname(__FILE__) + '/../spec_helper'
describe FoosHelper do
it "should do something" do
helper.some_helper_method.should == @something
end
end
``` | This thread is kind of old, but I thought I'd reply with what I use:
```
# encoding: UTF-8
require 'spec_helper'
describe AuthHelper do
include AuthHelper # has methods #login and #logout that modify the session
describe "#login & #logout" do
it "logs in & out a user" do
user = User.new :username => "AnnOnymous"
login user
expect(session[:user]).to eq(user)
logout
expect(session[:user]).to be_nil
end
end
end
``` |
440,571 | I'm trying to build some unit tests for testing my Rails helpers, but I can never remember how to access them. Annoying. Suggestions? | 2009/01/13 | [
"https://Stackoverflow.com/questions/440571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4322/"
] | Stolen from here: <http://joakimandersson.se/archives/2006/10/05/test-your-rails-helpers/>
```
require File.dirname(__FILE__) + ‘/../test_helper’
require ‘user_helper’
class UserHelperTest < Test::Unit::TestCase
include UserHelper
def test_a_user_helper_method_here
end
end
```
[Stolen from Matt Darby, who also wrote in this thread.] You can do the same in RSpec as:
```
require File.dirname(__FILE__) + '/../spec_helper'
describe FoosHelper do
it "should do something" do
helper.some_helper_method.should == @something
end
end
``` | I just posted this answer on another thread asking the same question. I did the following in my project.
```
require_relative '../../app/helpers/import_helper'
``` |
440,571 | I'm trying to build some unit tests for testing my Rails helpers, but I can never remember how to access them. Annoying. Suggestions? | 2009/01/13 | [
"https://Stackoverflow.com/questions/440571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4322/"
] | In rails 3 you can do this (and in fact it's what the generator creates):
```
require 'test_helper'
class YourHelperTest < ActionView::TestCase
test "should work" do
assert_equal "result", your_helper_method
end
end
```
And of course [the rspec variant by Matt Darby](https://stackoverflow.com/a/441298/1152564) works in rails 3 too | You can do the same in RSpec as:
```
require File.dirname(__FILE__) + '/../spec_helper'
describe FoosHelper do
it "should do something" do
helper.some_helper_method.should == @something
end
end
``` |
440,571 | I'm trying to build some unit tests for testing my Rails helpers, but I can never remember how to access them. Annoying. Suggestions? | 2009/01/13 | [
"https://Stackoverflow.com/questions/440571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4322/"
] | You can do the same in RSpec as:
```
require File.dirname(__FILE__) + '/../spec_helper'
describe FoosHelper do
it "should do something" do
helper.some_helper_method.should == @something
end
end
``` | This thread is kind of old, but I thought I'd reply with what I use:
```
# encoding: UTF-8
require 'spec_helper'
describe AuthHelper do
include AuthHelper # has methods #login and #logout that modify the session
describe "#login & #logout" do
it "logs in & out a user" do
user = User.new :username => "AnnOnymous"
login user
expect(session[:user]).to eq(user)
logout
expect(session[:user]).to be_nil
end
end
end
``` |
440,571 | I'm trying to build some unit tests for testing my Rails helpers, but I can never remember how to access them. Annoying. Suggestions? | 2009/01/13 | [
"https://Stackoverflow.com/questions/440571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4322/"
] | You can do the same in RSpec as:
```
require File.dirname(__FILE__) + '/../spec_helper'
describe FoosHelper do
it "should do something" do
helper.some_helper_method.should == @something
end
end
``` | I just posted this answer on another thread asking the same question. I did the following in my project.
```
require_relative '../../app/helpers/import_helper'
``` |
440,571 | I'm trying to build some unit tests for testing my Rails helpers, but I can never remember how to access them. Annoying. Suggestions? | 2009/01/13 | [
"https://Stackoverflow.com/questions/440571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4322/"
] | In rails 3 you can do this (and in fact it's what the generator creates):
```
require 'test_helper'
class YourHelperTest < ActionView::TestCase
test "should work" do
assert_equal "result", your_helper_method
end
end
```
And of course [the rspec variant by Matt Darby](https://stackoverflow.com/a/441298/1152564) works in rails 3 too | This thread is kind of old, but I thought I'd reply with what I use:
```
# encoding: UTF-8
require 'spec_helper'
describe AuthHelper do
include AuthHelper # has methods #login and #logout that modify the session
describe "#login & #logout" do
it "logs in & out a user" do
user = User.new :username => "AnnOnymous"
login user
expect(session[:user]).to eq(user)
logout
expect(session[:user]).to be_nil
end
end
end
``` |
440,571 | I'm trying to build some unit tests for testing my Rails helpers, but I can never remember how to access them. Annoying. Suggestions? | 2009/01/13 | [
"https://Stackoverflow.com/questions/440571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4322/"
] | In rails 3 you can do this (and in fact it's what the generator creates):
```
require 'test_helper'
class YourHelperTest < ActionView::TestCase
test "should work" do
assert_equal "result", your_helper_method
end
end
```
And of course [the rspec variant by Matt Darby](https://stackoverflow.com/a/441298/1152564) works in rails 3 too | I just posted this answer on another thread asking the same question. I did the following in my project.
```
require_relative '../../app/helpers/import_helper'
``` |
440,571 | I'm trying to build some unit tests for testing my Rails helpers, but I can never remember how to access them. Annoying. Suggestions? | 2009/01/13 | [
"https://Stackoverflow.com/questions/440571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4322/"
] | This thread is kind of old, but I thought I'd reply with what I use:
```
# encoding: UTF-8
require 'spec_helper'
describe AuthHelper do
include AuthHelper # has methods #login and #logout that modify the session
describe "#login & #logout" do
it "logs in & out a user" do
user = User.new :username => "AnnOnymous"
login user
expect(session[:user]).to eq(user)
logout
expect(session[:user]).to be_nil
end
end
end
``` | I just posted this answer on another thread asking the same question. I did the following in my project.
```
require_relative '../../app/helpers/import_helper'
``` |
221,498 | I’m building a Lightning component to edit html and need a robust WYSIWYG rich text editor (RTE) with “add link” feature and embed features. I really need the “add link” feature. When I search for RTE and Lightning I found and considered the following:
Trailblazer gives UI guidelines if you want to layout your own markup for a RTE but why reinvent the wheel when there are good plugins out there.
<http://lightningdesignsystem.com/components/rich-text-editor/>
The old ui:inputRichText is not supported when LockerService is activated:
So this leaves `<lightning:inputRichText />`. But this RTE lacks is deficient in both add link and image features.
```
<lightning:inputRichText value="{!v.body}" aura:id="iBody">
</lightning:inputRichText>
```
I’ve seen code that suggests you can add a button to let uses insert an image.
```
<lightning:inputRichText value="{!v.body}">
<lightning:insertImageButton/>
</lightning:inputRichText>
```
But this image uploader has a 1MB limit and has a terrible way of dealing with files that are too big. The user is told a serious error happened and they are asked to send a report into SF.
Is there some inner component that can be added to provide a Add Hyperlink feature?
Or, can we get the RTE that is used in Salesforce Lightning? Its the CKE editor and it’d be good enough. Is there a way to use this in our Lightning apps? I’ll guess that it might be imported as a static resource etc. Has anyone tried this and had success? | 2018/06/14 | [
"https://salesforce.stackexchange.com/questions/221498",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/2437/"
] | I figured it out: if your Salesforce Instance has access to Einstein Bots, there will be an **Einstein Bots Settings** section under the **Chat Buttons** section in **Setup**.
[](https://i.stack.imgur.com/Ijq2Z.png)
If you leave **Einstein Bots Configuration** blank, then (curiously enough) the preview for Einstein Bot will redirect the user to a Live Agent.
To fix this issue, simply fill in **Einstein Bots Configuration** as I have done in the picture above. | *[@Antonio\_Cucciniello](https://salesforce.stackexchange.com/users/65079/antonio-cucciniello)'s comment solved this for me, sharing as an answer to make this more noticable.*
---
If your bot has any **Apex actions**, make sure you don't have any errors. This will automatically try transferring you to an agent.
Inside your Bot Builder's top left dropdown go to:
`Performance` ➡ `Event Logs`
Visually check the **Errors** column for any "✓" marks on any rows.
If you see any, double click the logs `Session ID`, and explore what Event's have Errors. (if it was a recent log, you might need to wait a couple minutes for the log to load its data)
To see the actual error, click the "" on the row showing the Error column with "⚠". (It's kind of confusing to click the radio input to show you the error)
When I checked, I found that my bot had error:
```
[{"message":"You don't have access to the Apex class: Bot_SearchFAQ","errorCode":"INSUFFICIENT_ACCESS"}]
```
It was easy to fix once I saw this error. ([add the permission set to my bot](https://developer.salesforce.com/docs/atlas.en-us.bot_cookbook.meta/bot_cookbook/bot_cookbook_call_apex_action.htm#apex-perm-info)) |
16,765,085 | How can I detect which UIButton has been tapped:
```
-(void) topScorer {
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
[button1 addTarget:self
action:@selector(buttonClicked:)
forControlEvents:UIControlEventTouchDown];
[button1 setTitle:@"Button1" forState:UIControlStateNormal];
button1.frame = CGRectMake(16, self.view.bounds.size.height*0.6, 60, 60);
UIImage *img1 = [UIImage imageNamed:@"img1.png"];
button1.layer.cornerRadius = 10;
button1.layer.masksToBounds = YES;
[button1 setImage:img1 forState:UIScrollViewDecelerationRateNormal];
button1.tag = 1;
[self.view addSubview:button1];
UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
[button2 addTarget:self
action:@selector(buttonClicked:)
forControlEvents:UIControlEventTouchDown];
[button2 setTitle:@"Button2" forState:UIControlStateNormal];
button2.frame = CGRectMake(92, self.view.bounds.size.height*0.6, 60, 60);
UIImage *img2 = [UIImage imageNamed:@"img2.png"];
button2.layer.cornerRadius = 10;
button2.layer.masksToBounds = YES;
[button2 setImage:img2 forState:UIScrollViewDecelerationRateNormal];
button2.tag = 2;
[self.view addSubview:button2];
}
-(void) buttonClicked: (id)sender {
// How can I detect here which button is tapped?
// For Example, I want to do this:
// if button1 is pressed, do something
// if button 2 is pressed, do another thing
}
``` | 2013/05/27 | [
"https://Stackoverflow.com/questions/16765085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1019442/"
] | Cast your sender to a UIButton and compare the tag value.
```
UIButton *button = (UIButton *)sender;
if (button.tag == 1) {
} else {
}
``` | Store the button in a property on your view controller and then check against that property:
```
@property (nonatomic, weak) UIButton *buttonOne;
- (void)buttonTapped:(id)sender {
if (sender == buttonOne) {
// button one was tapped
}
}
```
or simply assign different selectors to each button.
```
[buttonOne addTarget:self
action:@selector(buttonOneTapped:)
forControlEvents:UIControlEventTouchUp];
[buttonTwo addTarget:self
action:@selector(buttonTwoTapped:)
forControlEvents:UIControlEventTouchUp];
``` |
22,691,075 | This question is a part of my current problem, so let's start with the big picture.
I am trying to sort a dictionary by the values in descending order. My dictionary is 1-to-1 corresponding, such as:
>
> ('ID1':value1, 'ID2':value2, ......)
>
>
>
I followed [this thread](https://stackoverflow.com/questions/613183/python-sort-a-dictionary-by-value) and find my answer:
```
import operator
sorted_dict = sorted(original_dict.iteritems(), key = operator.itemgetter(1), reverse = True)
```
Then I tried to extract the keys in `sorted_dict` since I thought it is a `dictionary`. However, it turns out that `sorted_dict` is a `list`, thus has no `keys()` method.
In fact, the `sorted_dict` is organized as:
>
> [('ID1', value1), ('ID2', value2), .....] # a list composed of tuples
>
>
>
But what I need is a list of ids such as:
>
> ['ID1', 'ID2', ......]
>
>
>
So now, the problem turns to **How to extract variable in specific position for each of the tuples in a list?**
Any suggestions? Thanks. | 2014/03/27 | [
"https://Stackoverflow.com/questions/22691075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2633803/"
] | You can do that using [list comprehension](http://www.secnetix.de/olli/Python/list_comprehensions.hawk) as follows:
```
>>> ids = [element[0] for element in sorted_dict]
>>> print ids
['ID1', 'ID2', 'ID3', ...]
```
This gets the first element of each `tuple` in the `sorted_dict` list of tuples | Using list comprehension:
```
[i for (i,_) in sorted_dict]
```
should solve your problem |
22,691,075 | This question is a part of my current problem, so let's start with the big picture.
I am trying to sort a dictionary by the values in descending order. My dictionary is 1-to-1 corresponding, such as:
>
> ('ID1':value1, 'ID2':value2, ......)
>
>
>
I followed [this thread](https://stackoverflow.com/questions/613183/python-sort-a-dictionary-by-value) and find my answer:
```
import operator
sorted_dict = sorted(original_dict.iteritems(), key = operator.itemgetter(1), reverse = True)
```
Then I tried to extract the keys in `sorted_dict` since I thought it is a `dictionary`. However, it turns out that `sorted_dict` is a `list`, thus has no `keys()` method.
In fact, the `sorted_dict` is organized as:
>
> [('ID1', value1), ('ID2', value2), .....] # a list composed of tuples
>
>
>
But what I need is a list of ids such as:
>
> ['ID1', 'ID2', ......]
>
>
>
So now, the problem turns to **How to extract variable in specific position for each of the tuples in a list?**
Any suggestions? Thanks. | 2014/03/27 | [
"https://Stackoverflow.com/questions/22691075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2633803/"
] | You can do that using [list comprehension](http://www.secnetix.de/olli/Python/list_comprehensions.hawk) as follows:
```
>>> ids = [element[0] for element in sorted_dict]
>>> print ids
['ID1', 'ID2', 'ID3', ...]
```
This gets the first element of each `tuple` in the `sorted_dict` list of tuples | Use `map` plus `itemgetter` to process a list and get the first element
```
import operator
first_elements = map(operator.itemgetter(0), sorted_list)
``` |
22,691,075 | This question is a part of my current problem, so let's start with the big picture.
I am trying to sort a dictionary by the values in descending order. My dictionary is 1-to-1 corresponding, such as:
>
> ('ID1':value1, 'ID2':value2, ......)
>
>
>
I followed [this thread](https://stackoverflow.com/questions/613183/python-sort-a-dictionary-by-value) and find my answer:
```
import operator
sorted_dict = sorted(original_dict.iteritems(), key = operator.itemgetter(1), reverse = True)
```
Then I tried to extract the keys in `sorted_dict` since I thought it is a `dictionary`. However, it turns out that `sorted_dict` is a `list`, thus has no `keys()` method.
In fact, the `sorted_dict` is organized as:
>
> [('ID1', value1), ('ID2', value2), .....] # a list composed of tuples
>
>
>
But what I need is a list of ids such as:
>
> ['ID1', 'ID2', ......]
>
>
>
So now, the problem turns to **How to extract variable in specific position for each of the tuples in a list?**
Any suggestions? Thanks. | 2014/03/27 | [
"https://Stackoverflow.com/questions/22691075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2633803/"
] | Using list comprehension:
```
[i for (i,_) in sorted_dict]
```
should solve your problem | Use `map` plus `itemgetter` to process a list and get the first element
```
import operator
first_elements = map(operator.itemgetter(0), sorted_list)
``` |
4,476,917 | >
> **Possible Duplicate:**
>
> [How many data a list can hold at the maximum](https://stackoverflow.com/questions/3767979/how-many-data-a-list-can-hold-at-the-maximum)
>
>
>
What is the maximum number of elements a list can hold? | 2010/12/18 | [
"https://Stackoverflow.com/questions/4476917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/489718/"
] | didnt get ya completely but to append a new tr to a specific tr you can use
```
$('#trUniqueId').append(
$('<tr/>').attr("id","newtrId")
);
``` | Try this
```
$(‘ tblDoc tr:last’).after(
"<tr><td style=’width:150px;’>value1</td><td style=’width: 150px’>value2</td><td style=’width: 150px’></td></tr>"
);
``` |
4,476,917 | >
> **Possible Duplicate:**
>
> [How many data a list can hold at the maximum](https://stackoverflow.com/questions/3767979/how-many-data-a-list-can-hold-at-the-maximum)
>
>
>
What is the maximum number of elements a list can hold? | 2010/12/18 | [
"https://Stackoverflow.com/questions/4476917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/489718/"
] | didnt get ya completely but to append a new tr to a specific tr you can use
```
$('#trUniqueId').append(
$('<tr/>').attr("id","newtrId")
);
``` | Alfred is correct, your question is very vague.
However, to add a new row (newID) after the existing row (uniqueID), use the following code:
$('#uniqueID').after('<tr id="newID">' + CELL CONTENT + '</tr>');
As for pulling in the information via Ajax, we'll need to see code samples. |
130,462 | I am doing some hands-on training with Kali linux and one of the exercise I came across was to make an exe file containing malicious payload(say to obtain reverse shell), send it to a victim and hope for the victim to download the exe file. If he/she downloads it, it is fairly easy after that.
Now this isn't tricky at all, assuming the fact that many users aren't aware of security. But in real world, to carry out this attack, there must be more hurdles that an attacker needs to cross for exploitation?
What are those security measures that stops attempt to exploit users? For example I can think of firewall which tries to detect malicious looking requests.
Please answer the question for both internal and external attacks. | 2016/07/19 | [
"https://security.stackexchange.com/questions/130462",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/110848/"
] | There are a number of ways that people attempt to mitigate these attacks.
**External**
* Prevent spam filter from allowing MIME types frequently associated with malware (it's highly unlikely there is a business relevant reason to send .exe or .bat files for instance)
* Use Anti-Virus as .exe's can be detected even after several rounds of encoding. Preferably you'd want "behavioural based" anti-virus which block applications based on actions they attempt to take.
* Educate your staff on how to spot threats and what to do should they encounter them.
* If you're IT department is big enough and you want to pull your hair out figuring it out, software restriction policies can be implemented to only allow known .exe's from running
* Disable the ability for executables to run from the temp directory / directories
* Implement firewall egress filtering. Set up a proxy with deep packet inspection that intercepts SSL / TLS connections and blocks outbound traffic that seems suspicious.
**Internal**
* Do not give local admin access to end users. Just don't. If they need to raise privileges assign them a special account that they have to use the "Run As..." functionality to use, but end users should not have administrative privileges on their workstations.
* Software restrictions / egress filtering / AV / Education / disabling executables from temp directory all still apply for internal
* Segregate your network to prevent lateral movement in the instance there is compromise | You'd be surprised how successful something like this can be - especially for a typical user who may not have any security controls in place. Also, I would argue that if you are able to convince a user to execute code you have provided, a malicious exploit is probably not even necessary - (i.e. "Microsoft Tech Support calls" that obtain remote access to systems utilizing legitimate tools).
In a corporate environment, there would be a variety of security measures that should help to prevent (stop it from happening) and control (limit the successfulness) of such an attack. Most companies take a layered security approach with multiple measures in place.
Walking through how such an attack would take place, here are some of the controls that might be implemented for an attack like this:
1. Provide malicious file to user via email or other means
* Email filtering (Antispam, AV, whitelisting), Email policies (Attachment restrictions such as size or file type)
2. User saves file and launches it
* User awareness training, group policy restrictions (prevent files can be launched from), application whitelisting (prevents unknown files from running), Endpoint AV (scans/deletes/blocks known malicious files).
3. File launches and establishes connection back to attacker (perhaps via an exploit or via legitimate software
* Endpoint and/or network (egress) filtering or proxy (block unknown/untrusted connections), system patches (block known exploits)
4. Attacker gains control of system, exfiltrates data, maintains access, and spreads laterally
* Restricted user permissions (i.e. non-admin), monitoring tools (to record forensic activity for later review)
I'm sure there are more but this was briefly pulled from the top of my head - but you can always take an attack, walk through the appropriate steps, then think of potential mitigations for those steps - and of course you can then rinse, repeat with more attacks against those mitigations. |
130,462 | I am doing some hands-on training with Kali linux and one of the exercise I came across was to make an exe file containing malicious payload(say to obtain reverse shell), send it to a victim and hope for the victim to download the exe file. If he/she downloads it, it is fairly easy after that.
Now this isn't tricky at all, assuming the fact that many users aren't aware of security. But in real world, to carry out this attack, there must be more hurdles that an attacker needs to cross for exploitation?
What are those security measures that stops attempt to exploit users? For example I can think of firewall which tries to detect malicious looking requests.
Please answer the question for both internal and external attacks. | 2016/07/19 | [
"https://security.stackexchange.com/questions/130462",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/110848/"
] | There are a number of ways that people attempt to mitigate these attacks.
**External**
* Prevent spam filter from allowing MIME types frequently associated with malware (it's highly unlikely there is a business relevant reason to send .exe or .bat files for instance)
* Use Anti-Virus as .exe's can be detected even after several rounds of encoding. Preferably you'd want "behavioural based" anti-virus which block applications based on actions they attempt to take.
* Educate your staff on how to spot threats and what to do should they encounter them.
* If you're IT department is big enough and you want to pull your hair out figuring it out, software restriction policies can be implemented to only allow known .exe's from running
* Disable the ability for executables to run from the temp directory / directories
* Implement firewall egress filtering. Set up a proxy with deep packet inspection that intercepts SSL / TLS connections and blocks outbound traffic that seems suspicious.
**Internal**
* Do not give local admin access to end users. Just don't. If they need to raise privileges assign them a special account that they have to use the "Run As..." functionality to use, but end users should not have administrative privileges on their workstations.
* Software restrictions / egress filtering / AV / Education / disabling executables from temp directory all still apply for internal
* Segregate your network to prevent lateral movement in the instance there is compromise | First and foremost you can adopt a firewall policy of "allow what's needed, block the rest". That will only go so far because your malicious outgoing link may take advantage of a hole you have poked in the firewall.
Enterprise grade products will "hook" certain functions like connect(). By hooking the function an analysis engine determines if the connection is legit or bad. This decision take many data points into account like where is the connection going, what prompted the connection, etc...
If you OSX and want to see this in action get a copy of a tool called Little Snitch. This program will hook outgoing connections and allow you to decide if it should be allowed or not. |
130,462 | I am doing some hands-on training with Kali linux and one of the exercise I came across was to make an exe file containing malicious payload(say to obtain reverse shell), send it to a victim and hope for the victim to download the exe file. If he/she downloads it, it is fairly easy after that.
Now this isn't tricky at all, assuming the fact that many users aren't aware of security. But in real world, to carry out this attack, there must be more hurdles that an attacker needs to cross for exploitation?
What are those security measures that stops attempt to exploit users? For example I can think of firewall which tries to detect malicious looking requests.
Please answer the question for both internal and external attacks. | 2016/07/19 | [
"https://security.stackexchange.com/questions/130462",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/110848/"
] | You'd be surprised how successful something like this can be - especially for a typical user who may not have any security controls in place. Also, I would argue that if you are able to convince a user to execute code you have provided, a malicious exploit is probably not even necessary - (i.e. "Microsoft Tech Support calls" that obtain remote access to systems utilizing legitimate tools).
In a corporate environment, there would be a variety of security measures that should help to prevent (stop it from happening) and control (limit the successfulness) of such an attack. Most companies take a layered security approach with multiple measures in place.
Walking through how such an attack would take place, here are some of the controls that might be implemented for an attack like this:
1. Provide malicious file to user via email or other means
* Email filtering (Antispam, AV, whitelisting), Email policies (Attachment restrictions such as size or file type)
2. User saves file and launches it
* User awareness training, group policy restrictions (prevent files can be launched from), application whitelisting (prevents unknown files from running), Endpoint AV (scans/deletes/blocks known malicious files).
3. File launches and establishes connection back to attacker (perhaps via an exploit or via legitimate software
* Endpoint and/or network (egress) filtering or proxy (block unknown/untrusted connections), system patches (block known exploits)
4. Attacker gains control of system, exfiltrates data, maintains access, and spreads laterally
* Restricted user permissions (i.e. non-admin), monitoring tools (to record forensic activity for later review)
I'm sure there are more but this was briefly pulled from the top of my head - but you can always take an attack, walk through the appropriate steps, then think of potential mitigations for those steps - and of course you can then rinse, repeat with more attacks against those mitigations. | First and foremost you can adopt a firewall policy of "allow what's needed, block the rest". That will only go so far because your malicious outgoing link may take advantage of a hole you have poked in the firewall.
Enterprise grade products will "hook" certain functions like connect(). By hooking the function an analysis engine determines if the connection is legit or bad. This decision take many data points into account like where is the connection going, what prompted the connection, etc...
If you OSX and want to see this in action get a copy of a tool called Little Snitch. This program will hook outgoing connections and allow you to decide if it should be allowed or not. |
65,852,340 | I have written a code for a drag and drop using vanilla javascript. When I pick the first div, it does move to last automatically while I was trying to move next.
I don't want to use the jquery library.
What I tried is I created the main div that acts as a container so that inside of that container each div can be moved easily
I have attached what I tried, but I don't understand why this is happening.
```js
const draggables = document.querySelectorAll('.draggable')
const containers = document.querySelectorAll('.mainContainer')
draggables.forEach(draggable => {
draggable.addEventListener('dragstart', () => {
draggable.classList.add('dragging')
})
draggable.addEventListener('dragend', () => {
draggable.classList.remove('dragging')
})
})
containers.forEach(container => {
container.addEventListener('dragover', e => {
e.preventDefault()
const afterElement = getDragAfterElement(container, e.clientY)
const draggable = document.querySelector('.dragging')
if (afterElement == null) {
container.appendChild(draggable)
} else {
container.insertBefore(draggable, afterElement)
}
})
})
function getDragAfterElement(container, y) {
const draggableElements = [...container.querySelectorAll('.draggable:not(.dragging)')]
return draggableElements.reduce((closest, child) => {
const box = child.getBoundingClientRect()
const offset = y - box.top - box.height / 2
if (offset < 0 && offset > closest.offset) {
return { offset: offset, element: child }
} else {
return closest
}
}, { offset: Number.NEGATIVE_INFINITY }).element
}
```
```css
body {
font-family: sans-serif;
}
.mainContainer {
padding: 6px 0;
width: 100%;
}
.draggable {
cursor: move;
display: inline-block;
margin: 0 6px;
z-index: 1;
color: #fff;
background-color: #087ee5;
border: 1px solid #0675d6;
border-radius: 4px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.4);
text-align: center;
max-width: 300px;
min-width: 30px;
border-collapse: separate;
vertical-align: middle;
padding-left: 7px;
padding-right: 7px;
padding-top: 10px;
padding-bottom: 10px;
}
.draggable.dragging {
opacity: 0.5;
}
```
```html
<div class="mainContainer">
<p class="draggable" draggable="true">MOVE 1</p>
<p class="draggable" draggable="true">MOVE 2</p>
<p class="draggable" draggable="true">MOVE 3</p>
<p class="draggable" draggable="true">MOVE 4</p>
</div>
``` | 2021/01/22 | [
"https://Stackoverflow.com/questions/65852340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8133198/"
] | Add an event listener for the dragables on mouseover.
check if the dragable is already in your hand.
if not than append the Node of the dragable in your hand after the Node with mouseover
change the position of the dragged element to absolute and define its position x & y through top and left | I would recommend NOT using the drag events and instead use mouse events. I have had MUCH better luck and reliability with this and you get off screen dragging as well:
```
handleDragStart = () => {
// Once mouse down is detected, you THEN start up the window listeners
// You also append something to the body of your DOM to escape
// your drag graphic from getting covered
window.addEventListener('mousemove', handleDragItem);
// Use mouse up to see if you moused up on something you were targetting
// You can use mouse over events on your targets to have easy state tracking
// No matter what, when window mouse up happens, you clean up all
// event listeners involved
window.addEventListener('mouseup', handleStopDrag);
});
```
Each element involved int he drag and drop can have these events as well paired with the starter window event (a JSX way to look at it to save some typing)
```
<div
onMouseDown={this.handleDragStart(index, width, height)}
onMouseMove={this.handleDragEnter(index)}
onMouseUp={this.handleDrop(index)}
onMouseOut={this.handleDragOut(index)}
/>
``` |
65,852,340 | I have written a code for a drag and drop using vanilla javascript. When I pick the first div, it does move to last automatically while I was trying to move next.
I don't want to use the jquery library.
What I tried is I created the main div that acts as a container so that inside of that container each div can be moved easily
I have attached what I tried, but I don't understand why this is happening.
```js
const draggables = document.querySelectorAll('.draggable')
const containers = document.querySelectorAll('.mainContainer')
draggables.forEach(draggable => {
draggable.addEventListener('dragstart', () => {
draggable.classList.add('dragging')
})
draggable.addEventListener('dragend', () => {
draggable.classList.remove('dragging')
})
})
containers.forEach(container => {
container.addEventListener('dragover', e => {
e.preventDefault()
const afterElement = getDragAfterElement(container, e.clientY)
const draggable = document.querySelector('.dragging')
if (afterElement == null) {
container.appendChild(draggable)
} else {
container.insertBefore(draggable, afterElement)
}
})
})
function getDragAfterElement(container, y) {
const draggableElements = [...container.querySelectorAll('.draggable:not(.dragging)')]
return draggableElements.reduce((closest, child) => {
const box = child.getBoundingClientRect()
const offset = y - box.top - box.height / 2
if (offset < 0 && offset > closest.offset) {
return { offset: offset, element: child }
} else {
return closest
}
}, { offset: Number.NEGATIVE_INFINITY }).element
}
```
```css
body {
font-family: sans-serif;
}
.mainContainer {
padding: 6px 0;
width: 100%;
}
.draggable {
cursor: move;
display: inline-block;
margin: 0 6px;
z-index: 1;
color: #fff;
background-color: #087ee5;
border: 1px solid #0675d6;
border-radius: 4px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.4);
text-align: center;
max-width: 300px;
min-width: 30px;
border-collapse: separate;
vertical-align: middle;
padding-left: 7px;
padding-right: 7px;
padding-top: 10px;
padding-bottom: 10px;
}
.draggable.dragging {
opacity: 0.5;
}
```
```html
<div class="mainContainer">
<p class="draggable" draggable="true">MOVE 1</p>
<p class="draggable" draggable="true">MOVE 2</p>
<p class="draggable" draggable="true">MOVE 3</p>
<p class="draggable" draggable="true">MOVE 4</p>
</div>
``` | 2021/01/22 | [
"https://Stackoverflow.com/questions/65852340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8133198/"
] | Add an event listener for the dragables on mouseover.
check if the dragable is already in your hand.
if not than append the Node of the dragable in your hand after the Node with mouseover
change the position of the dragged element to absolute and define its position x & y through top and left | If your issue here is to stop dragging and place the object you'r dragging into, I would define "areas" where you could drop your element, this areas depend on how many elements you have, in this case (4) you could have the same areas
1 area will be the same are that the dragging element has
3 areas are in between the other elements + the start and end space
so you need to calculate when this element is going to be dropped, I also would use the events `mousedown` and `mouseup` and if you want to know if the element is being "dragged" you can check if the element was `mousedown` + `mousemove`
In my case I did a simliar solution before and I made this "areas" making half of each element and that way it could have some space between those, and the far left and right could be `< first_element.position.X` and `> last_element.position.X` |
65,852,340 | I have written a code for a drag and drop using vanilla javascript. When I pick the first div, it does move to last automatically while I was trying to move next.
I don't want to use the jquery library.
What I tried is I created the main div that acts as a container so that inside of that container each div can be moved easily
I have attached what I tried, but I don't understand why this is happening.
```js
const draggables = document.querySelectorAll('.draggable')
const containers = document.querySelectorAll('.mainContainer')
draggables.forEach(draggable => {
draggable.addEventListener('dragstart', () => {
draggable.classList.add('dragging')
})
draggable.addEventListener('dragend', () => {
draggable.classList.remove('dragging')
})
})
containers.forEach(container => {
container.addEventListener('dragover', e => {
e.preventDefault()
const afterElement = getDragAfterElement(container, e.clientY)
const draggable = document.querySelector('.dragging')
if (afterElement == null) {
container.appendChild(draggable)
} else {
container.insertBefore(draggable, afterElement)
}
})
})
function getDragAfterElement(container, y) {
const draggableElements = [...container.querySelectorAll('.draggable:not(.dragging)')]
return draggableElements.reduce((closest, child) => {
const box = child.getBoundingClientRect()
const offset = y - box.top - box.height / 2
if (offset < 0 && offset > closest.offset) {
return { offset: offset, element: child }
} else {
return closest
}
}, { offset: Number.NEGATIVE_INFINITY }).element
}
```
```css
body {
font-family: sans-serif;
}
.mainContainer {
padding: 6px 0;
width: 100%;
}
.draggable {
cursor: move;
display: inline-block;
margin: 0 6px;
z-index: 1;
color: #fff;
background-color: #087ee5;
border: 1px solid #0675d6;
border-radius: 4px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.4);
text-align: center;
max-width: 300px;
min-width: 30px;
border-collapse: separate;
vertical-align: middle;
padding-left: 7px;
padding-right: 7px;
padding-top: 10px;
padding-bottom: 10px;
}
.draggable.dragging {
opacity: 0.5;
}
```
```html
<div class="mainContainer">
<p class="draggable" draggable="true">MOVE 1</p>
<p class="draggable" draggable="true">MOVE 2</p>
<p class="draggable" draggable="true">MOVE 3</p>
<p class="draggable" draggable="true">MOVE 4</p>
</div>
``` | 2021/01/22 | [
"https://Stackoverflow.com/questions/65852340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8133198/"
] | Add an event listener for the dragables on mouseover.
check if the dragable is already in your hand.
if not than append the Node of the dragable in your hand after the Node with mouseover
change the position of the dragged element to absolute and define its position x & y through top and left | **If your list is limited to one row adding calculation for X-axis can fix the problem.**
Simply change e.clientY to **e.clientX**
```
const afterElement = getDragAfterElement(container, e.clientX)
```
Use left coordinates and the width rather than height and top
```
offset = x - box.left - box.width / 2;
``` |
23,860,150 | I have this little simple trigger..
```
BEGIN
DECLARE FILE_NAME VARCHAR(250);
DECLARE FILE_REFR VARCHAR(500);
SET FILE_NAME = 'Foo';
SET FILE_REFR = 'Bar';
--- I'd like to execute the next statement, using variable FILE_REFR between %% in a LIKE clause:
SELECT COUNT(*) INTO @num_rows FROM referers WHERE filename = FILE_NAME AND ref NOT LIKE "%FILE_REFR%";
...
...
...
END
```
Unfortunately, the variable name is not being picked up as a variable.. but as a CHAR, I know there is something missing there.
Help is more than appreciated.. :) | 2014/05/25 | [
"https://Stackoverflow.com/questions/23860150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1395287/"
] | Use the variable as:
```
CONCAT('%', FILE_REFR, '%');
```
So the complete select query is:
```
SELECT COUNT(*) INTO @num_rows FROM referers WHERE filename = FILE_NAME AND ref NOT LIKE CONCAT('%', FILE_REFR, '%');
```
Thanks | Is this what you want?
```
SELECT COUNT(*) INTO @num_rows
FROM referers
WHERE filename = FILE_NAME AND
ref NOT LIKE CONCAT('%', FILE_REFR, '%');
```
MySQL does not find variables inside string literals. Instead you have to use `CONCAT()` to piece the pattern together. |
9,500,907 | I just tested the TTS feature and I'm really disappointed. While the text is mostly recognizable the quality of the sound is horrible.
There is too much noise and it sounds as if there is a lot of clipping as well. I know that TTS can never be as good as a pre-recorded sound file, but I think I'd be satisfied if at least the clipping could be fixed.
I'd try `KEY_PARAM_VOLUME` but it's only supported since API 11 (I use 8), so I'm not sure if that would fix the clipping issue.
Also I'm pretty sure that if I'm streaming the sound to a file the clipping gets stored as well, so no gain from doing that and then using `SoundPool`to play at a lower volume.
Are there any other ways to improve TTS quality? | 2012/02/29 | [
"https://Stackoverflow.com/questions/9500907",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1189831/"
] | You can do
```
myOption map { success } getOrElse handleTheError
```
or with `scalaz`,
```
myOption.cata(success, handleTheError)
```
where `success` is something like
```
def success(op: Whatever) = {
doSomethingWith(op)
Path(request.path) match {
case "work" => println("--Let's work--")
case "holiday" => println("--Let's relax--")
case _ => println("--Let's drink--")
}
}
```
### Update
Your pseudocode
```
x -> y match {
case a -> c => {}
case a -> d => {}
case b => {}
}
```
can be literally translated to scala as
```
(x, y) match {
case (a, c) => {}
case (a, d) => {}
case (b, _) => {}
}
```
It looks nice (and that's probably what you wanted) if inner matcher have only few options (`c` and `d` in this case), but it leads to code duplication (repeating of pattern `a`). So, in general I'd prefer `map {} getOrElse {}`, or separation of pattern-matchers on smaller functions. But I repeat, in your case it looks reasonable. | If the scrutinees (the expressions on which you match) do not depend on each other, i.e. you can compute them independently, you could perform both `match`es at the same time by wrapping the scrutinees in a tuple.
So your example:
```
x match {
case a => {
y match {
case c => fooC(...)
case d => fooD(...)
}
}
case b => fooB(...)
}
```
could be rewritten as:
```
(x,y) match {
case (a, c) => fooC(...)
case (a, d) => fooD(...)
case (b, _) => fooB(...)
}
```
...as long as `y` doesn't depend on `x`. |
54,654,667 | I have numeric format of date `20001016083256` and I want to convert it into `datetime` format something like `yymmddhhmiss`.
Expected result is
```
2000-10-16 08:32:56
```
Is that possible in SQL Server?
Thanks a lot | 2019/02/12 | [
"https://Stackoverflow.com/questions/54654667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9501823/"
] | Because `iterations[-1]` will evaluate to `undefined` (which is slow as it has to go up the whole prototype chain and can't take a fast path) also doing math with `NaN` will always be slow as it is the non common case.
Also initializing `iterations` with numbers will make the whole test more useful.
Pro Tip: If you try to compare the performance of two codes, they should both result in the same operation at the end ...
---
Some general words about performance tests:
Performance is the compiler's job these days, code optimized by the compiler will always be faster than code you are trying to optimize through some "tricks". Therefore you should write code that is likely by the compiler to optimize, and that is in every case, the *code that everyone else* writes (also your coworkers will love you if you do so). Optimizing that is the most benefitial from the engine's view. Therefore I'd write:
```
let acc = 0;
for(const value of array) acc += value;
// or
const acc = array.reduce((a, b) => a + b, 0);
```
However in the end *it's just a loop*, you won't waste much time if the loop is performing bad, but you will if the whole algorithm performs bad (time complexity of O(n²) or more). Focus on the important things, not the loops. | To elaborate on Jonas Wilms' answer, Javascript does not work with negative indice (unlike languages like Python).
`iterations[-1]` is equal to `iteration["-1"]`, which look for the property named -1 in the array object. That's why `iterations[-1]` will evaluate to `undefined`. |
29,248,748 | I have two two-dimensional arrays,
```
a = [[17360, "Z51.89"],
[17361, "S93.601A"],
[17362, "H66.91"],
[17363, "H25.12"],
[17364, "Z01.01"],
[17365, "Z00.121"],
[17366, "Z00.129"],
[17367, "K57.90"],
[17368, "I63.9"]]
```
and
```
b = [[17360, "I87.2"],
[17361, "s93.601"],
[17362, "h66.91"],
[17363, "h25.12"],
[17364, "Z51.89"],
[17365, "z00.121"],
[17366, "z00.129"],
[17367, "k55.9"],
[17368, "I63.9"]]
```
I would like to count similar rows in both the arrays irrespective of the character case, i.e., `"h25.12"` would be equal to `"H25.12"`.
I tried,
```
count = a.count - (a - b).count
```
But `(a - b)` returns
```
[[17360, "Z51.89"],
[17361, "S93.601A"],
[17362, "H66.91"],
[17363, "H25.12"],
[17364, "Z01.01"],
[17365, "Z00.121"],
[17366, "Z00.129"],
[17367, "K57.90"]]
```
I need the count as `5` since there are five similar rows when we do not consider the character case. | 2015/03/25 | [
"https://Stackoverflow.com/questions/29248748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1896986/"
] | It will convert second element of inner array to upcase for both array then you can perform subtraction, then It will return exact result that you want
```
a.map{|first,second| [first,second.upcase]} - b.map{|first,second| [first,second.upcase]}
``` | Using [Proc](http://ruby-doc.org/core-2.2.0/Proc.html) and '[&](http://ruby-doc.org/core-2.2.0/Array.html#method-i-26)':
```
procedure = Proc.new { |i, j| [i, j.upcase] }
(a.map(&procedure) & b.map(&procedure)).count
#=> 5
```
For better understanding, let's simplify it:
```
new_a = a.map {|i, j| [i, j.upcase]}
new_b = b.map {|i, j| [i, j.upcase]}
# Set intersection using '&'
(new_a & new_b).count
#=> 5
``` |
29,248,748 | I have two two-dimensional arrays,
```
a = [[17360, "Z51.89"],
[17361, "S93.601A"],
[17362, "H66.91"],
[17363, "H25.12"],
[17364, "Z01.01"],
[17365, "Z00.121"],
[17366, "Z00.129"],
[17367, "K57.90"],
[17368, "I63.9"]]
```
and
```
b = [[17360, "I87.2"],
[17361, "s93.601"],
[17362, "h66.91"],
[17363, "h25.12"],
[17364, "Z51.89"],
[17365, "z00.121"],
[17366, "z00.129"],
[17367, "k55.9"],
[17368, "I63.9"]]
```
I would like to count similar rows in both the arrays irrespective of the character case, i.e., `"h25.12"` would be equal to `"H25.12"`.
I tried,
```
count = a.count - (a - b).count
```
But `(a - b)` returns
```
[[17360, "Z51.89"],
[17361, "S93.601A"],
[17362, "H66.91"],
[17363, "H25.12"],
[17364, "Z01.01"],
[17365, "Z00.121"],
[17366, "Z00.129"],
[17367, "K57.90"]]
```
I need the count as `5` since there are five similar rows when we do not consider the character case. | 2015/03/25 | [
"https://Stackoverflow.com/questions/29248748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1896986/"
] | You can convert Arrays to Hash, and use [Enumerable#count](http://ruby-doc.org/core-2.2.1/Enumerable.html#method-i-count) with a block.
```
b_hash = b.to_h
a.to_h.count {|k, v| b_hash[k] && b_hash[k].downcase == v.downcase }
# => 5
``` | I have assumed that the ith element of `a` is to be compared with the ith element of `b`. (Edit: a subsequent comment by the OP confirmed this interpretation.)
I would be inclined to use indices to avoid the construction of relatively large temporary arrays. Here are two ways that might be done.
**#1 Use indices**
```
[a.size,b.size].min.size.times.count do |i|
af,al=a[i]
bf,bl=b[i];
af==bf && al.downcase==bl.downcase
end
#=> 5
```
**#2 Use `Refinements`**
My purpose in giving this solution is to illustrate the use of [Refinements](http://ruby-doc.org/core-2.1.5/doc/syntax/refinements_rdoc.html). I would not argue for its use for the problem at hand, but this problem provides a good vehicle for showing how the technique can be applied.
I could not figure out how best to do this, so I posted this [question](https://stackoverflow.com/questions/29290275/using-refinements-hierarchically) on SO. I've applied @ZackAnderson's answer below.
```
module M
refine String do
alias :dbl_eql :==
def ==(other)
downcase.dbl_eql(other.downcase)
end
end
refine Array do
def ==(other)
zip(other).all? {|x, y| x == y}
end
end
end
'a' == 'A' #=> false (as expected)
[1,'a'] == [1,'A'] #=> false (as expected)
using M
'a' == 'A' #=> true
[1,'a'] == [1,'A'] #=> true
```
I could use [Enumerable#zip](http://ruby-doc.org/core-2.2.0/Enumerable.html#method-i-zip), but for variety I'll use [Object#to\_enum](http://ruby-doc.org/core-2.2.1/Object.html#method-i-to_enum) and [Kernel#loop](http://ruby-doc.org/core-2.2.0/Kernel.html#method-i-loop) in conjunction with [Enumerator#next](http://ruby-doc.org/core-2.1.5/Enumerator.html#method-i-next):
```
ea, eb = a.to_enum, b.to_enum
cnt = 0
loop do
cnt += 1 if ea.next == eb.next
end
cnt #=> 5
``` |
29,248,748 | I have two two-dimensional arrays,
```
a = [[17360, "Z51.89"],
[17361, "S93.601A"],
[17362, "H66.91"],
[17363, "H25.12"],
[17364, "Z01.01"],
[17365, "Z00.121"],
[17366, "Z00.129"],
[17367, "K57.90"],
[17368, "I63.9"]]
```
and
```
b = [[17360, "I87.2"],
[17361, "s93.601"],
[17362, "h66.91"],
[17363, "h25.12"],
[17364, "Z51.89"],
[17365, "z00.121"],
[17366, "z00.129"],
[17367, "k55.9"],
[17368, "I63.9"]]
```
I would like to count similar rows in both the arrays irrespective of the character case, i.e., `"h25.12"` would be equal to `"H25.12"`.
I tried,
```
count = a.count - (a - b).count
```
But `(a - b)` returns
```
[[17360, "Z51.89"],
[17361, "S93.601A"],
[17362, "H66.91"],
[17363, "H25.12"],
[17364, "Z01.01"],
[17365, "Z00.121"],
[17366, "Z00.129"],
[17367, "K57.90"]]
```
I need the count as `5` since there are five similar rows when we do not consider the character case. | 2015/03/25 | [
"https://Stackoverflow.com/questions/29248748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1896986/"
] | Instead of `a - b` you should do this:
```
a.map{|k,v| [k,v.downcase]} - b.map{|k,v| [k,v.downcase]} # case-insensitive
``` | It will convert second element of inner array to upcase for both array then you can perform subtraction, then It will return exact result that you want
```
a.map{|first,second| [first,second.upcase]} - b.map{|first,second| [first,second.upcase]}
``` |
29,248,748 | I have two two-dimensional arrays,
```
a = [[17360, "Z51.89"],
[17361, "S93.601A"],
[17362, "H66.91"],
[17363, "H25.12"],
[17364, "Z01.01"],
[17365, "Z00.121"],
[17366, "Z00.129"],
[17367, "K57.90"],
[17368, "I63.9"]]
```
and
```
b = [[17360, "I87.2"],
[17361, "s93.601"],
[17362, "h66.91"],
[17363, "h25.12"],
[17364, "Z51.89"],
[17365, "z00.121"],
[17366, "z00.129"],
[17367, "k55.9"],
[17368, "I63.9"]]
```
I would like to count similar rows in both the arrays irrespective of the character case, i.e., `"h25.12"` would be equal to `"H25.12"`.
I tried,
```
count = a.count - (a - b).count
```
But `(a - b)` returns
```
[[17360, "Z51.89"],
[17361, "S93.601A"],
[17362, "H66.91"],
[17363, "H25.12"],
[17364, "Z01.01"],
[17365, "Z00.121"],
[17366, "Z00.129"],
[17367, "K57.90"]]
```
I need the count as `5` since there are five similar rows when we do not consider the character case. | 2015/03/25 | [
"https://Stackoverflow.com/questions/29248748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1896986/"
] | It will convert second element of inner array to upcase for both array then you can perform subtraction, then It will return exact result that you want
```
a.map{|first,second| [first,second.upcase]} - b.map{|first,second| [first,second.upcase]}
``` | ```
a.count - (a.map{|e| [e[0],e[1].downcase] } - b.map{|e| [e[0],e[1].downcase] }).count
```
The above maps `a` and `b` to new arrays where the second sub-array element is downcase. |
29,248,748 | I have two two-dimensional arrays,
```
a = [[17360, "Z51.89"],
[17361, "S93.601A"],
[17362, "H66.91"],
[17363, "H25.12"],
[17364, "Z01.01"],
[17365, "Z00.121"],
[17366, "Z00.129"],
[17367, "K57.90"],
[17368, "I63.9"]]
```
and
```
b = [[17360, "I87.2"],
[17361, "s93.601"],
[17362, "h66.91"],
[17363, "h25.12"],
[17364, "Z51.89"],
[17365, "z00.121"],
[17366, "z00.129"],
[17367, "k55.9"],
[17368, "I63.9"]]
```
I would like to count similar rows in both the arrays irrespective of the character case, i.e., `"h25.12"` would be equal to `"H25.12"`.
I tried,
```
count = a.count - (a - b).count
```
But `(a - b)` returns
```
[[17360, "Z51.89"],
[17361, "S93.601A"],
[17362, "H66.91"],
[17363, "H25.12"],
[17364, "Z01.01"],
[17365, "Z00.121"],
[17366, "Z00.129"],
[17367, "K57.90"]]
```
I need the count as `5` since there are five similar rows when we do not consider the character case. | 2015/03/25 | [
"https://Stackoverflow.com/questions/29248748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1896986/"
] | Instead of `a - b` you should do this:
```
a.map{|k,v| [k,v.downcase]} - b.map{|k,v| [k,v.downcase]} # case-insensitive
``` | Using [Proc](http://ruby-doc.org/core-2.2.0/Proc.html) and '[&](http://ruby-doc.org/core-2.2.0/Array.html#method-i-26)':
```
procedure = Proc.new { |i, j| [i, j.upcase] }
(a.map(&procedure) & b.map(&procedure)).count
#=> 5
```
For better understanding, let's simplify it:
```
new_a = a.map {|i, j| [i, j.upcase]}
new_b = b.map {|i, j| [i, j.upcase]}
# Set intersection using '&'
(new_a & new_b).count
#=> 5
``` |
29,248,748 | I have two two-dimensional arrays,
```
a = [[17360, "Z51.89"],
[17361, "S93.601A"],
[17362, "H66.91"],
[17363, "H25.12"],
[17364, "Z01.01"],
[17365, "Z00.121"],
[17366, "Z00.129"],
[17367, "K57.90"],
[17368, "I63.9"]]
```
and
```
b = [[17360, "I87.2"],
[17361, "s93.601"],
[17362, "h66.91"],
[17363, "h25.12"],
[17364, "Z51.89"],
[17365, "z00.121"],
[17366, "z00.129"],
[17367, "k55.9"],
[17368, "I63.9"]]
```
I would like to count similar rows in both the arrays irrespective of the character case, i.e., `"h25.12"` would be equal to `"H25.12"`.
I tried,
```
count = a.count - (a - b).count
```
But `(a - b)` returns
```
[[17360, "Z51.89"],
[17361, "S93.601A"],
[17362, "H66.91"],
[17363, "H25.12"],
[17364, "Z01.01"],
[17365, "Z00.121"],
[17366, "Z00.129"],
[17367, "K57.90"]]
```
I need the count as `5` since there are five similar rows when we do not consider the character case. | 2015/03/25 | [
"https://Stackoverflow.com/questions/29248748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1896986/"
] | You can zip them and then use the block form of count:
```
a.zip(b).count{|e| e[0][1].downcase == e[1][1].downcase}
``` | You want to count similar, so &(AND) operation is more suitable.
```
(a.map { |k, v| [k, v.upcase] } & b.map { |k, v| [k, v.upcase] }).count
``` |
29,248,748 | I have two two-dimensional arrays,
```
a = [[17360, "Z51.89"],
[17361, "S93.601A"],
[17362, "H66.91"],
[17363, "H25.12"],
[17364, "Z01.01"],
[17365, "Z00.121"],
[17366, "Z00.129"],
[17367, "K57.90"],
[17368, "I63.9"]]
```
and
```
b = [[17360, "I87.2"],
[17361, "s93.601"],
[17362, "h66.91"],
[17363, "h25.12"],
[17364, "Z51.89"],
[17365, "z00.121"],
[17366, "z00.129"],
[17367, "k55.9"],
[17368, "I63.9"]]
```
I would like to count similar rows in both the arrays irrespective of the character case, i.e., `"h25.12"` would be equal to `"H25.12"`.
I tried,
```
count = a.count - (a - b).count
```
But `(a - b)` returns
```
[[17360, "Z51.89"],
[17361, "S93.601A"],
[17362, "H66.91"],
[17363, "H25.12"],
[17364, "Z01.01"],
[17365, "Z00.121"],
[17366, "Z00.129"],
[17367, "K57.90"]]
```
I need the count as `5` since there are five similar rows when we do not consider the character case. | 2015/03/25 | [
"https://Stackoverflow.com/questions/29248748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1896986/"
] | You can zip them and then use the block form of count:
```
a.zip(b).count{|e| e[0][1].downcase == e[1][1].downcase}
``` | Using [Proc](http://ruby-doc.org/core-2.2.0/Proc.html) and '[&](http://ruby-doc.org/core-2.2.0/Array.html#method-i-26)':
```
procedure = Proc.new { |i, j| [i, j.upcase] }
(a.map(&procedure) & b.map(&procedure)).count
#=> 5
```
For better understanding, let's simplify it:
```
new_a = a.map {|i, j| [i, j.upcase]}
new_b = b.map {|i, j| [i, j.upcase]}
# Set intersection using '&'
(new_a & new_b).count
#=> 5
``` |
29,248,748 | I have two two-dimensional arrays,
```
a = [[17360, "Z51.89"],
[17361, "S93.601A"],
[17362, "H66.91"],
[17363, "H25.12"],
[17364, "Z01.01"],
[17365, "Z00.121"],
[17366, "Z00.129"],
[17367, "K57.90"],
[17368, "I63.9"]]
```
and
```
b = [[17360, "I87.2"],
[17361, "s93.601"],
[17362, "h66.91"],
[17363, "h25.12"],
[17364, "Z51.89"],
[17365, "z00.121"],
[17366, "z00.129"],
[17367, "k55.9"],
[17368, "I63.9"]]
```
I would like to count similar rows in both the arrays irrespective of the character case, i.e., `"h25.12"` would be equal to `"H25.12"`.
I tried,
```
count = a.count - (a - b).count
```
But `(a - b)` returns
```
[[17360, "Z51.89"],
[17361, "S93.601A"],
[17362, "H66.91"],
[17363, "H25.12"],
[17364, "Z01.01"],
[17365, "Z00.121"],
[17366, "Z00.129"],
[17367, "K57.90"]]
```
I need the count as `5` since there are five similar rows when we do not consider the character case. | 2015/03/25 | [
"https://Stackoverflow.com/questions/29248748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1896986/"
] | Instead of `a - b` you should do this:
```
a.map{|k,v| [k,v.downcase]} - b.map{|k,v| [k,v.downcase]} # case-insensitive
``` | ```
a.count - (a.map{|e| [e[0],e[1].downcase] } - b.map{|e| [e[0],e[1].downcase] }).count
```
The above maps `a` and `b` to new arrays where the second sub-array element is downcase. |
29,248,748 | I have two two-dimensional arrays,
```
a = [[17360, "Z51.89"],
[17361, "S93.601A"],
[17362, "H66.91"],
[17363, "H25.12"],
[17364, "Z01.01"],
[17365, "Z00.121"],
[17366, "Z00.129"],
[17367, "K57.90"],
[17368, "I63.9"]]
```
and
```
b = [[17360, "I87.2"],
[17361, "s93.601"],
[17362, "h66.91"],
[17363, "h25.12"],
[17364, "Z51.89"],
[17365, "z00.121"],
[17366, "z00.129"],
[17367, "k55.9"],
[17368, "I63.9"]]
```
I would like to count similar rows in both the arrays irrespective of the character case, i.e., `"h25.12"` would be equal to `"H25.12"`.
I tried,
```
count = a.count - (a - b).count
```
But `(a - b)` returns
```
[[17360, "Z51.89"],
[17361, "S93.601A"],
[17362, "H66.91"],
[17363, "H25.12"],
[17364, "Z01.01"],
[17365, "Z00.121"],
[17366, "Z00.129"],
[17367, "K57.90"]]
```
I need the count as `5` since there are five similar rows when we do not consider the character case. | 2015/03/25 | [
"https://Stackoverflow.com/questions/29248748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1896986/"
] | Instead of `a - b` you should do this:
```
a.map{|k,v| [k,v.downcase]} - b.map{|k,v| [k,v.downcase]} # case-insensitive
``` | I have assumed that the ith element of `a` is to be compared with the ith element of `b`. (Edit: a subsequent comment by the OP confirmed this interpretation.)
I would be inclined to use indices to avoid the construction of relatively large temporary arrays. Here are two ways that might be done.
**#1 Use indices**
```
[a.size,b.size].min.size.times.count do |i|
af,al=a[i]
bf,bl=b[i];
af==bf && al.downcase==bl.downcase
end
#=> 5
```
**#2 Use `Refinements`**
My purpose in giving this solution is to illustrate the use of [Refinements](http://ruby-doc.org/core-2.1.5/doc/syntax/refinements_rdoc.html). I would not argue for its use for the problem at hand, but this problem provides a good vehicle for showing how the technique can be applied.
I could not figure out how best to do this, so I posted this [question](https://stackoverflow.com/questions/29290275/using-refinements-hierarchically) on SO. I've applied @ZackAnderson's answer below.
```
module M
refine String do
alias :dbl_eql :==
def ==(other)
downcase.dbl_eql(other.downcase)
end
end
refine Array do
def ==(other)
zip(other).all? {|x, y| x == y}
end
end
end
'a' == 'A' #=> false (as expected)
[1,'a'] == [1,'A'] #=> false (as expected)
using M
'a' == 'A' #=> true
[1,'a'] == [1,'A'] #=> true
```
I could use [Enumerable#zip](http://ruby-doc.org/core-2.2.0/Enumerable.html#method-i-zip), but for variety I'll use [Object#to\_enum](http://ruby-doc.org/core-2.2.1/Object.html#method-i-to_enum) and [Kernel#loop](http://ruby-doc.org/core-2.2.0/Kernel.html#method-i-loop) in conjunction with [Enumerator#next](http://ruby-doc.org/core-2.1.5/Enumerator.html#method-i-next):
```
ea, eb = a.to_enum, b.to_enum
cnt = 0
loop do
cnt += 1 if ea.next == eb.next
end
cnt #=> 5
``` |
29,248,748 | I have two two-dimensional arrays,
```
a = [[17360, "Z51.89"],
[17361, "S93.601A"],
[17362, "H66.91"],
[17363, "H25.12"],
[17364, "Z01.01"],
[17365, "Z00.121"],
[17366, "Z00.129"],
[17367, "K57.90"],
[17368, "I63.9"]]
```
and
```
b = [[17360, "I87.2"],
[17361, "s93.601"],
[17362, "h66.91"],
[17363, "h25.12"],
[17364, "Z51.89"],
[17365, "z00.121"],
[17366, "z00.129"],
[17367, "k55.9"],
[17368, "I63.9"]]
```
I would like to count similar rows in both the arrays irrespective of the character case, i.e., `"h25.12"` would be equal to `"H25.12"`.
I tried,
```
count = a.count - (a - b).count
```
But `(a - b)` returns
```
[[17360, "Z51.89"],
[17361, "S93.601A"],
[17362, "H66.91"],
[17363, "H25.12"],
[17364, "Z01.01"],
[17365, "Z00.121"],
[17366, "Z00.129"],
[17367, "K57.90"]]
```
I need the count as `5` since there are five similar rows when we do not consider the character case. | 2015/03/25 | [
"https://Stackoverflow.com/questions/29248748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1896986/"
] | You can convert Arrays to Hash, and use [Enumerable#count](http://ruby-doc.org/core-2.2.1/Enumerable.html#method-i-count) with a block.
```
b_hash = b.to_h
a.to_h.count {|k, v| b_hash[k] && b_hash[k].downcase == v.downcase }
# => 5
``` | You can zip them and then use the block form of count:
```
a.zip(b).count{|e| e[0][1].downcase == e[1][1].downcase}
``` |
70,579,713 | We are using default DOF grids to present the data in the database. We are using this function out of the box and we are doing only the required xml configuration.
In some cases, the tables contain several hundred thousand records and the DOF grid does not show any data, it shows only empty page, although it has to load only 400 records (by default) on the page.
We tryed to find a configuration parameter which can be related to this behavior, but without success, and we have no more options, since we are limited to the configuration in this case.
We were not able to find any particular reason for this behavior, or any good resolution of this problem. | 2022/01/04 | [
"https://Stackoverflow.com/questions/70579713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17830578/"
] | The error is because Rust did not infer the type you expected.
In your code, the type of `value` is inferred to be `&i32` because `input` is a reference of a element in `inputs`, and you `push` a `value` later, therefore the type of `stack` is inferred to be `Vec<&i32>`.
A best fix is to explicitly specify the type of stack:
```rust
let mut stack: Vec<i32> = Vec::new();
```
And because `i32` has implemented `Copy` trait, you should never need to clone a `i32` value, if it is a reference, just dereference it.
Fixed code:
```rust
#[derive(Debug)]
pub enum CalculatorInput {
Add,
Subtract,
Multiply,
Divide,
Value(i32),
}
pub fn evaluate(inputs: &[CalculatorInput]) -> Option<i32> {
let mut stack: Vec<i32> = Vec::new();
for input in inputs {
match input {
CalculatorInput::Value(value) => {
stack.push(*value);
}
operator => {
if stack.len() < 2 {
return None;
}
let second = stack.pop().unwrap();
let first = stack.pop().unwrap();
let result = match operator {
CalculatorInput::Add => first + second,
CalculatorInput::Subtract => first - second,
CalculatorInput::Multiply => first * second,
CalculatorInput::Divide => first / second,
CalculatorInput::Value(_) => return None,
};
stack.push(result);
}
}
}
if stack.len() != 1 {
None
} else {
Some(stack.pop().unwrap())
}
}
``` | You have the same behavior with this simple exemple
```
fn main() {
let mut stack = Vec::new();
let a = String::from("test");
stack.push(&a.clone());
//-------- ^
println!("{:?}", stack);
}
```
and the good way is to not borrow when clone.
```
fn main() {
let mut stack = Vec::new();
let a = String::from("test");
stack.push(a.clone());
//-------- ^
println!("{:?}", stack);
}
```
The variable should be used like this `stack.push(result.clone());` and change code like this
```
pub fn evaluate(inputs: &[CalculatorInput]) -> Option<i32> {
let mut stack: Vec<i32> = Vec::new();
//---------------- ^
for input in inputs {
match input {
CalculatorInput::Value(value) => {
stack.push(value.clone());
//----------------- ^
},
operator => {
if stack.len() < 2 {
return None;
}
let second = stack.pop().unwrap();
let first = stack.pop().unwrap();
let result = match operator {
CalculatorInput::Add => first + second,
CalculatorInput::Subtract => first - second,
CalculatorInput::Multiply => first * second,
CalculatorInput::Divide => first / second,
CalculatorInput::Value(_) => return None,
};
stack.push(result.clone());
//-^
}
}
}
if stack.len() != 1 {
None
} else {
Some(stack.pop().unwrap())
//------- ^
}
}
``` |
2,119,399 | In an exam there is given the general equation for quadratic: $ax^2+bx+c=0$.
It is asking: what does $\dfrac{1}{{x\_1}^3}+\dfrac{1}{{x\_2}^3}$ equal? | 2017/01/29 | [
"https://math.stackexchange.com/questions/2119399",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/411175/"
] | BIG HINT:
$$\frac{1}{x\_1^3}+\frac{1}{x\_2^3}=\frac{x\_1^3+x\_2^3}{x\_1^3x\_2^3}=\frac{(x\_1+x\_2)(x\_1^2-x\_1x\_2+x\_2^2)}{x\_1^3x\_2^3}=\frac{(x\_1+x\_2)((x\_1+x\_2)^2-3x\_1x\_2)}{(x\_1x\_2)^3}$$ | If $x\_{1}$ and $x\_{2}$ are the roots then
$x\_{1} + x\_{2} = -\frac{b}{a}$ and $x\_{1} \cdot x\_{2}=\frac{c}{a}$, now $\frac{1}{x\_{1}}+\frac{1}{x\_{2}} = -\frac{b}{c}$ and $$\frac{1}{x\_{1}^{3}}+\frac{1}{x\_{2}^{3}} = \left(\frac{1}{x\_{1}}+\frac{1}{x\_{2}}\right)^3- 3\cdot\frac{1}{x\_{1}.x\_{2}}\left(\frac{1}{x\_{1}}+\frac{1}{x\_{2}}\right) = \frac{3abc-b^{3}}{c^{3}}$$ |
2,119,399 | In an exam there is given the general equation for quadratic: $ax^2+bx+c=0$.
It is asking: what does $\dfrac{1}{{x\_1}^3}+\dfrac{1}{{x\_2}^3}$ equal? | 2017/01/29 | [
"https://math.stackexchange.com/questions/2119399",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/411175/"
] | BIG HINT:
$$\frac{1}{x\_1^3}+\frac{1}{x\_2^3}=\frac{x\_1^3+x\_2^3}{x\_1^3x\_2^3}=\frac{(x\_1+x\_2)(x\_1^2-x\_1x\_2+x\_2^2)}{x\_1^3x\_2^3}=\frac{(x\_1+x\_2)((x\_1+x\_2)^2-3x\_1x\_2)}{(x\_1x\_2)^3}$$ | Let $\dfrac1{x^3}=y\iff x^3=?$
$$(-c)^3=(ax^2+bx)^3\iff -c^3=a^3(x^3)^2+b^3(x^3)+3ab(x^3)(-c)$$
$$\iff-c^3=\dfrac{a^3}{y^2}+\dfrac{b^3}y-\dfrac{3abc}y$$
$$\iff c^3y^2+(b^3-3abc)y+a^3=0$$ whose roots are $\dfrac1{x\_1^3},\dfrac1{x\_2^3}$
Can you apply Vieta's formula now? |
2,119,399 | In an exam there is given the general equation for quadratic: $ax^2+bx+c=0$.
It is asking: what does $\dfrac{1}{{x\_1}^3}+\dfrac{1}{{x\_2}^3}$ equal? | 2017/01/29 | [
"https://math.stackexchange.com/questions/2119399",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/411175/"
] | Let $\dfrac1{x^3}=y\iff x^3=?$
$$(-c)^3=(ax^2+bx)^3\iff -c^3=a^3(x^3)^2+b^3(x^3)+3ab(x^3)(-c)$$
$$\iff-c^3=\dfrac{a^3}{y^2}+\dfrac{b^3}y-\dfrac{3abc}y$$
$$\iff c^3y^2+(b^3-3abc)y+a^3=0$$ whose roots are $\dfrac1{x\_1^3},\dfrac1{x\_2^3}$
Can you apply Vieta's formula now? | If $x\_{1}$ and $x\_{2}$ are the roots then
$x\_{1} + x\_{2} = -\frac{b}{a}$ and $x\_{1} \cdot x\_{2}=\frac{c}{a}$, now $\frac{1}{x\_{1}}+\frac{1}{x\_{2}} = -\frac{b}{c}$ and $$\frac{1}{x\_{1}^{3}}+\frac{1}{x\_{2}^{3}} = \left(\frac{1}{x\_{1}}+\frac{1}{x\_{2}}\right)^3- 3\cdot\frac{1}{x\_{1}.x\_{2}}\left(\frac{1}{x\_{1}}+\frac{1}{x\_{2}}\right) = \frac{3abc-b^{3}}{c^{3}}$$ |
12,176 | What are the best ways to translate `For all you know`?
For example:
>
> For all you know, she could be lying to you.
>
>
> In response to a friend getting upset that her friend isn't picking up her phone, I respond, "For all you know, something could have happened."
>
>
> A neighbor sends us some vegetables and I tell my wife, "We better wash them first, for all we know, they could be covered in pesticide"
>
>
> | 2015/01/22 | [
"https://chinese.stackexchange.com/questions/12176",
"https://chinese.stackexchange.com",
"https://chinese.stackexchange.com/users/3011/"
] | Agree with StumpyJoePete.
As we all know = Everybody knows.
For all you know = You don't really know for sure.
I think Damian Siniakowicz's suggestion will work.
We better wash the vegetables first, for all we know, they could be covered in pesticide
我们还是先把蔬菜洗一下,说不定有農藥呢。
A couple more suggestions:
我们还是先把蔬菜洗一下,誰知道有沒有農藥呢?
我们还是先把蔬菜洗一下,可能有農藥呢。 | Just found this interesting [discussion](http://forum.wordreference.com/showthread.php?t=477816). It offered a definition:
>
> This expression [for all you know] can be used in any context where the speaker wishes to convey that the listener is failing (deliberately or otherwise) to consider all the possibilities.
>
>
>
And some paraphrases:
```
it wouldn't be surprising if
it would make sense to think
You have no knowledge that would disprove that
As far as you're concerned, it is entirely possible that
You might very well assume that
```
All typical English style phrases that defy direct translation.
没准, 说不定, 谁知道 are all good, but the style is a bit off because the "you" part is omitted. So I propose this:
>
> For all you know, she could be lying to you.
> 你也说不准, 也许她对你撒谎了呢。
>
>
>
Also:
* for all I know -- 我也不敢肯定.
* for all we know -- 我们都说不准.
But sometimes it might be better to drop the pronoun and just use 说不准 and alike, depends on the situation and mood. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.