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
35,807,588
How can fix it (zend version 2.5) ? ServiceLocatorAwareInterface is deprecated and will be removed in version 3.0, along with the ServiceLocatorAwareInitializer. Please update your class Teacher\Controller\TeacherController to remove the implementation, and start injecting your dependencies via factory instead I tried : ``` class TeacherControllerFactory implements FactoryInterface { public function __invoke(ContainerInterface $container, $name, array $options = null) { return new TeacherController( $container->getServiceLocator()->get(TeacherService::class) ); } /** * Create and return TeacherController instance * * For use with zend-servicemanager v2; proxies to __invoke(). * * @param ServiceLocatorInterface $container * @return TeacherController */ public function createService(ServiceLocatorInterface $container) { return $this($container, TeacherController::class); } } ```
2016/03/04
[ "https://Stackoverflow.com/questions/35807588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2017595/" ]
Have a look [here](https://github.com/zendframework/zend-mvc/issues/87). The patch is already merged. Here is the [link to the patch](https://github.com/zendframework/zend-mvc/pull/88). [This Link](http://www.zfdaily.com/2012/07/getting-dependencies-into-zf2-controllers/) helped me to inject dependencies right.
You need add **~E\_USER\_DEPRECATED** You can add in the public/index.php ``` ini_set ( "error_reporting", E_ALL & ~ E_DEPRECATED & ~E_USER_DEPRECATED & ~ E_STRICT ); ``` or ``` error_reporting ( E_ALL & ~ E_DEPRECATED & ~ E_USER_DEPRECATED & ~ E_STRICT ); ``` > > User-generated warning message. This is like an E\_DEPRECATED, except > it is generated in PHP code by using the PHP function trigger\_error(). > > > <http://php.net/manual/en/errorfunc.constants.php>
39,440,027
Edit: the problem didn't lie in NtQuerySystemInformation but in the file type (bObjectType) having changed in this new edition of Windows 10 to the value 34. in Creators Update it's 35. I have been using the following code successfully to retrieve a list of files in use by a given process, but since the Windows 10 "anniversary update" it's no longer working. Windows 10 version 1607 Build 14393.105 Any idea? ``` function GetFileNameHandle(hFile: THandle): String; var lpExitCode: DWORD; pThreadParam: TGetFileNameThreadParam; hThread: THandle; Ret: Cardinal; begin Result := ''; ZeroMemory(@pThreadParam, SizeOf(TGetFileNameThreadParam)); pThreadParam.hFile := hFile; hThread := CreateThread(nil, 0, @GetFileNameHandleThr, @pThreadParam, 0, {PDWORD(nil)^} Ret); if hThread <> 0 then try case WaitForSingleObject(hThread, 100) of WAIT_OBJECT_0: begin GetExitCodeThread(hThread, lpExitCode); if lpExitCode = STATUS_SUCCESS then Result := pThreadParam.FileName; end; WAIT_TIMEOUT: TerminateThread(hThread, 0); end; finally CloseHandle(hThread); end; end; procedure DeleteUpToFull(var src: String; UpTo: String); begin Delete(src,1,Pos(Upto,src)+Length(UpTo)-1); end; procedure ConvertDevicePath(var dvc: string); var i: integer; root: string; device: string; buffer: string; //drvs: string; begin // much faster without using GetReadyDiskDrives setlength(buffer, 1000); for i := Ord('a') to Ord('z') do begin root := Chr(i) + ':'; if (QueryDosDevice(PChar(root), pchar(buffer), 1000) <> 0) then begin device := pchar(buffer); if finds(device+'\',dvc) then begin DeleteUpToFull(dvc,device+'\'); dvc := root[1] + ':\' + dvc; Exit; end; end; end; end; //get the pid of the process which had open the specified file function GetHandlesByProcessID(const ProcessID: Integer; Results: TStringList; TranslatePaths: Boolean): Boolean; var hProcess : THandle; hFile : THandle; ReturnLength: DWORD; SystemInformationLength : DWORD; Index : Integer; pHandleInfo : PSYSTEM_HANDLE_INFORMATION; hQuery : THandle; FileName : string; r: byte; begin Result := False; Results.Clear; pHandleInfo := nil; ReturnLength := 1024; pHandleInfo := AllocMem(ReturnLength); hQuery := NTQuerySystemInformation(DWORD(SystemHandleInformation), pHandleInfo, 1024, @ReturnLength); r := 0; // loop safe-guard While (hQuery = $C0000004) and (r < 10) do begin Inc(r); FreeMem(pHandleInfo); SystemInformationLength := ReturnLength; pHandleInfo := AllocMem(ReturnLength+1024); hQuery := NTQuerySystemInformation(DWORD(SystemHandleInformation), pHandleInfo, SystemInformationLength, @ReturnLength);//Get the list of handles end; // if hQuery = 0 then // RaiseLastOSError; try if (hQuery = STATUS_SUCCESS) then begin for Index := 0 to pHandleInfo^.uCount-1 do begin // filter to requested process if pHandleInfo.Handles[Index].uIdProcess <> ProcessID then Continue; // http://www.codeproject.com/Articles/18975/Listing-Used-Files // For an object of type file, the value bObjectType in SYSTEM_HANDLE is 28 in Windows XP, Windows 2000, and Window 7; 25 in Windows Vista; and 26 in Windows 2000. // XP = 28 // W7 = 28 // W8 = 31 if (pHandleInfo.Handles[Index].ObjectType < 25) or (pHandleInfo.Handles[Index].ObjectType > 31) then Continue; hProcess := OpenProcess(PROCESS_DUP_HANDLE, FALSE, pHandleInfo.Handles[Index].uIdProcess); if(hProcess <> INVALID_HANDLE_VALUE) then begin try if not DuplicateHandle(hProcess, pHandleInfo.Handles[Index].Handle, GetCurrentProcess(), @hFile, 0 ,FALSE, DUPLICATE_SAME_ACCESS) then hFile := INVALID_HANDLE_VALUE; finally CloseHandle(hProcess); end; if (hFile <> INVALID_HANDLE_VALUE) then begin try FileName := GetFileNameHandle(hFile); finally CloseHandle(hFile); end; end else FileName := ''; if FileName <> '' then begin if TranslatePaths then begin ConvertDevicePath(FileName); if not FileExists(Filename) then FileName := '\##\'+Filename; //Continue; end; Results.Add(FileName); end; end; end; end; finally if pHandleInfo <> nil then FreeMem(pHandleInfo); end; end; ```
2016/09/11
[ "https://Stackoverflow.com/questions/39440027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/623437/" ]
The next code (in C++) works 100% correct on all Windows versions (Win 10 1607 as well). Also, I use `SystemExtendedHandleInformation` in place of `SystemHandleInformation`, and advise you to do so, too. It is present from XP onwards. However, the code with `SystemHandleInformation` also works correctly, I just checked it. ```cpp NTSTATUS GetHandlesByProcessID() { union { PVOID buf; PSYSTEM_HANDLE_INFORMATION_EX pshti; }; NTSTATUS status; ULONG ReturnLength = 1024;//not reasonable value for start query,but let be ULONG UniqueProcessId = GetCurrentProcessId(); do { status = STATUS_INSUFFICIENT_RESOURCES; if (buf = new BYTE[ReturnLength]) { if (0 <= (status = ZwQuerySystemInformation(SystemExtendedHandleInformation, buf, ReturnLength, &ReturnLength))) { if (ULONG_PTR NumberOfHandles = pshti->NumberOfHandles) { SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX* Handles = pshti->Handles; do { if (Handles->UniqueProcessId == UniqueProcessId) { DbgPrint("%u, %p\n", Handles->ObjectTypeIndex, Handles->HandleValue); } } while (Handles++, --NumberOfHandles); } } delete buf; } } while (status == STATUS_INFO_LENGTH_MISMATCH); return status; } ``` I think this is like a `repeat until` in a Delphi loop :) `r := 0; // loop safe-guard` - this is not needed. About the hard-coded `ObjectTypeIndex` - beginning in Win 8.1, you can exactly get this info from the OS. You need to call [`ZwQueryObject()`](https://msdn.microsoft.com/en-us/library/windows/hardware/ff567062(v=vs.85).aspx) with [`ObjectTypesInformation`](http://processhacker.sourceforge.net/doc/ntobapi_8h_source.html#l00034) (in some sources, this is named `ObjectAllTypeInformation`, see ntifs.h) to get an array of [`OBJECT_TYPE_INFORMATION`](http://processhacker.sourceforge.net/doc/ntobapi_8h_source.html#l00068) structs. Look for the [`TypeIndex`](http://processhacker.sourceforge.net/doc/ntobapi_8h_source.html#l00088) member - it exactly cooresponds to the [`ObjectTypeIndex`](http://processhacker.sourceforge.net/doc/ntexapi_8h_source.html#l01871) from [`SYSTEM_HANDLE_TABLE_ENTRY_INFO_EX`](http://processhacker.sourceforge.net/doc/ntexapi_8h_source.html#l01864). Before Win 8.1, there also exists ways to get this 'on the fly' by using `ObjectAllTypeInformation` but it is more complex.
I just tested the code from my blog article "[Running multiple instances of Microsoft Lync](http://www.remkoweijnen.nl/blog/2012/03/07/running-multiple-instances-of-lync-howto/)" on Windows 10 Anniversary Update on it appears to work without any issues. Here's the code that I tested (takes process name eg foobar.exe as parameter): ``` program ListHandles; {$APPTYPE CONSOLE} uses JwaWinBase, JwaWinNT, JwaWinType, JwaNtStatus, JwaNative, JwaWinsta, SysUtils, StrUtils; {$IFDEF RELEASE} // Leave out Relocation Table in Release version {$SetPEFlags IMAGE_FILE_RELOCS_STRIPPED} {$ENDIF RELEASE} {$SetPEOptFlags IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE} // No need for RTTI {$WEAKLINKRTTI ON} {$RTTI EXPLICIT METHODS([]) PROPERTIES([]) FIELDS([])} var dwPid: DWORD; hProcess: THandle; {$ALIGN 8} {$MINENUMSIZE 4} type _SYSTEM_HANDLE = record ProcessId: ULONG; ObjectTypeNumber: Byte; Flags: Byte; Handle: USHORT; _Object: PVOID; GrantedAccess: ACCESS_MASK; end; SYSTEM_HANDLE = _SYSTEM_HANDLE; PSYSTEM_HANDLE = ^SYSTEM_HANDLE; _SYSTEM_HANDLE_INFORMATION = record HandleCount: ULONG; Handles: array[0..0] of SYSTEM_HANDLE; end; SYSTEM_HANDLE_INFORMATION = _SYSTEM_HANDLE_INFORMATION; PSYSTEM_HANDLE_INFORMATION = ^SYSTEM_HANDLE_INFORMATION; _OBJECT_NAME_INFORMATION = record Length: USHORT; MaximumLength: USHORT; Pad: DWORD; Name: array[0..MAX_PATH-1] of Char; end; OBJECT_NAME_INFORMATION = _OBJECT_NAME_INFORMATION; POBJECT_NAME_INFORMATION = ^OBJECT_NAME_INFORMATION; function GetObjectName(const hObject: THandle): String; var oni: OBJECT_NAME_INFORMATION; cbSize: DWORD; nts: NTSTATUS; begin Result := ''; cbSize := SizeOf(oni) - (2 * SizeOf(USHORT)); oni.Length := 0; oni.MaximumLength := cbSize; nts := NtQueryObject(hObject, ObjectNameInformation, @oni, cbSize, @cbSize); if (nts = STATUS_SUCCESS) and (oni.Length > 0) then begin Result := oni.Name; end; end; function GetCurrentSessionId: DWORD; asm mov eax,fs:[$00000018]; // Get TEB mov eax,[eax+$30]; // PPEB mov eax,[eax+$1d4]; // PEB.SessionId end; function GetProcessByName(const ProcessName: string): DWORD; var ProcName: PChar; Count: Integer; tsapi: PTS_ALL_PROCESSES_INFO_ARRAY; i: Integer; dwSessionId: DWORD; begin Result := 0; tsapi := nil; if not WinStationGetAllProcesses(SERVERNAME_CURRENT, 0, Count, tsapi) then Exit; ProcName := PChar(ProcessName); dwSessionId := GetCurrentSessionId; WriteLn(Format('Looking for Process %s in Session %d', [ProcessName, dwSessionId])); for i := 0 to Count - 1 do begin with tsapi^[i], tsapi^[i].pTsProcessInfo^ do begin if (dwSessionId = SessionId) and (ImageName.Buffer <> nil) and (StrIComp(ProcName, ImageName.Buffer) = 0) then begin Result := UniqueProcessId; WriteLn(Format('%s has Pid %d', [ProcessName, Result])); Break end; end; end; if tsapi <> nil then WinStationFreeGAPMemory(0, tsapi, Count); end; procedure EnumHandles; var shi: PSYSTEM_HANDLE_INFORMATION; cbSize: DWORD; cbRet: DWORD; nts: NTSTATUS; i: Integer; hDupHandle: THandle; dwErr: DWORD; ObjectName: string; begin WriteLn('Enumerating Handles'); cbSize := $5000; GetMem(shi, cbSize); repeat cbSize := cbSize * 2; ReallocMem(shi, cbSize); nts := NtQuerySystemInformation(SystemHandleInformation, shi, cbSize, @cbRet); until nts <> STATUS_INFO_LENGTH_MISMATCH; if nts = STATUS_SUCCESS then begin for i := 0 to shi^.HandleCount - 1 do begin if shi^.Handles[i].GrantedAccess <> $0012019f then begin if shi^.Handles[i].ProcessId = dwPid then begin nts := NtDuplicateObject(hProcess, shi^.Handles[i].Handle, GetCurrentProcess, @hDupHandle, 0, 0, 0); if nts = STATUS_SUCCESS then begin ObjectName := GetObjectName(hDupHandle); if (ObjectName <> '') then begin WriteLn(Format('Handle=%d Name=%s', [shi^.Handles[i].Handle, ObjectName])); CloseHandle(hDupHandle); end; end; end; end; end; end else begin dwErr := RtlNtStatusToDosError(nts); WriteLn(Format('Failed to read handles, NtQuerySystemInformation failed with %.8x => %d (%s)', [nts, SysErrorMessage(dwErr)])); end; FreeMem(shi); end; procedure AnyKey; begin WriteLn('Finished'); WriteLn('Press any key to continue'); ReadLn; end; begin try dwPid := GetProcessByName(ParamStr(1)); if dwPid = 0 then begin WriteLn('Process was not found, exiting.'); Exit; end; WriteLn(Format('Opening Process %d with PROCESS_DUP_HANDLE', [dwPid])); hProcess := OpenProcess(PROCESS_DUP_HANDLE, False, dwPid); if hProcess = 0 then begin WriteLn(Format('OpenProcess failed with %s', [SysErrorMessage(GetLastError)])); Exit; end else begin WriteLn(Format('Process Handle is %d', [hProcess])); end; EnumHandles; except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end. ```
31,073,977
I have been searching through stackOverflow and whatever google proposes but I wasn't able to get it to work. I am intending to draw a simple 2D Graph in a scrollview, the distance between my datapoints is `kStepX` and I want the scrollview to be at least the width of the screen, if I have more datapoints it should scroll but no more than 100 points. I think I have a problem with my Autolayout and sizing the contentWidth, so here is what I have done so far: 1. I added a UIScrollView with the following constraints: * Leading Space to Superview =0 * Top space to superview =0 * Height = width of superview * Width = width of superview 2. I then added a UIView (called GraphView) as a Child with the following constraints: * zero space to all 4 bounds of scrollview * center X and center Y to scrollview in my GraphViewController I set the contenSize as: ``` historyScrollView.contentSize = CGSizeMake(MAX(SCREEN_WIDTH,sizeof(data)*kStepX), kGraphHeight); ``` but it does not scroll! if I set a fix width in the storyboard the scrollview scrolls further than I have data.. What am I doing wrong?
2015/06/26
[ "https://Stackoverflow.com/questions/31073977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3545176/" ]
You should not be setting the `contentSize` of the `scrollView` when using auto layout. That should be calculated from your constraints if they are setup correctly. What you are missing is to set a width and height constraints on the view inside the scrollView. A `scrollView` determines it's `contentSize` based on the size the subviews have. Since an `UIView` does not have an intrinsic size, you will need to add `width` and `height` constraints to it, then update it when you need it with the right value Something like this should work: ``` innerViewWidthConstraint.constant = MAX(SCREEN_WIDTH,sizeof(data)*kStepX) innerViewHeightConstraint.constant = kGraphHeight // You might need to layout the views too [historyScrollView layoutIfNeeded] ``` Hope this helps! Good luck :)
Take ScrollView in side in your Main View and give `Top`,`Bottom`,`Leading`,`Trailing`,`Center X` and `Center Y`. after take `GraphView` inside you `scrollview` and also set constrain of `GraphView`. set height of `GraphView` ``` @property (weak, nonatomic) IBOutlet NSLayoutConstraint *HeightGraphView; ``` whenEver you set your `HeightGraphView` then automatically set ScrollView contentSize. see my demo its working for Vertically scrolling, apply same for Horizontal scrolling. [Demo Vertical Scrolling](http://ge.tt/5r5b1mC2/v/0)
6,564,962
I'm trying to get a jQuery accordion/tab Shortcode to look like this ``` [accordions] [accordion title="Accordion 1"]Accordion 1 Content[/accordion] [accordion title="Accordion 2"]Accordion 2 Content[/accordion] [accordion title="Accordion 3"]Accordion 3 Content[/accordion] [/accordions] ``` I've tried many ways but I just cant seem to get it to work How can this be done?
2011/07/03
[ "https://Stackoverflow.com/questions/6564962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/493600/" ]
It seems to me that your problem is not with multi-threading, but with inputting something in a GUI from the application fetching the URLs from the database. Why don't you simply reuse the class (or some of the code, if it's impossible to reuse the classes as is) of your GUI application (i.e. the URL indexing method) inside the application which fetches the URLs from the database. My guess is that you could very well index these 15 URLs one after the other, in a single thread. I would try doing that before trying to use threads. The program would look like this: 1. Fetch the 15 URLs from the database and put them into a List 2. Iterate through the list and index each URL 3. Sleep for some time, 4. Go to 1 EDIT: Since it seems the URLs must be indexed again and again until the list of URLs changes, I would use this algorithm: 1. Create a thread pool using `Executors.newCachedThreadPool()` 2. Get the URLs from the database 3. For each URL, create a task which will index the URL again and again, until interrupted (check that `Thread.interrupted()` returns false at each iteration) 4. submit each task to the executorService created at step 1, and keep the returned `Future` inside a list 5. Sleep/wait until the list of URLs to index changes 6. Cancel each `Future` (`cancel(true)`) of the list of `Future` instances 7. Go to step 2.
[`SwingWorker`](http://download.oracle.com/javase/6/docs/api/javax/swing/SwingWorker.html), shown [here](https://stackoverflow.com/questions/4637215/can-a-progress-bar-be-used-in-a-class-outside-main/4637725#4637725), is a good choice.
3,792,402
I have an update to my app that has been reviewed and is **Pending Developer Release**. I have found a bug in this version and would actually like to reject this binary and keep my existing binary. Once I fix the bug, I would like to re-upload a new binary. Is this possible?
2010/09/25
[ "https://Stackoverflow.com/questions/3792402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/457940/" ]
It took me a little while to find the answer to this. It can be done, but the answer isn't very intuitive. In iTunes Connect, select your new application & load the details for it. Click the "Binary Details" link. Once this screen is open, there will be a "Reject this Binary" button on this screen. I found this within the [iTunes Developer guide](http://itunesconnect.apple.com/docs/iTunesConnect_DeveloperGuide.pdf)(Link PDF has only 1 page and no other information) under the Rejecting Your Binary section. Apple really could have made the button more obvious. > > **Note :** Link PDF has only 1 page and no other information > > >
From the [iTunes Connect Developer Guide:](http://itunesconnect.apple.com/docs/iTunesConnect_DeveloperGuide.pdf) NOTE: You can only use the Version Release Control on app updates. It is not available for the first version of your app since you already have the ability to control when your first version goes live, using the Availability Date setting within Rights and Pricing. If you decide that you do not want to ever release a Pending Developer Release version, you will need to click the Release This Version button anyway, in order to create a new version of your app. You are not permitted to skip over an entire version.
3,792,402
I have an update to my app that has been reviewed and is **Pending Developer Release**. I have found a bug in this version and would actually like to reject this binary and keep my existing binary. Once I fix the bug, I would like to re-upload a new binary. Is this possible?
2010/09/25
[ "https://Stackoverflow.com/questions/3792402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/457940/" ]
Attaching screenshots from the App Store Connect (previously known as iTunes Connect) interface: Select the version, then click on "cancel this release" > > You can only edit some information while your version is pending developer release. To edit all information, **cancel this release**. > > > [![ Stor](https://i.stack.imgur.com/yTgvX.png)](https://i.stack.imgur.com/yTgvX.png) You will be prompted with a confirmation dialog: > > Are you sure you want to cancel the release of version 2.6? > > > If you cancel this release, you must choose a new binary and resubmit this app version. Your version will be reviewed again by App Review. > > > ![Cancel Release dialog](https://i.stack.imgur.com/bRYGR.png)
From the [iTunes Connect Developer Guide:](http://itunesconnect.apple.com/docs/iTunesConnect_DeveloperGuide.pdf) NOTE: You can only use the Version Release Control on app updates. It is not available for the first version of your app since you already have the ability to control when your first version goes live, using the Availability Date setting within Rights and Pricing. If you decide that you do not want to ever release a Pending Developer Release version, you will need to click the Release This Version button anyway, in order to create a new version of your app. You are not permitted to skip over an entire version.
3,792,402
I have an update to my app that has been reviewed and is **Pending Developer Release**. I have found a bug in this version and would actually like to reject this binary and keep my existing binary. Once I fix the bug, I would like to re-upload a new binary. Is this possible?
2010/09/25
[ "https://Stackoverflow.com/questions/3792402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/457940/" ]
Explanation to kernix answer: * select app in itunesconnect; * select app version; * you will see "You can only edit some information while your version is pending developer release. To edit all information, cancel this release." at the top of the page. Just click on "cancel this release" link.
From the [iTunes Connect Developer Guide:](http://itunesconnect.apple.com/docs/iTunesConnect_DeveloperGuide.pdf) NOTE: You can only use the Version Release Control on app updates. It is not available for the first version of your app since you already have the ability to control when your first version goes live, using the Availability Date setting within Rights and Pricing. If you decide that you do not want to ever release a Pending Developer Release version, you will need to click the Release This Version button anyway, in order to create a new version of your app. You are not permitted to skip over an entire version.
3,792,402
I have an update to my app that has been reviewed and is **Pending Developer Release**. I have found a bug in this version and would actually like to reject this binary and keep my existing binary. Once I fix the bug, I would like to re-upload a new binary. Is this possible?
2010/09/25
[ "https://Stackoverflow.com/questions/3792402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/457940/" ]
It took me a little while to find the answer to this. It can be done, but the answer isn't very intuitive. In iTunes Connect, select your new application & load the details for it. Click the "Binary Details" link. Once this screen is open, there will be a "Reject this Binary" button on this screen. I found this within the [iTunes Developer guide](http://itunesconnect.apple.com/docs/iTunesConnect_DeveloperGuide.pdf)(Link PDF has only 1 page and no other information) under the Rejecting Your Binary section. Apple really could have made the button more obvious. > > **Note :** Link PDF has only 1 page and no other information > > >
Attaching screenshots from the App Store Connect (previously known as iTunes Connect) interface: Select the version, then click on "cancel this release" > > You can only edit some information while your version is pending developer release. To edit all information, **cancel this release**. > > > [![ Stor](https://i.stack.imgur.com/yTgvX.png)](https://i.stack.imgur.com/yTgvX.png) You will be prompted with a confirmation dialog: > > Are you sure you want to cancel the release of version 2.6? > > > If you cancel this release, you must choose a new binary and resubmit this app version. Your version will be reviewed again by App Review. > > > ![Cancel Release dialog](https://i.stack.imgur.com/bRYGR.png)
3,792,402
I have an update to my app that has been reviewed and is **Pending Developer Release**. I have found a bug in this version and would actually like to reject this binary and keep my existing binary. Once I fix the bug, I would like to re-upload a new binary. Is this possible?
2010/09/25
[ "https://Stackoverflow.com/questions/3792402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/457940/" ]
It took me a little while to find the answer to this. It can be done, but the answer isn't very intuitive. In iTunes Connect, select your new application & load the details for it. Click the "Binary Details" link. Once this screen is open, there will be a "Reject this Binary" button on this screen. I found this within the [iTunes Developer guide](http://itunesconnect.apple.com/docs/iTunesConnect_DeveloperGuide.pdf)(Link PDF has only 1 page and no other information) under the Rejecting Your Binary section. Apple really could have made the button more obvious. > > **Note :** Link PDF has only 1 page and no other information > > >
Explanation to kernix answer: * select app in itunesconnect; * select app version; * you will see "You can only edit some information while your version is pending developer release. To edit all information, cancel this release." at the top of the page. Just click on "cancel this release" link.
3,792,402
I have an update to my app that has been reviewed and is **Pending Developer Release**. I have found a bug in this version and would actually like to reject this binary and keep my existing binary. Once I fix the bug, I would like to re-upload a new binary. Is this possible?
2010/09/25
[ "https://Stackoverflow.com/questions/3792402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/457940/" ]
Attaching screenshots from the App Store Connect (previously known as iTunes Connect) interface: Select the version, then click on "cancel this release" > > You can only edit some information while your version is pending developer release. To edit all information, **cancel this release**. > > > [![ Stor](https://i.stack.imgur.com/yTgvX.png)](https://i.stack.imgur.com/yTgvX.png) You will be prompted with a confirmation dialog: > > Are you sure you want to cancel the release of version 2.6? > > > If you cancel this release, you must choose a new binary and resubmit this app version. Your version will be reviewed again by App Review. > > > ![Cancel Release dialog](https://i.stack.imgur.com/bRYGR.png)
Explanation to kernix answer: * select app in itunesconnect; * select app version; * you will see "You can only edit some information while your version is pending developer release. To edit all information, cancel this release." at the top of the page. Just click on "cancel this release" link.
27,472,505
Under `rows`, I want to check and see if I have a value of `Submit` and the integer value that comes after it. How can I retrieve these two values without using Array.filter()? Google Analytics JS api doesn't like the filter command. ``` { "rows": [ [ "Load", "11" ], [ "No Thanks", "7" ], [ "NoThanks", "3" ], [ "No_Thanks", "2" ], [ "Results", "88" ], [ "Sent", "1" ], [ "Sign Up", "9" ], [ "XOut", "161" ], [ "Submit", "30" ] ] } ```
2014/12/14
[ "https://Stackoverflow.com/questions/27472505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1830549/" ]
Just use a for loop... ``` var submitFound for(var i = 0; i < rows.length; i++) { var row = rows[i] if (row[0] === 'Submit') { submitFound = true break } } if (submitFound) // do stuff ```
Assuming the structure you have in your question is assigned to returnData: ``` var returnedData = {...}; //Structure from the question var value = -1; for(var i = 0; i < returnedData.rows.length; i++){ var row = returnedData.rows[i]; if (row[0] == 'Submit') { value = row[1]; break; } } if (value > -1) { // Do whatever with the value } ```
27,472,505
Under `rows`, I want to check and see if I have a value of `Submit` and the integer value that comes after it. How can I retrieve these two values without using Array.filter()? Google Analytics JS api doesn't like the filter command. ``` { "rows": [ [ "Load", "11" ], [ "No Thanks", "7" ], [ "NoThanks", "3" ], [ "No_Thanks", "2" ], [ "Results", "88" ], [ "Sent", "1" ], [ "Sign Up", "9" ], [ "XOut", "161" ], [ "Submit", "30" ] ] } ```
2014/12/14
[ "https://Stackoverflow.com/questions/27472505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1830549/" ]
Just use a for loop... ``` var submitFound for(var i = 0; i < rows.length; i++) { var row = rows[i] if (row[0] === 'Submit') { submitFound = true break } } if (submitFound) // do stuff ```
Here is an alternative, if you don't wanna use a loop try this : ``` // this object is simplified for test var json={ "rows": [ [ "Load", "11" ], [ "Submit", "30" ] ] }; var stringJson=JSON.stringify(json); var valueOfSubmit= stringJson.match("\"Submit\"\,\"([^)]+)\"\]")[1]; alert(valueOfSubmit); ``` Best regards
13,515,083
I am building an entire system using PHP and MySQL. I want to create usergroups. For example I want *ADMIN1* to be able to **ADD USER**, and **REMOVE USER** BUT I want *ADMIN2* to be able to **ADD USER** only What is the standard way to do this? Thanks.
2012/11/22
[ "https://Stackoverflow.com/questions/13515083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1799131/" ]
You can use system used in drupal ("table\_name"): "users" [uid, name] "users\_roles" [uid, rid] "role" [rid, name] "permission" [pid, rid, name]
I create roles for this, for example ADMIN1, ADMIN2 or whatever descriptive names suits best. Each user is then assigned a Role, and for pages or functions with limited access I check if the logged on user is part of the required role.
13,515,083
I am building an entire system using PHP and MySQL. I want to create usergroups. For example I want *ADMIN1* to be able to **ADD USER**, and **REMOVE USER** BUT I want *ADMIN2* to be able to **ADD USER** only What is the standard way to do this? Thanks.
2012/11/22
[ "https://Stackoverflow.com/questions/13515083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1799131/" ]
You could use a simple login system and use sessions to allow access to certain pages e.g. ``` session_start(); if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) { header ("Location: login.php"); } ``` This example just stops the user from accessing any other pages without first logging in. The login page would change the session like so: ``` if (!empty ($username) && !empty ($password)){ $sql = mysql_query ("SELECT * FROM users WHERE username='".$username."' AND password ='".$password."' LIMIT 1"); if (mysql_num_rows ($sql) > 0){ $_SESSION['login']=1; $_SESSION['username']=$username; header ("Location: index.php"); } ``` That's just a basic example but hopefully you can see what can be done using a user's table and sessions :)
I create roles for this, for example ADMIN1, ADMIN2 or whatever descriptive names suits best. Each user is then assigned a Role, and for pages or functions with limited access I check if the logged on user is part of the required role.
13,515,083
I am building an entire system using PHP and MySQL. I want to create usergroups. For example I want *ADMIN1* to be able to **ADD USER**, and **REMOVE USER** BUT I want *ADMIN2* to be able to **ADD USER** only What is the standard way to do this? Thanks.
2012/11/22
[ "https://Stackoverflow.com/questions/13515083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1799131/" ]
You can use system used in drupal ("table\_name"): "users" [uid, name] "users\_roles" [uid, rid] "role" [rid, name] "permission" [pid, rid, name]
There aren't *usergroups* in mysql. You'll need to use the grant syntax: <https://dev.mysql.com/doc/refman/5.5/en/grant.html>
13,515,083
I am building an entire system using PHP and MySQL. I want to create usergroups. For example I want *ADMIN1* to be able to **ADD USER**, and **REMOVE USER** BUT I want *ADMIN2* to be able to **ADD USER** only What is the standard way to do this? Thanks.
2012/11/22
[ "https://Stackoverflow.com/questions/13515083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1799131/" ]
You could use a simple login system and use sessions to allow access to certain pages e.g. ``` session_start(); if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) { header ("Location: login.php"); } ``` This example just stops the user from accessing any other pages without first logging in. The login page would change the session like so: ``` if (!empty ($username) && !empty ($password)){ $sql = mysql_query ("SELECT * FROM users WHERE username='".$username."' AND password ='".$password."' LIMIT 1"); if (mysql_num_rows ($sql) > 0){ $_SESSION['login']=1; $_SESSION['username']=$username; header ("Location: index.php"); } ``` That's just a basic example but hopefully you can see what can be done using a user's table and sessions :)
There aren't *usergroups* in mysql. You'll need to use the grant syntax: <https://dev.mysql.com/doc/refman/5.5/en/grant.html>
13,515,083
I am building an entire system using PHP and MySQL. I want to create usergroups. For example I want *ADMIN1* to be able to **ADD USER**, and **REMOVE USER** BUT I want *ADMIN2* to be able to **ADD USER** only What is the standard way to do this? Thanks.
2012/11/22
[ "https://Stackoverflow.com/questions/13515083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1799131/" ]
You can use system used in drupal ("table\_name"): "users" [uid, name] "users\_roles" [uid, rid] "role" [rid, name] "permission" [pid, rid, name]
Are you looking for something like this? ``` Create user ‘admin1’ identified by ‘YOUR_PASSWORD’; Revoke all on * from ‘admin1’; Grant insert, delete, update, select on YOUR_TABLE to ‘admin1’; Create user ‘admin2’ identified by ‘YOUR_PASSWORD’; Revoke all on * from ‘admin2’; Grant insert on YOUR_TABLE to ‘admin2’; ```
13,515,083
I am building an entire system using PHP and MySQL. I want to create usergroups. For example I want *ADMIN1* to be able to **ADD USER**, and **REMOVE USER** BUT I want *ADMIN2* to be able to **ADD USER** only What is the standard way to do this? Thanks.
2012/11/22
[ "https://Stackoverflow.com/questions/13515083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1799131/" ]
You could use a simple login system and use sessions to allow access to certain pages e.g. ``` session_start(); if (!(isset($_SESSION['login']) && $_SESSION['login'] != '')) { header ("Location: login.php"); } ``` This example just stops the user from accessing any other pages without first logging in. The login page would change the session like so: ``` if (!empty ($username) && !empty ($password)){ $sql = mysql_query ("SELECT * FROM users WHERE username='".$username."' AND password ='".$password."' LIMIT 1"); if (mysql_num_rows ($sql) > 0){ $_SESSION['login']=1; $_SESSION['username']=$username; header ("Location: index.php"); } ``` That's just a basic example but hopefully you can see what can be done using a user's table and sessions :)
Are you looking for something like this? ``` Create user ‘admin1’ identified by ‘YOUR_PASSWORD’; Revoke all on * from ‘admin1’; Grant insert, delete, update, select on YOUR_TABLE to ‘admin1’; Create user ‘admin2’ identified by ‘YOUR_PASSWORD’; Revoke all on * from ‘admin2’; Grant insert on YOUR_TABLE to ‘admin2’; ```
17,736,419
I am trying to resize the buttons in a button array I made, but I don't know how Here's my code ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.game); final TableLayout container = (TableLayout) findViewById(R.id.tableLayout5); Button btn[][] = new Button[10][10]; for(int i = 0; i<10; i++){ for(int j = 0; j<10; j++){ btn [i][j] = new Button(this); container.addView(btn[i][j],i); } } } ```
2013/07/19
[ "https://Stackoverflow.com/questions/17736419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2585782/" ]
``` var p = System.Diagnostics.Process.Start("notepad"); p.WaitForExit(); ```
You can use the Process class to start external processes. It will let you start arbitrary programs <http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx>
17,736,419
I am trying to resize the buttons in a button array I made, but I don't know how Here's my code ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.game); final TableLayout container = (TableLayout) findViewById(R.id.tableLayout5); Button btn[][] = new Button[10][10]; for(int i = 0; i<10; i++){ for(int j = 0; j<10; j++){ btn [i][j] = new Button(this); container.addView(btn[i][j],i); } } } ```
2013/07/19
[ "https://Stackoverflow.com/questions/17736419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2585782/" ]
You can use the `Process` class. It lets you specify some options about how you want to execute it, and also provides a method which waits the process to exit before executing the next statement. look at this link (the msdn reference): <http://msdn.microsoft.com/fr-fr/library/system.diagnostics.process.aspx> basically what you can do is: ``` Process p; // some code to initialize it, like p = startProcessWithoutOutput(path, args, true); p.WaitForExit(); ``` an example of initializing the process (that's just some code I used once somewhere): ``` private Process startProcessWithOutput(string command, string args, bool showWindow) { Process p = new Process(); p.StartInfo = new ProcessStartInfo(command, args); p.StartInfo.RedirectStandardOutput = false; p.StartInfo.RedirectStandardError = true; p.StartInfo.UseShellExecute = false; p.StartInfo.CreateNoWindow = !showWindow; p.ErrorDataReceived += (s, a) => addLogLine(a.Data); p.Start(); p.BeginErrorReadLine(); return p; } ``` as you can see in this code you can also do some output redirection, error redirection.... If you dig in the class I think you'll find quite quickly what you need.
You can use the Process class to start external processes. It will let you start arbitrary programs <http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx>
17,736,419
I am trying to resize the buttons in a button array I made, but I don't know how Here's my code ``` @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.game); final TableLayout container = (TableLayout) findViewById(R.id.tableLayout5); Button btn[][] = new Button[10][10]; for(int i = 0; i<10; i++){ for(int j = 0; j<10; j++){ btn [i][j] = new Button(this); container.addView(btn[i][j],i); } } } ```
2013/07/19
[ "https://Stackoverflow.com/questions/17736419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2585782/" ]
You can use the `Process` class. It lets you specify some options about how you want to execute it, and also provides a method which waits the process to exit before executing the next statement. look at this link (the msdn reference): <http://msdn.microsoft.com/fr-fr/library/system.diagnostics.process.aspx> basically what you can do is: ``` Process p; // some code to initialize it, like p = startProcessWithoutOutput(path, args, true); p.WaitForExit(); ``` an example of initializing the process (that's just some code I used once somewhere): ``` private Process startProcessWithOutput(string command, string args, bool showWindow) { Process p = new Process(); p.StartInfo = new ProcessStartInfo(command, args); p.StartInfo.RedirectStandardOutput = false; p.StartInfo.RedirectStandardError = true; p.StartInfo.UseShellExecute = false; p.StartInfo.CreateNoWindow = !showWindow; p.ErrorDataReceived += (s, a) => addLogLine(a.Data); p.Start(); p.BeginErrorReadLine(); return p; } ``` as you can see in this code you can also do some output redirection, error redirection.... If you dig in the class I think you'll find quite quickly what you need.
``` var p = System.Diagnostics.Process.Start("notepad"); p.WaitForExit(); ```
261,045
I just upgraded to Eclipse 3.4 for the second time and I think its for good now. The first time (right when it was released) was too buggy for me to stomach (mainly the PDT 2.0 plug-in); but now it seems to be all worked out. My problem is the Javascript validator. If I define a class in one JS file in my project, then try to use it in another, it tells me that the type is undefined. This is really annoying as some of my scripts are littered with red squigglys. Another problem is that this code: ``` var m_dialogFrame = document.getElementById(m_dialogId); ``` Makes a yellow squiggle saying "Type mismatch: cannot convert from Element to \_\_\_m\_dialogBody5" I can fix it by adding ``` /** * @type Element */ ``` Before it, but that, also, will be messy. Also, both: ``` new XMLHttpRequest(); ``` And ``` new ActiveXObject("Microsoft.XMLHTTP"); ``` Get red squiggles saying "x cannot be resolved to a type" The last problem is with: if (m\_options.width != "auto") Gets a red squiggly because: "The operator != is undefined for the argument type(s) Number, String" How can I fix these issues, or just scrap the entire Javascript validation tool? BTW: it looks frikin awesome if I can get it to work.
2008/11/04
[ "https://Stackoverflow.com/questions/261045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Looks like this problem is due to the default browser for Eclipse not having the required libraries. Try below steps to add the required library: Project -> Properties -> JavaScript -> JavaScript Libraries -> Libraries(tab) -> Add Runtime Library -> select 'Internet Explorer Library' This should resolve the issue. It did for me.
After hours of looking around I have found how to definetly remove JS validation. This means editing your .project file, so back it up before just in case. * Close Eclipse * Open your .project file * look for the following line : <nature>org.eclipse.wst.jsdt.core.jsNature</nature> * delete it * save your file and start Eclipse There no more red or yellow squibble all over the place... but no more js validation. If anyone knows how to do it properly without editing .project file please share.
261,045
I just upgraded to Eclipse 3.4 for the second time and I think its for good now. The first time (right when it was released) was too buggy for me to stomach (mainly the PDT 2.0 plug-in); but now it seems to be all worked out. My problem is the Javascript validator. If I define a class in one JS file in my project, then try to use it in another, it tells me that the type is undefined. This is really annoying as some of my scripts are littered with red squigglys. Another problem is that this code: ``` var m_dialogFrame = document.getElementById(m_dialogId); ``` Makes a yellow squiggle saying "Type mismatch: cannot convert from Element to \_\_\_m\_dialogBody5" I can fix it by adding ``` /** * @type Element */ ``` Before it, but that, also, will be messy. Also, both: ``` new XMLHttpRequest(); ``` And ``` new ActiveXObject("Microsoft.XMLHTTP"); ``` Get red squiggles saying "x cannot be resolved to a type" The last problem is with: if (m\_options.width != "auto") Gets a red squiggly because: "The operator != is undefined for the argument type(s) Number, String" How can I fix these issues, or just scrap the entire Javascript validation tool? BTW: it looks frikin awesome if I can get it to work.
2008/11/04
[ "https://Stackoverflow.com/questions/261045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Apparently to fully disable the validation you should also disable "Report problems as you type" under JavaScript -> Editor.
The answer of user85835 helped me a bit but I also needed to follow these two extra steps. First in order to actually remove the warnings and errors and avoid having them recreated immediately do like this: 1. Disable automatic immediate rebuild after clean which is done in the Clean... window. 2. Clean project Then close Eclipse and remove the <nature>org.eclipse.wst.jsdt.core.jsNature</nature> as user85835 describes. But before restarting Eclipse also do this second step. 1. In your .project file look for a <buildCommand> XML block containing a <name>org.eclipse.wst.jsdt.core.javascriptValidator</name>. 2. If you find this delete this block too. Then save your .project file and start Eclipse again Restore clean and rebuild settings as you wish to have them. This worked for me.
261,045
I just upgraded to Eclipse 3.4 for the second time and I think its for good now. The first time (right when it was released) was too buggy for me to stomach (mainly the PDT 2.0 plug-in); but now it seems to be all worked out. My problem is the Javascript validator. If I define a class in one JS file in my project, then try to use it in another, it tells me that the type is undefined. This is really annoying as some of my scripts are littered with red squigglys. Another problem is that this code: ``` var m_dialogFrame = document.getElementById(m_dialogId); ``` Makes a yellow squiggle saying "Type mismatch: cannot convert from Element to \_\_\_m\_dialogBody5" I can fix it by adding ``` /** * @type Element */ ``` Before it, but that, also, will be messy. Also, both: ``` new XMLHttpRequest(); ``` And ``` new ActiveXObject("Microsoft.XMLHTTP"); ``` Get red squiggles saying "x cannot be resolved to a type" The last problem is with: if (m\_options.width != "auto") Gets a red squiggly because: "The operator != is undefined for the argument type(s) Number, String" How can I fix these issues, or just scrap the entire Javascript validation tool? BTW: it looks frikin awesome if I can get it to work.
2008/11/04
[ "https://Stackoverflow.com/questions/261045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Looks like this problem is due to the default browser for Eclipse not having the required libraries. Try below steps to add the required library: Project -> Properties -> JavaScript -> JavaScript Libraries -> Libraries(tab) -> Add Runtime Library -> select 'Internet Explorer Library' This should resolve the issue. It did for me.
I found that old validation errors will stick around in the problems view and highlighted in the files until after you tell it to validate again, so after saving your JSP validation preferences, right click on a project to validate everything in it; that will make the errors go away.
261,045
I just upgraded to Eclipse 3.4 for the second time and I think its for good now. The first time (right when it was released) was too buggy for me to stomach (mainly the PDT 2.0 plug-in); but now it seems to be all worked out. My problem is the Javascript validator. If I define a class in one JS file in my project, then try to use it in another, it tells me that the type is undefined. This is really annoying as some of my scripts are littered with red squigglys. Another problem is that this code: ``` var m_dialogFrame = document.getElementById(m_dialogId); ``` Makes a yellow squiggle saying "Type mismatch: cannot convert from Element to \_\_\_m\_dialogBody5" I can fix it by adding ``` /** * @type Element */ ``` Before it, but that, also, will be messy. Also, both: ``` new XMLHttpRequest(); ``` And ``` new ActiveXObject("Microsoft.XMLHTTP"); ``` Get red squiggles saying "x cannot be resolved to a type" The last problem is with: if (m\_options.width != "auto") Gets a red squiggly because: "The operator != is undefined for the argument type(s) Number, String" How can I fix these issues, or just scrap the entire Javascript validation tool? BTW: it looks frikin awesome if I can get it to work.
2008/11/04
[ "https://Stackoverflow.com/questions/261045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Looks like this problem is due to the default browser for Eclipse not having the required libraries. Try below steps to add the required library: Project -> Properties -> JavaScript -> JavaScript Libraries -> Libraries(tab) -> Add Runtime Library -> select 'Internet Explorer Library' This should resolve the issue. It did for me.
Apparently to fully disable the validation you should also disable "Report problems as you type" under JavaScript -> Editor.
261,045
I just upgraded to Eclipse 3.4 for the second time and I think its for good now. The first time (right when it was released) was too buggy for me to stomach (mainly the PDT 2.0 plug-in); but now it seems to be all worked out. My problem is the Javascript validator. If I define a class in one JS file in my project, then try to use it in another, it tells me that the type is undefined. This is really annoying as some of my scripts are littered with red squigglys. Another problem is that this code: ``` var m_dialogFrame = document.getElementById(m_dialogId); ``` Makes a yellow squiggle saying "Type mismatch: cannot convert from Element to \_\_\_m\_dialogBody5" I can fix it by adding ``` /** * @type Element */ ``` Before it, but that, also, will be messy. Also, both: ``` new XMLHttpRequest(); ``` And ``` new ActiveXObject("Microsoft.XMLHTTP"); ``` Get red squiggles saying "x cannot be resolved to a type" The last problem is with: if (m\_options.width != "auto") Gets a red squiggly because: "The operator != is undefined for the argument type(s) Number, String" How can I fix these issues, or just scrap the entire Javascript validation tool? BTW: it looks frikin awesome if I can get it to work.
2008/11/04
[ "https://Stackoverflow.com/questions/261045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Looks like this problem is due to the default browser for Eclipse not having the required libraries. Try below steps to add the required library: Project -> Properties -> JavaScript -> JavaScript Libraries -> Libraries(tab) -> Add Runtime Library -> select 'Internet Explorer Library' This should resolve the issue. It did for me.
This is very painful. One way to solve the problem for me was to exclude all the js files from the build. Properties->javascript->Libraries->Source tab and exclude all the files that give you problems....its a pitty because I wanted some autocomplete.... : ( but need to finish the project for work.... If somebody has a solution it would be highly appreciated : )
261,045
I just upgraded to Eclipse 3.4 for the second time and I think its for good now. The first time (right when it was released) was too buggy for me to stomach (mainly the PDT 2.0 plug-in); but now it seems to be all worked out. My problem is the Javascript validator. If I define a class in one JS file in my project, then try to use it in another, it tells me that the type is undefined. This is really annoying as some of my scripts are littered with red squigglys. Another problem is that this code: ``` var m_dialogFrame = document.getElementById(m_dialogId); ``` Makes a yellow squiggle saying "Type mismatch: cannot convert from Element to \_\_\_m\_dialogBody5" I can fix it by adding ``` /** * @type Element */ ``` Before it, but that, also, will be messy. Also, both: ``` new XMLHttpRequest(); ``` And ``` new ActiveXObject("Microsoft.XMLHTTP"); ``` Get red squiggles saying "x cannot be resolved to a type" The last problem is with: if (m\_options.width != "auto") Gets a red squiggly because: "The operator != is undefined for the argument type(s) Number, String" How can I fix these issues, or just scrap the entire Javascript validation tool? BTW: it looks frikin awesome if I can get it to work.
2008/11/04
[ "https://Stackoverflow.com/questions/261045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Unfortunately, you might just have to scrap the JavaScript validation. In my experience, the JavaScript tools which come bundled with Eclipse 3.4 have a hard time... well, *understanding* JavaScript at all, generating bogus warnings and errors as a result. For example, the common practice of using an `Object` as a poor man's namespace causes it to get completely lost. Here's [a screenshot of the kind of mess it makes](http://www.jonathanbuchanan.plus.com/images/eclipsejs.png) when trying to understand [this JavaScript file](http://code.google.com/p/js-forms/source/browse/trunk/time.js) - note the useless outline view and the spurious (and incorrect) warnings and errors (including not seeming to understand than `String.split` returns an `Array`).
Apparently to fully disable the validation you should also disable "Report problems as you type" under JavaScript -> Editor.
261,045
I just upgraded to Eclipse 3.4 for the second time and I think its for good now. The first time (right when it was released) was too buggy for me to stomach (mainly the PDT 2.0 plug-in); but now it seems to be all worked out. My problem is the Javascript validator. If I define a class in one JS file in my project, then try to use it in another, it tells me that the type is undefined. This is really annoying as some of my scripts are littered with red squigglys. Another problem is that this code: ``` var m_dialogFrame = document.getElementById(m_dialogId); ``` Makes a yellow squiggle saying "Type mismatch: cannot convert from Element to \_\_\_m\_dialogBody5" I can fix it by adding ``` /** * @type Element */ ``` Before it, but that, also, will be messy. Also, both: ``` new XMLHttpRequest(); ``` And ``` new ActiveXObject("Microsoft.XMLHTTP"); ``` Get red squiggles saying "x cannot be resolved to a type" The last problem is with: if (m\_options.width != "auto") Gets a red squiggly because: "The operator != is undefined for the argument type(s) Number, String" How can I fix these issues, or just scrap the entire Javascript validation tool? BTW: it looks frikin awesome if I can get it to work.
2008/11/04
[ "https://Stackoverflow.com/questions/261045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
This is very painful. One way to solve the problem for me was to exclude all the js files from the build. Properties->javascript->Libraries->Source tab and exclude all the files that give you problems....its a pitty because I wanted some autocomplete.... : ( but need to finish the project for work.... If somebody has a solution it would be highly appreciated : )
I found that old validation errors will stick around in the problems view and highlighted in the files until after you tell it to validate again, so after saving your JSP validation preferences, right click on a project to validate everything in it; that will make the errors go away.
261,045
I just upgraded to Eclipse 3.4 for the second time and I think its for good now. The first time (right when it was released) was too buggy for me to stomach (mainly the PDT 2.0 plug-in); but now it seems to be all worked out. My problem is the Javascript validator. If I define a class in one JS file in my project, then try to use it in another, it tells me that the type is undefined. This is really annoying as some of my scripts are littered with red squigglys. Another problem is that this code: ``` var m_dialogFrame = document.getElementById(m_dialogId); ``` Makes a yellow squiggle saying "Type mismatch: cannot convert from Element to \_\_\_m\_dialogBody5" I can fix it by adding ``` /** * @type Element */ ``` Before it, but that, also, will be messy. Also, both: ``` new XMLHttpRequest(); ``` And ``` new ActiveXObject("Microsoft.XMLHTTP"); ``` Get red squiggles saying "x cannot be resolved to a type" The last problem is with: if (m\_options.width != "auto") Gets a red squiggly because: "The operator != is undefined for the argument type(s) Number, String" How can I fix these issues, or just scrap the entire Javascript validation tool? BTW: it looks frikin awesome if I can get it to work.
2008/11/04
[ "https://Stackoverflow.com/questions/261045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Unfortunately, you might just have to scrap the JavaScript validation. In my experience, the JavaScript tools which come bundled with Eclipse 3.4 have a hard time... well, *understanding* JavaScript at all, generating bogus warnings and errors as a result. For example, the common practice of using an `Object` as a poor man's namespace causes it to get completely lost. Here's [a screenshot of the kind of mess it makes](http://www.jonathanbuchanan.plus.com/images/eclipsejs.png) when trying to understand [this JavaScript file](http://code.google.com/p/js-forms/source/browse/trunk/time.js) - note the useless outline view and the spurious (and incorrect) warnings and errors (including not seeming to understand than `String.split` returns an `Array`).
After hours of looking around I have found how to definetly remove JS validation. This means editing your .project file, so back it up before just in case. * Close Eclipse * Open your .project file * look for the following line : <nature>org.eclipse.wst.jsdt.core.jsNature</nature> * delete it * save your file and start Eclipse There no more red or yellow squibble all over the place... but no more js validation. If anyone knows how to do it properly without editing .project file please share.
261,045
I just upgraded to Eclipse 3.4 for the second time and I think its for good now. The first time (right when it was released) was too buggy for me to stomach (mainly the PDT 2.0 plug-in); but now it seems to be all worked out. My problem is the Javascript validator. If I define a class in one JS file in my project, then try to use it in another, it tells me that the type is undefined. This is really annoying as some of my scripts are littered with red squigglys. Another problem is that this code: ``` var m_dialogFrame = document.getElementById(m_dialogId); ``` Makes a yellow squiggle saying "Type mismatch: cannot convert from Element to \_\_\_m\_dialogBody5" I can fix it by adding ``` /** * @type Element */ ``` Before it, but that, also, will be messy. Also, both: ``` new XMLHttpRequest(); ``` And ``` new ActiveXObject("Microsoft.XMLHTTP"); ``` Get red squiggles saying "x cannot be resolved to a type" The last problem is with: if (m\_options.width != "auto") Gets a red squiggly because: "The operator != is undefined for the argument type(s) Number, String" How can I fix these issues, or just scrap the entire Javascript validation tool? BTW: it looks frikin awesome if I can get it to work.
2008/11/04
[ "https://Stackoverflow.com/questions/261045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
This is very painful. One way to solve the problem for me was to exclude all the js files from the build. Properties->javascript->Libraries->Source tab and exclude all the files that give you problems....its a pitty because I wanted some autocomplete.... : ( but need to finish the project for work.... If somebody has a solution it would be highly appreciated : )
After hours of looking around I have found how to definetly remove JS validation. This means editing your .project file, so back it up before just in case. * Close Eclipse * Open your .project file * look for the following line : <nature>org.eclipse.wst.jsdt.core.jsNature</nature> * delete it * save your file and start Eclipse There no more red or yellow squibble all over the place... but no more js validation. If anyone knows how to do it properly without editing .project file please share.
261,045
I just upgraded to Eclipse 3.4 for the second time and I think its for good now. The first time (right when it was released) was too buggy for me to stomach (mainly the PDT 2.0 plug-in); but now it seems to be all worked out. My problem is the Javascript validator. If I define a class in one JS file in my project, then try to use it in another, it tells me that the type is undefined. This is really annoying as some of my scripts are littered with red squigglys. Another problem is that this code: ``` var m_dialogFrame = document.getElementById(m_dialogId); ``` Makes a yellow squiggle saying "Type mismatch: cannot convert from Element to \_\_\_m\_dialogBody5" I can fix it by adding ``` /** * @type Element */ ``` Before it, but that, also, will be messy. Also, both: ``` new XMLHttpRequest(); ``` And ``` new ActiveXObject("Microsoft.XMLHTTP"); ``` Get red squiggles saying "x cannot be resolved to a type" The last problem is with: if (m\_options.width != "auto") Gets a red squiggly because: "The operator != is undefined for the argument type(s) Number, String" How can I fix these issues, or just scrap the entire Javascript validation tool? BTW: it looks frikin awesome if I can get it to work.
2008/11/04
[ "https://Stackoverflow.com/questions/261045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Unfortunately, you might just have to scrap the JavaScript validation. In my experience, the JavaScript tools which come bundled with Eclipse 3.4 have a hard time... well, *understanding* JavaScript at all, generating bogus warnings and errors as a result. For example, the common practice of using an `Object` as a poor man's namespace causes it to get completely lost. Here's [a screenshot of the kind of mess it makes](http://www.jonathanbuchanan.plus.com/images/eclipsejs.png) when trying to understand [this JavaScript file](http://code.google.com/p/js-forms/source/browse/trunk/time.js) - note the useless outline view and the spurious (and incorrect) warnings and errors (including not seeming to understand than `String.split` returns an `Array`).
I found that old validation errors will stick around in the problems view and highlighted in the files until after you tell it to validate again, so after saving your JSP validation preferences, right click on a project to validate everything in it; that will make the errors go away.
23,771,787
I have Drupal 7 Open Atrium 2 site hosted on Pantheon. While doing some performance profiling, I looked into the Inspector, in the Networks tab, and saw that I had a 404, as well as a loading of a CSS file that was taking a long time. This css file was essentially a link to the domain. I don't understand where or why Drupal is adding these "phantom" stylesheet links to the domain. It seems like, there is an array of stylesheets somewhere, and Drupal is grabbing the final blank item in the array and adding it as a stylesheet link. In one case, it is giving a relative link "/" + "" + random characters for css caching. In the other case, it is appending the blank item in the array to the site domain mysite.pantheon.com + "" + random characters. UPDATE: [ I checked the $css variable through my html.tpl.php file (print\_r($css)), and discovered I do have one of the phantom listings in there: ``` [http://mysite.gotpantheon.com/] => Array ( [type] => external [group] => 100 [every_page] => 1 [weight] => 999.009 [media] => all [preprocess] => 1 [data] => http://mysite.gotpantheon.com/ [browsers] => Array ( [IE] => 1 [!IE] => 1 ) ) ``` How can I check where this css item is being added? It's odd that this css "file" is listed with an absolute url, while all the others are relative urls (ie. module/example/style.css) ] Here are the two phantom links in my html head: Showing up right after my final css file declared in my themes .info file. (note that it is outside of the "style" tag.) ``` <style> ... ... @import url("http://my-site.gotpantheon.com/sites/all/themes/oak_intranet/css/oak_intranet.css?n5w7ml"); </style> <link type="text/css" rel="stylesheet" href="?n5w7ml" media="all" /> ``` Showing up randomly after an IE stylesheet that came as part of the install. ``` <!--[if lte IE 8]> <link type="text/css" rel="stylesheet" href="http://mysite.gotpantheon.com/profiles/openatrium/modules/panopoly/panopoly_core/css/panopoly-fonts-ie-open-sans-bold-italic.css?n5w7ml" media="all" /> <![endif]--> <link type="text/css" rel="stylesheet" href="http://mysite.gotpantheon.com/" media="all" /> ``` For a while, I was stuck on the ?n5w7ml characters appearing, and there is a good answer for why that is happening here: [Weird characters at the end of src/href attributes in head tag](https://stackoverflow.com/questions/3625419/weird-characters-at-the-end-of-src-href-attributes-in-head-tag) **MORE INFO:** Here is where the IE styles get added in panopoly\_core.module. I thought maybe there would be something in here that is registering an extra css file (a blank or something) and just appending it to the base url. Not seeing it though. ``` /** * Implemenets hook_page_build(). */ function panopoly_core_page_build(&$page) { // This fixes a bug that causes @font-face declarations to break in IE6-8. // @see http://www.smashingmagazine.com/2012/07/11/avoiding-faux-weights-styles-... $path = drupal_get_path('module', 'panopoly_core'); drupal_add_css($path . '/css/panopoly-fonts-ie-open-sans.css', array('group' => CSS_THEME, 'every_page' => TRUE, 'browsers' => array('IE' => 'lte IE 8', '!IE' => FALSE), 'preprocess' => FALSE)); drupal_add_css($path . '/css/panopoly-fonts-ie-open-sans-bold.css', array('group' => CSS_THEME, 'every_page' => TRUE, 'browsers' => array('IE' => 'lte IE 8', '!IE' => FALSE), 'preprocess' => FALSE)); drupal_add_css($path . '/css/panopoly-fonts-ie-open-sans-italic.css', array('group' => CSS_THEME, 'every_page' => TRUE, 'browsers' => array('IE' => 'lte IE 8', '!IE' => FALSE), 'preprocess' => FALSE)); drupal_add_css($path . '/css/panopoly-fonts-ie-open-sans-bold-italic.css', array('group' => CSS_THEME, 'every_page' => TRUE, 'browsers' => array('IE' => 'lte IE 8', '!IE' => FALSE), 'preprocess' => FALSE)); } ``` **UPDATE:** So, I noted that in my css array, there were only two stylesheets that were external, one being my phantom domain stylesheet instance. I took my site to my localhost and searched for the term "external" in all the core files. Though there were many listed, I am lucky that the first one was the colorizer.module. There is a drupal\_add\_css on line 54. I added a 'test' => 'test' item to the array there and reloaded my site. My phantom css file in the print($css) array now has that test item. Also, it is the only one. For some reason, either colorizer's css file is not being added and a blank is added instead? ``` [http://mysite.loc:8888/] => Array ( [type] => external [group] => 100 [every_page] => 1 [weight] => 999.008 [test] => test [media] => all [preprocess] => 1 [data] => http://mysite.loc:8888/ [browsers] => Array ( [IE] => 1 [!IE] => 1 ) ) ```
2014/05/20
[ "https://Stackoverflow.com/questions/23771787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1432612/" ]
One trick in the Sql Server world that I'm sure easily translates to other Sql environments is to test for a value in the update, and if null, just use the existing value. ``` UPDATE city SET Population = @population --sql server syntax for parameters, ...--other columns IDTimeZone = Case When @IDTimeZone IS NULL Then IDTimeZone Else @IDTImeZone End, ...--other columns WHERE IDCity = @IDCity ``` The gist of it is pretty simple...is there a value? if yes, set it...otherwise, simply set it to whatever the previous value is in the table, effectively not changing that column value.
My first question to you would be: can't you cache the time zone data somewhere rather than query it every time? Ok, that out of the way, if I understand your question, you want to issue the update though the user may not have selected a timezone. As far as the database is concerned, the foreign key field of your CITY table will accept a NULL value unless the database designer has deliberately defined the field as NOT NULL -- which is a possibility. But...you are executing an Update statement, so the city record must already exist. My second question to you would be: why aren't you reading in the existing record and pre-loading the timezone drop down with the value that's already there (along with sunrise, sunset and all that other stuff)? So whether the user changes it or leaves it alone, you're fine. Your only problem would be when inserting a new city record and the user has not selected a time zone and the timezone field has been declared NOT NULL. Well, then tell the user that the time zone is required information and refuse to proceed until they select something. Have I missed something?
51,551,370
I'm using *Ubuntu 18.04* and *boost.asio* to send a POST request to a rest API. When the server is receiving the request it catches it but I can't seem to define its content type. I have a function `collectRequestData` that is supposed to parse the body of the request and return it where it is then saved to a MySQL database. When I print what the function returns it prints `null` when it should be the JSON text it was sent. When I print the `"Content-Type"` before the function is called it prints undefined when I think it should be `"application/json"`. My end goal here is when I run my client code by `./file.o localhost 8080 /licence '{JSON formatted text}'` it connects to localhost port 8080 path /licence (which it does correctly) and then saves the JSON text to the MySQL database. Which it is not doing correctly and I'm pretty sure the cause is the `"Content-Type"` I'm new to working with servers and JavaScript so if anyone sees me doing something wrong please point it out. Also if you could give extra detail to help me understand a suggestion it would be much appreciated. --- Below is my client code that sends the POST request ``` #include <iostream> #include <istream> #include <ostream> #include <string> #include <boost/asio.hpp> using boost::asio::ip::tcp; using namespace std; int main(int argc, char* argv[]) { cout << "main -start" << endl; try { boost::asio::io_service io_service; string ipAddress = argv[1]; //"localhost" for loop back or ip address otherwise, i.e.- www.boost.org; string portNum = argv[2]; //"8000" for instance; string hostAddress; if (portNum.compare("80") != 0) // add the ":" only if the port number is not 80 (proprietary port number). { hostAddress = ipAddress + ":" + portNum; } else { hostAddress = ipAddress; } string wordToQuery = "";//this will be used for entry indexing string queryStr = argv[3]; //"/api/v1/similar?word=" + wordToQuery; string json = argv[4]; // Get a list of endpoints corresponding to the server name. tcp::resolver resolver(io_service); tcp::resolver::query query(ipAddress, portNum); tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); // Try each endpoint until we successfully establish a connection. tcp::socket socket(io_service); boost::asio::connect(socket, endpoint_iterator); // Form the request. We specify the "Connection: close" header so that the // server will close the socket after transmitting the response. This will // allow us to treat all data up until the EOF as the content. string typeJSON = application/json; boost::asio::streambuf request; std::ostream request_stream(&request); request_stream << "POST " << queryStr << " HTTP/1.1\r\n"; // note that you can change it if you wish to HTTP/1.0 request_stream << "Host: " << hostAddress << "\r\n"; request_stream << "User-Agent: C/1.0"; request_stream << "Content-Type: application/json; charset=utf-8\r\n"; request_stream << "Accept: */*\r\n"; request_stream << "Content-Length: " << json.length() << "\r\n"; request_stream << "Connection: close\r\n\r\n"; request_stream << json; // Send the request. boost::asio::write(socket, request); // Read the response status line. The response streambuf will automatically // grow to accommodate the entire line. The growth may be limited by passing // a maximum size to the streambuf constructor. boost::asio::streambuf response; boost::asio::read_until(socket, response, "\r\n"); // Check that response is OK. std::istream response_stream(&response); std::string http_version; response_stream >> http_version; unsigned int status_code; response_stream >> status_code; std::string status_message; std::getline(response_stream, status_message); if (!response_stream || http_version.substr(0, 5) != "HTTP/") { std::cout << "Invalid response\n"; return 1; } if (status_code != 200) { std::cout << "Response returned with status code " << status_code << "\n"; return 1; } // Read the response headers, which are terminated by a blank line. boost::asio::read_until(socket, response, "\r\n\r\n"); // Process the response headers. std::string header; while (std::getline(response_stream, header) && header != "\r") { std::cout << header << "\n"; } std::cout << "\n"; // Write whatever content we already have to output. if (response.size() > 0) { std::cout << &response; } // Read until EOF, writing data to output as we go. boost::system::error_code error; while (boost::asio::read(socket, response,boost::asio::transfer_at_least(1), error)) { std::cout << &response; } if (error != boost::asio::error::eof) { throw boost::system::system_error(error); } } catch (std::exception& e) { std::cout << "Exception: " << e.what() << "\n"; } return 0; } ``` --- Below is the part of my server that handles the POST request ``` app.post('/licence', function (req, res) { collectRequestData(req, result => { //console.log(request.headers['Content-Type']); console.log(result); sleep(5000); connection.query('INSERT INTO licence SET ?', result, function (error, results) { if (error) throw error; res.end(JSON.stringify(results)); }); //res.end(`Parsed data belonging to ${result.fname}`); }); }); function collectRequestData(request, callback) { console.log(request.headers['Content-Type']); const FORM_URLENCODED = 'application/json'; if(request.headers['Content-Type'] === FORM_URLENCODED) { let body = ''; request.on('data', chunk => { body += chunk.toString(); }); request.on('end', () => { callback(JSON.parse(body)); }); } else { callback(null); } } ```
2018/07/27
[ "https://Stackoverflow.com/questions/51551370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9986496/" ]
You are missing an end of line ``` request_stream << "User-Agent: C/1.0"; ``` should be ``` request_stream << "User-Agent: C/1.0\r\n"; ``` Means your content type header never gets recognised because it isn't on a separate line
I'm assuming you're using nodeJS for the server nodejs gives you the request header in lower case so ``` function collectRequestData(request, callback) { console.log(request.headers['content-type']); const FORM_URLENCODED = 'application/json'; if(request.headers['content-type'] === FORM_URLENCODED) { let body = ''; ``` once you fix the other issue identified by @john, of course i.e. > > You are missing an end of line > > > `request_stream << "User-Agent: C/1.0";` > > > should be > > > `request_stream << "User-Agent: C/1.0\r\n";` > > >
51,551,370
I'm using *Ubuntu 18.04* and *boost.asio* to send a POST request to a rest API. When the server is receiving the request it catches it but I can't seem to define its content type. I have a function `collectRequestData` that is supposed to parse the body of the request and return it where it is then saved to a MySQL database. When I print what the function returns it prints `null` when it should be the JSON text it was sent. When I print the `"Content-Type"` before the function is called it prints undefined when I think it should be `"application/json"`. My end goal here is when I run my client code by `./file.o localhost 8080 /licence '{JSON formatted text}'` it connects to localhost port 8080 path /licence (which it does correctly) and then saves the JSON text to the MySQL database. Which it is not doing correctly and I'm pretty sure the cause is the `"Content-Type"` I'm new to working with servers and JavaScript so if anyone sees me doing something wrong please point it out. Also if you could give extra detail to help me understand a suggestion it would be much appreciated. --- Below is my client code that sends the POST request ``` #include <iostream> #include <istream> #include <ostream> #include <string> #include <boost/asio.hpp> using boost::asio::ip::tcp; using namespace std; int main(int argc, char* argv[]) { cout << "main -start" << endl; try { boost::asio::io_service io_service; string ipAddress = argv[1]; //"localhost" for loop back or ip address otherwise, i.e.- www.boost.org; string portNum = argv[2]; //"8000" for instance; string hostAddress; if (portNum.compare("80") != 0) // add the ":" only if the port number is not 80 (proprietary port number). { hostAddress = ipAddress + ":" + portNum; } else { hostAddress = ipAddress; } string wordToQuery = "";//this will be used for entry indexing string queryStr = argv[3]; //"/api/v1/similar?word=" + wordToQuery; string json = argv[4]; // Get a list of endpoints corresponding to the server name. tcp::resolver resolver(io_service); tcp::resolver::query query(ipAddress, portNum); tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); // Try each endpoint until we successfully establish a connection. tcp::socket socket(io_service); boost::asio::connect(socket, endpoint_iterator); // Form the request. We specify the "Connection: close" header so that the // server will close the socket after transmitting the response. This will // allow us to treat all data up until the EOF as the content. string typeJSON = application/json; boost::asio::streambuf request; std::ostream request_stream(&request); request_stream << "POST " << queryStr << " HTTP/1.1\r\n"; // note that you can change it if you wish to HTTP/1.0 request_stream << "Host: " << hostAddress << "\r\n"; request_stream << "User-Agent: C/1.0"; request_stream << "Content-Type: application/json; charset=utf-8\r\n"; request_stream << "Accept: */*\r\n"; request_stream << "Content-Length: " << json.length() << "\r\n"; request_stream << "Connection: close\r\n\r\n"; request_stream << json; // Send the request. boost::asio::write(socket, request); // Read the response status line. The response streambuf will automatically // grow to accommodate the entire line. The growth may be limited by passing // a maximum size to the streambuf constructor. boost::asio::streambuf response; boost::asio::read_until(socket, response, "\r\n"); // Check that response is OK. std::istream response_stream(&response); std::string http_version; response_stream >> http_version; unsigned int status_code; response_stream >> status_code; std::string status_message; std::getline(response_stream, status_message); if (!response_stream || http_version.substr(0, 5) != "HTTP/") { std::cout << "Invalid response\n"; return 1; } if (status_code != 200) { std::cout << "Response returned with status code " << status_code << "\n"; return 1; } // Read the response headers, which are terminated by a blank line. boost::asio::read_until(socket, response, "\r\n\r\n"); // Process the response headers. std::string header; while (std::getline(response_stream, header) && header != "\r") { std::cout << header << "\n"; } std::cout << "\n"; // Write whatever content we already have to output. if (response.size() > 0) { std::cout << &response; } // Read until EOF, writing data to output as we go. boost::system::error_code error; while (boost::asio::read(socket, response,boost::asio::transfer_at_least(1), error)) { std::cout << &response; } if (error != boost::asio::error::eof) { throw boost::system::system_error(error); } } catch (std::exception& e) { std::cout << "Exception: " << e.what() << "\n"; } return 0; } ``` --- Below is the part of my server that handles the POST request ``` app.post('/licence', function (req, res) { collectRequestData(req, result => { //console.log(request.headers['Content-Type']); console.log(result); sleep(5000); connection.query('INSERT INTO licence SET ?', result, function (error, results) { if (error) throw error; res.end(JSON.stringify(results)); }); //res.end(`Parsed data belonging to ${result.fname}`); }); }); function collectRequestData(request, callback) { console.log(request.headers['Content-Type']); const FORM_URLENCODED = 'application/json'; if(request.headers['Content-Type'] === FORM_URLENCODED) { let body = ''; request.on('data', chunk => { body += chunk.toString(); }); request.on('end', () => { callback(JSON.parse(body)); }); } else { callback(null); } } ```
2018/07/27
[ "https://Stackoverflow.com/questions/51551370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9986496/" ]
You are missing an end of line ``` request_stream << "User-Agent: C/1.0"; ``` should be ``` request_stream << "User-Agent: C/1.0\r\n"; ``` Means your content type header never gets recognised because it isn't on a separate line
First of all, i think you should double check whether the server is right or not. Offering one method: ``` curl "http://localhost:8080/licence" --data "{json format text}" -v ``` If this command responses the same result as yours, it is the problem of server. If not, try to assemble the same request package content in your code as the curl, especially "\r\n" and so on.
51,551,370
I'm using *Ubuntu 18.04* and *boost.asio* to send a POST request to a rest API. When the server is receiving the request it catches it but I can't seem to define its content type. I have a function `collectRequestData` that is supposed to parse the body of the request and return it where it is then saved to a MySQL database. When I print what the function returns it prints `null` when it should be the JSON text it was sent. When I print the `"Content-Type"` before the function is called it prints undefined when I think it should be `"application/json"`. My end goal here is when I run my client code by `./file.o localhost 8080 /licence '{JSON formatted text}'` it connects to localhost port 8080 path /licence (which it does correctly) and then saves the JSON text to the MySQL database. Which it is not doing correctly and I'm pretty sure the cause is the `"Content-Type"` I'm new to working with servers and JavaScript so if anyone sees me doing something wrong please point it out. Also if you could give extra detail to help me understand a suggestion it would be much appreciated. --- Below is my client code that sends the POST request ``` #include <iostream> #include <istream> #include <ostream> #include <string> #include <boost/asio.hpp> using boost::asio::ip::tcp; using namespace std; int main(int argc, char* argv[]) { cout << "main -start" << endl; try { boost::asio::io_service io_service; string ipAddress = argv[1]; //"localhost" for loop back or ip address otherwise, i.e.- www.boost.org; string portNum = argv[2]; //"8000" for instance; string hostAddress; if (portNum.compare("80") != 0) // add the ":" only if the port number is not 80 (proprietary port number). { hostAddress = ipAddress + ":" + portNum; } else { hostAddress = ipAddress; } string wordToQuery = "";//this will be used for entry indexing string queryStr = argv[3]; //"/api/v1/similar?word=" + wordToQuery; string json = argv[4]; // Get a list of endpoints corresponding to the server name. tcp::resolver resolver(io_service); tcp::resolver::query query(ipAddress, portNum); tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); // Try each endpoint until we successfully establish a connection. tcp::socket socket(io_service); boost::asio::connect(socket, endpoint_iterator); // Form the request. We specify the "Connection: close" header so that the // server will close the socket after transmitting the response. This will // allow us to treat all data up until the EOF as the content. string typeJSON = application/json; boost::asio::streambuf request; std::ostream request_stream(&request); request_stream << "POST " << queryStr << " HTTP/1.1\r\n"; // note that you can change it if you wish to HTTP/1.0 request_stream << "Host: " << hostAddress << "\r\n"; request_stream << "User-Agent: C/1.0"; request_stream << "Content-Type: application/json; charset=utf-8\r\n"; request_stream << "Accept: */*\r\n"; request_stream << "Content-Length: " << json.length() << "\r\n"; request_stream << "Connection: close\r\n\r\n"; request_stream << json; // Send the request. boost::asio::write(socket, request); // Read the response status line. The response streambuf will automatically // grow to accommodate the entire line. The growth may be limited by passing // a maximum size to the streambuf constructor. boost::asio::streambuf response; boost::asio::read_until(socket, response, "\r\n"); // Check that response is OK. std::istream response_stream(&response); std::string http_version; response_stream >> http_version; unsigned int status_code; response_stream >> status_code; std::string status_message; std::getline(response_stream, status_message); if (!response_stream || http_version.substr(0, 5) != "HTTP/") { std::cout << "Invalid response\n"; return 1; } if (status_code != 200) { std::cout << "Response returned with status code " << status_code << "\n"; return 1; } // Read the response headers, which are terminated by a blank line. boost::asio::read_until(socket, response, "\r\n\r\n"); // Process the response headers. std::string header; while (std::getline(response_stream, header) && header != "\r") { std::cout << header << "\n"; } std::cout << "\n"; // Write whatever content we already have to output. if (response.size() > 0) { std::cout << &response; } // Read until EOF, writing data to output as we go. boost::system::error_code error; while (boost::asio::read(socket, response,boost::asio::transfer_at_least(1), error)) { std::cout << &response; } if (error != boost::asio::error::eof) { throw boost::system::system_error(error); } } catch (std::exception& e) { std::cout << "Exception: " << e.what() << "\n"; } return 0; } ``` --- Below is the part of my server that handles the POST request ``` app.post('/licence', function (req, res) { collectRequestData(req, result => { //console.log(request.headers['Content-Type']); console.log(result); sleep(5000); connection.query('INSERT INTO licence SET ?', result, function (error, results) { if (error) throw error; res.end(JSON.stringify(results)); }); //res.end(`Parsed data belonging to ${result.fname}`); }); }); function collectRequestData(request, callback) { console.log(request.headers['Content-Type']); const FORM_URLENCODED = 'application/json'; if(request.headers['Content-Type'] === FORM_URLENCODED) { let body = ''; request.on('data', chunk => { body += chunk.toString(); }); request.on('end', () => { callback(JSON.parse(body)); }); } else { callback(null); } } ```
2018/07/27
[ "https://Stackoverflow.com/questions/51551370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9986496/" ]
It feels a web-server issue, you are probably not compliant with the http protocol specification. Try using boost::beast, available in boost 1.66 and over. It's a wrapper over boost::asio that adds high level web-server and web-socket functionality. You don't need to bother with low-level HTTP implementation. [sample code](https://www.boost.org/doc/libs/develop/libs/beast/example/http/server/small/http_server_small.cpp)
I'm assuming you're using nodeJS for the server nodejs gives you the request header in lower case so ``` function collectRequestData(request, callback) { console.log(request.headers['content-type']); const FORM_URLENCODED = 'application/json'; if(request.headers['content-type'] === FORM_URLENCODED) { let body = ''; ``` once you fix the other issue identified by @john, of course i.e. > > You are missing an end of line > > > `request_stream << "User-Agent: C/1.0";` > > > should be > > > `request_stream << "User-Agent: C/1.0\r\n";` > > >
51,551,370
I'm using *Ubuntu 18.04* and *boost.asio* to send a POST request to a rest API. When the server is receiving the request it catches it but I can't seem to define its content type. I have a function `collectRequestData` that is supposed to parse the body of the request and return it where it is then saved to a MySQL database. When I print what the function returns it prints `null` when it should be the JSON text it was sent. When I print the `"Content-Type"` before the function is called it prints undefined when I think it should be `"application/json"`. My end goal here is when I run my client code by `./file.o localhost 8080 /licence '{JSON formatted text}'` it connects to localhost port 8080 path /licence (which it does correctly) and then saves the JSON text to the MySQL database. Which it is not doing correctly and I'm pretty sure the cause is the `"Content-Type"` I'm new to working with servers and JavaScript so if anyone sees me doing something wrong please point it out. Also if you could give extra detail to help me understand a suggestion it would be much appreciated. --- Below is my client code that sends the POST request ``` #include <iostream> #include <istream> #include <ostream> #include <string> #include <boost/asio.hpp> using boost::asio::ip::tcp; using namespace std; int main(int argc, char* argv[]) { cout << "main -start" << endl; try { boost::asio::io_service io_service; string ipAddress = argv[1]; //"localhost" for loop back or ip address otherwise, i.e.- www.boost.org; string portNum = argv[2]; //"8000" for instance; string hostAddress; if (portNum.compare("80") != 0) // add the ":" only if the port number is not 80 (proprietary port number). { hostAddress = ipAddress + ":" + portNum; } else { hostAddress = ipAddress; } string wordToQuery = "";//this will be used for entry indexing string queryStr = argv[3]; //"/api/v1/similar?word=" + wordToQuery; string json = argv[4]; // Get a list of endpoints corresponding to the server name. tcp::resolver resolver(io_service); tcp::resolver::query query(ipAddress, portNum); tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); // Try each endpoint until we successfully establish a connection. tcp::socket socket(io_service); boost::asio::connect(socket, endpoint_iterator); // Form the request. We specify the "Connection: close" header so that the // server will close the socket after transmitting the response. This will // allow us to treat all data up until the EOF as the content. string typeJSON = application/json; boost::asio::streambuf request; std::ostream request_stream(&request); request_stream << "POST " << queryStr << " HTTP/1.1\r\n"; // note that you can change it if you wish to HTTP/1.0 request_stream << "Host: " << hostAddress << "\r\n"; request_stream << "User-Agent: C/1.0"; request_stream << "Content-Type: application/json; charset=utf-8\r\n"; request_stream << "Accept: */*\r\n"; request_stream << "Content-Length: " << json.length() << "\r\n"; request_stream << "Connection: close\r\n\r\n"; request_stream << json; // Send the request. boost::asio::write(socket, request); // Read the response status line. The response streambuf will automatically // grow to accommodate the entire line. The growth may be limited by passing // a maximum size to the streambuf constructor. boost::asio::streambuf response; boost::asio::read_until(socket, response, "\r\n"); // Check that response is OK. std::istream response_stream(&response); std::string http_version; response_stream >> http_version; unsigned int status_code; response_stream >> status_code; std::string status_message; std::getline(response_stream, status_message); if (!response_stream || http_version.substr(0, 5) != "HTTP/") { std::cout << "Invalid response\n"; return 1; } if (status_code != 200) { std::cout << "Response returned with status code " << status_code << "\n"; return 1; } // Read the response headers, which are terminated by a blank line. boost::asio::read_until(socket, response, "\r\n\r\n"); // Process the response headers. std::string header; while (std::getline(response_stream, header) && header != "\r") { std::cout << header << "\n"; } std::cout << "\n"; // Write whatever content we already have to output. if (response.size() > 0) { std::cout << &response; } // Read until EOF, writing data to output as we go. boost::system::error_code error; while (boost::asio::read(socket, response,boost::asio::transfer_at_least(1), error)) { std::cout << &response; } if (error != boost::asio::error::eof) { throw boost::system::system_error(error); } } catch (std::exception& e) { std::cout << "Exception: " << e.what() << "\n"; } return 0; } ``` --- Below is the part of my server that handles the POST request ``` app.post('/licence', function (req, res) { collectRequestData(req, result => { //console.log(request.headers['Content-Type']); console.log(result); sleep(5000); connection.query('INSERT INTO licence SET ?', result, function (error, results) { if (error) throw error; res.end(JSON.stringify(results)); }); //res.end(`Parsed data belonging to ${result.fname}`); }); }); function collectRequestData(request, callback) { console.log(request.headers['Content-Type']); const FORM_URLENCODED = 'application/json'; if(request.headers['Content-Type'] === FORM_URLENCODED) { let body = ''; request.on('data', chunk => { body += chunk.toString(); }); request.on('end', () => { callback(JSON.parse(body)); }); } else { callback(null); } } ```
2018/07/27
[ "https://Stackoverflow.com/questions/51551370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9986496/" ]
The correct solution is a combination of what @john and @Jaromanda X said and I also had to change `const FORM_URLENCODED = 'application/json';` to `const FORM_URLENCODED = 'application/json; charset=utf-8'`
I'm assuming you're using nodeJS for the server nodejs gives you the request header in lower case so ``` function collectRequestData(request, callback) { console.log(request.headers['content-type']); const FORM_URLENCODED = 'application/json'; if(request.headers['content-type'] === FORM_URLENCODED) { let body = ''; ``` once you fix the other issue identified by @john, of course i.e. > > You are missing an end of line > > > `request_stream << "User-Agent: C/1.0";` > > > should be > > > `request_stream << "User-Agent: C/1.0\r\n";` > > >
51,551,370
I'm using *Ubuntu 18.04* and *boost.asio* to send a POST request to a rest API. When the server is receiving the request it catches it but I can't seem to define its content type. I have a function `collectRequestData` that is supposed to parse the body of the request and return it where it is then saved to a MySQL database. When I print what the function returns it prints `null` when it should be the JSON text it was sent. When I print the `"Content-Type"` before the function is called it prints undefined when I think it should be `"application/json"`. My end goal here is when I run my client code by `./file.o localhost 8080 /licence '{JSON formatted text}'` it connects to localhost port 8080 path /licence (which it does correctly) and then saves the JSON text to the MySQL database. Which it is not doing correctly and I'm pretty sure the cause is the `"Content-Type"` I'm new to working with servers and JavaScript so if anyone sees me doing something wrong please point it out. Also if you could give extra detail to help me understand a suggestion it would be much appreciated. --- Below is my client code that sends the POST request ``` #include <iostream> #include <istream> #include <ostream> #include <string> #include <boost/asio.hpp> using boost::asio::ip::tcp; using namespace std; int main(int argc, char* argv[]) { cout << "main -start" << endl; try { boost::asio::io_service io_service; string ipAddress = argv[1]; //"localhost" for loop back or ip address otherwise, i.e.- www.boost.org; string portNum = argv[2]; //"8000" for instance; string hostAddress; if (portNum.compare("80") != 0) // add the ":" only if the port number is not 80 (proprietary port number). { hostAddress = ipAddress + ":" + portNum; } else { hostAddress = ipAddress; } string wordToQuery = "";//this will be used for entry indexing string queryStr = argv[3]; //"/api/v1/similar?word=" + wordToQuery; string json = argv[4]; // Get a list of endpoints corresponding to the server name. tcp::resolver resolver(io_service); tcp::resolver::query query(ipAddress, portNum); tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); // Try each endpoint until we successfully establish a connection. tcp::socket socket(io_service); boost::asio::connect(socket, endpoint_iterator); // Form the request. We specify the "Connection: close" header so that the // server will close the socket after transmitting the response. This will // allow us to treat all data up until the EOF as the content. string typeJSON = application/json; boost::asio::streambuf request; std::ostream request_stream(&request); request_stream << "POST " << queryStr << " HTTP/1.1\r\n"; // note that you can change it if you wish to HTTP/1.0 request_stream << "Host: " << hostAddress << "\r\n"; request_stream << "User-Agent: C/1.0"; request_stream << "Content-Type: application/json; charset=utf-8\r\n"; request_stream << "Accept: */*\r\n"; request_stream << "Content-Length: " << json.length() << "\r\n"; request_stream << "Connection: close\r\n\r\n"; request_stream << json; // Send the request. boost::asio::write(socket, request); // Read the response status line. The response streambuf will automatically // grow to accommodate the entire line. The growth may be limited by passing // a maximum size to the streambuf constructor. boost::asio::streambuf response; boost::asio::read_until(socket, response, "\r\n"); // Check that response is OK. std::istream response_stream(&response); std::string http_version; response_stream >> http_version; unsigned int status_code; response_stream >> status_code; std::string status_message; std::getline(response_stream, status_message); if (!response_stream || http_version.substr(0, 5) != "HTTP/") { std::cout << "Invalid response\n"; return 1; } if (status_code != 200) { std::cout << "Response returned with status code " << status_code << "\n"; return 1; } // Read the response headers, which are terminated by a blank line. boost::asio::read_until(socket, response, "\r\n\r\n"); // Process the response headers. std::string header; while (std::getline(response_stream, header) && header != "\r") { std::cout << header << "\n"; } std::cout << "\n"; // Write whatever content we already have to output. if (response.size() > 0) { std::cout << &response; } // Read until EOF, writing data to output as we go. boost::system::error_code error; while (boost::asio::read(socket, response,boost::asio::transfer_at_least(1), error)) { std::cout << &response; } if (error != boost::asio::error::eof) { throw boost::system::system_error(error); } } catch (std::exception& e) { std::cout << "Exception: " << e.what() << "\n"; } return 0; } ``` --- Below is the part of my server that handles the POST request ``` app.post('/licence', function (req, res) { collectRequestData(req, result => { //console.log(request.headers['Content-Type']); console.log(result); sleep(5000); connection.query('INSERT INTO licence SET ?', result, function (error, results) { if (error) throw error; res.end(JSON.stringify(results)); }); //res.end(`Parsed data belonging to ${result.fname}`); }); }); function collectRequestData(request, callback) { console.log(request.headers['Content-Type']); const FORM_URLENCODED = 'application/json'; if(request.headers['Content-Type'] === FORM_URLENCODED) { let body = ''; request.on('data', chunk => { body += chunk.toString(); }); request.on('end', () => { callback(JSON.parse(body)); }); } else { callback(null); } } ```
2018/07/27
[ "https://Stackoverflow.com/questions/51551370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9986496/" ]
It feels a web-server issue, you are probably not compliant with the http protocol specification. Try using boost::beast, available in boost 1.66 and over. It's a wrapper over boost::asio that adds high level web-server and web-socket functionality. You don't need to bother with low-level HTTP implementation. [sample code](https://www.boost.org/doc/libs/develop/libs/beast/example/http/server/small/http_server_small.cpp)
First of all, i think you should double check whether the server is right or not. Offering one method: ``` curl "http://localhost:8080/licence" --data "{json format text}" -v ``` If this command responses the same result as yours, it is the problem of server. If not, try to assemble the same request package content in your code as the curl, especially "\r\n" and so on.
51,551,370
I'm using *Ubuntu 18.04* and *boost.asio* to send a POST request to a rest API. When the server is receiving the request it catches it but I can't seem to define its content type. I have a function `collectRequestData` that is supposed to parse the body of the request and return it where it is then saved to a MySQL database. When I print what the function returns it prints `null` when it should be the JSON text it was sent. When I print the `"Content-Type"` before the function is called it prints undefined when I think it should be `"application/json"`. My end goal here is when I run my client code by `./file.o localhost 8080 /licence '{JSON formatted text}'` it connects to localhost port 8080 path /licence (which it does correctly) and then saves the JSON text to the MySQL database. Which it is not doing correctly and I'm pretty sure the cause is the `"Content-Type"` I'm new to working with servers and JavaScript so if anyone sees me doing something wrong please point it out. Also if you could give extra detail to help me understand a suggestion it would be much appreciated. --- Below is my client code that sends the POST request ``` #include <iostream> #include <istream> #include <ostream> #include <string> #include <boost/asio.hpp> using boost::asio::ip::tcp; using namespace std; int main(int argc, char* argv[]) { cout << "main -start" << endl; try { boost::asio::io_service io_service; string ipAddress = argv[1]; //"localhost" for loop back or ip address otherwise, i.e.- www.boost.org; string portNum = argv[2]; //"8000" for instance; string hostAddress; if (portNum.compare("80") != 0) // add the ":" only if the port number is not 80 (proprietary port number). { hostAddress = ipAddress + ":" + portNum; } else { hostAddress = ipAddress; } string wordToQuery = "";//this will be used for entry indexing string queryStr = argv[3]; //"/api/v1/similar?word=" + wordToQuery; string json = argv[4]; // Get a list of endpoints corresponding to the server name. tcp::resolver resolver(io_service); tcp::resolver::query query(ipAddress, portNum); tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); // Try each endpoint until we successfully establish a connection. tcp::socket socket(io_service); boost::asio::connect(socket, endpoint_iterator); // Form the request. We specify the "Connection: close" header so that the // server will close the socket after transmitting the response. This will // allow us to treat all data up until the EOF as the content. string typeJSON = application/json; boost::asio::streambuf request; std::ostream request_stream(&request); request_stream << "POST " << queryStr << " HTTP/1.1\r\n"; // note that you can change it if you wish to HTTP/1.0 request_stream << "Host: " << hostAddress << "\r\n"; request_stream << "User-Agent: C/1.0"; request_stream << "Content-Type: application/json; charset=utf-8\r\n"; request_stream << "Accept: */*\r\n"; request_stream << "Content-Length: " << json.length() << "\r\n"; request_stream << "Connection: close\r\n\r\n"; request_stream << json; // Send the request. boost::asio::write(socket, request); // Read the response status line. The response streambuf will automatically // grow to accommodate the entire line. The growth may be limited by passing // a maximum size to the streambuf constructor. boost::asio::streambuf response; boost::asio::read_until(socket, response, "\r\n"); // Check that response is OK. std::istream response_stream(&response); std::string http_version; response_stream >> http_version; unsigned int status_code; response_stream >> status_code; std::string status_message; std::getline(response_stream, status_message); if (!response_stream || http_version.substr(0, 5) != "HTTP/") { std::cout << "Invalid response\n"; return 1; } if (status_code != 200) { std::cout << "Response returned with status code " << status_code << "\n"; return 1; } // Read the response headers, which are terminated by a blank line. boost::asio::read_until(socket, response, "\r\n\r\n"); // Process the response headers. std::string header; while (std::getline(response_stream, header) && header != "\r") { std::cout << header << "\n"; } std::cout << "\n"; // Write whatever content we already have to output. if (response.size() > 0) { std::cout << &response; } // Read until EOF, writing data to output as we go. boost::system::error_code error; while (boost::asio::read(socket, response,boost::asio::transfer_at_least(1), error)) { std::cout << &response; } if (error != boost::asio::error::eof) { throw boost::system::system_error(error); } } catch (std::exception& e) { std::cout << "Exception: " << e.what() << "\n"; } return 0; } ``` --- Below is the part of my server that handles the POST request ``` app.post('/licence', function (req, res) { collectRequestData(req, result => { //console.log(request.headers['Content-Type']); console.log(result); sleep(5000); connection.query('INSERT INTO licence SET ?', result, function (error, results) { if (error) throw error; res.end(JSON.stringify(results)); }); //res.end(`Parsed data belonging to ${result.fname}`); }); }); function collectRequestData(request, callback) { console.log(request.headers['Content-Type']); const FORM_URLENCODED = 'application/json'; if(request.headers['Content-Type'] === FORM_URLENCODED) { let body = ''; request.on('data', chunk => { body += chunk.toString(); }); request.on('end', () => { callback(JSON.parse(body)); }); } else { callback(null); } } ```
2018/07/27
[ "https://Stackoverflow.com/questions/51551370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9986496/" ]
The correct solution is a combination of what @john and @Jaromanda X said and I also had to change `const FORM_URLENCODED = 'application/json';` to `const FORM_URLENCODED = 'application/json; charset=utf-8'`
First of all, i think you should double check whether the server is right or not. Offering one method: ``` curl "http://localhost:8080/licence" --data "{json format text}" -v ``` If this command responses the same result as yours, it is the problem of server. If not, try to assemble the same request package content in your code as the curl, especially "\r\n" and so on.
62,292,427
I have the following text file: **file.text** ``` Cygwin value: c Unix-keep value: u Linux value: l Unix-16 value: u Solaris value: s Unix-replace-1 value: u Unix-replace-2 value: u ``` I want to replace all lines values based on previous string : starting with **Unix-** but excluding containing string **keep** So in the end affected lines sould be the ones after: Unix-replace-1 and Unix-replace-2 with value **value: NEW\_VERSION** Expected output: ``` Cygwin value: c Unix-keep value: u Linux value: l Unix-16 value: NEW_VERSION Solaris value: s Unix-replace-1 value: NEW_VERSION Unix-replace-2 value: NEW_VERSION ``` I tried following sed script: ``` sed '/^Unix-/ {n;s/.*/value: NEW_VERSION/}' file.text ``` but this can only get starting but not excluding -keep substrings. I am not sure how to combine the excluded ones. Any ideas?
2020/06/09
[ "https://Stackoverflow.com/questions/62292427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1778639/" ]
``` $ awk -v new='NEW_VERSION' 'f{$0=$1 FS new} {f=(/^Unix-/ && !/keep/)} 1' file Cygwin value: c Unix-keep value: u Linux value: l Unix-16 value: NEW_VERSION Solaris value: s Unix-replace-1 value: NEW_VERSION Unix-replace-2 value: NEW_VERSION ```
Using a proper [xml](/questions/tagged/xml "show questions tagged 'xml'") parser (**the question was originally plain XML before edited by OP**): The XML edited to be valid (closing tags missing) : ``` <project> <Cygwin> <version>c</version> </Cygwin> <Unix-keep> <version>u</version> </Unix-keep> <Linux> <version>l</version> </Linux> <Solaris> <version>s</version> </Solaris> <Unix-replace-1> <version>u</version> </Unix-replace-1> <AIX> <version>a</version> </AIX> <Unix-replace-2> <version>u</version> </Unix-replace-2> </project> ``` The command: ``` xmlstarlet ed -u '//project/* [starts-with(name(), "Unix") and not(starts-with(name(), "Unix-keep"))] /version ' -v 'NEW_VERSION' file ``` To edit the file *in place*, use ``` xmlstarlet ed -L -u ... ```
2,372,627
I have the following XML: ``` <Content name="contentName1"> <!-- Some sub elements here --> </Content> <Sequence Name="sequenceName1"> <Content name="contentName1" /> <!-- Some sub elements here --> </Sequence> ``` with the following XSD ``` <xs:element maxOccurs="unbounded" name="Content"> <xs:complexType> <xs:attribute name="Name" type="xs:string" use="required" /> <!-- other definitions here --> </xs:complexType> </xs:element> <xs:element maxOccurs="unbounded" name="Sequence"> <xs:complexType> <xs:sequence> <xs:element maxOccurs="unbounded" name="Content"> <xs:complexType> <xs:attribute name="ContentName" type="xs:string" use="required" /> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name="Name" type="xs:string" use="required" /> </xs:complexType> </xs:element> ``` In the XSD, how can I tell to the ContentName attribute of the Content elements of Sequence to only accepts value declared in the ContentName of Content elements? e.g: with the XML provided above, only contentName1 will be accepted in the Content of sequence.
2010/03/03
[ "https://Stackoverflow.com/questions/2372627", "https://Stackoverflow.com", "https://Stackoverflow.com/users/155166/" ]
Identity constraint definitions are used for enforcing the unique, primary key and foreign key relations. you need to first define a key element for the content element and then use a keyref in the inner content element for the schema validator to enforce the condition you mentioned. Refer the below link it has some examples as well, also the tutorial in xfront for xsd covers some examples - <http://www.w3.org/TR/xmlschema11-1/#Identity-constraint_Definition_details> <http://www.xfront.com/files/xml-schema.html>
i am not good in xsd too, but maybe you will change `<xs:attribute name="Name" type="xs:string" use="required" />` to `<xs:attribute name="Name" type="contentNames" use="required" />` and create ``` <xs:simpleType name="contentNames" > <xs:restriction base="xs:token"> <xs:enumeration value="contentName1"/> <xs:enumeration value="contentName2"/> <xs:pattern value="contentName[1234567890][1234567890]"/> <xs:enumeration value="contentName1"/> </xs:restriction> </xs:simpleType> ``` for ``` <xs:pattern value="contentName[1234567890][1234567890]"/> ``` contentName1-99 but dont know if you can use `<xs:enumeration/>` too, you can try
3,326,334
The Below code is running well... ``` <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" > <fx:Declarations> <mx:HTTPService id="httpRSS" url="http://www.petefreitag.com/rss/" resultFormat="object" /> </fx:Declarations> <s:Panel id="reader" title="Blog Reader" width="500"> <mx:DataGrid width="485" id="entries" dataProvider="{httpRSS.lastResult.rss.channel.item}" click="{body.htmlText=httpRSS.lastResult.rss.channel.item[entries.selectedIndex].description}"> <mx:columns> <mx:DataGridColumn dataField="title" headerText="TITLE"/> <mx:DataGridColumn dataField="pubDate" headerText="Date"/> </mx:columns> </mx:DataGrid> <mx:TextArea id="body" editable="false" width="485" x="3" y="142" height="155"/> </s:Panel> <s:Button label="Load" x="10" y="329" click="{httpRSS.send()}"/> </s:Application> ``` But when Textarea is changed to spark Textrea like below ``` <s:TextArea id="body" editable="false" width="485" x="3" y="142" height="155"/> ``` Then htmlText doesn't support Spark Textarea. Hence produces error. How does one go about displaying HTML formatted text with spark Text Area Property.
2010/07/24
[ "https://Stackoverflow.com/questions/3326334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/401185/" ]
Check out the content property in the [TextArea docs](http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/spark/components/TextArea.html?allClasses=1). Note the example at the end of the page.. it shows how to embed HTML.
Can also use : ``` (myTextArea.textDisplay as StyleableTextField).htmlText = text; ```
3,326,334
The Below code is running well... ``` <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" > <fx:Declarations> <mx:HTTPService id="httpRSS" url="http://www.petefreitag.com/rss/" resultFormat="object" /> </fx:Declarations> <s:Panel id="reader" title="Blog Reader" width="500"> <mx:DataGrid width="485" id="entries" dataProvider="{httpRSS.lastResult.rss.channel.item}" click="{body.htmlText=httpRSS.lastResult.rss.channel.item[entries.selectedIndex].description}"> <mx:columns> <mx:DataGridColumn dataField="title" headerText="TITLE"/> <mx:DataGridColumn dataField="pubDate" headerText="Date"/> </mx:columns> </mx:DataGrid> <mx:TextArea id="body" editable="false" width="485" x="3" y="142" height="155"/> </s:Panel> <s:Button label="Load" x="10" y="329" click="{httpRSS.send()}"/> </s:Application> ``` But when Textarea is changed to spark Textrea like below ``` <s:TextArea id="body" editable="false" width="485" x="3" y="142" height="155"/> ``` Then htmlText doesn't support Spark Textarea. Hence produces error. How does one go about displaying HTML formatted text with spark Text Area Property.
2010/07/24
[ "https://Stackoverflow.com/questions/3326334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/401185/" ]
If you're using the **RichEditableText** component instead, you can do it this way using the TextConverter class ``` var myStr:String = "I contain <b>html</b> tags!"; myRichEditableText.textFlow = TextConverter.importToFlow(myStr, TextConverter.TEXT_FIELD_HTML_FORMAT); ```
Check out the content property in the [TextArea docs](http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/spark/components/TextArea.html?allClasses=1). Note the example at the end of the page.. it shows how to embed HTML.
3,326,334
The Below code is running well... ``` <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" > <fx:Declarations> <mx:HTTPService id="httpRSS" url="http://www.petefreitag.com/rss/" resultFormat="object" /> </fx:Declarations> <s:Panel id="reader" title="Blog Reader" width="500"> <mx:DataGrid width="485" id="entries" dataProvider="{httpRSS.lastResult.rss.channel.item}" click="{body.htmlText=httpRSS.lastResult.rss.channel.item[entries.selectedIndex].description}"> <mx:columns> <mx:DataGridColumn dataField="title" headerText="TITLE"/> <mx:DataGridColumn dataField="pubDate" headerText="Date"/> </mx:columns> </mx:DataGrid> <mx:TextArea id="body" editable="false" width="485" x="3" y="142" height="155"/> </s:Panel> <s:Button label="Load" x="10" y="329" click="{httpRSS.send()}"/> </s:Application> ``` But when Textarea is changed to spark Textrea like below ``` <s:TextArea id="body" editable="false" width="485" x="3" y="142" height="155"/> ``` Then htmlText doesn't support Spark Textarea. Hence produces error. How does one go about displaying HTML formatted text with spark Text Area Property.
2010/07/24
[ "https://Stackoverflow.com/questions/3326334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/401185/" ]
body.textFlow = TextFlowUtil.importFromString(yourHTMLString);
I don't think you can. You should stick to using the Halo TextArea component or you should investigate the Text Layout Framework to accomplish your goals.
3,326,334
The Below code is running well... ``` <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" > <fx:Declarations> <mx:HTTPService id="httpRSS" url="http://www.petefreitag.com/rss/" resultFormat="object" /> </fx:Declarations> <s:Panel id="reader" title="Blog Reader" width="500"> <mx:DataGrid width="485" id="entries" dataProvider="{httpRSS.lastResult.rss.channel.item}" click="{body.htmlText=httpRSS.lastResult.rss.channel.item[entries.selectedIndex].description}"> <mx:columns> <mx:DataGridColumn dataField="title" headerText="TITLE"/> <mx:DataGridColumn dataField="pubDate" headerText="Date"/> </mx:columns> </mx:DataGrid> <mx:TextArea id="body" editable="false" width="485" x="3" y="142" height="155"/> </s:Panel> <s:Button label="Load" x="10" y="329" click="{httpRSS.send()}"/> </s:Application> ``` But when Textarea is changed to spark Textrea like below ``` <s:TextArea id="body" editable="false" width="485" x="3" y="142" height="155"/> ``` Then htmlText doesn't support Spark Textarea. Hence produces error. How does one go about displaying HTML formatted text with spark Text Area Property.
2010/07/24
[ "https://Stackoverflow.com/questions/3326334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/401185/" ]
It can be also used in spark textArea: > > var myStr:String = "I contain **html** tags!"; > > textAarea.textFlow = TextConverter.importToFlow(myStr, TextConverter.TEXT\_FIELD\_HTML\_FORMAT); > > > This sometime will not work, if the HTML code is big and have some tags that can`t be rendered TextFlowUtil.importFromString(yourHTMLString);
David Gassner's Flashbuilder 4 & Flex 4 has a section on this. Take a look at TextFlowUtil. If you want to embed the HTML directly into the Spark TextArea (or RichText / RichEditableText), you can use the content tag as a child, then add the p or span tags thereafter - The supported HTML tags are part of the s namespace too.
3,326,334
The Below code is running well... ``` <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" > <fx:Declarations> <mx:HTTPService id="httpRSS" url="http://www.petefreitag.com/rss/" resultFormat="object" /> </fx:Declarations> <s:Panel id="reader" title="Blog Reader" width="500"> <mx:DataGrid width="485" id="entries" dataProvider="{httpRSS.lastResult.rss.channel.item}" click="{body.htmlText=httpRSS.lastResult.rss.channel.item[entries.selectedIndex].description}"> <mx:columns> <mx:DataGridColumn dataField="title" headerText="TITLE"/> <mx:DataGridColumn dataField="pubDate" headerText="Date"/> </mx:columns> </mx:DataGrid> <mx:TextArea id="body" editable="false" width="485" x="3" y="142" height="155"/> </s:Panel> <s:Button label="Load" x="10" y="329" click="{httpRSS.send()}"/> </s:Application> ``` But when Textarea is changed to spark Textrea like below ``` <s:TextArea id="body" editable="false" width="485" x="3" y="142" height="155"/> ``` Then htmlText doesn't support Spark Textarea. Hence produces error. How does one go about displaying HTML formatted text with spark Text Area Property.
2010/07/24
[ "https://Stackoverflow.com/questions/3326334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/401185/" ]
If you're using the **RichEditableText** component instead, you can do it this way using the TextConverter class ``` var myStr:String = "I contain <b>html</b> tags!"; myRichEditableText.textFlow = TextConverter.importToFlow(myStr, TextConverter.TEXT_FIELD_HTML_FORMAT); ```
I don't think you can. You should stick to using the Halo TextArea component or you should investigate the Text Layout Framework to accomplish your goals.
3,326,334
The Below code is running well... ``` <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" > <fx:Declarations> <mx:HTTPService id="httpRSS" url="http://www.petefreitag.com/rss/" resultFormat="object" /> </fx:Declarations> <s:Panel id="reader" title="Blog Reader" width="500"> <mx:DataGrid width="485" id="entries" dataProvider="{httpRSS.lastResult.rss.channel.item}" click="{body.htmlText=httpRSS.lastResult.rss.channel.item[entries.selectedIndex].description}"> <mx:columns> <mx:DataGridColumn dataField="title" headerText="TITLE"/> <mx:DataGridColumn dataField="pubDate" headerText="Date"/> </mx:columns> </mx:DataGrid> <mx:TextArea id="body" editable="false" width="485" x="3" y="142" height="155"/> </s:Panel> <s:Button label="Load" x="10" y="329" click="{httpRSS.send()}"/> </s:Application> ``` But when Textarea is changed to spark Textrea like below ``` <s:TextArea id="body" editable="false" width="485" x="3" y="142" height="155"/> ``` Then htmlText doesn't support Spark Textarea. Hence produces error. How does one go about displaying HTML formatted text with spark Text Area Property.
2010/07/24
[ "https://Stackoverflow.com/questions/3326334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/401185/" ]
body.textFlow = TextFlowUtil.importFromString(yourHTMLString);
Can also use : ``` (myTextArea.textDisplay as StyleableTextField).htmlText = text; ```
3,326,334
The Below code is running well... ``` <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" > <fx:Declarations> <mx:HTTPService id="httpRSS" url="http://www.petefreitag.com/rss/" resultFormat="object" /> </fx:Declarations> <s:Panel id="reader" title="Blog Reader" width="500"> <mx:DataGrid width="485" id="entries" dataProvider="{httpRSS.lastResult.rss.channel.item}" click="{body.htmlText=httpRSS.lastResult.rss.channel.item[entries.selectedIndex].description}"> <mx:columns> <mx:DataGridColumn dataField="title" headerText="TITLE"/> <mx:DataGridColumn dataField="pubDate" headerText="Date"/> </mx:columns> </mx:DataGrid> <mx:TextArea id="body" editable="false" width="485" x="3" y="142" height="155"/> </s:Panel> <s:Button label="Load" x="10" y="329" click="{httpRSS.send()}"/> </s:Application> ``` But when Textarea is changed to spark Textrea like below ``` <s:TextArea id="body" editable="false" width="485" x="3" y="142" height="155"/> ``` Then htmlText doesn't support Spark Textarea. Hence produces error. How does one go about displaying HTML formatted text with spark Text Area Property.
2010/07/24
[ "https://Stackoverflow.com/questions/3326334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/401185/" ]
Check out the content property in the [TextArea docs](http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/spark/components/TextArea.html?allClasses=1). Note the example at the end of the page.. it shows how to embed HTML.
I don't think you can. You should stick to using the Halo TextArea component or you should investigate the Text Layout Framework to accomplish your goals.
3,326,334
The Below code is running well... ``` <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" > <fx:Declarations> <mx:HTTPService id="httpRSS" url="http://www.petefreitag.com/rss/" resultFormat="object" /> </fx:Declarations> <s:Panel id="reader" title="Blog Reader" width="500"> <mx:DataGrid width="485" id="entries" dataProvider="{httpRSS.lastResult.rss.channel.item}" click="{body.htmlText=httpRSS.lastResult.rss.channel.item[entries.selectedIndex].description}"> <mx:columns> <mx:DataGridColumn dataField="title" headerText="TITLE"/> <mx:DataGridColumn dataField="pubDate" headerText="Date"/> </mx:columns> </mx:DataGrid> <mx:TextArea id="body" editable="false" width="485" x="3" y="142" height="155"/> </s:Panel> <s:Button label="Load" x="10" y="329" click="{httpRSS.send()}"/> </s:Application> ``` But when Textarea is changed to spark Textrea like below ``` <s:TextArea id="body" editable="false" width="485" x="3" y="142" height="155"/> ``` Then htmlText doesn't support Spark Textarea. Hence produces error. How does one go about displaying HTML formatted text with spark Text Area Property.
2010/07/24
[ "https://Stackoverflow.com/questions/3326334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/401185/" ]
If you're using the **RichEditableText** component instead, you can do it this way using the TextConverter class ``` var myStr:String = "I contain <b>html</b> tags!"; myRichEditableText.textFlow = TextConverter.importToFlow(myStr, TextConverter.TEXT_FIELD_HTML_FORMAT); ```
It can be also used in spark textArea: > > var myStr:String = "I contain **html** tags!"; > > textAarea.textFlow = TextConverter.importToFlow(myStr, TextConverter.TEXT\_FIELD\_HTML\_FORMAT); > > > This sometime will not work, if the HTML code is big and have some tags that can`t be rendered TextFlowUtil.importFromString(yourHTMLString);
3,326,334
The Below code is running well... ``` <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" > <fx:Declarations> <mx:HTTPService id="httpRSS" url="http://www.petefreitag.com/rss/" resultFormat="object" /> </fx:Declarations> <s:Panel id="reader" title="Blog Reader" width="500"> <mx:DataGrid width="485" id="entries" dataProvider="{httpRSS.lastResult.rss.channel.item}" click="{body.htmlText=httpRSS.lastResult.rss.channel.item[entries.selectedIndex].description}"> <mx:columns> <mx:DataGridColumn dataField="title" headerText="TITLE"/> <mx:DataGridColumn dataField="pubDate" headerText="Date"/> </mx:columns> </mx:DataGrid> <mx:TextArea id="body" editable="false" width="485" x="3" y="142" height="155"/> </s:Panel> <s:Button label="Load" x="10" y="329" click="{httpRSS.send()}"/> </s:Application> ``` But when Textarea is changed to spark Textrea like below ``` <s:TextArea id="body" editable="false" width="485" x="3" y="142" height="155"/> ``` Then htmlText doesn't support Spark Textarea. Hence produces error. How does one go about displaying HTML formatted text with spark Text Area Property.
2010/07/24
[ "https://Stackoverflow.com/questions/3326334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/401185/" ]
It can be also used in spark textArea: > > var myStr:String = "I contain **html** tags!"; > > textAarea.textFlow = TextConverter.importToFlow(myStr, TextConverter.TEXT\_FIELD\_HTML\_FORMAT); > > > This sometime will not work, if the HTML code is big and have some tags that can`t be rendered TextFlowUtil.importFromString(yourHTMLString);
I don't think you can. You should stick to using the Halo TextArea component or you should investigate the Text Layout Framework to accomplish your goals.
3,326,334
The Below code is running well... ``` <?xml version="1.0" encoding="utf-8"?> <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" > <fx:Declarations> <mx:HTTPService id="httpRSS" url="http://www.petefreitag.com/rss/" resultFormat="object" /> </fx:Declarations> <s:Panel id="reader" title="Blog Reader" width="500"> <mx:DataGrid width="485" id="entries" dataProvider="{httpRSS.lastResult.rss.channel.item}" click="{body.htmlText=httpRSS.lastResult.rss.channel.item[entries.selectedIndex].description}"> <mx:columns> <mx:DataGridColumn dataField="title" headerText="TITLE"/> <mx:DataGridColumn dataField="pubDate" headerText="Date"/> </mx:columns> </mx:DataGrid> <mx:TextArea id="body" editable="false" width="485" x="3" y="142" height="155"/> </s:Panel> <s:Button label="Load" x="10" y="329" click="{httpRSS.send()}"/> </s:Application> ``` But when Textarea is changed to spark Textrea like below ``` <s:TextArea id="body" editable="false" width="485" x="3" y="142" height="155"/> ``` Then htmlText doesn't support Spark Textarea. Hence produces error. How does one go about displaying HTML formatted text with spark Text Area Property.
2010/07/24
[ "https://Stackoverflow.com/questions/3326334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/401185/" ]
If you're using the **RichEditableText** component instead, you can do it this way using the TextConverter class ``` var myStr:String = "I contain <b>html</b> tags!"; myRichEditableText.textFlow = TextConverter.importToFlow(myStr, TextConverter.TEXT_FIELD_HTML_FORMAT); ```
Can also use : ``` (myTextArea.textDisplay as StyleableTextField).htmlText = text; ```
14,614,856
I have been looking for hours for a way of setting a condition on the list of items that an APYDataGridBundle grid should return but could not find an answer. Is there a way to set a DQL Query and pass it to the grid to display the exact query results I want to fetch? This is the code: ``` public function filteredlistAction(){ // Create simple grid based on the entity $source = new Entity('ACMEBundle:MyEntity'); // Get a grid instance $grid = $this->get('grid'); // Attach the source to the grid $grid->setSource($source); ... ... **$grid->getColumns()->getColumnById('myentity_filter_column')->setData('the exact value I tried to match');** // Manage the grid redirection, exports and the response of the controller return $grid->getGridResponse('ACMEBundle:MyEntity:index_filteredlist.html.twig'); } ```
2013/01/30
[ "https://Stackoverflow.com/questions/14614856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1607360/" ]
You can add a callback (closure or callable) to run before `QueryBuilder` execution - its done like this : ``` $source->manipulateQuery( function ($query) { $query->resetDQLPart('orderBy'); } ); $grid->setSource($source); ``` `$query` is an instance of `QueryBuilder` so you can change whatever you need to [Example taken from docs here](https://github.com/Abhoryo/APYDataGridBundle/blob/master/Resources/doc/grid_configuration/manipulate_query.md)
A more "complicated" query. ``` $estaActivo = 'ACTIVO'; $tableAlias = $source->getTableAlias(); $source->manipulateQuery( function ($query) use ($tableAlias, $estaActivo) { $query->andWhere($tableAlias . '.estado = :estaActivo') ->andWhere($tableAlias . '.tipoUsuario IN (:rol)') ->setParameter('estaActivo', $estaActivo) ->setParameter('rol', array('VENDEDOR','SUPERVISOR'), \Doctrine\DBAL\Connection::PARAM_STR_ARRAY); } ); ``` Cheers!
42,215,380
Full code: <https://github.com/kenpeter/test_infinite_scroll_1> I have a reducer. It has a prop called `list`. `createList([], 0)` calls remote api and gets data, then assign to `list`. ./reducers/loadMore.js ``` import { MORE_LIST } from "../actions/types"; import { createList } from "../utils/func"; const initState = { list: createList([], 0) // <-------------------- }; // able to fire export default function list(state = initState, action = {}) { switch(action.type) { case MORE_LIST: return { list: action.list, } default: return state; } } ``` ./utils/func.js ``` import _ from 'lodash'; import axios from "axios"; // clone the array export function createList(arr=[],start=0) { let apiUrl = "http://www.mangaeden.com/api/list/0?p=0"; return axios.get(apiUrl).then((obj) => { let arr = obj.data.manga; // array of obj //console.log("--- start ---"); //console.log(arr); return arr; }); } ``` The issue I have with `function createList(arr=[],start=0)` is `arr` has data from remote api, but it is not able to return back to `list` in `./reducers/loadMore.js`
2017/02/13
[ "https://Stackoverflow.com/questions/42215380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/350878/" ]
I feel that making ajax requests in your initial state for your reducer is an anti-pattern. Instead, I would just have the initial state as an empty array and then either as your app starts or in an appropriate component's lifecycle (`componentWillMount` for example) I would dispatch an action to fetch the data. You can use indicators like loading bars/spinners etc. to indicate to the user that data is coming back. Additionally, you can perform a check on the length of your array or just do a `.map` on the empty array anyway and this won't get errors.
Your createList returns a Promise. So in your `client/actions/loadMore.js` you need to do: ``` return createList(list, list.length+1).then((tmpList) => { dispatch({ type: MORE_LIST, list: tmpList }); }); ``` Also, as [patric](https://stackoverflow.com/users/3363019/patrick "patrick") mentioned, the following code in `client/reducers/loadMore.js` is async, ``` const initState = { list: createList([], 0) }; ``` the `initState.list` here is a Promise. Instead initialize it with empty list and dispatch the loadMore() action in the ComponentDidMount method of your component/container
72,470,998
What is the best way to pass data between two components which don't have parent-child relation in Angular 13
2022/06/02
[ "https://Stackoverflow.com/questions/72470998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8844206/" ]
**1. Shared service.** Shared service ``` import { Injectable } from '@angular/core'; import { Observable, Subject } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class MessageService { private subject = new Subject<any>(); sendMessage(message: string) { this.subject.next({ text: message }); } onMessage(): Observable<any> { return this.subject.asObservable(); } } ``` Component A ``` export class ComponentA implements OnInit, OnDestroy { isAlive = true; constructor(private messageService: MessageService) { } ngOnInit(): void { this.messageService.onMessage() .pipe(takeWhile(() => this.isAlive)).subscribe(message => { // Do anything }); } ngOnDestroy() { this.isAlive = false; } } ``` Component B ``` export class ComponentB { constructor(private messageService: MessageService) { } sendMessage(): void { // send message to subscribers via observable subject this.messageService.sendMessage('Hello!'); } } ``` **2. Ngrx store** Ngrx is bit complex and may be too much for small projects. Here is the [complete documentation](https://ngrx.io/guide/store). **3. LocalStorage or SessionStorage** Depending on your requirement you can use these storages. But they are not like observables. Therefore, if a new value available, they don't knock. You have to manually check the storage for new values.
Here is a little example, this example shares the value of current theme of page to any component ``` component1.html <div (click)="switchTheme()"></div> ``` --- ``` component1.ts import { Component, OnInit } from '@angular/core'; import { SwitcherService } from 'services/switcher.service'; @Component({ selector: 'app-component1', templateUrl: './component1.html', styleUrls: ['./component1.scss'] }) export class component1 implements OnInit { currentTheme: any; constructor(private sw: SwitcherService) { } ngOnInit(): void { this.applyCurrentLayoutSettings(); } applyCurrentLayoutSettings() { // here is the theme this.sw.getCurrentThemeObservable().subscribe( (theme: any) => this.currentTheme = theme ); } switchTheme() { const invertedTheme = this.invertTheme(); this.sw.switchCurrentTheme(invertedTheme); } invertTheme() { return this.currentTheme == 'dark' ? 'light': 'dark'; } ``` --- ``` switcher.service.ts import { Injectable } from '@angular/core'; import { BehaviorSubject, Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class SwitcherService { private currentThemeSubject: BehaviorSubject<any>; private currentTheme: Observable<any>; constructor() { if( !this.getCurrentTheme() ) { this.setCurrentTheme('dark'); } this.currentThemeSubject = new BehaviorSubject<any>(this.getCurrentTheme()); this.currentTheme = this.currentThemeSubject.asObservable(); } switchCurrentTheme(theme: string) { this.setCurrentTheme(theme); this.currentThemeSubject.next(theme); } getCurrentThemeValue() { return this.currentThemeSubject.value; } getCurrentThemeObservable() { return this.currentTheme; } getCurrentTheme() { return localStorage.getItem('currentTheme'); } setCurrentTheme(theme: string) { localStorage.setItem('currentTheme', theme); } } ``` --- ``` component2.ts import { Component, OnInit } from '@angular/core'; import { SwitcherService } from 'services/switcher.service'; @Component({ selector: 'app-component2', templateUrl: './component2.html', styleUrls: ['./component2.scss'] }) export class component2 implements OnInit { currentTheme: any; constructor(private sw: SwitcherService) { } ngOnInit(): void { // here is the theme this.sw.getCurrentThemeObservable().subscribe( (theme: any) => this.currentTheme = theme ); } } ```
40,016,807
Hi I am creating one html page in which I am dragging some `buttons` in one `Div`using jQuery-ui and jquery-ui-punch. But dragging and dropping not happening . I don't understand why it's not working. `sourcePopover` is popover which having buttons which I want to drag in `fav_id`. Here is my HTML/JavaScript code. ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset=utf-8> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <link rel="stylesheet" href="bootstrap-3.3.6-dist/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="bootstrap-3.3.6-dist/css/bootstrap-theme.min.css"> <!--Font Awesome --> <script src="js/jquery-2.1.4.min.js"></script> <script src="bootstrap-3.3.6-dist/js/bootstrap.min.js"></script> <script src="js/jquery-ui.min.js"></script> <link href="css/jquery-ui.css" rel="stylesheet" type="text/css"/> <script src="js/jquery.ui.touch-punch.min.js"></script> <script type="text/javascript"> /*Function to show popover when select button click*/ $(function(){ // Enables popover #2 $("#btn_select_source").popover({ container: 'body', animation:true, html : true, content: function() { return $("#sourcePopover").html(); }, title: function() { return $("#sourcePopoverTitle").html(); } }) }); $(function(){ $("#sourcePopover button").draggable({ revert: "invalid", refreshPositions: true, drag: function (event, ui) { ui.helper.addClass("draggable"); }, stop: function (event, ui) { ui.helper.removeClass("draggable"); var image = this.src.split("/")[this.src.split("/").length - 1]; if ($.ui.ddmanager.drop(ui.helper.data("draggable"), event)) { alert(image + " dropped."); } else { alert(image + " not dropped."); } } }); $("#fav_div").droppable({ drop: function (event, ui) { if ($("#fav_div button").length == 0) { $("#fav_div").html(""); } ui.draggable.addClass("dropped"); $("#fav_div").append(ui.draggable); } }); }); </script> <style type="text/css"> .draggable { filter: alpha(opacity=60); opacity: 0.6; } .dropped { position: static !important; } </style> </head> <body style="background-color:#080808;" onload="init()"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 grid-padding-5px margin-top-10px"> <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 remove-grid-padding" id="fav_div"> <a data-toggle="popover" data-trigger="focus" id="a_select_source"> <button type="button" class="btn btn-secondary" id="btn_select_source" onclick="buttonSourcePressed(this.id)"> Select<br/>Source</button></a> </div> <div id="sourcePopover" class="container"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 remove-grid-padding margin-2px" > <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4 padding-2px" > <button class="btn btn-secondary btn-popup-sources center-block" id="source_btn_disc" > <img src="images/DISC.png" class="img-responsive popup-source-image" style="padding:5px" > <br/> <span class="popup-source-text"> Disc </span> </button> <button class="btn btn-secondary btn-popup-sources center-block" id="source_btn_BT"> <img src="images/BT.png" class="img-responsive popup-source-image" > <br/> <span class="popup-source-text"> Bluetooth </span> </button> </div> </div> </div> </body> </html> ``` Please give me hint or reference.
2016/10/13
[ "https://Stackoverflow.com/questions/40016807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1139398/" ]
`Buttons` can be made to be **draggable** and **droppable** adding a simple functionality to the **draggable class** as shown. By using `cancel:false` So your function will look like this after the implementation - ``` $(function () { $("#dvSource button").draggable({ cancel :false, revert: "invalid", refreshPositions: true, drag: function (event, ui) { ui.helper.addClass("draggable"); }, ``` Here is the [documentation](http://api.jqueryui.com/draggable/#option-cancel) to the cancel event since it doesnt trigger the first click event Here is the code i am using without any bootstrap so i have omitted the classes as per your coding style shown above. ``` <html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="http://code.jquery.com/ui/1.8.24/jquery-ui.min.js" type="text/javascript"></script> <link href="http://code.jquery.com/ui/1.8.24/themes/blitzer/jquery-ui.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui-touch-punch/0.2.3/jquery.ui.touch-punch.min.js"></script> </head> <body> <div> <style type="text/css"> body { font-family: Arial; font-size: 10pt; } img { height: 100px; width: 100px; margin: 2px; } .draggable { filter: alpha(opacity=60); opacity: 0.6; } .dropped { position: static !important; } #dvSource, #dvDest { border: 5px solid #ccc; padding: 5px; min-height: 100px; width: 430px; } </style> <script type="text/javascript"> $(function () { $("#dvSource button").draggable({ cancel :false, revert: "invalid", refreshPositions: true, drag: function (event, ui) { ui.helper.addClass("draggable"); }, stop: function (event, ui) { ui.helper.removeClass("draggable"); /*var image = this.src.split("/")[this.src.split("/").length - 1];*/ /*if ($.ui.ddmanager.drop(ui.helper.data("draggable"), event)) { alert(image + " dropped."); } else { alert(image + " not dropped."); }*/ } }); $("#dvDest").droppable({ drop: function (event, ui) { if ($("#dvDest button").length == 0) { $("#dvDest").html(""); } ui.draggable.addClass("dropped"); $("#dvDest").append(ui.draggable); } }); }); </script> <div id="dvSource"> <a data-toggle="popover" id="a_select_source"> <button type="button" class="btn btn-secondary" id="btn_select_source">Select<br/>Source</button> </a> </div> <hr /> <div id="dvDest" > <button class="btn btn-secondary btn-popup-sources center-block" id="source_btn_disc" > <img src="images/DISC.png" class="img-responsive popup-source-image" style="padding:5px" > <br/> <span class="popup-source-text"> Disc </span> </button> <button class="btn btn-secondary btn-popup-sources center-block" id="source_btn_disc" > <img src="images/DISC.png" class="img-responsive popup-source-image" style="padding:5px" > <br/> <span class="popup-source-text"> Disc </span> </button> <button class="btn btn-secondary btn-popup-sources center-block" id="source_btn_disc" > <img src="images/DISC.png" class="img-responsive popup-source-image" style="padding:5px" > <br/> <span class="popup-source-text"> Disc </span> </button> </div> </div> </body> </html> ``` **Another error in your code** was that you are not specifying what does this snippet does which will throw an `undefined error` therefore **it is not required**.You can still use it by changing the `src` attribute with your required type. ``` /* var image = this.src.split("/")[this.src.split("/").length - 1]; if ($.ui.ddmanager.drop(ui.helper.data("draggable"), event)) { alert(image + " dropped."); } else { alert(image + " not dropped."); } */ ``` This code is used to track the image dropped from the div and not used for the button. Screenshots for the working code can be seen here - [![img2](https://i.stack.imgur.com/DIzej.png)](https://i.stack.imgur.com/DIzej.png) [![img1](https://i.stack.imgur.com/dYwHo.png)](https://i.stack.imgur.com/dYwHo.png)
for touch event in mobile using jquery you have to include below like file ``` <script src="file:///android_asset/jquery/jquery.ui.touch-punch.min.js" type="text/javascript"></script> ``` you can get this file from here : <https://github.com/furf/jquery-ui-touch-punch> make sure to include this after `jquery-ui.min.js` file
40,016,807
Hi I am creating one html page in which I am dragging some `buttons` in one `Div`using jQuery-ui and jquery-ui-punch. But dragging and dropping not happening . I don't understand why it's not working. `sourcePopover` is popover which having buttons which I want to drag in `fav_id`. Here is my HTML/JavaScript code. ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset=utf-8> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <link rel="stylesheet" href="bootstrap-3.3.6-dist/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="bootstrap-3.3.6-dist/css/bootstrap-theme.min.css"> <!--Font Awesome --> <script src="js/jquery-2.1.4.min.js"></script> <script src="bootstrap-3.3.6-dist/js/bootstrap.min.js"></script> <script src="js/jquery-ui.min.js"></script> <link href="css/jquery-ui.css" rel="stylesheet" type="text/css"/> <script src="js/jquery.ui.touch-punch.min.js"></script> <script type="text/javascript"> /*Function to show popover when select button click*/ $(function(){ // Enables popover #2 $("#btn_select_source").popover({ container: 'body', animation:true, html : true, content: function() { return $("#sourcePopover").html(); }, title: function() { return $("#sourcePopoverTitle").html(); } }) }); $(function(){ $("#sourcePopover button").draggable({ revert: "invalid", refreshPositions: true, drag: function (event, ui) { ui.helper.addClass("draggable"); }, stop: function (event, ui) { ui.helper.removeClass("draggable"); var image = this.src.split("/")[this.src.split("/").length - 1]; if ($.ui.ddmanager.drop(ui.helper.data("draggable"), event)) { alert(image + " dropped."); } else { alert(image + " not dropped."); } } }); $("#fav_div").droppable({ drop: function (event, ui) { if ($("#fav_div button").length == 0) { $("#fav_div").html(""); } ui.draggable.addClass("dropped"); $("#fav_div").append(ui.draggable); } }); }); </script> <style type="text/css"> .draggable { filter: alpha(opacity=60); opacity: 0.6; } .dropped { position: static !important; } </style> </head> <body style="background-color:#080808;" onload="init()"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 grid-padding-5px margin-top-10px"> <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 remove-grid-padding" id="fav_div"> <a data-toggle="popover" data-trigger="focus" id="a_select_source"> <button type="button" class="btn btn-secondary" id="btn_select_source" onclick="buttonSourcePressed(this.id)"> Select<br/>Source</button></a> </div> <div id="sourcePopover" class="container"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 remove-grid-padding margin-2px" > <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4 padding-2px" > <button class="btn btn-secondary btn-popup-sources center-block" id="source_btn_disc" > <img src="images/DISC.png" class="img-responsive popup-source-image" style="padding:5px" > <br/> <span class="popup-source-text"> Disc </span> </button> <button class="btn btn-secondary btn-popup-sources center-block" id="source_btn_BT"> <img src="images/BT.png" class="img-responsive popup-source-image" > <br/> <span class="popup-source-text"> Bluetooth </span> </button> </div> </div> </div> </body> </html> ``` Please give me hint or reference.
2016/10/13
[ "https://Stackoverflow.com/questions/40016807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1139398/" ]
@pritishvaidya has answered that you should add attribute `cancel:false` in draggable, that is absolutely correct. Apart from this I have changed some code that was not working. Changes I have done listed below. 1. In `stop` function inside draggable you are trying to get image name but It is not working. This is also preventing from drag and drop. 2. You were trying to check whether image has been dropped or not by calling drop function and passing ui.helper.data("draggable") but I have changed it to ui.helper.data("ui-draggable"). This change may not be necessary because it is depend on your jquery-ui version. Click Run code snippet below to find your drag and drop working. Edit: You have to bind draggable when popover is shown every time So you can use `shown.bs.popover` event of popover. I am also hiding popover when button is droped. Please take a look on updated code ```js $(function(){ $("#btn_select_source").popover({ container: 'body', animation:true, html : true, content: function() { return $("#sourcePopover").html(); }, title: function() { return $("#sourcePopoverTitle").html(); } }); $('#btn_select_source').on('shown.bs.popover', function () { makeButtonDraggable(); }); }); function init(){} function buttonSourcePressed(c){} function makeButtonDraggable(){ $(".popover-content button").draggable({ cancel :false, revert: "invalid", refreshPositions: true, drag: function (event, ui) { ui.helper.addClass("draggable"); }, stop: function (event, ui) { ui.helper.removeClass("draggable"); var image = $(this).find('img').attr('src').split("/")[$(this).find('img').attr('src').split("/").length - 1]; if ($.ui.ddmanager.drop(ui.helper.data("ui-draggable"), event)) { alert(image + " dropped."); $("#btn_select_source").popover('hide') } else { alert(image + " not dropped."); } } }); $("#fav_div").droppable({ drop: function (event, ui) { if ($("#fav_div button").length == 0) { $("#fav_div").html(""); } ui.draggable.addClass("dropped"); $("#fav_div").append(ui.draggable); } }); } ``` ```css .draggable{ filter: alpha(opacity=60); opacity: 0.6; } .dropped{ position: static !important; } ``` ```html <!doctype html> <html lang="en"> <head> <meta charset=utf-8> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap-theme.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet" type="text/css"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui-touch-punch/0.2.3/jquery.ui.touch-punch.min.js"></script> </head> <body style="background-color:#080808;" onload="init()" > <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 grid-padding-5px margin-top-10px"> <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 remove-grid-padding" id="fav_div" style="border:1px solid blue;"> <a data-toggle="popover" data-trigger="focus" id="a_select_source"> <button type="button" class="btn btn-secondary" id="btn_select_source" onclick="buttonSourcePressed(this.id)"> Select<br/>Source</button> </a> </div> <div id="sourcePopover" class="container "> <button class="btn btn-secondary btn-popup-sources center-block" id="source_btn_disc" > <img src="images/DISC.png" class="img-responsive popup-source-image" style="padding:5px" > <br/> <span class="popup-source-text"> Disc </span> </button> <button class="btn btn-secondary btn-popup-sources center-block" id="source_btn_BT"> <img src="images/BT.png" class="img-responsive popup-source-image" > <br/> <span class="popup-source-text"> Bluetooth </span> </button> </div> </div> </body> ```
for touch event in mobile using jquery you have to include below like file ``` <script src="file:///android_asset/jquery/jquery.ui.touch-punch.min.js" type="text/javascript"></script> ``` you can get this file from here : <https://github.com/furf/jquery-ui-touch-punch> make sure to include this after `jquery-ui.min.js` file
40,016,807
Hi I am creating one html page in which I am dragging some `buttons` in one `Div`using jQuery-ui and jquery-ui-punch. But dragging and dropping not happening . I don't understand why it's not working. `sourcePopover` is popover which having buttons which I want to drag in `fav_id`. Here is my HTML/JavaScript code. ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset=utf-8> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <link rel="stylesheet" href="bootstrap-3.3.6-dist/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="bootstrap-3.3.6-dist/css/bootstrap-theme.min.css"> <!--Font Awesome --> <script src="js/jquery-2.1.4.min.js"></script> <script src="bootstrap-3.3.6-dist/js/bootstrap.min.js"></script> <script src="js/jquery-ui.min.js"></script> <link href="css/jquery-ui.css" rel="stylesheet" type="text/css"/> <script src="js/jquery.ui.touch-punch.min.js"></script> <script type="text/javascript"> /*Function to show popover when select button click*/ $(function(){ // Enables popover #2 $("#btn_select_source").popover({ container: 'body', animation:true, html : true, content: function() { return $("#sourcePopover").html(); }, title: function() { return $("#sourcePopoverTitle").html(); } }) }); $(function(){ $("#sourcePopover button").draggable({ revert: "invalid", refreshPositions: true, drag: function (event, ui) { ui.helper.addClass("draggable"); }, stop: function (event, ui) { ui.helper.removeClass("draggable"); var image = this.src.split("/")[this.src.split("/").length - 1]; if ($.ui.ddmanager.drop(ui.helper.data("draggable"), event)) { alert(image + " dropped."); } else { alert(image + " not dropped."); } } }); $("#fav_div").droppable({ drop: function (event, ui) { if ($("#fav_div button").length == 0) { $("#fav_div").html(""); } ui.draggable.addClass("dropped"); $("#fav_div").append(ui.draggable); } }); }); </script> <style type="text/css"> .draggable { filter: alpha(opacity=60); opacity: 0.6; } .dropped { position: static !important; } </style> </head> <body style="background-color:#080808;" onload="init()"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 grid-padding-5px margin-top-10px"> <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 remove-grid-padding" id="fav_div"> <a data-toggle="popover" data-trigger="focus" id="a_select_source"> <button type="button" class="btn btn-secondary" id="btn_select_source" onclick="buttonSourcePressed(this.id)"> Select<br/>Source</button></a> </div> <div id="sourcePopover" class="container"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 remove-grid-padding margin-2px" > <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4 padding-2px" > <button class="btn btn-secondary btn-popup-sources center-block" id="source_btn_disc" > <img src="images/DISC.png" class="img-responsive popup-source-image" style="padding:5px" > <br/> <span class="popup-source-text"> Disc </span> </button> <button class="btn btn-secondary btn-popup-sources center-block" id="source_btn_BT"> <img src="images/BT.png" class="img-responsive popup-source-image" > <br/> <span class="popup-source-text"> Bluetooth </span> </button> </div> </div> </div> </body> </html> ``` Please give me hint or reference.
2016/10/13
[ "https://Stackoverflow.com/questions/40016807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1139398/" ]
for touch event in mobile using jquery you have to include below like file ``` <script src="file:///android_asset/jquery/jquery.ui.touch-punch.min.js" type="text/javascript"></script> ``` you can get this file from here : <https://github.com/furf/jquery-ui-touch-punch> make sure to include this after `jquery-ui.min.js` file
You are trying to drag your button then you have to prevent button default behavior. like: button, select tag etc has default behavior, when you try to do something with click or touch it will fire that default event. So you just have to prevent that default event by using `cancel: false` on `draggable()` see more about [cancel](http://api.jqueryui.com/draggable/#option-cancel) And here working link <https://jsfiddle.net/L3j9qy4h/1/> with your code just after useing `cancel: false` .
40,016,807
Hi I am creating one html page in which I am dragging some `buttons` in one `Div`using jQuery-ui and jquery-ui-punch. But dragging and dropping not happening . I don't understand why it's not working. `sourcePopover` is popover which having buttons which I want to drag in `fav_id`. Here is my HTML/JavaScript code. ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset=utf-8> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <link rel="stylesheet" href="bootstrap-3.3.6-dist/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="bootstrap-3.3.6-dist/css/bootstrap-theme.min.css"> <!--Font Awesome --> <script src="js/jquery-2.1.4.min.js"></script> <script src="bootstrap-3.3.6-dist/js/bootstrap.min.js"></script> <script src="js/jquery-ui.min.js"></script> <link href="css/jquery-ui.css" rel="stylesheet" type="text/css"/> <script src="js/jquery.ui.touch-punch.min.js"></script> <script type="text/javascript"> /*Function to show popover when select button click*/ $(function(){ // Enables popover #2 $("#btn_select_source").popover({ container: 'body', animation:true, html : true, content: function() { return $("#sourcePopover").html(); }, title: function() { return $("#sourcePopoverTitle").html(); } }) }); $(function(){ $("#sourcePopover button").draggable({ revert: "invalid", refreshPositions: true, drag: function (event, ui) { ui.helper.addClass("draggable"); }, stop: function (event, ui) { ui.helper.removeClass("draggable"); var image = this.src.split("/")[this.src.split("/").length - 1]; if ($.ui.ddmanager.drop(ui.helper.data("draggable"), event)) { alert(image + " dropped."); } else { alert(image + " not dropped."); } } }); $("#fav_div").droppable({ drop: function (event, ui) { if ($("#fav_div button").length == 0) { $("#fav_div").html(""); } ui.draggable.addClass("dropped"); $("#fav_div").append(ui.draggable); } }); }); </script> <style type="text/css"> .draggable { filter: alpha(opacity=60); opacity: 0.6; } .dropped { position: static !important; } </style> </head> <body style="background-color:#080808;" onload="init()"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 grid-padding-5px margin-top-10px"> <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 remove-grid-padding" id="fav_div"> <a data-toggle="popover" data-trigger="focus" id="a_select_source"> <button type="button" class="btn btn-secondary" id="btn_select_source" onclick="buttonSourcePressed(this.id)"> Select<br/>Source</button></a> </div> <div id="sourcePopover" class="container"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 remove-grid-padding margin-2px" > <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4 padding-2px" > <button class="btn btn-secondary btn-popup-sources center-block" id="source_btn_disc" > <img src="images/DISC.png" class="img-responsive popup-source-image" style="padding:5px" > <br/> <span class="popup-source-text"> Disc </span> </button> <button class="btn btn-secondary btn-popup-sources center-block" id="source_btn_BT"> <img src="images/BT.png" class="img-responsive popup-source-image" > <br/> <span class="popup-source-text"> Bluetooth </span> </button> </div> </div> </div> </body> </html> ``` Please give me hint or reference.
2016/10/13
[ "https://Stackoverflow.com/questions/40016807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1139398/" ]
@pritishvaidya has answered that you should add attribute `cancel:false` in draggable, that is absolutely correct. Apart from this I have changed some code that was not working. Changes I have done listed below. 1. In `stop` function inside draggable you are trying to get image name but It is not working. This is also preventing from drag and drop. 2. You were trying to check whether image has been dropped or not by calling drop function and passing ui.helper.data("draggable") but I have changed it to ui.helper.data("ui-draggable"). This change may not be necessary because it is depend on your jquery-ui version. Click Run code snippet below to find your drag and drop working. Edit: You have to bind draggable when popover is shown every time So you can use `shown.bs.popover` event of popover. I am also hiding popover when button is droped. Please take a look on updated code ```js $(function(){ $("#btn_select_source").popover({ container: 'body', animation:true, html : true, content: function() { return $("#sourcePopover").html(); }, title: function() { return $("#sourcePopoverTitle").html(); } }); $('#btn_select_source').on('shown.bs.popover', function () { makeButtonDraggable(); }); }); function init(){} function buttonSourcePressed(c){} function makeButtonDraggable(){ $(".popover-content button").draggable({ cancel :false, revert: "invalid", refreshPositions: true, drag: function (event, ui) { ui.helper.addClass("draggable"); }, stop: function (event, ui) { ui.helper.removeClass("draggable"); var image = $(this).find('img').attr('src').split("/")[$(this).find('img').attr('src').split("/").length - 1]; if ($.ui.ddmanager.drop(ui.helper.data("ui-draggable"), event)) { alert(image + " dropped."); $("#btn_select_source").popover('hide') } else { alert(image + " not dropped."); } } }); $("#fav_div").droppable({ drop: function (event, ui) { if ($("#fav_div button").length == 0) { $("#fav_div").html(""); } ui.draggable.addClass("dropped"); $("#fav_div").append(ui.draggable); } }); } ``` ```css .draggable{ filter: alpha(opacity=60); opacity: 0.6; } .dropped{ position: static !important; } ``` ```html <!doctype html> <html lang="en"> <head> <meta charset=utf-8> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap-theme.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet" type="text/css"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui-touch-punch/0.2.3/jquery.ui.touch-punch.min.js"></script> </head> <body style="background-color:#080808;" onload="init()" > <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 grid-padding-5px margin-top-10px"> <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 remove-grid-padding" id="fav_div" style="border:1px solid blue;"> <a data-toggle="popover" data-trigger="focus" id="a_select_source"> <button type="button" class="btn btn-secondary" id="btn_select_source" onclick="buttonSourcePressed(this.id)"> Select<br/>Source</button> </a> </div> <div id="sourcePopover" class="container "> <button class="btn btn-secondary btn-popup-sources center-block" id="source_btn_disc" > <img src="images/DISC.png" class="img-responsive popup-source-image" style="padding:5px" > <br/> <span class="popup-source-text"> Disc </span> </button> <button class="btn btn-secondary btn-popup-sources center-block" id="source_btn_BT"> <img src="images/BT.png" class="img-responsive popup-source-image" > <br/> <span class="popup-source-text"> Bluetooth </span> </button> </div> </div> </body> ```
`Buttons` can be made to be **draggable** and **droppable** adding a simple functionality to the **draggable class** as shown. By using `cancel:false` So your function will look like this after the implementation - ``` $(function () { $("#dvSource button").draggable({ cancel :false, revert: "invalid", refreshPositions: true, drag: function (event, ui) { ui.helper.addClass("draggable"); }, ``` Here is the [documentation](http://api.jqueryui.com/draggable/#option-cancel) to the cancel event since it doesnt trigger the first click event Here is the code i am using without any bootstrap so i have omitted the classes as per your coding style shown above. ``` <html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="http://code.jquery.com/ui/1.8.24/jquery-ui.min.js" type="text/javascript"></script> <link href="http://code.jquery.com/ui/1.8.24/themes/blitzer/jquery-ui.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui-touch-punch/0.2.3/jquery.ui.touch-punch.min.js"></script> </head> <body> <div> <style type="text/css"> body { font-family: Arial; font-size: 10pt; } img { height: 100px; width: 100px; margin: 2px; } .draggable { filter: alpha(opacity=60); opacity: 0.6; } .dropped { position: static !important; } #dvSource, #dvDest { border: 5px solid #ccc; padding: 5px; min-height: 100px; width: 430px; } </style> <script type="text/javascript"> $(function () { $("#dvSource button").draggable({ cancel :false, revert: "invalid", refreshPositions: true, drag: function (event, ui) { ui.helper.addClass("draggable"); }, stop: function (event, ui) { ui.helper.removeClass("draggable"); /*var image = this.src.split("/")[this.src.split("/").length - 1];*/ /*if ($.ui.ddmanager.drop(ui.helper.data("draggable"), event)) { alert(image + " dropped."); } else { alert(image + " not dropped."); }*/ } }); $("#dvDest").droppable({ drop: function (event, ui) { if ($("#dvDest button").length == 0) { $("#dvDest").html(""); } ui.draggable.addClass("dropped"); $("#dvDest").append(ui.draggable); } }); }); </script> <div id="dvSource"> <a data-toggle="popover" id="a_select_source"> <button type="button" class="btn btn-secondary" id="btn_select_source">Select<br/>Source</button> </a> </div> <hr /> <div id="dvDest" > <button class="btn btn-secondary btn-popup-sources center-block" id="source_btn_disc" > <img src="images/DISC.png" class="img-responsive popup-source-image" style="padding:5px" > <br/> <span class="popup-source-text"> Disc </span> </button> <button class="btn btn-secondary btn-popup-sources center-block" id="source_btn_disc" > <img src="images/DISC.png" class="img-responsive popup-source-image" style="padding:5px" > <br/> <span class="popup-source-text"> Disc </span> </button> <button class="btn btn-secondary btn-popup-sources center-block" id="source_btn_disc" > <img src="images/DISC.png" class="img-responsive popup-source-image" style="padding:5px" > <br/> <span class="popup-source-text"> Disc </span> </button> </div> </div> </body> </html> ``` **Another error in your code** was that you are not specifying what does this snippet does which will throw an `undefined error` therefore **it is not required**.You can still use it by changing the `src` attribute with your required type. ``` /* var image = this.src.split("/")[this.src.split("/").length - 1]; if ($.ui.ddmanager.drop(ui.helper.data("draggable"), event)) { alert(image + " dropped."); } else { alert(image + " not dropped."); } */ ``` This code is used to track the image dropped from the div and not used for the button. Screenshots for the working code can be seen here - [![img2](https://i.stack.imgur.com/DIzej.png)](https://i.stack.imgur.com/DIzej.png) [![img1](https://i.stack.imgur.com/dYwHo.png)](https://i.stack.imgur.com/dYwHo.png)
40,016,807
Hi I am creating one html page in which I am dragging some `buttons` in one `Div`using jQuery-ui and jquery-ui-punch. But dragging and dropping not happening . I don't understand why it's not working. `sourcePopover` is popover which having buttons which I want to drag in `fav_id`. Here is my HTML/JavaScript code. ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset=utf-8> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <link rel="stylesheet" href="bootstrap-3.3.6-dist/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="bootstrap-3.3.6-dist/css/bootstrap-theme.min.css"> <!--Font Awesome --> <script src="js/jquery-2.1.4.min.js"></script> <script src="bootstrap-3.3.6-dist/js/bootstrap.min.js"></script> <script src="js/jquery-ui.min.js"></script> <link href="css/jquery-ui.css" rel="stylesheet" type="text/css"/> <script src="js/jquery.ui.touch-punch.min.js"></script> <script type="text/javascript"> /*Function to show popover when select button click*/ $(function(){ // Enables popover #2 $("#btn_select_source").popover({ container: 'body', animation:true, html : true, content: function() { return $("#sourcePopover").html(); }, title: function() { return $("#sourcePopoverTitle").html(); } }) }); $(function(){ $("#sourcePopover button").draggable({ revert: "invalid", refreshPositions: true, drag: function (event, ui) { ui.helper.addClass("draggable"); }, stop: function (event, ui) { ui.helper.removeClass("draggable"); var image = this.src.split("/")[this.src.split("/").length - 1]; if ($.ui.ddmanager.drop(ui.helper.data("draggable"), event)) { alert(image + " dropped."); } else { alert(image + " not dropped."); } } }); $("#fav_div").droppable({ drop: function (event, ui) { if ($("#fav_div button").length == 0) { $("#fav_div").html(""); } ui.draggable.addClass("dropped"); $("#fav_div").append(ui.draggable); } }); }); </script> <style type="text/css"> .draggable { filter: alpha(opacity=60); opacity: 0.6; } .dropped { position: static !important; } </style> </head> <body style="background-color:#080808;" onload="init()"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 grid-padding-5px margin-top-10px"> <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 remove-grid-padding" id="fav_div"> <a data-toggle="popover" data-trigger="focus" id="a_select_source"> <button type="button" class="btn btn-secondary" id="btn_select_source" onclick="buttonSourcePressed(this.id)"> Select<br/>Source</button></a> </div> <div id="sourcePopover" class="container"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 remove-grid-padding margin-2px" > <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4 padding-2px" > <button class="btn btn-secondary btn-popup-sources center-block" id="source_btn_disc" > <img src="images/DISC.png" class="img-responsive popup-source-image" style="padding:5px" > <br/> <span class="popup-source-text"> Disc </span> </button> <button class="btn btn-secondary btn-popup-sources center-block" id="source_btn_BT"> <img src="images/BT.png" class="img-responsive popup-source-image" > <br/> <span class="popup-source-text"> Bluetooth </span> </button> </div> </div> </div> </body> </html> ``` Please give me hint or reference.
2016/10/13
[ "https://Stackoverflow.com/questions/40016807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1139398/" ]
`Buttons` can be made to be **draggable** and **droppable** adding a simple functionality to the **draggable class** as shown. By using `cancel:false` So your function will look like this after the implementation - ``` $(function () { $("#dvSource button").draggable({ cancel :false, revert: "invalid", refreshPositions: true, drag: function (event, ui) { ui.helper.addClass("draggable"); }, ``` Here is the [documentation](http://api.jqueryui.com/draggable/#option-cancel) to the cancel event since it doesnt trigger the first click event Here is the code i am using without any bootstrap so i have omitted the classes as per your coding style shown above. ``` <html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="http://code.jquery.com/ui/1.8.24/jquery-ui.min.js" type="text/javascript"></script> <link href="http://code.jquery.com/ui/1.8.24/themes/blitzer/jquery-ui.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui-touch-punch/0.2.3/jquery.ui.touch-punch.min.js"></script> </head> <body> <div> <style type="text/css"> body { font-family: Arial; font-size: 10pt; } img { height: 100px; width: 100px; margin: 2px; } .draggable { filter: alpha(opacity=60); opacity: 0.6; } .dropped { position: static !important; } #dvSource, #dvDest { border: 5px solid #ccc; padding: 5px; min-height: 100px; width: 430px; } </style> <script type="text/javascript"> $(function () { $("#dvSource button").draggable({ cancel :false, revert: "invalid", refreshPositions: true, drag: function (event, ui) { ui.helper.addClass("draggable"); }, stop: function (event, ui) { ui.helper.removeClass("draggable"); /*var image = this.src.split("/")[this.src.split("/").length - 1];*/ /*if ($.ui.ddmanager.drop(ui.helper.data("draggable"), event)) { alert(image + " dropped."); } else { alert(image + " not dropped."); }*/ } }); $("#dvDest").droppable({ drop: function (event, ui) { if ($("#dvDest button").length == 0) { $("#dvDest").html(""); } ui.draggable.addClass("dropped"); $("#dvDest").append(ui.draggable); } }); }); </script> <div id="dvSource"> <a data-toggle="popover" id="a_select_source"> <button type="button" class="btn btn-secondary" id="btn_select_source">Select<br/>Source</button> </a> </div> <hr /> <div id="dvDest" > <button class="btn btn-secondary btn-popup-sources center-block" id="source_btn_disc" > <img src="images/DISC.png" class="img-responsive popup-source-image" style="padding:5px" > <br/> <span class="popup-source-text"> Disc </span> </button> <button class="btn btn-secondary btn-popup-sources center-block" id="source_btn_disc" > <img src="images/DISC.png" class="img-responsive popup-source-image" style="padding:5px" > <br/> <span class="popup-source-text"> Disc </span> </button> <button class="btn btn-secondary btn-popup-sources center-block" id="source_btn_disc" > <img src="images/DISC.png" class="img-responsive popup-source-image" style="padding:5px" > <br/> <span class="popup-source-text"> Disc </span> </button> </div> </div> </body> </html> ``` **Another error in your code** was that you are not specifying what does this snippet does which will throw an `undefined error` therefore **it is not required**.You can still use it by changing the `src` attribute with your required type. ``` /* var image = this.src.split("/")[this.src.split("/").length - 1]; if ($.ui.ddmanager.drop(ui.helper.data("draggable"), event)) { alert(image + " dropped."); } else { alert(image + " not dropped."); } */ ``` This code is used to track the image dropped from the div and not used for the button. Screenshots for the working code can be seen here - [![img2](https://i.stack.imgur.com/DIzej.png)](https://i.stack.imgur.com/DIzej.png) [![img1](https://i.stack.imgur.com/dYwHo.png)](https://i.stack.imgur.com/dYwHo.png)
You are trying to drag your button then you have to prevent button default behavior. like: button, select tag etc has default behavior, when you try to do something with click or touch it will fire that default event. So you just have to prevent that default event by using `cancel: false` on `draggable()` see more about [cancel](http://api.jqueryui.com/draggable/#option-cancel) And here working link <https://jsfiddle.net/L3j9qy4h/1/> with your code just after useing `cancel: false` .
40,016,807
Hi I am creating one html page in which I am dragging some `buttons` in one `Div`using jQuery-ui and jquery-ui-punch. But dragging and dropping not happening . I don't understand why it's not working. `sourcePopover` is popover which having buttons which I want to drag in `fav_id`. Here is my HTML/JavaScript code. ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset=utf-8> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <link rel="stylesheet" href="bootstrap-3.3.6-dist/css/bootstrap.min.css"> <!-- Optional theme --> <link rel="stylesheet" href="bootstrap-3.3.6-dist/css/bootstrap-theme.min.css"> <!--Font Awesome --> <script src="js/jquery-2.1.4.min.js"></script> <script src="bootstrap-3.3.6-dist/js/bootstrap.min.js"></script> <script src="js/jquery-ui.min.js"></script> <link href="css/jquery-ui.css" rel="stylesheet" type="text/css"/> <script src="js/jquery.ui.touch-punch.min.js"></script> <script type="text/javascript"> /*Function to show popover when select button click*/ $(function(){ // Enables popover #2 $("#btn_select_source").popover({ container: 'body', animation:true, html : true, content: function() { return $("#sourcePopover").html(); }, title: function() { return $("#sourcePopoverTitle").html(); } }) }); $(function(){ $("#sourcePopover button").draggable({ revert: "invalid", refreshPositions: true, drag: function (event, ui) { ui.helper.addClass("draggable"); }, stop: function (event, ui) { ui.helper.removeClass("draggable"); var image = this.src.split("/")[this.src.split("/").length - 1]; if ($.ui.ddmanager.drop(ui.helper.data("draggable"), event)) { alert(image + " dropped."); } else { alert(image + " not dropped."); } } }); $("#fav_div").droppable({ drop: function (event, ui) { if ($("#fav_div button").length == 0) { $("#fav_div").html(""); } ui.draggable.addClass("dropped"); $("#fav_div").append(ui.draggable); } }); }); </script> <style type="text/css"> .draggable { filter: alpha(opacity=60); opacity: 0.6; } .dropped { position: static !important; } </style> </head> <body style="background-color:#080808;" onload="init()"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 grid-padding-5px margin-top-10px"> <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 remove-grid-padding" id="fav_div"> <a data-toggle="popover" data-trigger="focus" id="a_select_source"> <button type="button" class="btn btn-secondary" id="btn_select_source" onclick="buttonSourcePressed(this.id)"> Select<br/>Source</button></a> </div> <div id="sourcePopover" class="container"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 remove-grid-padding margin-2px" > <div class="col-lg-4 col-md-4 col-sm-4 col-xs-4 padding-2px" > <button class="btn btn-secondary btn-popup-sources center-block" id="source_btn_disc" > <img src="images/DISC.png" class="img-responsive popup-source-image" style="padding:5px" > <br/> <span class="popup-source-text"> Disc </span> </button> <button class="btn btn-secondary btn-popup-sources center-block" id="source_btn_BT"> <img src="images/BT.png" class="img-responsive popup-source-image" > <br/> <span class="popup-source-text"> Bluetooth </span> </button> </div> </div> </div> </body> </html> ``` Please give me hint or reference.
2016/10/13
[ "https://Stackoverflow.com/questions/40016807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1139398/" ]
@pritishvaidya has answered that you should add attribute `cancel:false` in draggable, that is absolutely correct. Apart from this I have changed some code that was not working. Changes I have done listed below. 1. In `stop` function inside draggable you are trying to get image name but It is not working. This is also preventing from drag and drop. 2. You were trying to check whether image has been dropped or not by calling drop function and passing ui.helper.data("draggable") but I have changed it to ui.helper.data("ui-draggable"). This change may not be necessary because it is depend on your jquery-ui version. Click Run code snippet below to find your drag and drop working. Edit: You have to bind draggable when popover is shown every time So you can use `shown.bs.popover` event of popover. I am also hiding popover when button is droped. Please take a look on updated code ```js $(function(){ $("#btn_select_source").popover({ container: 'body', animation:true, html : true, content: function() { return $("#sourcePopover").html(); }, title: function() { return $("#sourcePopoverTitle").html(); } }); $('#btn_select_source').on('shown.bs.popover', function () { makeButtonDraggable(); }); }); function init(){} function buttonSourcePressed(c){} function makeButtonDraggable(){ $(".popover-content button").draggable({ cancel :false, revert: "invalid", refreshPositions: true, drag: function (event, ui) { ui.helper.addClass("draggable"); }, stop: function (event, ui) { ui.helper.removeClass("draggable"); var image = $(this).find('img').attr('src').split("/")[$(this).find('img').attr('src').split("/").length - 1]; if ($.ui.ddmanager.drop(ui.helper.data("ui-draggable"), event)) { alert(image + " dropped."); $("#btn_select_source").popover('hide') } else { alert(image + " not dropped."); } } }); $("#fav_div").droppable({ drop: function (event, ui) { if ($("#fav_div button").length == 0) { $("#fav_div").html(""); } ui.draggable.addClass("dropped"); $("#fav_div").append(ui.draggable); } }); } ``` ```css .draggable{ filter: alpha(opacity=60); opacity: 0.6; } .dropped{ position: static !important; } ``` ```html <!doctype html> <html lang="en"> <head> <meta charset=utf-8> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap-theme.min.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet" type="text/css"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui-touch-punch/0.2.3/jquery.ui.touch-punch.min.js"></script> </head> <body style="background-color:#080808;" onload="init()" > <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 grid-padding-5px margin-top-10px"> <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2 remove-grid-padding" id="fav_div" style="border:1px solid blue;"> <a data-toggle="popover" data-trigger="focus" id="a_select_source"> <button type="button" class="btn btn-secondary" id="btn_select_source" onclick="buttonSourcePressed(this.id)"> Select<br/>Source</button> </a> </div> <div id="sourcePopover" class="container "> <button class="btn btn-secondary btn-popup-sources center-block" id="source_btn_disc" > <img src="images/DISC.png" class="img-responsive popup-source-image" style="padding:5px" > <br/> <span class="popup-source-text"> Disc </span> </button> <button class="btn btn-secondary btn-popup-sources center-block" id="source_btn_BT"> <img src="images/BT.png" class="img-responsive popup-source-image" > <br/> <span class="popup-source-text"> Bluetooth </span> </button> </div> </div> </body> ```
You are trying to drag your button then you have to prevent button default behavior. like: button, select tag etc has default behavior, when you try to do something with click or touch it will fire that default event. So you just have to prevent that default event by using `cancel: false` on `draggable()` see more about [cancel](http://api.jqueryui.com/draggable/#option-cancel) And here working link <https://jsfiddle.net/L3j9qy4h/1/> with your code just after useing `cancel: false` .
25,256,023
I am inputting the following things: * book * 12.46 * music cd For some reason, the prompt for cost comes up and the next output line comes on the same line. Could someone help me to spot my mistake? ``` public class SalesTax { public static void main(String[] args) { // Input items for shopping cart HashMap<String, String> cart = new HashMap<String, String>(); // Create a Scanner Scanner input = new Scanner(System.in); // variables char done; boolean goods; double tax; // Pick items for list. do { System.out.print("Please enter an item."); String item = input.next(); System.out.print("Please enter the price for "+ item + ": "); String price = input.next(); if (item.contains("book")) { goods = false; } else if(item.contains("chocolate")) { goods = false; } else if(item.contains("pill")) { goods = false; } cart.put(item, price); System.out.print("Would you like to continue to add items? (Type Y) for Yes and (Type N) for No."); done = input.next().charAt(0); } while(Character.toUpperCase(done) == 'Y'); } } ```
2014/08/12
[ "https://Stackoverflow.com/questions/25256023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3930524/" ]
**problem:** ``` String item = input.next(); ``` By the time you input `music cd` it will consume **music** by `item` and `price` will consume the **cd** thus skipping it. **solution:** you need to call `input.nextLine();` to consume the whole line of string
you are using `System.out.print()` instead use System.out.println(); `print()` will just print the word and stays on the same line. `println()` will print the whole line and cursor goes to second line . And don't use the spaces while reading as you are writing it as `input.next();` > > The next() and hasNext() methods and their primitive-type companion methods (such as nextInt() and hasNextInt()) first skip any input that matches the delimiter pattern, and then attempt to return the next token. Both hasNext and next methods may block waiting for further input. Whether a hasNext method blocks has no connection to whether or not its associated next method will block. > > > **edit:** just change the declaration to this. ``` Scanner s = new Scanner(input).useDelimiter("\n"); ``` It will change the delimiter to new line and read the complete line.
25,256,023
I am inputting the following things: * book * 12.46 * music cd For some reason, the prompt for cost comes up and the next output line comes on the same line. Could someone help me to spot my mistake? ``` public class SalesTax { public static void main(String[] args) { // Input items for shopping cart HashMap<String, String> cart = new HashMap<String, String>(); // Create a Scanner Scanner input = new Scanner(System.in); // variables char done; boolean goods; double tax; // Pick items for list. do { System.out.print("Please enter an item."); String item = input.next(); System.out.print("Please enter the price for "+ item + ": "); String price = input.next(); if (item.contains("book")) { goods = false; } else if(item.contains("chocolate")) { goods = false; } else if(item.contains("pill")) { goods = false; } cart.put(item, price); System.out.print("Would you like to continue to add items? (Type Y) for Yes and (Type N) for No."); done = input.next().charAt(0); } while(Character.toUpperCase(done) == 'Y'); } } ```
2014/08/12
[ "https://Stackoverflow.com/questions/25256023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3930524/" ]
**problem:** ``` String item = input.next(); ``` By the time you input `music cd` it will consume **music** by `item` and `price` will consume the **cd** thus skipping it. **solution:** you need to call `input.nextLine();` to consume the whole line of string
By default, `next()` just gets input upto a whitespace so you'd have to use `nextLine()` instead, which will read in the whole line of input upto a carriage return.
25,256,023
I am inputting the following things: * book * 12.46 * music cd For some reason, the prompt for cost comes up and the next output line comes on the same line. Could someone help me to spot my mistake? ``` public class SalesTax { public static void main(String[] args) { // Input items for shopping cart HashMap<String, String> cart = new HashMap<String, String>(); // Create a Scanner Scanner input = new Scanner(System.in); // variables char done; boolean goods; double tax; // Pick items for list. do { System.out.print("Please enter an item."); String item = input.next(); System.out.print("Please enter the price for "+ item + ": "); String price = input.next(); if (item.contains("book")) { goods = false; } else if(item.contains("chocolate")) { goods = false; } else if(item.contains("pill")) { goods = false; } cart.put(item, price); System.out.print("Would you like to continue to add items? (Type Y) for Yes and (Type N) for No."); done = input.next().charAt(0); } while(Character.toUpperCase(done) == 'Y'); } } ```
2014/08/12
[ "https://Stackoverflow.com/questions/25256023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3930524/" ]
**problem:** ``` String item = input.next(); ``` By the time you input `music cd` it will consume **music** by `item` and `price` will consume the **cd** thus skipping it. **solution:** you need to call `input.nextLine();` to consume the whole line of string
use `input.nextLine()` to read an entire line from the keyboard. Means what ever the user typed till the user presses the enter key. One thing that I did not understand is, what is the use of having this in your code ``` if(item.contains("book")) { goods = false; } else if(item.contains("chocolate")) { goods = false; } else if(item.contains("pill")) { goods = false; } ``` ??? Can you please explain? Thanks,
1,523,300
I have a bat that starts 3 separate java windows like so: ``` start java -jar somejar.jar start java -jar _the_jar_I_want_to_close_.jar start java -jar someotherjar.jar ``` I need a bat command that closes ***ONLY*** \_the\_jar\_I\_want\_to\_close\_.jar. Unfortunately the only thing that differentiates these windows is the PID, but the PID changes every time they're launched. Here's what I've tried ---------------------- 1. Taskkill by PID `taskkill /PID ####` **Problem:** The PID is not constant. 2. Killing all processes from java `taskkill /IM java.exe` **Problem:** There are 2 other java windows that I don't want to stop 3. Killing all processes by image name: `taskkill /IM java` **Problem:** Same as above, only need to kill one window, not all three. Possibilities? -------------- 1. Is it possible to name the windows when I start them, so I can reference that name later?
2020/02/06
[ "https://superuser.com/questions/1523300", "https://superuser.com", "https://superuser.com/users/232563/" ]
You can use `plink.exe` to start your existing putty session. Create a new profile entry for Windows Terminal like this, where `putty-session` is the name of your putty session: ``` { "guid": "{141d171c-4fd9-426d-9008-8cbc4b0b05d3}", "name": "putty-session", "icon" : "ms-appx:///ProfileIcons/{9acb9455-ca41-5af7-950f-6bca1bc9722f}.png", "commandline": "plink.exe -load \"putty-session\"" } ``` For more details see this answer: <https://stackoverflow.com/questions/57363597/how-to-use-a-new-windows-terminal-app-for-ssh>
There is a *fork* of Putty that has a robust preferences menu where you can configure it to run in windows terminal. As documented [here](https://www.vcloudinfo.com/2019/06/putty-putty-putty-windows-terminal.html) As far as I know, there is currently no way to enable *standard* Putty to run within Windows Terminal. Also, see [this GitHub issue](https://github.com/microsoft/terminal/issues/1917#issuecomment-510259173) where they explain that since Putty is actually a complete GUI application it *can't* run within Windows Terminal.
69,125
I am not a mathematician. I have searched the internet about KL Divergence. What I learned is the the KL divergence measures the information lost when we approximate distribution of a model with respect to the input distribution. I have seen these between any two continuous or discrete distributions. Can we do it between continuous and discrete or vice versa?
2013/09/03
[ "https://stats.stackexchange.com/questions/69125", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/29874/" ]
No: KL divergence is only defined on distributions over a common space. It asks about the probability density of a point $x$ under two different distributions, $p(x)$ and $q(x)$. If $p$ is a distribution on $\mathbb{R}^3$ and $q$ a distribution on $\mathbb{Z}$, then $q(x)$ doesn't make sense for points $p \in \mathbb{R}^3$ and $p(z)$ doesn't make sense for points $z \in \mathbb{Z}$. In fact, we can't even do it for two continuous distributions over different-dimensional spaces (or discrete, or any case where the underlying probability spaces don't match). If you have a particular case in mind, it may be possible to come up with some similar-spirited measure of dissimilarity between distributions. For example, it might make sense to encode a continuous distribution under a code for a discrete one (obviously with lost information), e.g. by rounding to the nearest point in the discrete case.
Not in general. The KL divergence is $$ D\_{KL}(P \ || \ Q) = \int\_{\mathcal{X}} \log \left(\frac{dP}{dQ}\right)dP $$ provided that $P$ is absolutely continuous with respect to $Q$ and both $P$ and $Q$ are $\sigma$-finite (i.e. under conditions where $\frac{dP}{dQ}$ is well-defined). For a 'continuous-to-discrete' KL divergence between measures on some usual space, you have the case where Lebesgue measure is absolutely continuous with respect to counting measure, but counting measure is not $\sigma$-finite.
69,125
I am not a mathematician. I have searched the internet about KL Divergence. What I learned is the the KL divergence measures the information lost when we approximate distribution of a model with respect to the input distribution. I have seen these between any two continuous or discrete distributions. Can we do it between continuous and discrete or vice versa?
2013/09/03
[ "https://stats.stackexchange.com/questions/69125", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/29874/" ]
Yes, the KL divergence between continuous and discrete random variables is well defined. If $P$ and $Q$ are distributions on some space $\mathbb{X}$, then both $P$ and $Q$ have densities $f$, $g$ with respect to $\mu = P+Q$ and $$ D\_{KL}(P,Q) = \int\_{\mathbb{X}} f \log\frac{f}{g}d\mu. $$ For example, if $\mathbb{X} = [0,1]$, $P$ is Lebesgue's measure and $Q = \delta\_0$ is a point mass at $0$, then $f(x) = 1-\mathbb{1}\_{x=0}$, $g(x) = \mathbb{1}\_{x=0}$ and $$D\_{KL}(P, Q) = \infty.$$
Not in general. The KL divergence is $$ D\_{KL}(P \ || \ Q) = \int\_{\mathcal{X}} \log \left(\frac{dP}{dQ}\right)dP $$ provided that $P$ is absolutely continuous with respect to $Q$ and both $P$ and $Q$ are $\sigma$-finite (i.e. under conditions where $\frac{dP}{dQ}$ is well-defined). For a 'continuous-to-discrete' KL divergence between measures on some usual space, you have the case where Lebesgue measure is absolutely continuous with respect to counting measure, but counting measure is not $\sigma$-finite.
60,291,808
The snippet shows my html and js. In my php controller I just print\_r($\_POST) but I only see the form data for myName I can't figure out how to access zzz UPDATE: I added some code to make sure the send request is complete. However, if I don't submit the form the controller doesn't execute from just issuing the xhttp request. I still can't get any js data into php. I could create hidden inputs and fill those in from js and the submit but that seems ugly. can someone help? ```js function swagSend() { event.preventDefault(); var xhttp = new XMLHttpRequest(); xhttp.open("POST", "https://www.sustainablewestonma.org/wp-content/themes/twentytwelve-child/php/send_email.php", true); xhttp.onreadystatechange = function() { if (xhttp.readyState == 4 && xhttp.status == 200) { console.log(xhttp.responseText); } } var henry = "henry" xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhttp.send("zzz=" + henry); xhttp.onreadystatechange = function() { if (xhttp.readyState == 4 && xhttp.status == 200) { document.getElementById("myForm").submit(); } } } ``` ```html <form action="https://www.sustainablewestonma.org/wp-content/themes/twentytwelve-child/php/send_email.php" method="POST" id='myForm'> <input type='text' name='myname'> <button type='submit' value='submit' onClick=swagSend();>Submit</button> </form> ```
2020/02/19
[ "https://Stackoverflow.com/questions/60291808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4398966/" ]
When you pass a value to `useState` that value is used to initialize the state. It does not get set every time the component rerenders, so in your case the `path` is only ever set when the component mounts. Even if the props change, the `path` state will not. As your initial state depends on a prop, all you need to do is pull the relevant prop out of your props and pass it to the function that calculates the initial `path` value: ``` const Figure = (props) => { // get relevant prop const { importantProp } = props; // path will never change, even when props change const [path] = useState(calculatePath(importantProp)); return( <G> <Path d={path} /> </G> ) } ``` However, the `calculatePath` function still gets evaluated every render, even though the `path` value is not re-initialized. If `calculatePath` is an expensive operation, then consider using `useMemo` instead: You can ensure that `path` is updated only when a specific prop changes by adding that prop to the dependency array: ``` const Figure = (props) => { const { importantProp } = props; const path = useMemo(() => calculatePath(importantProp), [importantProp]); return( <G> <Path d={path} /> </G> ) } ``` And in that case, you don't need state at all. Adding the `importantProp` to the `useMemo` dependency array means that every time `importantProp` changes, React will recalculate your `path` variable. Using `useMemo` will prevent the expensive calculation from being evaluated on every render. I've created a [CodeSandbox example](https://codesandbox.io/s/boring-sun-ze3du) where you can see in the console that the path is only re-calculated when the specified prop `important` changes. If you change any other props, the `path` does not get recalculated.
You can use the hook **useMemo**, it returns the value to your const, it receives the function that returns the value and also an array, send an empty one to calculate just once, you can send some dependencies, props or state if needed to recalculate the value when they change. In your case you can do something like this: ``` const Figure = (props) => { const path = React.useMemo(() => { // calculate and return value for path }, []); return( <G> <Path d={path} /> </G> ) } ``` It was created for that porpuse. Hope it helps ;)!
60,291,808
The snippet shows my html and js. In my php controller I just print\_r($\_POST) but I only see the form data for myName I can't figure out how to access zzz UPDATE: I added some code to make sure the send request is complete. However, if I don't submit the form the controller doesn't execute from just issuing the xhttp request. I still can't get any js data into php. I could create hidden inputs and fill those in from js and the submit but that seems ugly. can someone help? ```js function swagSend() { event.preventDefault(); var xhttp = new XMLHttpRequest(); xhttp.open("POST", "https://www.sustainablewestonma.org/wp-content/themes/twentytwelve-child/php/send_email.php", true); xhttp.onreadystatechange = function() { if (xhttp.readyState == 4 && xhttp.status == 200) { console.log(xhttp.responseText); } } var henry = "henry" xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhttp.send("zzz=" + henry); xhttp.onreadystatechange = function() { if (xhttp.readyState == 4 && xhttp.status == 200) { document.getElementById("myForm").submit(); } } } ``` ```html <form action="https://www.sustainablewestonma.org/wp-content/themes/twentytwelve-child/php/send_email.php" method="POST" id='myForm'> <input type='text' name='myname'> <button type='submit' value='submit' onClick=swagSend();>Submit</button> </form> ```
2020/02/19
[ "https://Stackoverflow.com/questions/60291808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4398966/" ]
An even more elegant option is to use the callback form of `useState`. If you pass it a function, that function will be called only when the initial state needs to be calculated - that is, on the initial render: ``` const [path, setPath] = React.useState(heavyCalculation); ``` ```js const heavyCalculation = () => { console.log('doing heavy calculation'); return 0; }; const App = () => { const [path, setPath] = React.useState(heavyCalculation); React.useEffect(() => { setInterval(() => { setPath(path => path + 1); }, 1000); }, []); return 'Path is: ' + path; }; ReactDOM.render(<App />, document.querySelector('.react')); ``` ```html <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div class="react"></div> ``` As you can see in the snippet above, `doing heavy calculation` only gets logged once.
You can use the hook **useMemo**, it returns the value to your const, it receives the function that returns the value and also an array, send an empty one to calculate just once, you can send some dependencies, props or state if needed to recalculate the value when they change. In your case you can do something like this: ``` const Figure = (props) => { const path = React.useMemo(() => { // calculate and return value for path }, []); return( <G> <Path d={path} /> </G> ) } ``` It was created for that porpuse. Hope it helps ;)!
60,291,808
The snippet shows my html and js. In my php controller I just print\_r($\_POST) but I only see the form data for myName I can't figure out how to access zzz UPDATE: I added some code to make sure the send request is complete. However, if I don't submit the form the controller doesn't execute from just issuing the xhttp request. I still can't get any js data into php. I could create hidden inputs and fill those in from js and the submit but that seems ugly. can someone help? ```js function swagSend() { event.preventDefault(); var xhttp = new XMLHttpRequest(); xhttp.open("POST", "https://www.sustainablewestonma.org/wp-content/themes/twentytwelve-child/php/send_email.php", true); xhttp.onreadystatechange = function() { if (xhttp.readyState == 4 && xhttp.status == 200) { console.log(xhttp.responseText); } } var henry = "henry" xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhttp.send("zzz=" + henry); xhttp.onreadystatechange = function() { if (xhttp.readyState == 4 && xhttp.status == 200) { document.getElementById("myForm").submit(); } } } ``` ```html <form action="https://www.sustainablewestonma.org/wp-content/themes/twentytwelve-child/php/send_email.php" method="POST" id='myForm'> <input type='text' name='myname'> <button type='submit' value='submit' onClick=swagSend();>Submit</button> </form> ```
2020/02/19
[ "https://Stackoverflow.com/questions/60291808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4398966/" ]
When you pass a value to `useState` that value is used to initialize the state. It does not get set every time the component rerenders, so in your case the `path` is only ever set when the component mounts. Even if the props change, the `path` state will not. As your initial state depends on a prop, all you need to do is pull the relevant prop out of your props and pass it to the function that calculates the initial `path` value: ``` const Figure = (props) => { // get relevant prop const { importantProp } = props; // path will never change, even when props change const [path] = useState(calculatePath(importantProp)); return( <G> <Path d={path} /> </G> ) } ``` However, the `calculatePath` function still gets evaluated every render, even though the `path` value is not re-initialized. If `calculatePath` is an expensive operation, then consider using `useMemo` instead: You can ensure that `path` is updated only when a specific prop changes by adding that prop to the dependency array: ``` const Figure = (props) => { const { importantProp } = props; const path = useMemo(() => calculatePath(importantProp), [importantProp]); return( <G> <Path d={path} /> </G> ) } ``` And in that case, you don't need state at all. Adding the `importantProp` to the `useMemo` dependency array means that every time `importantProp` changes, React will recalculate your `path` variable. Using `useMemo` will prevent the expensive calculation from being evaluated on every render. I've created a [CodeSandbox example](https://codesandbox.io/s/boring-sun-ze3du) where you can see in the console that the path is only re-calculated when the specified prop `important` changes. If you change any other props, the `path` does not get recalculated.
An even more elegant option is to use the callback form of `useState`. If you pass it a function, that function will be called only when the initial state needs to be calculated - that is, on the initial render: ``` const [path, setPath] = React.useState(heavyCalculation); ``` ```js const heavyCalculation = () => { console.log('doing heavy calculation'); return 0; }; const App = () => { const [path, setPath] = React.useState(heavyCalculation); React.useEffect(() => { setInterval(() => { setPath(path => path + 1); }, 1000); }, []); return 'Path is: ' + path; }; ReactDOM.render(<App />, document.querySelector('.react')); ``` ```html <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div class="react"></div> ``` As you can see in the snippet above, `doing heavy calculation` only gets logged once.
2,808,733
Why **import org.apache.commons.lang.StringUtils** cannot be imported in android by default. Do i have to include an external library? Then where can i find that library on the web? ``` package com.myapps.urlencoding; import android.app.Activity; import org.apache.commons.lang.StringUtils; public class EncodeIdUtil extends Activity { /** Called when the activity is first created. */ private static Long multiplier=Long.parseLong("1zzzz",36); /** * Encodes the id. * @param id the id to encode * @return encoded string */ public static String encode(Long id) { return StringUtils.reverse(Long.toString((id*multiplier), 35)); } /** * Decodes the encoded id. * @param encodedId the encodedId to decode * @return the Id * @throws IllegalArgumentException if encodedId is not a validly encoded id. */ public static Long decode(String encodedId) throws IllegalArgumentException { long product; try { product = Long.parseLong(StringUtils.reverse(encodedId), 35); } catch (Exception e) { throw new IllegalArgumentException(); } if ( 0 != product % multiplier || product < 0) { throw new IllegalArgumentException(); } return product/multiplier; } } ```
2010/05/11
[ "https://Stackoverflow.com/questions/2808733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2355649/" ]
You don't say whether you are using Eclipse or Android Studio. In Android Studio, you would add, ``` import org.apache.commons.lang3.StringUtils; ``` to your source code file. In build.gradle, you need to change your dependency from something like, ``` dependencies { compile 'com.android.support:support-v4:+' } ``` to ``` dependencies { compile 'com.android.support:support-v4:+' compile 'org.apache.commons:commons-lang3:3.0' } ``` In other words, you would add to the dependency.
Apache Commons lang is a separate library. You can find it [here](http://commons.apache.org/lang/).
2,808,733
Why **import org.apache.commons.lang.StringUtils** cannot be imported in android by default. Do i have to include an external library? Then where can i find that library on the web? ``` package com.myapps.urlencoding; import android.app.Activity; import org.apache.commons.lang.StringUtils; public class EncodeIdUtil extends Activity { /** Called when the activity is first created. */ private static Long multiplier=Long.parseLong("1zzzz",36); /** * Encodes the id. * @param id the id to encode * @return encoded string */ public static String encode(Long id) { return StringUtils.reverse(Long.toString((id*multiplier), 35)); } /** * Decodes the encoded id. * @param encodedId the encodedId to decode * @return the Id * @throws IllegalArgumentException if encodedId is not a validly encoded id. */ public static Long decode(String encodedId) throws IllegalArgumentException { long product; try { product = Long.parseLong(StringUtils.reverse(encodedId), 35); } catch (Exception e) { throw new IllegalArgumentException(); } if ( 0 != product % multiplier || product < 0) { throw new IllegalArgumentException(); } return product/multiplier; } } ```
2010/05/11
[ "https://Stackoverflow.com/questions/2808733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2355649/" ]
Apache Commons lang is a separate library. You can find it [here](http://commons.apache.org/lang/).
If you are using Android Studio try to use workflow provided to add dependencies rather than manually adding the downloaded library or manually changing gradle files. 1. File -> Project Structure -> Modules -> app -> Dependencies Tab 2. Click '+' in the bottom left corner and select "Library dependency" 3. In the search field type: "org.apache.commons:commons-lang3" and click Search 4. Select "org.apache.commons:commons-lang3:3.7" [![enter image description here](https://i.stack.imgur.com/XFSMO.png)](https://i.stack.imgur.com/XFSMO.png)
2,808,733
Why **import org.apache.commons.lang.StringUtils** cannot be imported in android by default. Do i have to include an external library? Then where can i find that library on the web? ``` package com.myapps.urlencoding; import android.app.Activity; import org.apache.commons.lang.StringUtils; public class EncodeIdUtil extends Activity { /** Called when the activity is first created. */ private static Long multiplier=Long.parseLong("1zzzz",36); /** * Encodes the id. * @param id the id to encode * @return encoded string */ public static String encode(Long id) { return StringUtils.reverse(Long.toString((id*multiplier), 35)); } /** * Decodes the encoded id. * @param encodedId the encodedId to decode * @return the Id * @throws IllegalArgumentException if encodedId is not a validly encoded id. */ public static Long decode(String encodedId) throws IllegalArgumentException { long product; try { product = Long.parseLong(StringUtils.reverse(encodedId), 35); } catch (Exception e) { throw new IllegalArgumentException(); } if ( 0 != product % multiplier || product < 0) { throw new IllegalArgumentException(); } return product/multiplier; } } ```
2010/05/11
[ "https://Stackoverflow.com/questions/2808733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2355649/" ]
Apache Commons lang is a separate library. You can find it [here](http://commons.apache.org/lang/).
just add following dependency in module level gradle file(build.gradle) ``` implementation 'org.apache.commons:commons-lang3:3.7' ```
2,808,733
Why **import org.apache.commons.lang.StringUtils** cannot be imported in android by default. Do i have to include an external library? Then where can i find that library on the web? ``` package com.myapps.urlencoding; import android.app.Activity; import org.apache.commons.lang.StringUtils; public class EncodeIdUtil extends Activity { /** Called when the activity is first created. */ private static Long multiplier=Long.parseLong("1zzzz",36); /** * Encodes the id. * @param id the id to encode * @return encoded string */ public static String encode(Long id) { return StringUtils.reverse(Long.toString((id*multiplier), 35)); } /** * Decodes the encoded id. * @param encodedId the encodedId to decode * @return the Id * @throws IllegalArgumentException if encodedId is not a validly encoded id. */ public static Long decode(String encodedId) throws IllegalArgumentException { long product; try { product = Long.parseLong(StringUtils.reverse(encodedId), 35); } catch (Exception e) { throw new IllegalArgumentException(); } if ( 0 != product % multiplier || product < 0) { throw new IllegalArgumentException(); } return product/multiplier; } } ```
2010/05/11
[ "https://Stackoverflow.com/questions/2808733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2355649/" ]
You don't say whether you are using Eclipse or Android Studio. In Android Studio, you would add, ``` import org.apache.commons.lang3.StringUtils; ``` to your source code file. In build.gradle, you need to change your dependency from something like, ``` dependencies { compile 'com.android.support:support-v4:+' } ``` to ``` dependencies { compile 'com.android.support:support-v4:+' compile 'org.apache.commons:commons-lang3:3.0' } ``` In other words, you would add to the dependency.
Android offers a subset of that functionality in [android.text.TextUtils](http://developer.android.com/reference/android/text/TextUtils.html). Depending on what you need from StringUtils, that might be an option. E.g., it has join, split.
2,808,733
Why **import org.apache.commons.lang.StringUtils** cannot be imported in android by default. Do i have to include an external library? Then where can i find that library on the web? ``` package com.myapps.urlencoding; import android.app.Activity; import org.apache.commons.lang.StringUtils; public class EncodeIdUtil extends Activity { /** Called when the activity is first created. */ private static Long multiplier=Long.parseLong("1zzzz",36); /** * Encodes the id. * @param id the id to encode * @return encoded string */ public static String encode(Long id) { return StringUtils.reverse(Long.toString((id*multiplier), 35)); } /** * Decodes the encoded id. * @param encodedId the encodedId to decode * @return the Id * @throws IllegalArgumentException if encodedId is not a validly encoded id. */ public static Long decode(String encodedId) throws IllegalArgumentException { long product; try { product = Long.parseLong(StringUtils.reverse(encodedId), 35); } catch (Exception e) { throw new IllegalArgumentException(); } if ( 0 != product % multiplier || product < 0) { throw new IllegalArgumentException(); } return product/multiplier; } } ```
2010/05/11
[ "https://Stackoverflow.com/questions/2808733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2355649/" ]
Android offers a subset of that functionality in [android.text.TextUtils](http://developer.android.com/reference/android/text/TextUtils.html). Depending on what you need from StringUtils, that might be an option. E.g., it has join, split.
If you are using Android Studio try to use workflow provided to add dependencies rather than manually adding the downloaded library or manually changing gradle files. 1. File -> Project Structure -> Modules -> app -> Dependencies Tab 2. Click '+' in the bottom left corner and select "Library dependency" 3. In the search field type: "org.apache.commons:commons-lang3" and click Search 4. Select "org.apache.commons:commons-lang3:3.7" [![enter image description here](https://i.stack.imgur.com/XFSMO.png)](https://i.stack.imgur.com/XFSMO.png)
2,808,733
Why **import org.apache.commons.lang.StringUtils** cannot be imported in android by default. Do i have to include an external library? Then where can i find that library on the web? ``` package com.myapps.urlencoding; import android.app.Activity; import org.apache.commons.lang.StringUtils; public class EncodeIdUtil extends Activity { /** Called when the activity is first created. */ private static Long multiplier=Long.parseLong("1zzzz",36); /** * Encodes the id. * @param id the id to encode * @return encoded string */ public static String encode(Long id) { return StringUtils.reverse(Long.toString((id*multiplier), 35)); } /** * Decodes the encoded id. * @param encodedId the encodedId to decode * @return the Id * @throws IllegalArgumentException if encodedId is not a validly encoded id. */ public static Long decode(String encodedId) throws IllegalArgumentException { long product; try { product = Long.parseLong(StringUtils.reverse(encodedId), 35); } catch (Exception e) { throw new IllegalArgumentException(); } if ( 0 != product % multiplier || product < 0) { throw new IllegalArgumentException(); } return product/multiplier; } } ```
2010/05/11
[ "https://Stackoverflow.com/questions/2808733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2355649/" ]
Android offers a subset of that functionality in [android.text.TextUtils](http://developer.android.com/reference/android/text/TextUtils.html). Depending on what you need from StringUtils, that might be an option. E.g., it has join, split.
just add following dependency in module level gradle file(build.gradle) ``` implementation 'org.apache.commons:commons-lang3:3.7' ```
2,808,733
Why **import org.apache.commons.lang.StringUtils** cannot be imported in android by default. Do i have to include an external library? Then where can i find that library on the web? ``` package com.myapps.urlencoding; import android.app.Activity; import org.apache.commons.lang.StringUtils; public class EncodeIdUtil extends Activity { /** Called when the activity is first created. */ private static Long multiplier=Long.parseLong("1zzzz",36); /** * Encodes the id. * @param id the id to encode * @return encoded string */ public static String encode(Long id) { return StringUtils.reverse(Long.toString((id*multiplier), 35)); } /** * Decodes the encoded id. * @param encodedId the encodedId to decode * @return the Id * @throws IllegalArgumentException if encodedId is not a validly encoded id. */ public static Long decode(String encodedId) throws IllegalArgumentException { long product; try { product = Long.parseLong(StringUtils.reverse(encodedId), 35); } catch (Exception e) { throw new IllegalArgumentException(); } if ( 0 != product % multiplier || product < 0) { throw new IllegalArgumentException(); } return product/multiplier; } } ```
2010/05/11
[ "https://Stackoverflow.com/questions/2808733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2355649/" ]
You don't say whether you are using Eclipse or Android Studio. In Android Studio, you would add, ``` import org.apache.commons.lang3.StringUtils; ``` to your source code file. In build.gradle, you need to change your dependency from something like, ``` dependencies { compile 'com.android.support:support-v4:+' } ``` to ``` dependencies { compile 'com.android.support:support-v4:+' compile 'org.apache.commons:commons-lang3:3.0' } ``` In other words, you would add to the dependency.
If you are using Android Studio try to use workflow provided to add dependencies rather than manually adding the downloaded library or manually changing gradle files. 1. File -> Project Structure -> Modules -> app -> Dependencies Tab 2. Click '+' in the bottom left corner and select "Library dependency" 3. In the search field type: "org.apache.commons:commons-lang3" and click Search 4. Select "org.apache.commons:commons-lang3:3.7" [![enter image description here](https://i.stack.imgur.com/XFSMO.png)](https://i.stack.imgur.com/XFSMO.png)
2,808,733
Why **import org.apache.commons.lang.StringUtils** cannot be imported in android by default. Do i have to include an external library? Then where can i find that library on the web? ``` package com.myapps.urlencoding; import android.app.Activity; import org.apache.commons.lang.StringUtils; public class EncodeIdUtil extends Activity { /** Called when the activity is first created. */ private static Long multiplier=Long.parseLong("1zzzz",36); /** * Encodes the id. * @param id the id to encode * @return encoded string */ public static String encode(Long id) { return StringUtils.reverse(Long.toString((id*multiplier), 35)); } /** * Decodes the encoded id. * @param encodedId the encodedId to decode * @return the Id * @throws IllegalArgumentException if encodedId is not a validly encoded id. */ public static Long decode(String encodedId) throws IllegalArgumentException { long product; try { product = Long.parseLong(StringUtils.reverse(encodedId), 35); } catch (Exception e) { throw new IllegalArgumentException(); } if ( 0 != product % multiplier || product < 0) { throw new IllegalArgumentException(); } return product/multiplier; } } ```
2010/05/11
[ "https://Stackoverflow.com/questions/2808733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2355649/" ]
You don't say whether you are using Eclipse or Android Studio. In Android Studio, you would add, ``` import org.apache.commons.lang3.StringUtils; ``` to your source code file. In build.gradle, you need to change your dependency from something like, ``` dependencies { compile 'com.android.support:support-v4:+' } ``` to ``` dependencies { compile 'com.android.support:support-v4:+' compile 'org.apache.commons:commons-lang3:3.0' } ``` In other words, you would add to the dependency.
just add following dependency in module level gradle file(build.gradle) ``` implementation 'org.apache.commons:commons-lang3:3.7' ```
25,424,816
In my windows 8 application, I would like to read a PDF line by line then I would like to assign a String array. How can I do it? ``` public StringBuilder addd= new StringBuilder(); string[] array; private async void btndosyasec_Click(object sender, RoutedEventArgs e) { FileOpenPicker openPicker = new FileOpenPicker(); openPicker.ViewMode = PickerViewMode.List; openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; openPicker.FileTypeFilter.Add(".pdf"); StorageFile file = await openPicker.PickSingleFileAsync(); if (file != null) { PdfReader reader = new PdfReader((await file.OpenReadAsync()).AsStream()); for (int page = 1; page <= reader.NumberOfPages; page++) { addd.Append(PdfTextExtractor.GetTextFromPage(reader, page)); string tmp= PdfTextExtractor.GetTextFromPage(reader, page); array[page] = tmp.ToString(); reader.Close(); } } } ```
2014/08/21
[ "https://Stackoverflow.com/questions/25424816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3963572/" ]
Hi I had this problem too, I used this code, it worked. You will need a reference to the iTextSharp lib. ``` using iTextSharp.text.pdf; using iTextSharp.text.pdf.parser; PdfReader reader = new PdfReader(@"D:\test pdf\Blood Journal.pdf"); int intPageNum = reader.NumberOfPages; string[] words; string line; for (int i = 1; i <= intPageNum; i++) { text = PdfTextExtractor.GetTextFromPage(reader, i, new LocationTextExtractionStrategy()); words = text.Split('\n'); for (int j = 0, len = words.Length; j < len; j++) { line = Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(words[j])); } } ``` words array contains lines of pdf file
If you are looking for something **Licence Free/Open Source** with basic text extraction from PDF, then you can go for **PdfClown** which has Support for both .Net Framework as well as .NET CORE (though Beta version w.r.t .NET Standard 2.0). For More Info or Samples, take look at <https://www.nuget.org/packages/PdfClown.NetStandard/0.2.0-beta> <https://sourceforge.net/p/clown/code/HEAD/tree/trunk/dotNET/pdfclown.samples.cli/> Below sample is w.r.t .NET CORE. ``` public class PdfClownUtil { private static readonly string fileSrcPath = "MyTestDoc.pdf"; private readonly StringBuilder stringBuilder_1 = new StringBuilder(); public string GetPdfTextContent() { PdfDocuments.Document document = new File(fileSrcPath).Document; StringBuilder stringBuilder_2 = new StringBuilder(); TextExtractor extractor = new TextExtractor(); foreach (Page page in document.Pages) { // Approach-1: Extract(new ContentScanner(page)); // Approach-2 with additional Options: IList<ITextString> textStrings = extractor.Extract(page)[TextExtractor.DefaultArea]; foreach (ITextString textString in textStrings) { stringBuilder_2.Append(textString.Text); } stringBuilder_2.AppendLine(); } var content = stringBuilder_2.ToString(); return content; } // Approach-1: private void Extract(ContentScanner level) { if (level == null) { return; } while (level.MoveNext()) { ContentObject content = level.Current; if (content is ShowText) { Font font = level.State.Font; // Extract the current text chunk, decoding it! this.stringBuilder_1.Append(font.Decode(((ShowText)content).Text)); } else if (content is Text || content is ContainerObject) { // Scan the inner level! Extract(level.ChildLevel); } } } } ```
25,424,816
In my windows 8 application, I would like to read a PDF line by line then I would like to assign a String array. How can I do it? ``` public StringBuilder addd= new StringBuilder(); string[] array; private async void btndosyasec_Click(object sender, RoutedEventArgs e) { FileOpenPicker openPicker = new FileOpenPicker(); openPicker.ViewMode = PickerViewMode.List; openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; openPicker.FileTypeFilter.Add(".pdf"); StorageFile file = await openPicker.PickSingleFileAsync(); if (file != null) { PdfReader reader = new PdfReader((await file.OpenReadAsync()).AsStream()); for (int page = 1; page <= reader.NumberOfPages; page++) { addd.Append(PdfTextExtractor.GetTextFromPage(reader, page)); string tmp= PdfTextExtractor.GetTextFromPage(reader, page); array[page] = tmp.ToString(); reader.Close(); } } } ```
2014/08/21
[ "https://Stackoverflow.com/questions/25424816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3963572/" ]
Hi I had this problem too, I used this code, it worked. You will need a reference to the iTextSharp lib. ``` using iTextSharp.text.pdf; using iTextSharp.text.pdf.parser; PdfReader reader = new PdfReader(@"D:\test pdf\Blood Journal.pdf"); int intPageNum = reader.NumberOfPages; string[] words; string line; for (int i = 1; i <= intPageNum; i++) { text = PdfTextExtractor.GetTextFromPage(reader, i, new LocationTextExtractionStrategy()); words = text.Split('\n'); for (int j = 0, len = words.Length; j < len; j++) { line = Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(words[j])); } } ``` words array contains lines of pdf file
Below code work for iText7 ``` using iText.Kernel.Pdf; using iText.Kernel.Pdf.Canvas.Parser; using iText.Kernel.Pdf.Canvas.Parser.Listener; public void ExtractTextFromPDF(string filePath) { PdfReader pdfReader = new PdfReader(filePath); PdfDocument pdfDoc = new PdfDocument(pdfReader); for (int page = 1; page <= pdfDoc.GetNumberOfPages(); page++) { ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy(); string pageContent = PdfTextExtractor.GetTextFromPage(pdfDoc.GetPage(page), strategy); Console.WriteLine("pageContent : " + pageContent); } pdfDoc.Close(); pdfReader.Close(); } ```
25,424,816
In my windows 8 application, I would like to read a PDF line by line then I would like to assign a String array. How can I do it? ``` public StringBuilder addd= new StringBuilder(); string[] array; private async void btndosyasec_Click(object sender, RoutedEventArgs e) { FileOpenPicker openPicker = new FileOpenPicker(); openPicker.ViewMode = PickerViewMode.List; openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; openPicker.FileTypeFilter.Add(".pdf"); StorageFile file = await openPicker.PickSingleFileAsync(); if (file != null) { PdfReader reader = new PdfReader((await file.OpenReadAsync()).AsStream()); for (int page = 1; page <= reader.NumberOfPages; page++) { addd.Append(PdfTextExtractor.GetTextFromPage(reader, page)); string tmp= PdfTextExtractor.GetTextFromPage(reader, page); array[page] = tmp.ToString(); reader.Close(); } } } ```
2014/08/21
[ "https://Stackoverflow.com/questions/25424816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3963572/" ]
Below code work for iText7 ``` using iText.Kernel.Pdf; using iText.Kernel.Pdf.Canvas.Parser; using iText.Kernel.Pdf.Canvas.Parser.Listener; public void ExtractTextFromPDF(string filePath) { PdfReader pdfReader = new PdfReader(filePath); PdfDocument pdfDoc = new PdfDocument(pdfReader); for (int page = 1; page <= pdfDoc.GetNumberOfPages(); page++) { ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy(); string pageContent = PdfTextExtractor.GetTextFromPage(pdfDoc.GetPage(page), strategy); Console.WriteLine("pageContent : " + pageContent); } pdfDoc.Close(); pdfReader.Close(); } ```
If you are looking for something **Licence Free/Open Source** with basic text extraction from PDF, then you can go for **PdfClown** which has Support for both .Net Framework as well as .NET CORE (though Beta version w.r.t .NET Standard 2.0). For More Info or Samples, take look at <https://www.nuget.org/packages/PdfClown.NetStandard/0.2.0-beta> <https://sourceforge.net/p/clown/code/HEAD/tree/trunk/dotNET/pdfclown.samples.cli/> Below sample is w.r.t .NET CORE. ``` public class PdfClownUtil { private static readonly string fileSrcPath = "MyTestDoc.pdf"; private readonly StringBuilder stringBuilder_1 = new StringBuilder(); public string GetPdfTextContent() { PdfDocuments.Document document = new File(fileSrcPath).Document; StringBuilder stringBuilder_2 = new StringBuilder(); TextExtractor extractor = new TextExtractor(); foreach (Page page in document.Pages) { // Approach-1: Extract(new ContentScanner(page)); // Approach-2 with additional Options: IList<ITextString> textStrings = extractor.Extract(page)[TextExtractor.DefaultArea]; foreach (ITextString textString in textStrings) { stringBuilder_2.Append(textString.Text); } stringBuilder_2.AppendLine(); } var content = stringBuilder_2.ToString(); return content; } // Approach-1: private void Extract(ContentScanner level) { if (level == null) { return; } while (level.MoveNext()) { ContentObject content = level.Current; if (content is ShowText) { Font font = level.State.Font; // Extract the current text chunk, decoding it! this.stringBuilder_1.Append(font.Decode(((ShowText)content).Text)); } else if (content is Text || content is ContainerObject) { // Scan the inner level! Extract(level.ChildLevel); } } } } ```
13,525
Hi guys, I'm working on the sound design for an animation and I need to create the sound of fairy dust. Visually think magic wand, or the sparkles that surround Tinkerbell. Light and magical and darting around. I'm thinking the sounds needs to be light, high frequency and glistening, maybe chime like but not too musical. I have been recording bells and Glockenspiel with various processing but its not quite getting there. Have any of you had any experience creating sounds for fairy dust or magical sparkles? Would be great to hear some techniques on how you have achieved this abstract sound. Many thanks, Tom
2012/04/13
[ "https://sound.stackexchange.com/questions/13525", "https://sound.stackexchange.com", "https://sound.stackexchange.com/users/3766/" ]
Have you tried the Bell Tree? It's definitely the staple for that type of sound. Check out the samples [here](http://www.compositiontoday.com/sound_bank/percussion/bell_tree.asp). It is a bit of a cliché, but you can always process it more to make it more unique. Perhaps also think about other layers to go with it. This depends very much on how it looks visually, is it real world (like smoke or something) or is it CGI particle type effects? Sometimes it helps to start with lots of very small sounds and find ways of triggering them at different rates, with a bit of randomness. This can be a bit difficult with traditional sequencers, but is much easier in something like Max/msp or PD. Because they're not linear you don't have to paste loads of individual sounds onto a timeline, just set up the patch and adjust the settings. I've probably got a few patches around if you're interested. Banks of tuned resonant filters can also add that bell like resonance to otherwise non-tuned sounds. Good luck!
You can always use matchstick striking sounds instead of white noise. They have their own dynamics, and i find them very easy to use on abstract sounds.
13,525
Hi guys, I'm working on the sound design for an animation and I need to create the sound of fairy dust. Visually think magic wand, or the sparkles that surround Tinkerbell. Light and magical and darting around. I'm thinking the sounds needs to be light, high frequency and glistening, maybe chime like but not too musical. I have been recording bells and Glockenspiel with various processing but its not quite getting there. Have any of you had any experience creating sounds for fairy dust or magical sparkles? Would be great to hear some techniques on how you have achieved this abstract sound. Many thanks, Tom
2012/04/13
[ "https://sound.stackexchange.com/questions/13525", "https://sound.stackexchange.com", "https://sound.stackexchange.com/users/3766/" ]
Have you tried the Bell Tree? It's definitely the staple for that type of sound. Check out the samples [here](http://www.compositiontoday.com/sound_bank/percussion/bell_tree.asp). It is a bit of a cliché, but you can always process it more to make it more unique. Perhaps also think about other layers to go with it. This depends very much on how it looks visually, is it real world (like smoke or something) or is it CGI particle type effects? Sometimes it helps to start with lots of very small sounds and find ways of triggering them at different rates, with a bit of randomness. This can be a bit difficult with traditional sequencers, but is much easier in something like Max/msp or PD. Because they're not linear you don't have to paste loads of individual sounds onto a timeline, just set up the patch and adjust the settings. I've probably got a few patches around if you're interested. Banks of tuned resonant filters can also add that bell like resonance to otherwise non-tuned sounds. Good luck!
I like Mark's answer, seconded. Done this sound numerous times. There's a lot of freedom but I've found most people like something sparkly, often some processed bell tree works.
13,525
Hi guys, I'm working on the sound design for an animation and I need to create the sound of fairy dust. Visually think magic wand, or the sparkles that surround Tinkerbell. Light and magical and darting around. I'm thinking the sounds needs to be light, high frequency and glistening, maybe chime like but not too musical. I have been recording bells and Glockenspiel with various processing but its not quite getting there. Have any of you had any experience creating sounds for fairy dust or magical sparkles? Would be great to hear some techniques on how you have achieved this abstract sound. Many thanks, Tom
2012/04/13
[ "https://sound.stackexchange.com/questions/13525", "https://sound.stackexchange.com", "https://sound.stackexchange.com/users/3766/" ]
Have you tried the Bell Tree? It's definitely the staple for that type of sound. Check out the samples [here](http://www.compositiontoday.com/sound_bank/percussion/bell_tree.asp). It is a bit of a cliché, but you can always process it more to make it more unique. Perhaps also think about other layers to go with it. This depends very much on how it looks visually, is it real world (like smoke or something) or is it CGI particle type effects? Sometimes it helps to start with lots of very small sounds and find ways of triggering them at different rates, with a bit of randomness. This can be a bit difficult with traditional sequencers, but is much easier in something like Max/msp or PD. Because they're not linear you don't have to paste loads of individual sounds onto a timeline, just set up the patch and adjust the settings. I've probably got a few patches around if you're interested. Banks of tuned resonant filters can also add that bell like resonance to otherwise non-tuned sounds. Good luck!
Crystallizer does a great job. I would start by processing ice in a glass, glass debris, or a bell tree and then chop off the attack and doppler it or futz with the spacial feeling in Enigma. You can then layer and blend it with some sand blowing in the wind or wind buffets. I did something similar for Science Channel's cube logo animation when the cube breaks into a bunch of little cubes and then sucks back into the big orange cube. I used ice cubes and wood blocks through the same process. I also put in some blocks that were graphic specific and threw them through the doppler anomaly setting and reversed them when needed. It was kind of a washy high end sound. I bet using glass debris or a bell tree as the source material would result in fairy dust.
13,525
Hi guys, I'm working on the sound design for an animation and I need to create the sound of fairy dust. Visually think magic wand, or the sparkles that surround Tinkerbell. Light and magical and darting around. I'm thinking the sounds needs to be light, high frequency and glistening, maybe chime like but not too musical. I have been recording bells and Glockenspiel with various processing but its not quite getting there. Have any of you had any experience creating sounds for fairy dust or magical sparkles? Would be great to hear some techniques on how you have achieved this abstract sound. Many thanks, Tom
2012/04/13
[ "https://sound.stackexchange.com/questions/13525", "https://sound.stackexchange.com", "https://sound.stackexchange.com/users/3766/" ]
Crystallizer does a great job. I would start by processing ice in a glass, glass debris, or a bell tree and then chop off the attack and doppler it or futz with the spacial feeling in Enigma. You can then layer and blend it with some sand blowing in the wind or wind buffets. I did something similar for Science Channel's cube logo animation when the cube breaks into a bunch of little cubes and then sucks back into the big orange cube. I used ice cubes and wood blocks through the same process. I also put in some blocks that were graphic specific and threw them through the doppler anomaly setting and reversed them when needed. It was kind of a washy high end sound. I bet using glass debris or a bell tree as the source material would result in fairy dust.
I like Mark's answer, seconded. Done this sound numerous times. There's a lot of freedom but I've found most people like something sparkly, often some processed bell tree works.
13,525
Hi guys, I'm working on the sound design for an animation and I need to create the sound of fairy dust. Visually think magic wand, or the sparkles that surround Tinkerbell. Light and magical and darting around. I'm thinking the sounds needs to be light, high frequency and glistening, maybe chime like but not too musical. I have been recording bells and Glockenspiel with various processing but its not quite getting there. Have any of you had any experience creating sounds for fairy dust or magical sparkles? Would be great to hear some techniques on how you have achieved this abstract sound. Many thanks, Tom
2012/04/13
[ "https://sound.stackexchange.com/questions/13525", "https://sound.stackexchange.com", "https://sound.stackexchange.com/users/3766/" ]
Crystallizer does a great job. I would start by processing ice in a glass, glass debris, or a bell tree and then chop off the attack and doppler it or futz with the spacial feeling in Enigma. You can then layer and blend it with some sand blowing in the wind or wind buffets. I did something similar for Science Channel's cube logo animation when the cube breaks into a bunch of little cubes and then sucks back into the big orange cube. I used ice cubes and wood blocks through the same process. I also put in some blocks that were graphic specific and threw them through the doppler anomaly setting and reversed them when needed. It was kind of a washy high end sound. I bet using glass debris or a bell tree as the source material would result in fairy dust.
Bell tree with a white noise swoosh. Resonant filter the whole sound to give it movement. Also some kind of envelope to give the sound some impact if it's coming from a wand or something.
13,525
Hi guys, I'm working on the sound design for an animation and I need to create the sound of fairy dust. Visually think magic wand, or the sparkles that surround Tinkerbell. Light and magical and darting around. I'm thinking the sounds needs to be light, high frequency and glistening, maybe chime like but not too musical. I have been recording bells and Glockenspiel with various processing but its not quite getting there. Have any of you had any experience creating sounds for fairy dust or magical sparkles? Would be great to hear some techniques on how you have achieved this abstract sound. Many thanks, Tom
2012/04/13
[ "https://sound.stackexchange.com/questions/13525", "https://sound.stackexchange.com", "https://sound.stackexchange.com/users/3766/" ]
Have you tried the Bell Tree? It's definitely the staple for that type of sound. Check out the samples [here](http://www.compositiontoday.com/sound_bank/percussion/bell_tree.asp). It is a bit of a cliché, but you can always process it more to make it more unique. Perhaps also think about other layers to go with it. This depends very much on how it looks visually, is it real world (like smoke or something) or is it CGI particle type effects? Sometimes it helps to start with lots of very small sounds and find ways of triggering them at different rates, with a bit of randomness. This can be a bit difficult with traditional sequencers, but is much easier in something like Max/msp or PD. Because they're not linear you don't have to paste loads of individual sounds onto a timeline, just set up the patch and adjust the settings. I've probably got a few patches around if you're interested. Banks of tuned resonant filters can also add that bell like resonance to otherwise non-tuned sounds. Good luck!
Thanks for the tips guys. Really great advice. I have had fun experimenting with some of these techniques and have managed to create some pretty cool fairy dust. Cheers Tom
13,525
Hi guys, I'm working on the sound design for an animation and I need to create the sound of fairy dust. Visually think magic wand, or the sparkles that surround Tinkerbell. Light and magical and darting around. I'm thinking the sounds needs to be light, high frequency and glistening, maybe chime like but not too musical. I have been recording bells and Glockenspiel with various processing but its not quite getting there. Have any of you had any experience creating sounds for fairy dust or magical sparkles? Would be great to hear some techniques on how you have achieved this abstract sound. Many thanks, Tom
2012/04/13
[ "https://sound.stackexchange.com/questions/13525", "https://sound.stackexchange.com", "https://sound.stackexchange.com/users/3766/" ]
Crystallizer does a great job. I would start by processing ice in a glass, glass debris, or a bell tree and then chop off the attack and doppler it or futz with the spacial feeling in Enigma. You can then layer and blend it with some sand blowing in the wind or wind buffets. I did something similar for Science Channel's cube logo animation when the cube breaks into a bunch of little cubes and then sucks back into the big orange cube. I used ice cubes and wood blocks through the same process. I also put in some blocks that were graphic specific and threw them through the doppler anomaly setting and reversed them when needed. It was kind of a washy high end sound. I bet using glass debris or a bell tree as the source material would result in fairy dust.
Theres an absynth effect called Atherizer that makes sparkly sounds. I highly suggest. Also GRM tools has a combfilter plug that works towards the sparklies. Working with granulator plugins might prove sparkley
13,525
Hi guys, I'm working on the sound design for an animation and I need to create the sound of fairy dust. Visually think magic wand, or the sparkles that surround Tinkerbell. Light and magical and darting around. I'm thinking the sounds needs to be light, high frequency and glistening, maybe chime like but not too musical. I have been recording bells and Glockenspiel with various processing but its not quite getting there. Have any of you had any experience creating sounds for fairy dust or magical sparkles? Would be great to hear some techniques on how you have achieved this abstract sound. Many thanks, Tom
2012/04/13
[ "https://sound.stackexchange.com/questions/13525", "https://sound.stackexchange.com", "https://sound.stackexchange.com/users/3766/" ]
Crystallizer does a great job. I would start by processing ice in a glass, glass debris, or a bell tree and then chop off the attack and doppler it or futz with the spacial feeling in Enigma. You can then layer and blend it with some sand blowing in the wind or wind buffets. I did something similar for Science Channel's cube logo animation when the cube breaks into a bunch of little cubes and then sucks back into the big orange cube. I used ice cubes and wood blocks through the same process. I also put in some blocks that were graphic specific and threw them through the doppler anomaly setting and reversed them when needed. It was kind of a washy high end sound. I bet using glass debris or a bell tree as the source material would result in fairy dust.
You can always use matchstick striking sounds instead of white noise. They have their own dynamics, and i find them very easy to use on abstract sounds.
13,525
Hi guys, I'm working on the sound design for an animation and I need to create the sound of fairy dust. Visually think magic wand, or the sparkles that surround Tinkerbell. Light and magical and darting around. I'm thinking the sounds needs to be light, high frequency and glistening, maybe chime like but not too musical. I have been recording bells and Glockenspiel with various processing but its not quite getting there. Have any of you had any experience creating sounds for fairy dust or magical sparkles? Would be great to hear some techniques on how you have achieved this abstract sound. Many thanks, Tom
2012/04/13
[ "https://sound.stackexchange.com/questions/13525", "https://sound.stackexchange.com", "https://sound.stackexchange.com/users/3766/" ]
Crystallizer does a great job. I would start by processing ice in a glass, glass debris, or a bell tree and then chop off the attack and doppler it or futz with the spacial feeling in Enigma. You can then layer and blend it with some sand blowing in the wind or wind buffets. I did something similar for Science Channel's cube logo animation when the cube breaks into a bunch of little cubes and then sucks back into the big orange cube. I used ice cubes and wood blocks through the same process. I also put in some blocks that were graphic specific and threw them through the doppler anomaly setting and reversed them when needed. It was kind of a washy high end sound. I bet using glass debris or a bell tree as the source material would result in fairy dust.
Thanks for the tips guys. Really great advice. I have had fun experimenting with some of these techniques and have managed to create some pretty cool fairy dust. Cheers Tom
13,525
Hi guys, I'm working on the sound design for an animation and I need to create the sound of fairy dust. Visually think magic wand, or the sparkles that surround Tinkerbell. Light and magical and darting around. I'm thinking the sounds needs to be light, high frequency and glistening, maybe chime like but not too musical. I have been recording bells and Glockenspiel with various processing but its not quite getting there. Have any of you had any experience creating sounds for fairy dust or magical sparkles? Would be great to hear some techniques on how you have achieved this abstract sound. Many thanks, Tom
2012/04/13
[ "https://sound.stackexchange.com/questions/13525", "https://sound.stackexchange.com", "https://sound.stackexchange.com/users/3766/" ]
Have you tried the Bell Tree? It's definitely the staple for that type of sound. Check out the samples [here](http://www.compositiontoday.com/sound_bank/percussion/bell_tree.asp). It is a bit of a cliché, but you can always process it more to make it more unique. Perhaps also think about other layers to go with it. This depends very much on how it looks visually, is it real world (like smoke or something) or is it CGI particle type effects? Sometimes it helps to start with lots of very small sounds and find ways of triggering them at different rates, with a bit of randomness. This can be a bit difficult with traditional sequencers, but is much easier in something like Max/msp or PD. Because they're not linear you don't have to paste loads of individual sounds onto a timeline, just set up the patch and adjust the settings. I've probably got a few patches around if you're interested. Banks of tuned resonant filters can also add that bell like resonance to otherwise non-tuned sounds. Good luck!
Theres an absynth effect called Atherizer that makes sparkly sounds. I highly suggest. Also GRM tools has a combfilter plug that works towards the sparklies. Working with granulator plugins might prove sparkley
880,497
I'm using a ‘session group’, to keep multiple OS-level, window-managed terminal windows open to different `tmux` ‘windows’ (so they share a default working-directory, `tmux` settings, etceteras.) Those Terminal windows are different sizes. Normally, from a larger Terminal, I can do the following to start a new command: ``` :new-window vim ``` ![](https://i.stack.imgur.com/mntDx.png) However, if I *ever* switch to a different pane with that new, larger Terminal window, I am foreverafter stuck with this, when I switch back: ![](https://i.stack.imgur.com/mt0Ei.png) I have to kill the entire session, create an entirely new session, and link it to the session-group again, using `tmux new-session -t <blah>`, to restore the full terminal-width. Is there any other way to restore / change / set the ‘available width’ of a session (or window, idk)?
2015/02/20
[ "https://superuser.com/questions/880497", "https://superuser.com", "https://superuser.com/users/22030/" ]
Perhaps enabling the aggressive-resize option will help: ``` set-window-option -g aggressive-resize ``` A good overview of tmux options is given [here](https://mutelight.org/practical-tmux).
When attach screen you may use detach mode > > tmux attach -d > with will resize screen after disconnect other clients from the sessions (and someone who used small screen) > > > Or you can interactively detach by pressing Ctrl-B-Shift-D
880,497
I'm using a ‘session group’, to keep multiple OS-level, window-managed terminal windows open to different `tmux` ‘windows’ (so they share a default working-directory, `tmux` settings, etceteras.) Those Terminal windows are different sizes. Normally, from a larger Terminal, I can do the following to start a new command: ``` :new-window vim ``` ![](https://i.stack.imgur.com/mntDx.png) However, if I *ever* switch to a different pane with that new, larger Terminal window, I am foreverafter stuck with this, when I switch back: ![](https://i.stack.imgur.com/mt0Ei.png) I have to kill the entire session, create an entirely new session, and link it to the session-group again, using `tmux new-session -t <blah>`, to restore the full terminal-width. Is there any other way to restore / change / set the ‘available width’ of a session (or window, idk)?
2015/02/20
[ "https://superuser.com/questions/880497", "https://superuser.com", "https://superuser.com/users/22030/" ]
Perhaps enabling the aggressive-resize option will help: ``` set-window-option -g aggressive-resize ``` A good overview of tmux options is given [here](https://mutelight.org/practical-tmux).
Starting with tmux 3.1, the default option for `window-size` is `latest`. So all you need to do is upgrade.
880,497
I'm using a ‘session group’, to keep multiple OS-level, window-managed terminal windows open to different `tmux` ‘windows’ (so they share a default working-directory, `tmux` settings, etceteras.) Those Terminal windows are different sizes. Normally, from a larger Terminal, I can do the following to start a new command: ``` :new-window vim ``` ![](https://i.stack.imgur.com/mntDx.png) However, if I *ever* switch to a different pane with that new, larger Terminal window, I am foreverafter stuck with this, when I switch back: ![](https://i.stack.imgur.com/mt0Ei.png) I have to kill the entire session, create an entirely new session, and link it to the session-group again, using `tmux new-session -t <blah>`, to restore the full terminal-width. Is there any other way to restore / change / set the ‘available width’ of a session (or window, idk)?
2015/02/20
[ "https://superuser.com/questions/880497", "https://superuser.com", "https://superuser.com/users/22030/" ]
When attach screen you may use detach mode > > tmux attach -d > with will resize screen after disconnect other clients from the sessions (and someone who used small screen) > > > Or you can interactively detach by pressing Ctrl-B-Shift-D
Starting with tmux 3.1, the default option for `window-size` is `latest`. So all you need to do is upgrade.
65,949,029
I am trying to make a box with Header and I want some text inside the box. Below is what I want: [![enter image description here](https://i.stack.imgur.com/CSUe0.png)](https://i.stack.imgur.com/CSUe0.png) any help will be highly appreciated.
2021/01/29
[ "https://Stackoverflow.com/questions/65949029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10443857/" ]
After doing some looking, I found another [post on ServerFault](https://serverfault.com/questions/894878/subprocess-installed-pre-removal-script-returned-error-exit-status-5) that details issues with the install script. I was having this same issue, and after ensuring that all MySQL files were removed I went to `/var/lib/dpkg/info` and ran `sudo rm -rf ./mysql-*`. After doing that you should be OK to run `sudo dpkg --remove --force-remove-reinstreq mysql-server-8.0` followed by a `sudo dpkg --purge mysql-server-8.0` . This is a nuclear option and I would not recommend doing this until you are 100% sure that there are no more files from the MySQL install.
```sh cd /var/lib/dpkg/info sudo rm -rf ./mysql-* sudo dpkg --remove --force-remove-reinstreq mysql-server-8.0 ``` It is ok!
66,310,700
I'm new to Redis and would like to get advice from the experts on my use case. I have an event object that has start\_time\_of\_event and end\_time\_of\_event as two of the attributes(there are plenty more attributes in the object). I have millions of these events and need to store them in Redis so that I can query them at runtime. I was hoping to use the timestamp as key and the event object as the value. While querying, I need to get the list of events where start\_time\_of\_event <= current\_time and end\_time\_of\_event>=1 week from now. Not sure if ZRANGE, LRANGE or any other data structure in Redis supports using multiple(complex) keys. Any suggestions on what's the best way to achieve the above use case using Redis? Thanks a lot in advance.
2021/02/22
[ "https://Stackoverflow.com/questions/66310700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2869520/" ]
You should store events in two of Redis ZSETs, for one set score should be `start_time_of_event` and for another, the score would be `end_time_of_event` Let's call them `start_events` and `end_events` respectively. Add: ``` ZADD start_events start_time event ZADD end_events end_time event ``` Search ``` -- randomly generate a destination id, search the events -- and store in that based on the start time ZRANGESTORE random-start-time-dst start_events 0 current_time -- randomly generate a destination id for end-time search, post filter -- store results in that destination ZRANGESTORE random-end-time-dst end_events current_time+7.weeks -1 -- Take the intersection of these two sets ZINTER INT_MAX random-start-time-dst random-end-time-dst -- Delete the newly created collections to free up the memory DEL random-start-time-dst DEL random-end-time-dst ```
Another option would be to use [zeeSQL](https://zeesql.com) to store those informations inside a secondary index (an SQL table). Once those data are in a table, you can query them using standard SQL. It would be just a simple SQL query, without the need of maintaing the Redis structures.
13,776,174
Most of the Google Management APIs seem to have been enabled for Service Accounts. For example, I can retrieve calendars like so: ``` string scope = Google.Apis.Calendar.v3.CalendarService.Scopes.Calendar.ToString().ToLower(); string scope_url = "https://www.googleapis.com/auth/" + scope; string client_id = "[email protected]"; string key_file = @"\path\to\my-privatekey.p12"; string key_pass = "notasecret"; AuthorizationServerDescription desc = GoogleAuthenticationServer.Description; X509Certificate2 key = new X509Certificate2(key_file, key_pass, X509KeyStorageFlags.Exportable); AssertionFlowClient client = new AssertionFlowClient(desc, key) { ServiceAccountId = client_id, Scope = scope_url }; OAuth2Authenticator<AssertionFlowClient> auth = new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState); CalendarService service = new CalendarService(auth); var x = service.Calendars.Get("[email protected]").Fetch(); ``` However, identical code on the GroupssettingsService returns a 503 - Server Not Available. Does that mean service accounts can't be used with that API? In a possibly related issue, the scope of the Groups Settings Service seems to be `apps.groups.settings` but if you call ``` GroupssettingsService.Scopes.AppsGroupsSettings.ToString().ToLower(); ``` ...you get `appsgroupssettings` instead, without the embedded periods. Is there another method to use service accounts for the GroupssettingsService? Or any information on the correct scope string? Many thanks.
2012/12/08
[ "https://Stackoverflow.com/questions/13776174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/389034/" ]
This is a block pointer. If you are unfamiliar with blocks, this basically lets you assign an annonymous function inline as a parameter. The signature here says that the block takes an NSString as a parameter, and returns nothing. You would use it like this: ``` - (void)login:(NSString *)username password:(NSString *)password delegate:(void(^)(NSString *))delegate; [someReceiver login:yourUsername password:yourPassword delegate:^(NSString *aString) { // This is the block (annonymous function). Do something with the aString paramter }]; ```
It denotes a [block](http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Blocks/Articles/00_Introduction.html) - it's essentially a closure (lambda function, whatever you call it) - Apple's addition to the C language. In this case, it returns `void` and accepts an `NSString` object as its only argument.
226,554
I use a Monte-Carlo algorithm to estimate a target value `y=f(x)` that depends on a single input parameter `x`. Because the Monte-Carlo algorithm is stochastic, the target value `y` fluctuates. I now want to find the value of `x` that minimizes `y`. Obviously, I cannot use most of the standard optimization algorithms (like Newton's), because I cannot calculate gradients of `y` with respect to `x`. **What optimization algorithms would be useful in this kind of situation?** Here is a simple python code the illustrates the situation ``` import matplotlib.pyplot as plt import numpy as np from scipy import optimize def f(x): return -np.sin(x + np.pi/2 + 0.5 * np.random.random()) xs = np.linspace(-2, 2) ys = [f(x) for x in xs] plt.plot(xs, ys, 'o') optimize.minimize_scalar(f) ``` which results in the following 'minimum' > > > ``` > fun: -0.99996139255316596 > nfev: 38 > nit: 37 success: True > x: -0.22358360754884515 > > ``` > > The function is constructed such that its minimum is at `x=0`, see the figure produced by the above code: [![enter image description here](https://i.stack.imgur.com/GkJbp.png)](https://i.stack.imgur.com/GkJbp.png)
2016/07/31
[ "https://stats.stackexchange.com/questions/226554", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/88762/" ]
It sounds like you're interested in 'stochastic optimization', where the goal is to optimize a stochastic objective function (typically its expected value). Note that some people take this term to include methods for optimizing deterministic functions where the solver uses randomness (not what you want). These references may be useful: > > [Hannah (2014).](http://www.stat.columbia.edu/~liam/teaching/compstat-spr15/lauren-notes.pdf) Stochastic Optimization. > > > [Fu et al. (2005)](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.417.7733&rep=rep1&type=pdf). Simulation optimization: A review, new developments, and applications > > > [Amaran et al. (2014)](http://link.springer.com/article/10.1007/s10288-014-0275-2). Simulation optimization: A review of algorithms and applications > > > You may also be interested in Bayesian optimization. In this setting, the objective function can be stochastic, and the goal is to choose parameters that optimize its expected value, given the parameters. As with some other stochastic optimization methods, the objective function can be a black box, meaning you have the ability to evaluate it, but may not have a closed form expression (e.g. it might depend on the result of a simulation or physical experiment). Evaluating it may be very expensive. Bayesian optimization treats evaluations of the objective function as observed data, and uses them to update a probabilistic model of the objective function (e.g. using Gaussian process regression). New evaluation points are chosen in a way that trades off between exploration (sampling from uncertain regions to get a better estimate of the objective function) and exploitation (sampling from regions that are predicted to increase/decrease the objective function). > > [Brochu et al. (2010)](http://arxiv.org/abs/1012.2599). A Tutorial on Bayesian Optimization of Expensive Cost Functions, with Application to Active User Modeling and Hierarchical Reinforcement Learning. > > > [Snoek et al. (2012)](http://papers.nips.cc/paper/4522-practical). Practical Bayesian Optimization of Machine Learning Algorithms. > > > If you do have a closed form expression for the objective function (as in your example), it would make more sense to try to exploit this known structure than to throw it away and treat the function as a black box. For example, in the best case you may be able to derive an expression for the expected value given the parameters, then use standard, deterministic methods to optimize it.
You are trying to optimize a stochastic objective function because of random noise component in the objective function. For a noisy function like yours, You could use an [evolutionary optimization](https://en.wikipedia.org/wiki/Evolutionary_algorithm) methods such as genetic algortithm to solve stochastic optimization problems. Please have a look at this [mathworks website](http://www.mathworks.com/help/gads/examples/optimization-of-stochastic-objective-function.html?requestedDomain=www.mathworks.com) that demonstrates how to solve a problem like yours. I would add that in addition to using an evolutionary optimization which is able to find near optimal (it can also easily handle multiple optimal solutions). In order to find a more precise accurate solution, I would club evolutionary optimization with a local optimization. This is called hybrid optimization. The above steps can be easily demonstrated using `R`. I have specified both global optimization using GA and a hybrid optimization (global-local) optimization. ``` set.seed(1234) obj.f <- function(x) { fx <- sin(x+pi/2+0.5*rnorm(1)) return(fx) } #Global optimization only ga.opt.global <- ga(type = "real-valued", fitness = obj.f, min = -2, max = 2) summary(ga.opt.global) plot(ga.opt.global) # Hybrid Optimziation ga.opt.hybrid <- ga(type = "real-valued", fitness = obj.f, min = -2, max = 2,optim=TRUE,optimArgs = list(method = "Nelder-Mead")) summary(ga.opt.hybrid) plot(ga.opt.hybrid) ``` Please Note, I'm not sure what your overall objective is, but I have tried to provide an answer from a pure optimization point of you. As it turns out as evident from your plot any values between -0.5 to 0 is optimal. IF you run the above optimization multiple times you will be able to find almost all the optimal values. ``` > summary(ga.opt.global) +-----------------------------------+ | Genetic Algorithm | +-----------------------------------+ GA settings: Type = real-valued Population size = 50 Number of generations = 100 Elitism = 2 Crossover probability = 0.8 Mutation probability = 0.1 Search domain = x1 Min -2 Max 2 GA results: Iterations = 100 Fitness function value = 1 Solution = x1 [1,] 0.4520799 > summary(ga.opt.hybrid) +-----------------------------------+ | Genetic Algorithm | +-----------------------------------+ GA settings: Type = real-valued Population size = 50 Number of generations = 100 Elitism = 2 Crossover probability = 0.8 Mutation probability = 0.1 Search domain = x1 Min -2 Max 2 GA results: Iterations = 100 Fitness function value = 0.9999994 Solution = x1 [1,] -0.1413327 ```
5,713,653
I'm using a search view in my application. Now i just want to get the text typed in the SearchView text box and display it on another textview. If i typed the text and click a button i can do the same. But i don't want to use any extra buttons. I just want to display the result when i am pressing enter key.
2011/04/19
[ "https://Stackoverflow.com/questions/5713653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/669322/" ]
The above answer is good but not complete actually you need to set an action listener for your Search view . you can do this in two ways create a class that implements the necessary classes to be an OnQueryTextListener and make a new object of that and use it as your search view query text listener or use the following compact form: ``` SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView(); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { callSearch(query); return true; } @Override public boolean onQueryTextChange(String newText) { // if (searchView.isExpanded() && TextUtils.isEmpty(newText)) { callSearch(newText); // } return true; } public void callSearch(String query) { //Do searching } }); ```
This is what I have inside the `onCreateOptionsMenu(Menu menu)` function on my main activity: ``` MenuItem searchItem = menu.findItem(R.id.search); SearchView searchView = (SearchView) searchItem.getActionView(); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { // Do whatever you need. This will be fired only when submitting. return false; } @Override public boolean onQueryTextChange(String newText) { // Do whatever you need when text changes. // This will be fired every time you input any character. return false; } }); ```
5,713,653
I'm using a search view in my application. Now i just want to get the text typed in the SearchView text box and display it on another textview. If i typed the text and click a button i can do the same. But i don't want to use any extra buttons. I just want to display the result when i am pressing enter key.
2011/04/19
[ "https://Stackoverflow.com/questions/5713653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/669322/" ]
It also can be done with RXAndroid and RxBinding by Jake Wharton like this: ``` RxSearchView.queryTextChanges(searchView) .debounce(500, TimeUnit.MILLISECONDS) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Action1<CharSequence>() { @Override public void call(CharSequence charSequence) { if(charSequence!=null){ // Here you can get the text System.out.println("SEARCH===" + charSequence.toString()); } } }); ``` Code is subscribing to observe text change with some delay of 500 milliseconds. This is a link to git repo to get RXAndroid: <https://github.com/JakeWharton/RxBinding>
This is what I have inside the `onCreateOptionsMenu(Menu menu)` function on my main activity: ``` MenuItem searchItem = menu.findItem(R.id.search); SearchView searchView = (SearchView) searchItem.getActionView(); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { // Do whatever you need. This will be fired only when submitting. return false; } @Override public boolean onQueryTextChange(String newText) { // Do whatever you need when text changes. // This will be fired every time you input any character. return false; } }); ```
5,713,653
I'm using a search view in my application. Now i just want to get the text typed in the SearchView text box and display it on another textview. If i typed the text and click a button i can do the same. But i don't want to use any extra buttons. I just want to display the result when i am pressing enter key.
2011/04/19
[ "https://Stackoverflow.com/questions/5713653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/669322/" ]
Try to use [setOnQueryTextListener](http://developer.android.com/reference/android/widget/SearchView.html#setOnQueryTextListener%28android.widget.SearchView.OnQueryTextListener%29) of SearchView ``` new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextChange(String newText) { // your text view here textView.setText(newText); return true; } @Override public boolean onQueryTextSubmit(String query) { textView.setText(query); return true; } } ```
This is what I have inside the `onCreateOptionsMenu(Menu menu)` function on my main activity: ``` MenuItem searchItem = menu.findItem(R.id.search); SearchView searchView = (SearchView) searchItem.getActionView(); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { // Do whatever you need. This will be fired only when submitting. return false; } @Override public boolean onQueryTextChange(String newText) { // Do whatever you need when text changes. // This will be fired every time you input any character. return false; } }); ```
5,713,653
I'm using a search view in my application. Now i just want to get the text typed in the SearchView text box and display it on another textview. If i typed the text and click a button i can do the same. But i don't want to use any extra buttons. I just want to display the result when i am pressing enter key.
2011/04/19
[ "https://Stackoverflow.com/questions/5713653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/669322/" ]
The right way to solve this is to use **setOnQueryTextListener** This is a small exmple using Kotlin: ``` txtSearch = rootView.searchView txtSearch.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextChange(newText: String): Boolean { return false } override fun onQueryTextSubmit(query: String): Boolean { return false } }) ```
with extension functions, create `SearchViewExtensions.kt` ``` import android.view.View import androidx.appcompat.widget.SearchView inline fun SearchView.onQueryTextChanged(crossinline listener: (String) -> Unit) { this.setOnQueryTextListener(object: SearchView.OnQueryTextListener { override fun onQueryTextSubmit(query: String?): Boolean { return true } override fun onQueryTextChange(newText: String?): Boolean { listener(newText.orEmpty()) return true } }) } ``` and the ***magic*** in your fragment ``` mSearchView.onQueryTextChanged { query: String -> // do whatever } ```