text
stringlengths
15
59.8k
meta
dict
Q: how to refine jq output I have a json file. A simple example looks like: [ { "host": "a.com", "ip": "1.2.2.3", "port": 8, "name":"xyz" }, { "host": "b.com", "ip": "2.5.0.4", "port": 3, "name":"xyz" }, { "host": "c.com", "ip": "9.17.6.7", "port": 4, "name":"xyz" } ] I want to extract the "host" and "ip" value and add them in a comma separated values file. Each record in a line as follows: a.com,1.2.2.3 b.com,2.5.0.4 c.com,9.17.6.7 I installed jq library to parse the json file. I executed this command: cat test.json | jq '.[] | {host: .host, ip: .ip}' The output I get is as the following: { "host": "a.com", "ip": "1.2.2.3" } { "host": "b.com", "ip": "2.5.0.4" } { "host": "c.com", "ip": "9.17.6.7" } Is there any way I can extract the output as I want? This output that jq produced require additional script to parse it and save the values as I want in csv format, one item in a line. A: To remove quotes: $ cat test.json | jq -r '.[] | [ .host, .ip ] | @csv' | sed 's/"//g' a.com,1.2.2.3 b.com,2.5.0.4 c.com,9.17.6.7 If using OS X, use Homebrew to install GNU sed. A: Use the @csv format to produce CSV output from an array of the values. cat test.json | jq -r '.[] | [.host, .ip] | @csv' The -r option is needed to get raw output rather than JSON, which would wrap an extra set of quotes around the result and escape the quotes that surround each field.
{ "language": "en", "url": "https://stackoverflow.com/questions/52012899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I align an ajax spinner over a knockoutjs templated div I am binding certain html templates. Inside the bound div I have an image which is the ajax spinner. This image is never visible I guess because its overriden with the bound template. Where should I now put this image so it is centered over the div with the bound template? <div style="height: 100%; width: 100%;" data-bind="template: { name: $root.currentChildTemplate() }"> <img src="/Content/images/ajax-loader.gif" class="ajax-loader" /> </div> A: You can either include it in the template, or place it just outside the templated div, and set its position absolutely with CSS. <img src="/Content/images/ajax-loader.gif" class="ajax-loader" /> <div style="height: 100%; width: 100%;" data-bind="template: { name: $root.currentChildTemplate() }"></div> You could go a step further, and have it only visible when a certain observable is true. <img src="/Content/images/ajax-loader.gif" class="ajax-loader" data-bind="visible: ajaxLoading" />
{ "language": "en", "url": "https://stackoverflow.com/questions/17881516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: get error on "buildozer android debug deploy run" get this error Command failed: ./distribute.sh -m "kivy" when trying to $ buildozer android debug deploy run How to fix it? thanks A: That means something went wrong in the python-for-android build step, but there are tons of problems that would give that error. Could you set the buildozer token log_level = 2 in your buildozer.spec and try it again (by default it will be 1). This will get buildozer to print much more information about the build process, including hopefully more about the error. Then, could you include that error information here?
{ "language": "en", "url": "https://stackoverflow.com/questions/20572560", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Laravel Undefined offset when using Skip() in database query Hopefully a simple one, but I'm getting nowhere fast with it, I need to perform a query in Laravel where I skip the first two records in a database, running the query DB::table('recent_videos')->where('user_id', $userId)->orderBy('created_at')->get() pulls all records as expected, but when I use DB::table('recent_videos')->where('user_id', $userId)->orderBy('created_at')->skip(2)->get(); I get the following error: Your Video count not be created due to this error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'offset 2' at line 1 (SQL: select * from `recent_videos` where `user_id` = 1 order by `created_at` asc offset 2) I get that it's related to offset 2 but I can't work out how to fix it, Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/66341197", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multiple functions with one "function" How can I get by using one function with function names and executions? function RunA() { alert("I run function A!"); } RunB() { alert("I run function B!"); } If this was explained elsewhere, my apologies. Edit: Trying to create a name for each function without using function every time A: No but you could do function RunA(){ alert("I run function A!"); }; function RunB(){ alert("I run function B!"); }; function RunAB(){ RunA(); RunB(); }; A: Short answer: No. Long answer: While it might seem like a good idea to save as much typing as possible, generally even if this was syntactically valid it is not a good idea to overcomplicate well defined customs in the name of fancy looking code. Just use function RunA(){ alert("I run function A!"); }; function RunB(){ alert("I run function B!"); };
{ "language": "en", "url": "https://stackoverflow.com/questions/36605145", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Wht GetPostData() returns { } using cefpython3? I can't understand why if i launch this, fill the registration form in github and click "sign up" post data is {}. I'm using python 3.7, cefpython 66.0 code: import tkinter as tk from tkinter import messagebox from cefpython3 import cefpython as cef #import cefpython3 import threading import sys import time import webbrowser def on_browse(browser,frame,request,user_gesture,is_redirect): if user_gesture == True: print('user_gesture:',user_gesture) print('GetFirstPartyForCookies:',request.GetFirstPartyForCookies()) print('GetFlags',request.GetFlags()) print('GetHeaderMap',request.GetHeaderMap()) print('GetHeaderMultimap',request.GetHeaderMultimap()) print('GetMethod',request.GetMethod()) print('GetPostData',request.GetPostData()) print('GetUrl',request.GetUrl()) def test_thread(frame): global browser sys.excepthook = cef.ExceptHook window_info = cef.WindowInfo(frame.winfo_id()) window_info.SetAsChild(frame.winfo_id(), rect) cef.Initialize() browser = cef.CreateBrowserSync(window_info, url='http://www.github.com') browser.SetClientCallback('OnBeforeBrowse',on_browse) cef.MessageLoop() def on_closing(): print('closing') r.destroy() r = tk.Tk() r.geometry('800x600') r.protocol('WM_DELETE_WINDOW', on_closing) frame = tk.Frame(r, bg='blue', height=400) frame2 = tk.Frame(r, bg='white', height=200) frame.pack(side='top', fill='x') frame2.pack(side='top', fill='x') r.update() tk.Button(frame2, text='Exit', command=on_closing).pack(side='left') tk.Button(frame2, text='Show something', command=lambda: messagebox.showinfo('TITLE', 'Shown something')).pack(side='right') rect = [0, 0, frame.winfo_width(), frame.winfo_height()] print('browser: ', rect[2], 'x', rect[3]) thread = threading.Thread(target=test_thread, args=(frame,)) thread.start() r.mainloop() and this is how i fill the form output: browser: 800 x 400 user_gesture: True GetFirstPartyForCookies: GetFlags 0 GetHeaderMap {} GetHeaderMultimap [] GetMethod POST GetPostData {} GetUrl https://github.com/join closing >>> i was expecting to find something in GetPostData. Thanks to everyone that will help me! ****UPDATE**** as suggested I tried with official cefpython tkinter example. I added self.browser.SetClientCallback('OnBeforeResourceLoad',self.on_browse) in class browserFrame def embed_browser. Then i add this function before "def embed_browser" def on_browse(self, browser,frame,request): user_gesture = True if user_gesture == True: print('user_gesture:',user_gesture) print('GetFirstPartyForCookies:',request.GetFirstPartyForCookies()) print('GetFlags',request.GetFlags()) print('GetHeaderMap',request.GetHeaderMap()) print('GetHeaderMultimap',request.GetHeaderMultimap()) print('GetMethod',request.GetMethod()) print('GetPostData',request.GetPostData()) print('GetUrl',request.GetUrl()) I got this output: user_gesture: True GetFirstPartyForCookies: https://github.com/join GetFlags 0 GetHeaderMap {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'Content-Type': 'application/x-www-form-urlencoded', 'Origin': 'https://github.com', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36'} GetHeaderMultimap [('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8'), ('Content-Type', 'application/x-www-form-urlencoded'), ('Origin', 'https://github.com'), ('Upgrade-Insecure-Requests', '1'), ('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36')] GetMethod POST [CEF Python] ExceptHook: catched exception, will shutdown CEF Traceback (most recent call last): File "request_handler.pyx", line 117, in cefpython_py37.RequestHandler_OnBeforeResourceLoad File "C:\Users\*****\Desktop\tkinter_.py", line 166, in on_browse print('GetPostData',request.GetPostData()) File "request.pyx", line 83, in cefpython_py37.PyRequest.GetPostData File "request.pyx", line 122, in cefpython_py37.PyRequest.GetPostData File "C:\Python37\lib\urllib\parse.py", line 740, in parse_qsl value = _coerce_result(value) File "C:\Python37\lib\urllib\parse.py", line 103, in _encode_result return obj.encode(encoding, errors) UnicodeEncodeError: 'ascii' codec can't encode character '\u2713' in position 0: ordinal not in range(128)
{ "language": "en", "url": "https://stackoverflow.com/questions/57991859", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: extend jekyll / octopress with db? I've been looking to move my wp blog to octopress (based on jekyll). I'd like to have the option to add a member login/registration system to the site as well as other dynamic functionality later down the line, but I like the idea of having my content static, like octopress offers. I don't necessarily need comments on the blog. I've read that octopress is based on sinatra, but I'm not a ruby expert. Would it be possible to use sinatra to achieve what I want or do I need to use some other toolkit? Thanks, B A: After one day of no replies you're already disappointed in the 'ruby fanboys'... Not surprised it stays silent after such a comment. Anyway, both Jekyll and Octopress are specifically aimed at generating static pages. You put the generated HTML files on a server and that's it. So there is no dynamic element at all. So if you want to add dynamic layers like a login system, you're looking at a totally different beast. You could create it, but you'd have to write the whole system yourself. If you want use create CMS in Ruby, you might want to have a look at RefineryCMS
{ "language": "en", "url": "https://stackoverflow.com/questions/11418421", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: TypeError: Cannot read properties of null (reading 'getAllPostsRep') bloc cubit flutter i'm new in bloc, i have static data and need to write clean code using data layer "repositry and model" before write this line in initstate, the Loading widget was only work but i discover that i should write cubit dunction in the initstate to emit the state of loaded, notice that i didn't use loading state. just initial and loaded have this error TypeError: Cannot read properties of null (reading 'getAllPostsRep') The relevant error-causing widget was LayoutBuilder LayoutBuilder:file:///C:/Users/Michael/Desktop/task/New/lib/presentation/screens/home_screen.dart:34:24 When the exception was thrown, this was the stack packages/facebookui/business_logic/cubit/posts_cubit.dart 15:38 getAllPosts after written this line in initstate class _FeedState extends State<Feed> { List<PostModel> allPosts = []; @override void initState() { super.initState(); BlocProvider.of<PostsCubit>(context).getAllPosts(); } @override Widget build(BuildContext context) { return Expanded( flex: 2, child: Align( alignment: AlignmentDirectional.topStart, child: SingleChildScrollView( child: Align( alignment: AlignmentDirectional.topStart, child: Column( children: [ Stories(), //stories widget Card( child: Column( children: [ WhatsOnYourMind(), //img,textfield of create post CustomDivider(), LiveSection(), //live, video and photos section SizedBox( height: 20, ) ], ), ), //create room and rooms Rooms(), //all posts BlocBuilder<PostsCubit, PostsState>( builder: (context, state) { if (state is PostsLoaded) { setState(() { allPosts = (state).postsList; }); return Posts(allPosts: allPosts); } else { return Loading(); } }, ), ], ), ), ), ), ); } } this is repositry that get static data from flie post class PostsRepository { //charactersWebServices Future<List<PostModel>> getAllPostsRep() async { await Future.delayed(const Duration(seconds: 2)); //posts is a const data return posts; } } this is state part of 'posts_cubit.dart'; @immutable abstract class PostsState {} class PostsInitial extends PostsState {} class PostsLoaded extends PostsState { final List<PostModel> postsList; PostsLoaded(this.postsList); } this is cubit class PostsCubit extends Cubit<PostsState> { final PostsRepository postsRepository; List<PostModel> allposts = []; PostsCubit(this.postsRepository) : super(PostsInitial()); List<PostModel> getAllPosts() { postsRepository.getAllPostsRep().then((value) { emit(PostsLoaded(value)); allposts = value; }); return allposts; } } this is the const data List<PostModel> posts = [ PostModel( name: 'Abdullah Ghayad', time: 5, text: 'The APIC Text is the most comprehensive and up-to-date reference for infection prevention and control (IPC). Written, edited, and reviewed by more than 200 subject matter experts, it reflects the latest guidelines, regulations, and standards of practice.The APIC Text\’s 11 sections and 125 peer-reviewed chapters are broad ranging, covering everything from fundamental principles, microbiology, epidemiology, and surveillance to more specialized topics, including specialty care populations, special pathogens, occupational health, and supportive care.', comments: 5, like: 50, profileImage: 'http://c.files.bbci.co.uk/C870/production/_112921315_gettyimages-876284806.jpg', images: [ 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSCZlf5lc5tX-0gY-y94pGS0mQdL-D0lCH2OQ&usqp=CAU' ]), ] A: because postsRepository is null, you need to initialized it final PostsRepository postsRepository = PostsRepository(); and remvoe it from constructor
{ "language": "en", "url": "https://stackoverflow.com/questions/69424329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Selection in PDF files I'm working on an ebook conversion script. When I create a PDF file using emacs ps-print-buffer-with-faces and then ps2pdf, I can select the words one by one on my ebook (Sony PRS 600). Same when I use Microsoft Word to print to PDF. Yet, when I create a PDF using pdflatex, or latex -> dvips -> ps2pdf, I can't select but blocks of words, separated by punctuation signs. It seems that there is something in the structure of the PDF files generated by latex that ebooks don't understand -- but what? Do you know a switch to tell latex to behave properly, or a workaround? Thanks! CFP. A: Latex doesn't use a white space character to separate words. That's the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/3620876", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Angular 2, installing library from Github repository I'm learning how to create an Angular 2 library based on a project created with Angular-CLI. I'm going by these examples ng-demo-lib and ng-demo-app by Nikita Smolenskii. The library dependency is listed like this in package.json: "ng-demo-lib": "git+ssh://[email protected]/nsmolenskii/ng-demo-lib.git", The problem is, when I run npm install on ng-demo-app I get: npm ERR! git clone --template=/Users/xxx/.npm/_git-remotes/_templates --mirror ssh://[email protected]/nsmolenskii/ng-demo-lib.git /Users/xxx/.npm/_git-remotes/git-ssh-git-github-com-nsmolenskii-ng-demo-lib-git-ea5cc26b: Cloning into bare repository '/Users/xxx/.npm/_git-remotes/git-ssh-git-github-com-nsmolenskii-ng-demo-lib-git-ea5cc26b'... npm ERR! git clone --template=/Users/xxx/.npm/_git-remotes/_templates --mirror ssh://[email protected]/nsmolenskii/ng-demo-lib.git /Users/xxx/.npm/_git-remotes/git-ssh-git-github-com-nsmolenskii-ng-demo-lib-git-ea5cc26b: Permission denied (publickey). npm ERR! git clone --template=/Users/xxx/.npm/_git-remotes/_templates --mirror ssh://[email protected]/nsmolenskii/ng-demo-lib.git /Users/xxx/.npm/_git-remotes/git-ssh-git-github-com-nsmolenskii-ng-demo-lib-git-ea5cc26b: fatal: Could not read from remote repository. npm ERR! git clone --template=/Users/xxx/.npm/_git-remotes/_templates --mirror ssh://[email protected]/nsmolenskii/ng-demo-lib.git /Users/xxx/.npm/_git-remotes/git-ssh-git-github-com-nsmolenskii-ng-demo-lib-git-ea5cc26b: npm ERR! git clone --template=/Users/xxx/.npm/_git-remotes/_templates --mirror ssh://[email protected]/nsmolenskii/ng-demo-lib.git /Users/xxx/.npm/_git-remotes/git-ssh-git-github-com-nsmolenskii-ng-demo-lib-git-ea5cc26b: Please make sure you have the correct access rights npm ERR! git clone --template=/Users/xxx/.npm/_git-remotes/_templates --mirror ssh://[email protected]/nsmolenskii/ng-demo-lib.git /Users/xxx/.npm/_git-remotes/git-ssh-git-github-com-nsmolenskii-ng-demo-lib-git-ea5cc26b: and the repository exists. npm ERR! Darwin 16.4.0 npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" npm ERR! node v7.5.0 npm ERR! npm v4.1.2 npm ERR! code 128 npm ERR! Command failed: git clone --template=/Users/xxx/.npm/_git-remotes/_templates --mirror ssh://[email protected]/nsmolenskii/ng-demo-lib.git /Users/xxx/.npm/_git-remotes/git-ssh-git-github-com-nsmolenskii-ng-demo-lib-git-ea5cc26b npm ERR! Cloning into bare repository '/Users/xxx/.npm/_git-remotes/git-ssh-git-github-com-nsmolenskii-ng-demo-lib-git-ea5cc26b'... npm ERR! Permission denied (publickey). npm ERR! fatal: Could not read from remote repository. npm ERR! npm ERR! Please make sure you have the correct access rights npm ERR! and the repository exists. npm ERR! npm ERR! npm ERR! If you need help, you may report this error at: npm ERR! <https://github.com/npm/npm/issues> npm ERR! Please include the following file with any support request: npm ERR! /Users/xxx/Desktop/nsmolenskii/ng-demo-app/npm-debug.log I've never tried to import from a remote repository in the package.json. This is new to me. Is there something I need to set up so that Github knows my identity? How do I fix this permissions issue? A: try install form github like this npm i -D github:user-name/repo-name, or define like this in your package.json file: { "dependencies": { "repo-name": "github:user-name/repo-name" } } then run npm install
{ "language": "en", "url": "https://stackoverflow.com/questions/42796653", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Sending a String of Data to a Specific Client This could be a very hard question.. But here we go, so I have a Multi Client chat server, I handle the Multi - Client part with a new Class called ClientConnection, everytime a client connects, it creates a new instance of ClientConnection for that client, and incoming data is handled in that client's class. When a new client connects, it is added to a listView on my admin panel, now, I want to be able to boot a specific client from the server. I want to right click his IP and click boot. (The right click and menu are done and in place). I currently have this: private void cMDToolStripMenuItem_Click(object sender, EventArgs e) { foreach(ListViewItem LIST_ITEM in listView1.Items) { ClientConnection SPEC_client = (ClientConnection)LIST_ITEM.Tag; } } But I have a feeling it will just loop through ALL clients and kick all of them, which I don't want. How can I send data to just one?
{ "language": "en", "url": "https://stackoverflow.com/questions/13448757", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: fetch particular key values from a dictionary which has values in list I have following dictionary, from which I want to fetch only 'tcase_name' a = {'179781': [{'exec_id': '0', 'exec_on_build': '', 'exec_on_tplan': '', 'exec_status': 'n', 'execution_duration': '', 'execution_order': '1', 'execution_type': '2', 'external_id': '59', 'feature_id': '14799', 'full_external_id': 'TC-59', 'platform_id': '0', 'platform_name': '', 'status': '1', 'tc_id': '179781', 'tcase_id': '179781', 'tcase_name': 'test_20experiment', # HERE 'tcversion_id': '179782', 'tcversion_number': '', 'version': '1'}], '179821': [{'exec_id': '68588', 'exec_on_build': '160', 'exec_on_tplan': '178775', 'exec_status': 'b', 'execution_duration': '0.00', 'execution_order': '1', 'execution_type': '2', 'external_id': '60', 'feature_id': '14800', 'full_external_id': 'TC-60', 'platform_id': '0', 'platform_name': '', 'status': '1', 'tc_id': '179821', 'tcase_id': '179821', 'tcase_name': 'test_22experiment', # AND HERE 'tcversion_id': '179822', 'tcversion_number': '1', 'version': '1'}]} Here is what I tried: >>> a.keys() ['179821', '179781'] >>> a.values() [[{'tcase_id': '179821', 'status': '1', 'exec_id': '68588', 'tcversion_id': '179822', 'exec_on_tplan': '178775', 'version': '1', 'external_id': '60', 'tcversion_number': '1', 'tc_id': '179821', 'execution_type': '2', 'platform_id': '0', 'tcase_name': 'test_22experiment', 'execution_duration': '0.00', 'exec_on_build': '160', 'exec_status': 'b', 'full_external_id': 'TC-60', 'feature_id': '14800', 'execution_order': '1', 'platform_name': ''}], [{'tcase_id': '179781', 'status': '1', 'exec_id': '0', 'tcversion_id': '179782', 'exec_on_tplan': '', 'version': '1', 'external_id': '59', 'tcversion_number': '', 'tc_id': '179781', 'execution_type': '2', 'platform_id': '0', 'tcase_name': 'test_20experiment', 'execution_duration': '', 'exec_on_build': '', 'exec_status': 'n', 'full_external_id': 'TC-59', 'feature_id': '14799', 'execution_order': '1', 'platform_name': ''}]] >>> a.values()['tcase_name'] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: list indices must be integers, not str Can someone suggest me a way to get the required field values from this dictionary? A: You were doing the right thing. For the nested dictionary, if you can't understand it, print it out to see how it's structured. Here is a way to get your values that you should be able to manipulate to get whatever you want. for k,v in a.items(): # get the keys and values in the dict a. k, v are not special names. for e in v: # now lets get all of the elements in each value, which is a list of dicts print(e.get('tcase_name')) # use the dict method get to retrieve the value for a particular key of interest.
{ "language": "en", "url": "https://stackoverflow.com/questions/44123465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Implementing complex data structures in C++ What's the solution you adopt when you have to implement complex data structures in C++? I mean different kind of objects that should be referenced by other ones and, at the same time, reference other ones. It is really different from the available standard library containers. Do you try to make your code very C++ and use generic programming (container style template)? IMHO, it seems hard to implement and inconvenient, and it could make the code harder to understand or to work with. Moreover, do you implement any kind of iterator? Or maybe, on the other hand, you end up with "C style code"? I mean, in each class you implement a few pointers as member variables that reference other objects in order to build the suitable data structure. According to your experience, what are the advantages and disadvantages of these two approaches? Any other solution? A: There are a couple of guidelines that I follow when writing complex data structures in C++: * *Avoid raw pointers; use smart pointers. *Try to figure out early on if your data structure is cyclic or acyclic. If there are cycles in your data structure you won't be able to used share_ptr everywhere without creating a leak. At some point in your cyclic structure you want to break the cycle with a weak_ptr, so that objects can be released. *If my object holds onto other objects, and I want it to be a container, I implement the appropriate iterators when I need them, and not one second before. I usually need iterator support when I want to use one of the STL algorithms on my container. I could, of course, implement iterators that don't match the STL (in terms of naming or semantics) for my own use, but then I've added yet another way to do things in my code. I try to avoid that. *If my class is intended to hold different types, then I use templates to express that. There are ways to do this in C (using memcpy, etc), but while the code you'll end up with will be more understandable to C coders, you will lose most of the benefits of C++ (type safety, assignment operators, etc).
{ "language": "en", "url": "https://stackoverflow.com/questions/15600218", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Oracle 11g XE - ORA-31202: DBMS_LDAP: LDAP client/server error: SSL handshake failed when connecting AD I'm trying to integrate my oracle 11g XE instance (version forced by product I'm working with) with Samba based Active Directory on port 636. Unfortunetally, I'm getting error ORA-31202: DBMS_LDAP: LDAP client/server error: SSL handshake failed. I've set oracle wallet, trying with openssl an keytool (using SE version), but it's not working with any of them. I've seen same problem here, but it was resolved by adding java procedure which is not supported by XE. If anybody could help me, I'd be really, really grateful. I'm storing my test procedure below, but it's nothing more than minimal required standard one: declare l_retval varchar(100); p_session dbms_ldap.session; begin dbms_ldap.use_exception := true; p_session := dbms_ldap.init(hostname => 'myldaphost', portnum => 636); l_retval := DBMS_LDAP.open_ssl (p_session,'file:/u01/app/wallet2', 'xxxxx', 2); l_retval := dbms_ldap.simple_bind_s(ld => p_session, dn => 'myuserdn', passwd => 'xxxxx'); end; #EDIT: That's why I've managed to capture with tshark: 1 0.000000000 10.10.30.58 β†’ 10.10.30.29 TCP 74 34068 β†’ 636 [SYN] Seq=0 Win=64240 Len=0 MSS=1460 SACK_PERM=1 TSval=1812804240 TSecr=0 WS=128 2 0.001134994 10.10.30.29 β†’ 10.10.30.58 TCP 74 636 β†’ 34068 [SYN, ACK] Seq=0 Ack=1 Win=65160 Len=0 MSS=1460 SACK_PERM=1 TSval=3244251678 TSecr=1812804240 WS=128 3 0.001194794 10.10.30.58 β†’ 10.10.30.29 TCP 66 34068 β†’ 636 [ACK] Seq=1 Ack=1 Win=64256 Len=0 TSval=1812804241 TSecr=3244251678 4 0.062087948 10.10.30.58 β†’ 10.10.30.29 SSLv2 133 Client Hello 5 0.063469940 10.10.30.29 β†’ 10.10.30.58 TCP 66 636 β†’ 34068 [ACK] Seq=1 Ack=68 Win=65152 Len=0 TSval=3244251740 TSecr=1812804302 6 0.063480740 10.10.30.29 β†’ 10.10.30.58 TCP 66 636 β†’ 34068 [FIN, ACK] Seq=1 Ack=68 Win=65152 Len=0 TSval=3244251740 TSecr=1812804302 7 0.063532740 10.10.30.58 β†’ 10.10.30.29 SSLv3 73 Alert (Level: Fatal, Description: Close Notify) 8 0.063556040 10.10.30.58 β†’ 10.10.30.29 TCP 66 34068 β†’ 636 [FIN, ACK] Seq=75 Ack=2 Win=64256 Len=0 TSval=1812804303 TSecr=3244251740 9 0.064059637 10.10.30.29 β†’ 10.10.30.58 TCP 60 636 β†’ 34068 [RST] Seq=2 Win=0 Len=0
{ "language": "en", "url": "https://stackoverflow.com/questions/71882055", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to create an array from existing array by pairing every two values into key and value? This is what I want to do. I have an array. $arr = array('value1','value2','value3','value4','value5','value6'); Is it possible to pair every two values into something like: $new_arr = array('value1' => 'value2','value3' => 'value4', 'value5' => 'value6'); In the first array, there are no keys. They are all values. But I want to pair them..in the same order every key => value (the next to it..just like the example above) Is something like that possible? I badly need it.. A: This might do the trick: $res = array(); for ($i = 0; $i + 1 < count($arr); $i = $i + 2) { $res[$arr[$i]] = $arr[$i + 1]; } A: Assuming the array has even number of members you can do: for($i=0 ; $i<count($arr)-1 ; $i+=2) { $new_array[$arr[$i]] = $arr[$i+1]; } Where $arr is your existing array and $new_array is the new resultant associative array. Working Ideone link A: Try something like this: $new_arr = array(); for ($i = 0; $i < count($arr); $i += 2) { $new_arr[$arr[$i]] = $arr[$i + 1]; } Note that the value indexed by the last key is undefined if $arr contains an odd number of items. A: Of course it's possible. function array_pair($arr) { $retval = array(); foreach ($arr as $a) { if (isset($key)) { $retval[$key] = $a; unset($key); } else { $key = $a; } } return $retval; } Or you could do: function array_pair($arr) { $retval = array(); $values = array_values($arr); for ($i = 0; $i < count($values); $i += 2) $retval[$values[$i]] = $values[$i + 1]; return $retval; } A: An approach with odd / even indices. $new_arr = array(); $key = NULL; for($i=0; $i<count($arr); $i++){ if($i % 2){ // even indices are values, store it in $new_arr using $key $new_arr[ $key ] = $arr[$i]; } else{ // odd indices are keys, store them for future usage $key = $arr[$i]; } } Note: the last value will be ignored if the array length is odd.
{ "language": "en", "url": "https://stackoverflow.com/questions/3785135", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: error on a ajax request with python I've got a html file with following lines of code <script> function ButClick(){ $.ajax({ url: "../cgi-bin/test.py", type: "POST", data: {var1: 'Value 1', var2: 'Value 2'}, success: function(response){$("#TestDiv").html(response);} }) } </script> <form><input type='button' onclick="ButClick()" value="Click Me!" /></form> <div id='TestDiv'></div> and I've got a Python 3.4 script in test.py: #![...]/custom/bin/python # -*- coding: iso-8859-15 -*- import cgi import cgitb cgitb.enable() data=cgi.FieldStorage() print("Var1-Data lautet: " + data['var1'].value) I just want to perform an ajax reqest when clicking the button. But I'll getting following error: Traceback (most recent call last): File "test.py", line 12, in &lt;module&gt; print("Var1-Data lautet: " + data['var1'].value) File "[...]/custom/lib/python3.4/cgi.py", line 598, in __getitem__ raise KeyError(key) KeyError: 'var1' Can anybody please help me to find the error? A: now, I found myself a solution to my problem. There I, do not use CGI but PHP an Pyton. Certainly, this solution is not very elegant, but it does what I want. In addition, I must perform some MySQL queries. All in all I can by the way increase the performance of the whole page. My Code now looks like this: index.html <html> <head> <title>TEST</title> <script src="jquery.js"> </script> </head> <body> <script> function ButClick(){ var TestVar = "'Hallo! This is a test'"; $.post('test.php',{var:TestVar},function(response) $('#TestDiv').html(response)}); } </script> <form><input type='button' onclick="ButClick()" value="Click Me!" /></form> <div id='TestDiv'></div> </body> </body> </html> test.php <?php $param1=$_POST['var']; $command="python test.py $param1 $param2"; $buffer=''; ob_start(); // prevent outputting till you are done passthru($command); $buffer=ob_get_contents(); ob_end_clean(); echo "PHP and".$buffer; ?> test.py #path to your python interpreter #!/usr/bin/python #sys module to get access to the passed in parameters import sys # the first parameters in sys.argv[0] is the path to the current executing python script param1=sys.argv[1] PyAnswer="python back: " +param1 # send the result back to php print (PyAnswer) I hope, that I can help with these post some other people!
{ "language": "en", "url": "https://stackoverflow.com/questions/24204411", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: webpack-dev-server set cookie via proxy We have setup our development environment with webpack-dev-server. We use its proxy config to communicate with the backend. We have a common login page in the server which we use in all our applications. We it is called, it sets a session cookie which expected to passed with subsequent requests. We have used the following config but the cookie is not set in the browser for some reason. I can see it in response header in the network tab of dev tool. const config = { devServer: { index: "/", proxy: { "/rest_end_point/page": { target: "https://middleware_server", secure : false }, "/": { target: "https://middleware_server/app/login", secure : false }, } The https://middleware_server/app/login endpoint returns the login page with the set-cookie header. The proxy is used to avoid CORS errors when accessing login pages and API calls. Upto this point no code from the application is executed. Do we have to do something in the coomon login page to get the cookie set? the application is written with React. Any help would be appreciated. A: I have the same use case and this is what I have done. In my case, I have multiple proxy targets so I have configured the JSON (ProxySession.json) accordingly. Note: This approach is not dynamic. you need to get JSESSIONID manually(session ID) for the proxy the request. login into an application where you want your application to proxy. Get the JSESSIONID and add it in JSON file or replace directly in onProxyReq function and then run your dev server. Example: Webpack-dev.js // Webpack-dev.js const ProxySession = require("./ProxySession"); config = { output: {..........}, plugins: [.......], resolve: {......}, module: { rules: [......] }, devServer: { port: 8088, host: "0.0.0.0", disableHostCheck: true, proxy: { "/service/**": { target: ProxySession.proxyTarget, changeOrigin: true, onProxyReq: function(proxyReq) { proxyReq.setHeader("Cookie", "JSESSIONID=" + ProxySession[buildType].JSESSIONID + ";msa=" + ProxySession[buildType].msa + ";msa_rmc=" + ProxySession[buildType].msa_rmc + ";msa_rmc_disabled=" + ProxySession[buildType].msa_rmc); } }, "/j_spring_security_check": { target: ProxySession.proxyTarget, changeOrigin: true }, "/app_service/websock/**": { target: ProxySession.proxyTarget, changeOrigin: true, onProxyReq: function(proxyReq) { proxyReq.setHeader("Cookie", "JSESSIONID=" + ProxySession[buildType].JSESSIONID + ";msa=" + ProxySession[buildType].msa + ";msa_rmc=" + ProxySession[buildType].msa_rmc + ";msa_rmc_disabled=" + ProxySession[buildType].msa_rmc); } } } } ProxySession.json //ProxySession.json { "proxyTarget": "https://t.novare.me/", "build-type-1": { "JSESSIONID": "....", "msa": "....", "msa_rmc": ...." }, "build-type-2": { "JSESSIONID": ".....", "msa": ".....", "msa_rmc":"....." } } A: I met the exact same issue, and fixed it by this way: This is verified and worked, but it's not dynamic. proxy: { '/my-bff': { target: 'https://my.domain.com/my-bff', changeOrigin: true, pathRewrite: { '^/my-bff': '' }, withCredentials: true, headers: { Cookie: 'myToken=jx42NAQSFRwXJjyQLoax_sw7h1SdYGXog-gZL9bjFU7' }, }, }, To make it dynamic way, you should proxy to the login target, and append a onProxyRes to relay the cookies, something like: (not verified yet) onProxyRes: (proxyRes: any, req: any, res: any) => { Object.keys(proxyRes.headers).forEach(key => { res.append(key, proxyRes.headers[key]); }); }, A: "/api/**": { ... cookieDomainRewrite: { "someDomain.com": "localhost" }, withCredentials: true, ... } A: You can use this plugin to securely manage auth cookies for webpack-dev-server: A typical workflow would be: * *Configure a proxy to the production service *Login on the production site, copy authenticated cookies to the local dev server *The plugin automatically saves your cookie to system keychain A: https://github.com/chimurai/http-proxy-middleware#http-proxy-options use option.cookieDomainRewrite and option.cookiePathRewrite now A: cookies ?? devServer: { https: true, < ------------ on cookies host: "127.0.0.1", port: 9090, proxy: { "/s": { target: "https://xx < --- https secure: false, //pathRewrite: { "^/s": "/s" }, changeOrigin: true, withCredentials: true } } } . . . . . . . . . . .
{ "language": "en", "url": "https://stackoverflow.com/questions/56377371", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: Extract all url from sitemap.xml with PHP CURL I want to extract all url from sitemap.xml with PHP and CURL. My code work with content sitemap (e.g: http://www.phanmemtoday.com/sitemap.xml?page=1) but does not work with sitemap index (e.g: http://www.phanmemtoday.com/sitemap.xml). Please help me. Thank you! <?php $sUrl="http://domain.com/sitemap.xml"; $aXmlLinks = array($sUrl); $aOtherLinks = array(); while (!empty($aXmlLinks)) { foreach ($aXmlLinks as $i =>$sTmpUrl){ unset($aXmlLinks[$i]); $aTmp = getlinkfromxmlsitemap($sTmpUrl); echo "Array temp link:<br>"; print_r($aTmp); foreach ($aTmp as $sTmpUrl2) { if (strpos($sTmpUrl2, '.xml') !== false) { array_push($aXmlLinks,$sTmpUrl2); } else { array_push($aOtherLinks,$sTmpUrl2); } } } echo "<br>Array xml link:<br>"; print_r($aXmlLinks); echo "<br>Array product link:<br>"; print_r($aOtherLinks); echo "<br>-----------------------------------------<br>"; } print_r($aOtherLinks); function getlinkfromxmlsitemap($sUrl) { // echo "Get link from: $sUrl<br>"; $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch,CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0"); curl_setopt($ch, CURLOPT_URL, $sUrl); $data = curl_exec($ch); curl_close($ch); $links = array(); $count = preg_match_all('@<loc>(.+?)<\/loc>@', $data, $matches); for ($i = 0; $i < $count; ++$i) { $links[] = $matches[0][$i]; } return $links; } ?> A: Your code works well, but you can improve some things please check the following example thar will return a nested array with the links your looking: <?php $sUrl1="http://www.phanmemtoday.com/sitemap.xml?page=1"; $sUrl2="http://www.phanmemtoday.com/sitemap.xml"; $aXmlLinks = array($sUrl1,$sUrl2); $aOtherLinks = array(); while (!empty($aXmlLinks)) { foreach ($aXmlLinks as $i =>$sTmpUrl){ unset($aXmlLinks[$i]); $aTmp = getlinkfromxmlsitemap($sTmpUrl); array_push($aOtherLinks,$aTmp); } echo "<br>Array xml link:<br>"; print_r($aXmlLinks); echo "<br>Array product link:<br>"; print_r($aOtherLinks); echo "<br>-----------------------------------------<br>"; } print_r($aOtherLinks); function getlinkfromxmlsitemap($sUrl) { // echo "Get link from: $sUrl<br>"; $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch,CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0"); curl_setopt($ch, CURLOPT_URL, $sUrl); $data = curl_exec($ch); $error= curl_error($ch); curl_close($ch); $links = array(); $count = preg_match_all('@<loc>(.+?)<\/loc>@', $data, $matches); for ($i = 0; $i < $count; ++$i) { $links[] = $matches[0][$i]; } return $links; } ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/37980291", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Transfer big file from PC to a Pocket PC I need to transfer a big file from PC to PPC (Pocket PC) but I can't use RAPI. I need to: * *Convert an .sdf (big) file to a binary format *Transfer to PPC (through a Web service) *In PPC convert from binary to .sdf The problem is that in PPC I got an exception "out of memory" (in big file). With a small file it works excellently. What can I do? Maybe I can send the file in slices? A: What Conrad said, you need to send the file in smaller sizes, depending on what kind pf PPC you have. That could be as small as few mb, and then write to either a storage card or the main memory. I personaly use FTP to transfer "big" files ( Ranging in the hundreds of mb ) to transfer to my PPC, but im sure you can use any other solution you may desire. But you need to research the limits of your target PPC, they often have limited memory,storage and CPU. There is also a built in http downloader class in the .net compact framework you can use.
{ "language": "en", "url": "https://stackoverflow.com/questions/725526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why doesn't PHP permit private constants? Why doesn't PHP permit private constants? I am aware that there are workarounds, such as using a private static property instead. However, from an OOP or software design perspective, what was the reasoning? A: tl;tr What was the reasoning to not implement private constants? This is a good question. Did they really consider this? I don't know. * *When searching through the PHP internals mailing list, i found nothing about this topic. Unless a internal's member speaks up, we'll never know. With regard to the history of the language - a bit 1:1 C method wrapping, some bits from Perl (regexp), some bits Java (oop) - it's possible that this idea popped up, while looking for new language features. I would relate the concept of a "private constant" to VisualBasic or Java. I doubt that VB has a big or any influence on PHP. VB allows the definition of "private constants" in "Modules" - it's the default access scope. Visual Basic doesn't allow constants in Interfaces and Namespaces (but PHP does). PHP might include some OOP concepts from Java, but there is one big difference: constants are variables in Java. Their access modifiers / visibility levels are: "public, private, final and static". A private constant declaration looks like this: "private static final String MYCONST = "My Constant"; It's OOP - end of story. PHP constant access feels more hackish compared to that - BUT it's more simple and you still have the workaround at hand. *The first comment in the PHP manual for Class Constants is: It may seem obvious, but class constants are always publicly visible. They cannot be made private or protected. I do not see it state that in the docs anywhere. Why is this obvious? "Why is a class constant public by default and not private?" Maybe, it's a missing language feature, because not all class members can be hidden properly. And he is right, when you come from Java or VB to PHP this question pops up. *Let's take a look at the PHP spec. The current state of implementation in PHP is: class constants are always public and static. So, again and again, thumbs up for Facebook for writing such detailed document: the author considered different visibility or access-control levels. Let's take a look at interface, class, constant and visibility: * *How does the concept "const" differ from "private static"? The static variable can be changed, the constant cannot be changed. You cannot assign the runtime value of a function to a const (const A = sprintf('foo %s', 'bar');), but to a private static var. *An interface might have constants - they cannot be overridden. *A class might have a constant - which might be overridden by a inheriting class/interface. *There is also an OOP pattern called "constant interface pattern" - it describes the use of an interface solely to define constants, and having classes implement that interface in order to achieve convenient syntactic access to those constants. An interface is provided so you can describe a set of functions and then hide the final implementation of the functions in an implementing class. This allows you to change the implementation of the functions, without changing how you use it. Interfaces exist to expose an API. And by defining constants in an interface and implementing the interface by a class, the constants become part of the API. In fact, you are leaking implementations details into the API. That's why some consider this being an anti-pattern, among them Joshua Bloch (Java). Now, let's try to combine some concepts and see if they fit. Let's pretend we try to avoid the critique from above, then you need to introduce a syntax, which allows qualified access to the constant, but hides the constant in the API. You could come up with "Access control" via visibility levels: "public, private, protected, friend, foe". The goal is to prevent the users of a package or class from depending on unnecessary details of the implementation of that package or class. It is all about hiding implementation details, right? What about "private constants" in "interfaces"? That would actually solve the critique from above, right? But the combination of interface with "private", doesn't make sense. The concepts are contrary. That's why interface do not allow "private" access/visibility-levels. And a "private" constant in an "interface" would be mutually exclusive, too. What about "private constants" in "classes"? class a { /*private*/ const k = 'Class private constant k from a'; } class b extends a { const k = 'Overridden private constant a::k with Class constant k from b'; const k_a = parent::k; // fatal error: self-referencing constant #const k_selfref = self::k . ' + ' . self::k_selfref; // fatal error: "static::" is not allowed in compile-time constants #const k_staticref = static::k; } // direct static access would no longer work, if private // you need an instance of the parent class or an inheriting class instance echo a::k; echo b::k; echo b::k_a; $obj_b = new b; echo $obj_b::k; echo $obj_b::k_a; Is there a benefit? * *The private constant in the class wouldn't be exposed in the API. This is good OOP. *The access to the parent constant from outside would be a class and/or inheritance access. echo a::k, which now works - could respond with "Fatal error: Trying to access a private constant without a class instance or inheritance.". *(This might still work solely at compile-time, if there is no run-time value assignment to a const. But i'm not sure about this one.) Are there caveats? * *We would lose direct static access to constants. *Requiring that an instance of a class is created, just to access constants, is a waste of resources. Direct static access saves resources and is simple. If we introduce private, that's lost and the access would be bound to the instance. *A "private const" is implicitly a "private static const". The access operator is still "::". A possible follow-up change would be the switch to implicitly non-static constants. That's a BC break. If you switch the default behavior to non-static, the access operator changes from "::" to "->". This establishes a proper OOP object access to constants, which is comparable to Java's concept of "constants as variables with access level". This would work a bit like this: http://3v4l.org/UgEEm. The access operator changes to static, when the constant is declared as "public static const", right? Is the benefit good enough to implement it? I don't know. It's up for discussion. I like both: the const static access, because it's dead simple and the concept of "constants as variables" and proper access levels. After that's implemented, in order to save resources and keep going fast, everyone starts to (re-)declare "public static const", to drop the instance requirement and violate OOP ;) And btw: i found an HHVM overflow, while experimenting with code of this answer. A: Why doesn't PHP permit private constants? In PHP constants are part of the interface and the interface is public, always (that's what an interface is for). See as well PHP Interfaces. I'm pretty sure this is the reason design-wise. Regarding the comment under your question that someone wants to reduce the visibility of constants to change them later, I'd say this sounds more like a variable than a constant which does not change it's value. It's constant.
{ "language": "en", "url": "https://stackoverflow.com/questions/27757806", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: clicking on label 'for' both anchor tag and input tag I cannot get this work, looks like not possible, that's why i'm asking... This is the CSS used: label.btn { cursor:pointer; display:inline-block; } label.btn>input[type=checkbox] { display:none; } label.btn>input[type=checkbox]:checked~b { background:red; } /* not relevant, just for testing purpose */ #divtest { margin-top:1500px } Following HTML code will check the input, and then style for <b> tag is applied: <a href="#divtest" id="anchor"> <label class="btn"> <input type="checkbox"/><b>Click should scroll to '#divetest' element and check input for styling!</b> </label> </a> DEMO styling If i add attribute 'for' to the label to target the anchor tag, the default browser scrolling works, but then no more styling applied: <label class="btn" for="anchor"> DEMO anchor Now, the obvious question: Can i get these both behaviours working together in pure CSS? A: This won't work since the Input:checkbox is INSIDE the <label>. Browsers will set focus on the input upon a click on the label. A: An input element inside an a violates common sense as well as HTML5 CR. Nesting two interactive elements raises the issue which element is activated on mouse click. Instead of such construct, use valid and sensible HTML markup. Then please formulate the styling question in terms of desired or expected rendering vs. actual rendering, instead of saying that β€œthis” β€œdoes not work”.
{ "language": "en", "url": "https://stackoverflow.com/questions/17953461", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Eclipse CDT project temporary files What files can be safely removed from CDT project and workspace before archiving or saving in a source control system? Having MSVC experience, I tried to remove Debug and Release directories, this was really bad idea :( A: Are you using an Eclipse plug-in for your version control system of choice? They seem to take care of everything (at least in my experience with the CVS and Mercurial plugins). If not, you'll need to tell Eclipse to refresh pretty much your whole project whenever you've interacted with version control. The contents of the Debug and Release directories should all be autogenerated. If they're not, something's wrong. Rather than what you can delete, turn it around and consider what you need to keep: * *.project, .cproject and (if it exists) .settings *Your source directories *Your include directories *Any other human-created files at the top level e.g. Changelog, documentation It may also be worthwhile looking inside the .metadata directory in your workspace root; for example, any launch configurations you have created are stored by default in .metadata/.plugins/org.eclipse.debug.core/.launches/ . (Although I have seen them inside project directories from time to time.)
{ "language": "en", "url": "https://stackoverflow.com/questions/2325758", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: php if statement in html is matching all conditions I'm trying to get an if statement to test a php session and if it's true, show html and if it's not, don't show html. I did some research and found this <? $a = 2; if ($a == 2): ?> <p>Content</p> <? elseif ($a == 3): ?> <p>Other Content</p> <? else: ?> <p>Default Content</p> <? endif; ?> but when i run it, every condition seems to be met as it outputs everything, does anyone know why? thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/42180853", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to prevent a Javascript click event from happening twice? I had a big problem in getting a Google maps iframe to load on center, inside a twitter bootstrap modal. The solution that I found to work is loading the iframe by javascript, once the modal is opened. The problem that I have with my code at the moment is that once the modal is closed and re-opened, the iframe will be unloaded. So the question is how to prevent a click event from happening twice? My code: <script type="text/javascript"> $(function() { $("#map_link").click(function(event) { event.preventDefault(); $("#map").slideToggle(); $("#map").html('Iframe_code_is_situated_here').css('display','block'); }); }); </script> A: $("#map_link").one('click', function(event) { A: Keep track of whether or not it has been clicked and return false if it has been clicked $(function() { var click_limit = 1, clicks = 0; $("#map_link").click(function(event) { if (clicks++ === click_limit){ return false; } event.preventDefault(); $("#map").slideToggle(); $("#map").html('Iframe_code_is_situated_here').css('display','block'); }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/15350921", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Facebook SDK instruction not making sense about app id I have taken a picture of the Facebook instruction below. What is wrong with it? My app keeps crashing with exception concerning ApplicationId should not be null. But I have added my app id as <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/> in the manifest; that is after adding it as a string in the strings.xml resource as <string name="facebook_app_id">0000000000</string> So I figure the instructions is wrong because it does not say which uses-permission to add and it says to call the string resource key com.facebook.sdk.ApplicationId with value Facebook_app_id. Here is the link https://developers.facebook.com/docs/android/getting-started#eclipse A: Quite simply 1.) Create app on Facebook, get the app_id that you will subsequently use to attach to your app. 2.) Define your applicationId in the AndroidManifest.xml like this: <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/app_id"/> under <application android:label="@string/app_name".... tag where app_id is a string within your strings.xml. Example (Facebook Sample application): <application android:label="@string/app_name" android:icon="@drawable/icon" android:theme="@android:style/Theme.NoTitleBar" > <activity android:name=".HelloFacebookSampleActivity" android:label="@string/app_name" android:windowSoftInputMode="adjustResize"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> <activity android:name="com.facebook.LoginActivity" android:theme="@android:style/Theme.Translucent.NoTitleBar" android:label="@string/app_name" /> <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/app_id"/> </application> Note the value added under the <application> tag and in strings.xml (MAKE SURE TO DO THIS) <string name="app_id">xxxxxxxxxxxx</string> 3.) Set permissions in manifest <uses-permission android:name="android.permission.INTERNET"/> This is an android requirement, so the app can access the internet. So with permissions the above manifest will look like <uses-permission android:name="android.permission.INTERNET" /> <application android:label="@string/app_name" android:icon="@drawable/icon" android:theme="@android:style/Theme.NoTitleBar" > <activity android:name=".HelloFacebookSampleActivity" android:label="@string/app_name" android:windowSoftInputMode="adjustResize"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> <activity android:name="com.facebook.LoginActivity" android:theme="@android:style/Theme.Translucent.NoTitleBar" android:label="@string/app_name" /> <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/app_id"/> </application> A: I had the same problem. And here is how I solved it β€” I think. At least after doing these things, the problem went away. in strings.xml <?xml version="1.0" encoding="utf-8"?> <resources> …. <string name="com.facebook.sdk.ApplicationId">facebook_app_id</string> <string name="facebook_app_id">111111111</string> …. </resources> in manifest <application … > <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id" /> </application> </manifest> Notice there are two entries in the strings.xml file.
{ "language": "en", "url": "https://stackoverflow.com/questions/28775950", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: digging into child objects and reconstruct the data I've having currencies list in JSON that comes like this { "USD": { "symbol": "$", "name": "US Dollar", "symbol_native": "$", "decimal_digits": 2, "rounding": 0, "code": "USD", "name_plural": "US dollars" }, "CAD": { "symbol": "CA$", "name": "Canadian Dollar", "symbol_native": "$", "decimal_digits": 2, "rounding": 0, "code": "CAD", "name_plural": "Canadian dollars" }, } I want to format the output so I get it like this [{name: "US Dolloar", symbol: "$"}, {name: "Canadian Dolloar", symbol: "CA$"} ] but I'm finding it hard to do loadCurrencies() { this.http.get('assets/data/currencies.json').subscribe((response) => { this.currenciesList = response; console.log(this.currenciesList) }) } A: The following code should help you. const formattedData = Object.values(this.currenciesList).map(({ name, symbol }) => ({ name, symbol })) console.log(formattedData) A: Here is one approach: const data = { "USD": { "symbol": "$", "name": "US Dollar", "symbol_native": "$", "decimal_digits": 2, "rounding": 0, "code": "USD", "name_plural": "US dollars" }, "CAD": { "symbol": "CA$", "name": "Canadian Dollar", "symbol_native": "$", "decimal_digits": 2, "rounding": 0, "code": "CAD", "name_plural": "Canadian dollars" }, } const result = Object.values(data).map(({ name, symbol }) => ({ name, symbol })) console.log(result) A: loadCurrencies() { this.http.get('assets/data/currencies.json').subscribe((response) => { this.currenciesList = Object.values(response).map(obj => return { name: obj.name, symbol: obj.symbol }); console.log(this.currenciesList); }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/65632990", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to get access to Airbnb API? or Airbnb correct token? There are a few old, unofficial Airbnb APIs, and Airbnb is not giving access to new partners. If I get an Airbnb token to approve Airlock, I am still not able to access reservations. Maybe anyone has alternative solution? https://api.nobeds.com public string GetAirbnbAPIToken(string email, string password) { HttpClient client = new HttpClient(); var uri = new Uri("https://www.airbnb.com/api/v2/logins"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("x-airbnb-api-key", "your api key"); client.DefaultRequestHeaders.Add("x-airbnb-device-id", "111111111111111"); client.DefaultRequestHeaders.Add("user-agent", "Airbnb/19.18 AppVersion/19.18 iPhone/12.2 Type/Phone"); var credentials = new { email = email, password = password, type = "email" }; var response = client.PostAsync(uri, new StringContent(JsonConvert.SerializeObject(credentials), Encoding.UTF8, "application/json")).Result.Content; string responce = response.ReadAsStringAsync().Result; Debug.WriteLine("Airbnb responce: " + responce); //Open Airlock try { //https://www.airbnb.com/airlock?al_id=AIRLOCK_ID dynamic json = JsonConvert.DeserializeObject(responce); string airlock = Convert.ToString(json.client_error_info.airlock.airlockId); return "https://www.airbnb.com/airlock?al_id=" + airlock; } catch { } //Parse reservations try { dynamic json = JsonConvert.DeserializeObject(responce); string token = Convert.ToString(json.login.id); return Reservations(token).ToString(); } catch { return "Airbnb token error: " + responce; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/66456720", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it best to have many field in protobuf message or nested messages? I tried to find some recommendations on the web but could not find anything relevant. Let's say that I am creating a protocol buffer message that will contain a lot of fields (50+). Is it best to keep all the fields at the same level or to organize them in sub-messages? Is there any impacts on performances for one way or another? Example: message myMessage{ string field1 = 1; string field2 = 2; .... string fieldn = n; } vs message myMessage{ SubMessage1 groupedfieldsbasedonsomebusinesslogic1 = 1; SubMessage2 groupedfieldsbasedonsomebusinesslogic2 = 2; message SubMessage1{ string field1 = 1; string field2 = 2; ... string fieldx = x; } message SubMessage2{ string fieldxplus1 = x+1; ... string fieldn = n; } } I am not considering readability so much here as there are pros and cons when deserializing to have flat data or nested data. My question is really focus on the technical impacts. A: There is no "best" - everything is contextual, and only you have most of the context. However! Some minor thoughts on performance: * *a nested approach requires more objects; usually this is fine, unless your volumes are huge *a nested approach may make it easier to understand the object model and the relationships between certain parts of the data *a flat approach requires larger field numbers; field numbers 1-15 take a single byte header; field numbers 16-2047 require 2 bytes header (and so on); in reality this extra byte for a few fields is unlikely to hurt you much, and is offset by the overhead of the alternative (nested) approach: *a nested approach requires a length-prefix per sub-object, or a start/end token ("group" in the protocol); this isn't much in terms of extra size, but: * *length-prefixe requires the serializer to know the length in advance, which means either double-processing (a "compute length" sweep), or buffering; in most cases this isn't a big issue, but it may be problematic for very large sub-graphs *start/end tokens are something that google has been trying to kill, and is not well supported in all libraries (and IIRC it doesn't exist in "proto3" schemas); I still really like it though, in some cases :) protobuf-net (from the tags) supports the ability to encode arbitrary sub-data as groups, but it might be awkward if you need to x-plat later Out of all of these things, the one that I would focus on if it was me is the second one. Perhaps start with something that looks usable, and measure it for realistic data volumes; does it perform acceptably?
{ "language": "en", "url": "https://stackoverflow.com/questions/49670346", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: How can I compile the Rabbitmq-c library for iOS 5? I downloaded the source code for RabbitMQ-C from GitHub. It's written in C. Can I use this library for iOS 5 apps? How? A: I wrote a wrapper for ios5, disabled ARC, and rewrote a few vars definitions. It is all working now. :D I might write a bit more about this problem if I find the time.
{ "language": "en", "url": "https://stackoverflow.com/questions/11608243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Another way to call method without lodash? In my Meteor app, this voting function with a method call was working fine, until I included a compability script that exports lodash as var _ = runInContext(); Now I get error that _.contains is not a function. Is there another way to run this function and call without _.contains? On button click: "click [data-action='addLikes']": function (event) { event.preventDefault(); var song = Songs.findOne({_id: this._id}); upvote(song); } Server method: upvote = function(currentSong){ var user = Meteor.user(); if(!user){ return false; } if (currentSong) { if (_.contains(currentSong.voters, Meteor.userId())) { return false; } Songs.update(currentSong._id, {$addToSet: {voters: Meteor.userId()}, $inc: {likes: 1}}); } }; A: If currentSong.voters is just an array, you can go with two solutions: ES6: currentSong.voters.includes(Meteor.userId()) ES5: currentSong.voters.indexOf(Meteor.userId()) > -1 or a shorthand ~currentSong.voters.indexOf(Meteor.userId())
{ "language": "en", "url": "https://stackoverflow.com/questions/40027554", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Materialize autocomplete : Why AJAX called before entering any character? I'm using autocomplete with materialize and i'm retrieving the data with ajax call, it works fine but when i want to call ajax only after entering caracters(using onkeyup event), the drop down list will not be showing correctly !!!! Before i forget please help me to show a "NOT FOUND" in the drop down list if no data founded (because my else condition doesn't work). here is my code and thanks a lot in advance : $(document).ready(function() { var contents = $('#autocomplete-input')[0]; contents.onkeyup = function (e) { $.ajax({ type: 'GET', url: Routing.generate('crm_search_lead', {"search": $(this).val()}), success: function (response) { var contacts = {}; if (true === response.success) { var result = response.result; for (var i = 0; i < result.length; i++) { var lastName = result[i].lastName ? result[i].lastName : ''; var firstName = result[i].firstName ? result[i].firstName : ''; contacts[lastName + " " + firstName] = null; } $('input.autocomplete').autocomplete({ data: contacts, minLength: 2, }); } else { $('input.autocomplete').autocomplete({ data: { "NOT FOUND": null } }); } } }); } }); A: Hi people :) i resolve it by changing onkeyup() with focus() and it's totally logical because with onkeyup() the droplist will appear and disappear very quickly on every key entered.
{ "language": "en", "url": "https://stackoverflow.com/questions/51322776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQL merge not matched by target vs not matched by source What is the difference between NOT MATCHED BY SOURCE vs NOT MATCHED BY TARGET? For example: Does WHEN NOT MATCHED BY SOURCE mean that the records exist in the target but not in the source? - so we can delete them ? and WHEN NOT MATCHED BY TARGET - mean the records exists in the source but not in the target? so we can insert them? A: Use caution, as you may need to further qualify the WHEN NOT MATCHED BY SOURCE. For example, if the TARGET table has a column that the SOURCE does not .. and you are setting that target column during the aforementioned insert .. then you'll likely want to define that constraint: WHEN NOT MATCHED BY SOURCE AND (TARGET.SomeColumn = yada) A: WHEN NOT MATCHED BY TARGET - You should use this clause to insert new rows into the target table. The rows you insert into the table are those rows in the source table for which there are no matching rows in the target. WHEN NOT MATCHED BY SOURCE - If you want to delete a row from the target table that does not match a row in the source table A: Yow want to match target table with source table.at end your target table should be similar to source table WHEN NOT MATCHED BY SOURCE : focus on SOURCE : there is some rows in target that you don't have any equivalent for it in source table. so you should delete it. WHEN NOT MATCHED BY Target: focus on Target : there is some rows in Source that you don't have any equivalent for it in Target table. so you can insert them
{ "language": "en", "url": "https://stackoverflow.com/questions/39607333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "36" }
Q: Visual Studio crashes when attempting to read resource .txt file I am currently working on a project for my class and am running into a very confusing error. The code itself will launch the debugging window, whenever the file is not present. It simply prints the error message and continues with the rest of the code execution. However, when I try to invoke the readInventory() function (which was provided by my professor) into main() to read the inventory.txt file stated in f.open(), I keep getting an error. The .exe debug window opens for maybe a second, and then the error window with a green loading bar pops up saying the .exe stopped working. I have tried everything, moved the inventory.txt to different directories, and cannot get anything to work. Any kind of insight would be greatly appreciated! I have included the code I think is needed to fix the problem, but if more of the project is needed, let me know. readInventory() void readInventory(inventoryItem inv[], int & numberOfInvItems, int & lastOrderNum) { ifstream f; // open the inventory file f.open("inventory.txt"); if (f.fail()) { cout << "readFile:: error opening inventory.txt\n"; numberOfInvItems = READ_ERROR; return; } // read number of items from first line f >> numberOfInvItems >> lastOrderNum; // for each item, read the data for the item for (int i = 0; i < numberOfInvItems; i++) { f >> inv[i].prodCode >> inv[i].price; f.ignore(); // finished reading integer, getline() on string is next getline(f, inv[i].description); } f.close(); } main() int main(int numberOfInvItems, inventoryItem inv[], int lastOrderNum, char & option, bool orderItem2 , int lastOrderNumber, basket Order[], inventoryItem item[]) { int b = -1; const int MAX_INV_ITEMS = 10, MAX_BASKETS = 7; bool orderNumber2 = false; inventoryItem Inventory[MAX_INV_ITEMS]; basket Orders[MAX_BASKETS]; readInventory(inv, numberOfInvItems,lastOrderNum); for (int m = 0; m < numberOfInvItems; m++) { //Inventory[m].prodNum = m; Inventory[m].prodCode = inv[m].prodCode; Inventory[m].description = inv[m].description; Inventory[m].price = inv[m].price; } lastOrderNumber = lastOrderNum; while (option != 'X') { getmainOption(option, item, numberOfInvItems, Inventory, orderItem2, b, MAX_BASKETS, lastOrderNumber, Order); } system("pause"); return 0; } A: At a glance, here are some tips. Your code needs many more safety checks & small fixes: Your main function signature seems to be sus: int main(int numberOfInvItems, inventoryItem inv[], ...... .....) { } should really be int main(int argc, char *argv[]) { } Note: if this isn't your ACTUAL APPLICATION MAIN function, then do NOT call it main. Secondly, your code readInventory method should really return a bool if it was successful or not, and only return the correct values via the arguments: ie: bool readInventory(inventoryItem inv[], int& numberOfInvItems, int& lastOrderNum) { // Could not open if(f.fail()) return false; // Dont set NumberOfInvItems to READ_ERROR? WHAT DOES THAT EVEN MEAN? // ... // Successful return true; } and in your main function int main(...) { int numberOfInvItems = 0; int lastOrderNum = 0; // Ensure it was successful via the return type if(readInventory(inv, numberOfInvItems,lastOrderNum)) { // ALL VALUES WEOULD BE VALID HERE for(int i = 0; i < numberOfInvItems; ++i) { // ... } } } Thirdly, my opinion is to avoid using C arrays. I'd suggest swapping them to std::vectors, or at least, a std::array to help reduce possible bugs. Finally, in your for loop: for (int m = 0; m < numberOfInvItems; m++) { //Inventory[m].prodNum = m; Inventory[m].prodCode = inv[m].prodCode; Inventory[m].description = inv[m].description; Inventory[m].price = inv[m].price; } Have you verified, or FORCED both Inventory[] and inv[] to be the same size? what if one size is larger than the other - it WILL crash. Either iterate to the smallest of either one, or dont iterate at all. You should add debugging (std::couts or printf's) after each line to see where it crashes specifically. Debug Debug Debug. You can then determine what line / function / expression caused the problem. If it crashes and no debugging was printed at all, then its probably due to your dodgy main function.
{ "language": "en", "url": "https://stackoverflow.com/questions/52999997", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: python Iris in linux I just started using Iris, (and also Mac OS), and installed other modules using pip install module_name over the terminal. I did the same for Iris, but when I try to use: import iris.plot as iplt an error came up: ImportError: No module named plot Did 'pip install' do an incomplete job? Am I missing something? I tried installing Iris from source and due to my lack of experience with unix base installation (I mean, using terminal), I failed and confused. It has been a frustrating day. Any suggestion? A: There is no iris package in the pypi. If you have iris correctly installed then it should find the plot module irrespective of whether your dependencies are correctly installed or not. The following gives guidance on installing iris on the Mac OS: https://github.com/SciTools/installation-recipes/tree/master/osx10.9 A: If I'm not mistaken, you can't import a function as something else, only modules. If you want to import just plot, do from iris import plot A: I'd thoroughly recommend installing Iris through Conda (or Anaconda if you already have it). Once you have conda installed, it should be as simple as doing a: conda install -c rsignell iris We are working on formalising and automating the build process, and once that is complete, it should be a matter of using the "scitools" (maintained by the developers of Iris) channel as such: conda install -c scitools iris (The latter may not work just yet though) This will work for Linux and Mac (and apparently Windows). If this does not work for you, then it is a bug, and is probably best addressed in the Iris google group (a thread already exists). HTH
{ "language": "en", "url": "https://stackoverflow.com/questions/25539287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Continuously reading java WatchEvents I'm trying to synchronize two folders and their sub directories between a client and a server. I have a modified version of this class which I've posted below. In my Client class, I create a WatchDir object and call its processEvents() method in an infinite loop. The method returns a myTuple object (a struct containing the event type and a path object) if an event is registered and null if not. The problem is that this only seems to work for the first event to happen in the directory (i.e. if I add a file to the watched folder, my WatchDir object.processEvents() returns one Tuple with an ENTRY_CREATE event and never returns another Tuple for other file additions/deletions/modifications that happen after). I'd like for processEvents to be continuously called (hence the infinite while) returning a Tuple each time some event occurs. My modified WatchDir: import static java.nio.file.StandardWatchEventKinds.*; import static java.nio.file.LinkOption.*; import java.nio.file.attribute.*; import java.io.*; import java.util.*; import java.util.concurrent.TimeUnit; public class WatchDir { private final WatchService watcher; private final Map<WatchKey,Path> keys; private final boolean recursive; private boolean trace = false; public WatchDir(Path dir, boolean recursive) throws IOException { this.watcher = FileSystems.getDefault().newWatchService(); this.keys = new HashMap<WatchKey,Path>(); //holds the key for each subdirectory this.recursive = true; registerAll(dir); } public void registerAll(Path start) throws IOException { Files.walkFileTree(start, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { register(dir); return FileVisitResult.CONTINUE; } }); } public void register(Path dir) throws IOException { WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); keys.put(key, dir); } public myTuple processEvents() { WatchKey key; //while (true) { try { key = watcher.take(); } catch (InterruptedException e) { return new myTuple("INTERRUPTED", null); } Path dir = keys.get(key); //get next subdirectory path if (dir == null) return new myTuple("NULL DIRECTORY", null); for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind kind = event.kind(); WatchEvent<Path> ev = cast(event); Path name = ev.context(); Path child = dir.resolve(name); return new myTuple(event.kind().name(), child); } return null; //} } @SuppressWarnings("unchecked") static <T> WatchEvent<T> cast(WatchEvent<?> event) { return (WatchEvent<T>)event; } } My Client: import java.nio.file.attribute.*; import java.nio.file.*; import java.util.concurrent.TimeUnit; public class newClient { public static void main(String[] args) throws IOException { Path folder = Paths.get(System.getProperty("user.dir")); WatchDir watcher = new WatchDir(folder, true); myTuple thisTuple; while (true) { thisTuple = watcher.processEvents(); String event = thisTuple.getEvent(); Path path = thisTuple.getPath(); System.out.println(event+": "+path.toString()); } } } A: You don't reset the key. Read the docs again: Once the events have been processed the consumer invokes the key's reset method to reset the key which allows the key to be signalled and re-queued with further events. Probably here for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind kind = event.kind(); WatchEvent<Path> ev = cast(event); Path name = ev.context(); Path child = dir.resolve(name); return new myTuple(event.kind().name(), child); } key.reset(); return null;
{ "language": "en", "url": "https://stackoverflow.com/questions/27327860", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I loop-insert incremental dates into MySQL? How can I add rows to a table with only SQL that loops and increments a date e.g.: INSERT INTO my_table (the_date) VALUES ('2013-04-13'); INSERT INTO my_table (the_date) VALUES ('2013-04-14'); INSERT INTO my_table (the_date) VALUES ('2013-04-15'); INSERT INTO my_table (the_date) VALUES ('2013-04-16'); ... I need to insert a row for every day from 2013-05-07 for the next e.g. 1000 days. A: Something like this will do it:- INSERT INTO my_table (the_date) SELECT ADDDATE('2013-04-13', INTERVAL SomeNumber DAY) FROM (SELECT a.i+b.i*10+c.i*100+d.i*1000 AS SomeNumber FROM integers a, integers b, integers c, integers d) Sub1 WHERE SomeNumber BETWEEN 0 AND 1000 Relies on a table called integers with a single column called i with 10 rows, values from 0 to 9. The Between clause is just there so you can limit the range of numbers to add to the date A: Try this code: $starDate = new DateTime('2013-05-07'); for ($i=0; $i < 1000; $i++) { $consulta ="INSERT INTO my_table (the_date) VALUES ('".date_format($starDate, 'Y-m-d')."');"; $starDate = date_add($starDate, date_interval_create_from_date_string('1 days')); echo $consulta."</br>"; //try somthing like mysqli_query($consulta); } With php and mysqli....you can do this with pure sql too ;) I give you this way to do. Saludos ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/15204767", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to send task to exchange rather then queue in celery python What I understood from celery's documentations, when publishing tasks, you send them to exchange first and then exchange delegates it to queues. Now I want to send a task to specific custom made exchange which will delegate all tasks it receives to 3 different queues, which will have different consumers in the background, performing different tasks. class Tasks(object): def __init__(self, config_object={}): self.celery = Celery() self.celery.config_from_object(config_object) self.task_publisher = task_publisher def publish(self, task_name, job_id=None, params={}): if not job_id: job_id = uuid.uuid4() self.celery.send_task(task_name, [job_id, params], queue='new_queue') class config_object(object): CELERY_IGNORE_RESULT = True BROKER_PORT = 5672 BROKER_URL = 'amqp://guest:guest@localhost' CELERY_RESULT_BACKEND = 'amqp' tasks_service = Tasks(config_object) tasks_service.publish('logger.log_event', params={'a': 'b'}) This is how I can send a task to specific queue, if I Dont define the queue it gets sent to a default one, but my question is how do I define the exchange to send to? A: not sure if you have solved this problem. i came across the same thing last week. I am on Celery 4.1 and the solution I came up with was to just define the exchange name and the routing_key so in your publish method, you would do something like: def publish(self, task_name, job_id=None, params={}): if not job_id: job_id = uuid.uuid4() self.celery.send_task( task_name, [job_id, params], exchange='name.of.exchange', routing_key='*' )
{ "language": "en", "url": "https://stackoverflow.com/questions/46341805", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SMT let expression binding scope I'm using a simple let expression to shorten my SMT formula. I want bindings to use previously defined bindings as follows, but if I remove the commented line and have n refer to s it doesn't work: ;;;;;;;;;;;;;;;;;;;;; ; ; ; This is our state ; ; ; ;;;;;;;;;;;;;;;;;;;;; (declare-datatypes ((State 0)) (((rec (myArray String) (index Int)))) ) ;;;;;;;;;;;;;;;;;;;;;;;;;; ; ; ; This is our function f ; ; ; ;;;;;;;;;;;;;;;;;;;;;;;;;; (define-fun f ((in State)) State (let ( (s (myArray in)) (n (str.len (myArray in)))) ;;;;;;;;;;(n (str.len s))) in (rec (str.substr s 1 n) 1733)) ) I looked at the documentation here, and it's not clear whether it's indeed forbidden to have bindings refer to other (previously defined) bindings: The whole let construct is entirely equivalent to replacing each new parameter by its expression in the target expression, eliminating the new symbols completely (...) I guess it's a "shallow" replacement? A: From Section 3.6.1 of http://smtlib.cs.uiowa.edu/papers/smt-lib-reference-v2.6-r2017-07-18.pdf: Let. The let binder introduces and defines one or more local variables in parallel. Semantically, a term of the form (let ((x1 t1) Β· Β· Β· (xn tn)) t) (3.3) is equivalent to the term t[t1/x1, . . . , tn/xn] obtained from t by simultaneously replacing each free occurrence of xi in t by ti , for each i = 1, . . . , n, possibly after a suitable renaming of t’s bound variables to avoid capturing any variables in t1, . . . , tn. Because of the parallel semantics, the variables x1, . . . , xn in (3.3) must be pairwise distinct. Remark 3 (No sequential version of let). The language does not have a sequential version of let. Its effect is achieved by nesting lets, as in (let ((x1 t1)) (let ((x2 t2)) t)). As indicated in Remark 3, if you want to refer to an earlier definition you have to nest the let-expressions.
{ "language": "en", "url": "https://stackoverflow.com/questions/56235909", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does this twitter oauth API token request fail [Note: all oauth tokens/secrets below were created randomly; they are NOT my actual tokens/secrets] curl -o /tmp/test.txt 'https://api.twitter.com/oauth/request_token? oauth_timestamp=1345141469& consumer_key=UEIUyoBjBRomdvrVcUTn&oauth_access_token_secret=YePiEkSDFdYAOgscijMCazcSfBflykjsEyaaVbuJeO&oauth_access_token=47849378%2drZlzmwutYqGypbLsQUoZUsGdDkVVRkjkOkSfikNZC&oauth_nonce=1345141469& consumer_secret=rUOeZMYraAapKmXqYpxNLTOuGNmAQbGFqUEpPRlW& oauth_version=1%2e0& oauth_signature_method=HMAC%2dSHA1&oauth_signature=H0KLLecZNAAz%2bXoyrPRiUs37X3Zz%2bAcabMa5M4oDLkM' [I added newlines for clarity; actual command is one single line] Assuming all the other data is valid, why does the command above yield "Failed to validate oauth signature and token" (even when I use my real data)? In particular, is my signature "H0KLLecZNAAz%2bXoyrPRiUs37X3Zz%2bAcabMa5M4oDLkM" invalid, or am I doing something more fundamentally wrong. The program I used to generate this: #!/bin/perl use Digest::SHA; %twitter_auth_hash = ( "oauth_access_token" => "47849378-rZlzmwutYqGypbLsQUoZUsGdDkVVRkjkOkSfikNZC", "oauth_access_token_secret" => "YePiEkSDFdYAOgscijMCazcSfBflykjsEyaaVbuJeO", "consumer_key" => "UEIUyoBjBRomdvrVcUTn", "consumer_secret" => "rUOeZMYraAapKmXqYpxNLTOuGNmAQbGFqUEpPRlW" ); # if uncommented, pull my actual data # require "bc-private.pl"; $twitter_auth_hash{"oauth_signature_method"} = "HMAC-SHA1"; $twitter_auth_hash{"oauth_version"} = "1.0"; $twitter_auth_hash{"oauth_timestamp"} = time(); $twitter_auth_hash{"oauth_nonce"} = time(); for $i (keys %twitter_auth_hash) { push(@str,"$i=".urlencode($twitter_auth_hash{$i})); } $str = join("&",@str); # thing to sign $url = "GET $str"; # signing it $sig = urlencode(Digest::SHA::hmac_sha256_base64($url, "rUOeZMYraAapKmXqYpxNLTOuGNmAQbGFqUEpPRlW&YePiEkSDFdYAOgscijMCazcSfBflykjsEyaaVbuJeO")); # full URL incl sig $furl = "https://api.twitter.com/oauth/request_token?$str&oauth_signature=$sig"; # system("curl -o /tmp/testing.txt '$furl'"); print "FURL: $furl\n"; print "STR: $str\n"; print "SIG: $sig\n"; sub urlencode { my($str) = @_; $str=~s/([^a-zA-Z0-9])/"%".unpack("H2",$1)/iseg; $str=~s/ /\+/isg; return $str; } Note: I realize there are many other possible reasons this is failing, but current question is: am I sending the parameters correctly and am I computing the signature correctly. A: Twitter asks that you do a POST for the request token.
{ "language": "en", "url": "https://stackoverflow.com/questions/11993423", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Multiple accessors for same value in c# I have simple scenario where I have AnotherTest value based on Test value. This works fine most of the time so that whenever I provide Test I am sure to get AnotherTest easily. public sealed class Transaction { public string Test { get;set; } public string AnotherTest{ get { int indexLiteryS = Test.IndexOf("S"); return Test.Substring(indexLiteryS, 4); } } } However I wanted to be able to also set AnotherTest value and be able to read it without having to provide Test value. Is this possible? So kinda 2 types of get based which way it was set. I know I could create 3rdTest but I have some methods that use AnotherTest and other fields and I would have to write overloads of that methods. Edit: I read some file supplied by bank. I cut it in pieces put some stuff in Test value and every other field (AnotherTest and similar) of the Transaction gets filled automatically. However later on I would like to read Transaction from SQL that is already in nice format so I don't need to provide Test to get the rest of the fields. I would like to set those fields with set and then be able to use get without setting Test value. A: Yes, like so: public string Test { get; set; } public string AnotherTest { get { if(_anotherTest != null || Test == null) return _anotherTest; int indexLiteryS = Test.IndexOf("S") return Test.Substring(indexLiteryS, 4); } set { _anotherTest = value; } } private string _anotherTest; That getter could also be expressed as return (_anotherTest != null || Test == null) ? _anotherTest : Test.Substring(Test.IndexOf("S"), 4); A: I think this would do what you want it to do: public sealed class Transaction { public string Test { get;set; } public string AnotherTest{ get { if (_anotherTest != null) { return _anotherTest; } else { int indexLiteryS = Test.IndexOf("S"); return Test.Substring(indexLiteryS, 4); } } set { _anotherTest = value; } } private string _anotherTest = null; } A: I would suggest turning the problem over. It sounds like you're dealing with a big field and subfields within it. Instead, how about promoting those subfields to fields and constructing/deconstructing the big field when it's accessed.
{ "language": "en", "url": "https://stackoverflow.com/questions/10092883", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why is the Typescript type checker upset about this unspecified type? I have a react component whose props * *need to be serialized / stored, and *contain a function My storage utility doesn't like storing functions, and I don't need the functions stored. So I wrote a function that returns a copy of the props object without the function component: /** * Removes functions from the components props, so that the props can be pouched */ strippedProps(): Object { let strippedProps: Object = {}; Object.keys(this.props).forEach((key) => { let prop: any = this.props[key]; if (typeof (prop) != 'function') { strippedProps[key] = prop; } }) return strippedProps; } TS is angrily underlining, which I'm confused about, because prop here has specifically been declared as any. Why is TS unsatisfied with the first error (warning) here? How could I refactor in order to keep the compiler happy and meet the need of generating this dynamic object? A: Index signature is missing on this.props' type. Indexable Types Similarly to how we can use interfaces to describe function types, we can also describe types that we can β€œindex into” like a[10], or ageMap["daniel"]. Indexable types have an index signature that describes the types we can use to index into the object, along with the corresponding return types when indexing. Let’s take an example: To fix it, you'd need to tell Typescript that this.props' object type has strings as keys: interface QuestionViewProps { ... your definition, [key: string]: myType, } Second options is to just suppress the warning via "suppressImplicitAnyIndexErrors": true. Third options is to cast to , which wouldn't be type-safe anymore: let prop: any = (<any>this.props)[key];
{ "language": "en", "url": "https://stackoverflow.com/questions/44460453", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: passing array of json objects from php to android I'm trying pass an array of data from php to android through json object. But im getting "Parse error: syntax error".Please help me out.thanx ' //db details $dbhost="localhost"; $dbuser="root"; $dbpass=""; $dbdb="opac"; //connecting to the db $con=mysql_connect($dbhost, $dbuser, $dbpass) or die("connection error"); //selecting the db mysql_select_db($dbdb) or die("db selecction error"); $stk=$_POST[β€˜stock’]; $query=mysql_query("SELECT Title FROM books WHERE Stock>’$stk’”); if(!$query) { die('Could not get data: ' . mysql_error()); } $index=0; while($row = mysql_fetch_array($query, MYSQL_ASSOC)) { $output[$index]=$row; $index++; } echo json_encode($output); mysql_close(); ?> corresponding android file is....with the parsing error when the android file is executed it shows "unfortunately, has stopped" public class BooksActivity extends ListActivity { HttpClient httpclient; HttpPost httppost; ArrayList<NameValuePair> namevaluepairs; HttpResponse httpresponse; HttpEntity httpentity; ArrayList<NameValuePair> nameValuePairs; InputStream is; String result = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); setContentView(R.layout.activity_books); nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("stock","5")); //httppost try{ httpclient = new DefaultHttpClient(); httppost = new HttpPost("http://10.0.2.2:80/books.php"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httpresponse = httpclient.execute(httppost); httpentity = httpresponse.getEntity(); is = httpentity.getContent(); } catch(Exception e){ // Log.e("log_tag", "Error in http connection "+e.toString()); Toast.makeText(getBaseContext(), "http post error"+e, Toast.LENGTH_SHORT ).show(); } //result conversion try{ BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result=sb.toString(); } catch(Exception e){ //Log.e("log_tag", "Error in converting result "+e.toString()); Toast.makeText(getBaseContext(), "result conversion error"+e, Toast.LENGTH_SHORT ).show(); } //parsing json data try{ String[] returnString = new String[100]; JSONArray jArray = new JSONArray(result); ListView listView = (ListView) findViewById(R.id.list); for(int i=0;i<jArray.length();i++){ JSONObject json_data = jArray.getJSONObject(i); returnString[i] = json_data.getString("Title"); } ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.list, returnString); listView.setAdapter(adapter); }catch(JSONException e){ //Log.e("log_tag", "Error parsing data "+e.toString()); Toast.makeText(getBaseContext(), "parsing error"+e, Toast.LENGTH_SHORT ).show(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_books, menu); return true; } } A: Are you using backticks here? $stk=$_POST[β€˜stock’]; They need to be quote marks $stk=$_POST['stock']; Also this line has an utf-8 fancy-quote $query=mysql_query("SELECT Title FROM books WHERE Stock>`$stk”); which should be an ascii quote $query=mysql_query("SELECT Title FROM books WHERE Stock>$stk"); These are common errors when you copy code from blogs ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/15522070", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sender object ID in aspx client side event (javascript) I need help regarding a problem in the following code block: function(s, e) { form1.hfRaiseEvent.value = s.ID; } This function is called when the Client Side Click Event is fired. By the way i see it, s is the Sender Object while e is the Event Object. After iterating through the members of the Sender object i found in a forum post, i saw the .ID member which is supposed to return the id of the sender. The problem is that the string i get from this is the following: "undefined" No exceptions, just that string. Some extra info: * *I also tried e.target.id which was supposed to do the same as s.ID . Got the same result though. *fhRaiseEvent is a hidden field in which i store the ID of the control that raises the event. *The control that calls this function when clicked is a Devexpress ASPxEditor. Need some help with this. Thanks in advance. A: Got the answer from the Devexpress Team I can actually use pEditRefreshSum.JSProperties("cpID") = pEditRefreshSum.ID; to set the ID into a custom Property and then get it on js using the following line: form1.hfRaiseEvent.value = s.cpID; in order to get the ID Thanks for your replies. A: I don't think you have assigned anything to the ID of the ASPxEdit. It is null by default. You have to explicitly assign an ID. The ID property is inherited from System.Web.Control. See the MSDN documentation.
{ "language": "en", "url": "https://stackoverflow.com/questions/18105484", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Exception handling for regular expressions in R I've found several related questions, but haven't found one that I solves my problem yet, please let me know if I'm missing a question that addresses this. Essentially I want to use a regular expression to find a pattern but with an exception based on the preceding characters. For example, I have the following text object ("muffins") as a vector and I want to match the names ("Sarah","Muffins", and "Bob").: muffins [1] "Dear Sarah," [2] "I love your dog, Muffins, who is adorable and very friendly. However, I cannot say I enjoy the \"muffins\" he regularly leaves in my front yard. Please consider putting him on a leash outside and properly walking him like everyone else in the neighborhood." [3] "Sincerely," [4] "Bob" My approach was the search for capitalized words and then exclude words capitalized for grammatical reasons, such as the beginning of a sentence. pattern = "\\b[[:upper:]]\\w+\\b" m = gregexpr(pattern,muffins) regmatches(muffins,m) This pattern gets me most of the way, returning: [[1]] [1] "Dear" "Sarah" [[2]] [1] "Muffins" "However" "Please" [[3]] [1] "Sincerely" [[4]] [1] "Win" and I can identify some of the sentence beginnings with: pattern2 = "[.]\\s[[:upper:]]\\w+\\b" m = gregexpr(pattern2,muffins) regmatches(muffins,m) but I can't seem to do both simultaneously, where I say I want pattern where pattern2 is not the case. I've tried several combinations that I thought would work, but with little success. A few of the ones I tried: pattern2 = "(?<![.]\\s[[:upper:]]\\w+\\b)(\\b[[:upper:]]\\w+\\b)" pattern2 = "(^[.]\\s[[:upper:]]\\w+\\b)(\\b[[:upper:]]\\w+\\b)" Any advice or insight would be greatly appreciated! A: You maybe looking for a negative look-behind. pattern = "(?<!\\.\\s)\\b[[:upper:]]\\w+\\b" m = gregexpr(pattern,muffins, perl=TRUE) regmatches(muffins,m) # [[1]] # [1] "Dear" "Sarah" # # [[2]] # [1] "Muffins" # # [[3]] # [1] "Sincerely" # # [[4]] # [1] "Bob" The look behind part (?<!\\.\\s) makes sure there's not a period and a space immediately before the match. A: The below regex would match only the names Bob, Sarah and Muffins, (?<=^)[A-Z][a-z]+(?=$)|(?<!\. )[A-Z][a-z]+(?=,[^\n])|(?<= )[A-Z][a-z]+(?=,$) DEMO A: Trying to use regular expressions to identify names becomes a problem. There is no hope of working reliably. It is very complicated to match names from arbitrary data. If extracting these names is your goal, you need to approach this in a different way instead of simply trying to match an uppercase letter followed by word characters. Considering your vector is as you posted in your question: x <- c('Dear Sarah,', 'I love your dog, Muffins, who is adorable and very friendly. However, I cannot say I enjoy the "muffins" he regularly leaves in my front yard. Please consider putting him on a leash outside and properly walking him like everyone else in the neighborhood.', 'Sincerely', 'Bob') m = regmatches(x, gregexpr('(?<!\\. )[A-Z][a-z]{1,7}\\b(?! [A-Z])', x, perl=T)) Filter(length, m) # [[1]] # [1] "Sarah" # [[2]] # [1] "Muffins" # [[3]] # [1] "Bob"
{ "language": "en", "url": "https://stackoverflow.com/questions/24816441", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Is it possible to use SSE and SSE2 to make a 128-bit wide integer? I'm looking to understand SSE2's capabilities a little more, and would like to know if one could make a 128-bit wide integer that supports addition, subtraction, XOR and multiplication? A: SIMD is meant to work on multiple small values at the same time, hence there won't be any carry over to the higher unit and you must do that manually. In SSE2 there's no carry flag but you can easily calculate the carry as carry = sum < a or carry = sum < b like this. Worse yet, SSE2 doesn't have 64-bit comparisons either, so you must use some workaround like the one here Here is an untested, unoptimized C code based on the idea above: inline bool lessthan(__m128i a, __m128i b){ a = _mm_xor_si128(a, _mm_set1_epi32(0x80000000)); b = _mm_xor_si128(b, _mm_set1_epi32(0x80000000)); __m128i t = _mm_cmplt_epi32(a, b); __m128i u = _mm_cmpgt_epi32(a, b); __m128i z = _mm_or_si128(t, _mm_shuffle_epi32(t, 177)); z = _mm_andnot_si128(_mm_shuffle_epi32(u, 245),z); return _mm_cvtsi128_si32(z) & 1; } inline __m128i addi128(__m128i a, __m128i b) { __m128i sum = _mm_add_epi64(a, b); __m128i mask = _mm_set1_epi64(0x8000000000000000); if (lessthan(_mm_xor_si128(mask, sum), _mm_xor_si128(mask, a))) { __m128i ONE = _mm_setr_epi64(0, 1); sum = _mm_add_epi64(sum, ONE); } return sum; } As you can see, the code requires many more instructions and even after optimizing it may still be much longer than a simple 2 ADD/ADC pair in x86_64 (or 4 instructions in x86) SSE2 will help though, if you have multiple 128-bit integers to add in parallel. However you need to arrange the high and low parts of the values properly so that we can add all the low parts at once, and all the high parts at once See also * *practical BigNum AVX/SSE possible? *Can long integer routines benefit from SSE?
{ "language": "en", "url": "https://stackoverflow.com/questions/12200698", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Trying to fill h:selectOneMenu when date is selected At this moment my code works but I have to select a date twice if I want to get properly information. I tried to change the ajax event to dateSelect, but it adds an hash in my URL and do nothing. I just want to keep its current behaviour, but selecting a date one single time. Thanks in advance. <h:form> <h:panelGrid columns="2"> <h:outputLabel for="medico" value="MΓ©dico:" /> <h:inputText id="medico" value="#{pacienteControlador.pacienteActual.medico.nombre} #{pacienteControlador.pacienteActual.medico.apellidos}" disabled="true"/> <p:outputLabel for="fecha" value="Fecha:" /> <p:calendar id="fecha" value="#{pacienteControlador.calendarManagedBean.date}" pattern="dd/MM/yyyy"> <f:ajax event="blur" listener="#{pacienteControlador.citasDisponibles()}" render="hora" /> </p:calendar> <p:outputLabel for="hora" value="Hora:" /> <h:selectOneMenu id="hora" value="#{pacienteControlador.horaCita}"> <f:selectItems value="#{pacienteControlador.listaHorasLibres}" /> </h:selectOneMenu> </h:panelGrid> <h:commandButton value="Crear" action="#{pacienteControlador.crearCita()}"/> </h:form> A: Solution: Use p:ajax instead f:ajax <p:ajax event="dateSelect" listener="{pacienteControlador.citasDisponibles()}" update="hora" />
{ "language": "en", "url": "https://stackoverflow.com/questions/28004526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Callback as an option in node.js I am working with node.js and how can I set callback as an option of a specific function? For example: function sum(a, b, callback) { return callback(a+b) } var result = sum(a,b) // this seems to cause error: callback is not a function sum(a, b, function(sum) { // this works fine }) Is there any way to make both of the above (with and without callback) work? Thanks! A: Simply check that the callback argument is a function. if(typeof callback === 'function'){ return callback(a+b); } Thus, your sum function can be written as : function sum(a, b, callback) { if(typeof callback === 'function'){ return callback(a+b) } else { return a+b; } } (Demo JSFiddle) A: Hi you can have your code as below function sum(a, b, callback) { if(typeof callback === 'function'){ return callback(a+b) } else { return a+b; } } which is also mentioned in the above post
{ "language": "en", "url": "https://stackoverflow.com/questions/39013197", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What does this Oracle SQL Developer icon mean on my stored procedure? I've been creating stored procedures using Oracle SQL developer. For some reason, one of the icons does not contain a green circle. What gives? What does this non-green icon mean? A: I believe the green circle you're referring to is actually a green bug icon. That indicates that the procedure has been compiled for debug. If you are editing a stored procedure in SQL Developer, there should be a gear icon at the top of the edit screen that you use to compile the procedure. If you click the arrow to expand that, you should get options to compile the procedure or to compile for debug. If you select "Compile for Debug", you'll get the green bug icon. If you select "Compile", the bug icon will go away.
{ "language": "en", "url": "https://stackoverflow.com/questions/4169355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: DatetimePicker and other Controls in MenuStrip I know I can add a DateTimePicker to my MenuStrip with the following lines Dim dp = New ToolStripControlHost(New DateTimePicker) MenuStrip1.Items.Add(dp) But I can't figure out how to add a DateTimePicker to the MenuStrip at designtime. What's the trick behind it? I have been trying and searching for like an hour and I am about to give up even though I know there has to be a way! TL;DR How do I add a DateTimePicker to my MenuStrip at design-time? Alternatively we can add it to a ToolStrip instead. A: You are close to a solution in using the ToolStripControlHost, but you will need to derive from that class as shown in the linked-to example. The frustrating thing with that example is that it does not decorate the derived class with the System.Windows.Forms.Design.ToolStripItemDesignerAvailabilityAttribute to make it available on the design surface. The following is a minimalist implementation to get a working example. You may need to override the automatic sizing to suit your needs/wants for the control. The implementation overrides the Text property to prevent designer from assigning invalid text to the underlying DateTimerPicker control. <System.Windows.Forms.Design.ToolStripItemDesignerAvailability( System.Windows.Forms.Design.ToolStripItemDesignerAvailability.ToolStrip _ Or System.Windows.Forms.Design.ToolStripItemDesignerAvailability.StatusStrip _ Or System.Windows.Forms.Design.ToolStripItemDesignerAvailability.MenuStrip)> _ Public Class TSDatePicker : Inherits ToolStripControlHost Public Sub New() MyBase.New(New System.Windows.Forms.DateTimePicker()) End Sub Public ReadOnly Property ExposedControl() As DateTimePicker Get Return CType(Control, DateTimePicker) End Get End Property <Browsable(False), EditorBrowsable(EditorBrowsableState.Advanced), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)> Public Overrides Property Text As String Get Return ExposedControl.Text End Get Set(value As String) ' verify valid date Dim dt As DateTime If DateTime.TryParse(value, dt) Then ExposedControl.Text = value End If End Set End Property End Class A: Was going to add as a comment but I trust it justifies an answer. The only way I have succeeded in this is to add one at design time (to the form) and set Visible to False and use the menu item to set Visible to True (may also need to set the position and/or bring it to the front). You do need to manually handle setting Visible to False again.
{ "language": "en", "url": "https://stackoverflow.com/questions/43469427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Need help passing survey responses from HTML form to MySQL table I'm a bit stumped here... I've got a web page that displays a list of survey questions that are stored in a db table, and I'm trying to gather ratings responses on each question (strongly disagree -> strongly agree) and pass the values back to another table in my db. Here's a snippet of the form code: <form action="submitAnswers.php" name="subAns" method="post"> <fieldset> <legend>Survey Questions</legend> <input type="hidden" name="survey_id" value="<?php echo ($survey_id); ?>"> <table width=90% border=0 cellpadding='2' cellspacing='2'?> <tr bgcolor=#D0D0D0> <th>Question</th> <th>Strongly Disagree</th> <th>Somewhat Disagree</th> <th>Neither Disagree nor Agree</th> <th>Somewhat Agree</th> <th>Strongly Agree</th> </tr> <tr> <?php while ($row = mysql_fetch_array($res, MYSQL_ASSOC)) { echo "<td bgcolor='#E8E8E8'><font size='-1'>$row[quest_order]) $row[quest_text]</font></td>"; for ($i = 0; $i < 5; $i++) { //echo "<input type='hidden' name='qID' value='$quest_id'>"; echo "<td bgcolor='#E8E8E8'><input type='radio' name='$row[quest_id]' value='$i'></td>"; } echo "</tr>"; } ?> <br> </table><br> <input type="submit" name="submitAnswers" value="Submit Survey"></fieldset> </form> And here's the PHP in the 'submitAnswers.php' file: $survey_id=$_POST['survey_id']; $sql = "INSERT INTO survey_responses (survey_id) VALUES ('$survey_id')"; $res = send_sql($sql, $link, $db); foreach($_POST['quest_id'] as $id=>$value) { $sql = "INSERT INTO survey_answers (response_id, quest_id, response_value) VALUES (LAST_INSERT_ID(), $id, '$value')"; $res = send_sql($sql, $link, $db) or die("Cannot add survey"); } My insert statement into the 'survey_responses' table works just fine, but I don't know how to correct my radio buttons used to obtain the response score for each question. The values are being passed with POST (I confirmed this by looking at print_r($_POST);, which returned, for example: Array ( [survey_id] => 4 [6] => 0 [5] => 1 [4] => 2 [3] => 3 [2] => 4 [1] => 3 [submitAnswers] => Submit Survey ) but clearly I'm going about this wrong, as I'm not able to successfully iterate through and insert the question id# and response value for each one. I'm sure this is relatively simple, but I'm still new to programming and have been going over this for hours with little to no luck. Just hoping someone can help me fix this, and hopefully in the process better explain, or point me to a good resource covering how to handle dynamically sized forms that are retrieving database records and passing various amounts of information back to the db. Thanks! A: Use $sql = "INSERT INTO survey_answers (response_id, quest_id, response_value) VALUES ('".LAST_INSERT_ID()."', '".$id."', '."$value."')"; instead $sql = "INSERT INTO survey_answers (response_id, quest_id, response_value) VALUES (LAST_INSERT_ID(), $id, '$value')"; A: Ok I think I've got this licked, though there may be a better solution. In my form, I changed the radio buttons to read as follows: echo "<td bgcolor='#E8E8E8'><input type='radio' name='quest".$row[quest_id]."' value='$i'></td>"; The only change was adding 'quest' as a prefix to the ID# in the name attribute. In my PHP file: foreach ($_POST as $name=>$value) { if (strpos($name, "quest") !== FALSE) { $qID = substr($name, 5); $sql = "INSERT INTO survey_answers (response_id, quest_id, response_value) VALUES (LAST_INSERT_ID(), '$qID', '$value')"; $res = send_sql($sql, $link, $db) or die("Cannot add survey"); } } I'm checking the post values for those with the 'quest' prefix, then extracting the id# via substr. If there's a better way I'm all ears...
{ "language": "en", "url": "https://stackoverflow.com/questions/13864458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Inspect variable outside of anonymous class in Eclipse is it possible to get the value of a final variable declared outside an anonymous class (where the debugger currently is) in Eclipse? For example: final int x = 5; new Object() { { System.out.println(x); } }; This will compile and print "5", but if I try to inspect x on the println line I get the error "x cannot be resolved to a variable". A: Expand the "this" item on Variables view; it contains variable val$x where you can see the x and it's value.
{ "language": "en", "url": "https://stackoverflow.com/questions/5195898", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to obtain the returned cookie after a POST in PHP? Let's say I have a website called (example.com) which will have a php file (example.com/call.php). call.php will have a post method that will post to the website exampleOne.com/login.php with the right parameters. exampleOne.com will return a header with a cookie that will confirm the authentication of the user, how do I obtain the cookie or at least check if the header includes Set-Cookie in order to be informed that the user is authenticated? If this is not clear enough please let me know in the comments and I will try my best to clear everything up. (UPDATE 1: so the idea is that, how do I know that the other domain I am posting to has set up the cookie because the fact that the cookie has been set up (Set-cookie != null or "") means that the username and password are in fact correct) (Update 2 so my issue is that I want to make sure that user is a member of some forum which does not have an API and I cannot authenticate to that forum because i don't have access to their records, however, that forum authenticate the user and sets a cookie if the information is right and I want to be able to see that cookie to make sure I understand that the user is authenticated - hope this helps) A: You can use this code to do what you want. Pretty much you're just simulating a client when you do this by writing a HTTP request to a page and then processing the response headers that it sends back. This is also how you would build a proxy server, but that is sort of what you're doing. Let me know if you need any help. // // OPEN SOCKET TO SERVER // $_socket = @fsockopen($host, $port, $err_no, $err_str, 30); // // SET REQUEST HEADERS // $_request_headers = '... CONSTRUCT FULL HEADERS HERE ...'; fwrite($_socket, $_request_headers); // // PROCESS RESPONSE HEADERS // $_response_headers = $_response_keys = array(); $line = fgets($_socket, 8192); while (strspn($line, "\r\n") !== strlen($line)) { @list($name, $value) = explode(':', $line, 2); $name = trim($name); $_response_headers[strtolower($name)][] = trim($value); $_response_keys[strtolower($name)] = $name; $line = fgets($_socket, 8192); } sscanf(current($_response_keys), '%s %s', $_http_version, $_response_code); if (isset($_response_headers['set-cookie'])) { // DO WHAT YOU WANT HERE } For reference, you can find similar code in PHProxy that goes into much more detail. It will create headers for you, process response headers, and more. If you find that this example doesn't do everything you need, you should reference that software.
{ "language": "en", "url": "https://stackoverflow.com/questions/3294844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: FIELDDATA Data is too large I open kibana and do a search and i get the error where shards failed. I looked in the elasticsearch.log file and I saw this error: org.elasticsearch.common.breaker.CircuitBreakingException: [FIELDDATA] Data too large, data for [@timestamp] would be larger than limit of [622775500/593.9mb] Is there any way to increase that limit of 593.9mb? A: You can try to increase the fielddata circuit breaker limit to 75% (default is 60%) in your elasticsearch.yml config file and restart your cluster: indices.breaker.fielddata.limit: 75% Or if you prefer to not restart your cluster you can change the setting dynamically using: curl -XPUT localhost:9200/_cluster/settings -d '{ "persistent" : { "indices.breaker.fielddata.limit" : "40%" } }' Give it a try. A: I meet this problem,too. Then i check the fielddata memory. use below request: GET /_stats/fielddata?fields=* the output display: "logstash-2016.04.02": { "primaries": { "fielddata": { "memory_size_in_bytes": 53009116, "evictions": 0, "fields": { } } }, "total": { "fielddata": { "memory_size_in_bytes": 53009116, "evictions": 0, "fields": { } } } }, "logstash-2016.04.29": { "primaries": { "fielddata": { "memory_size_in_bytes":0, "evictions": 0, "fields": { } } }, "total": { "fielddata": { "memory_size_in_bytes":0, "evictions": 0, "fields": { } } } }, you can see my indexes name base datetime, and evictions is all 0. Addition, 2016.04.02 memory is 53009116, but 2016.04.29 is 0, too. so i can make conclusion, the old data have occupy all memory, so new data cant use it, and then when i make agg query new data , it raise the CircuitBreakingException you can set config/elasticsearch.yml indices.fielddata.cache.size: 20% it make es can evict data when reach the memory limit. but may be the real solution you should add you memory in furture.and monitor the fielddata memory use is good habits. more detail: https://www.elastic.co/guide/en/elasticsearch/guide/current/_limiting_memory_usage.html A: Alternative solution for CircuitBreakingException: [FIELDDATA] Data too large error is cleanup the old/unused FIELDDATA cache. I found out that fielddata.limit been shared across indices, so deleting a cache of an unused indice/field can solve the problem. curl -X POST "localhost:9200/MY_INDICE/_cache/clear?fields=foo,bar" For more info https://www.elastic.co/guide/en/elasticsearch/reference/7.x/indices-clearcache.html A: I think it is important to understand why this is happening in the first place. In my case, I had this error because I was running aggregations on "analyzed" fields. In case you really need your string field to be analyzed, you should consider using multifields and make it analyzed for searches and not_analyzed for aggregations. A: I ran into this issue the other day. In addition to checking the fielddata memory, I'd also consider checking the JVM and OS memory as well. In my case, the admin forgot to modify the ES_HEAP_SIZE and left it at 1gig. A: just use: ES_JAVA_OPTS="-Xms10g -Xmx10g" ./bin/elasticsearch since the default heap is 1G, if your data is big ,you should set it bigger
{ "language": "en", "url": "https://stackoverflow.com/questions/30811046", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: UITableView - how to recognize a cancel deletion? After the classic swipe to delete, there are two possibilities, * *The user has pressed the "Delete" Button, so this function is fired: *(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath *The user has pressed outside the button, so the edit state is cancelled. Does anyone knows which function (if it exists) is fired when the editing is cancelled, or how can I catch this event? so I can do some stuff right after the deletion is cancelled. Thanks. A: When the edit state is finished, you'll know via the UITableViewDelegate method - (void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath You just need to figure out how to differentiate between a delete and a cancel. You'll know it's a delete if the data source "tableView:commitEditingStyle:forRowAtIndexPath:" method is called. If it isn't, then the user cancelled.
{ "language": "en", "url": "https://stackoverflow.com/questions/17756892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Black Matlab image after saving using saveas function I am using Matlab2007b and I would like to plot and save a 3d surface. I manage to display the figure using meshz(X,Y,Z), but when calling: saveas(gca, fullfile(path,name), 'png') or saveas(gcf, fullfile(path,name), 'png') or even using File --> Save As... in the Figure window, the resulting figure appears black when I open it. Also, I get the following warning in the console: Warning: Problems in UIW_SetUpGLPrinting In graphics\private\render at 142 In print at 267 In saveas at 159 Has anyone already experienced this issue? Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/46604914", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SSL connection issue when calling GRPC service from Alpine Linux Image using Zulu jdk 11 I have a spring boot application which calls a GRPC service using Netty. When I run my code in my local machine (MacOS and zulu jdk without JCE) I am able to connect to the GRPC service. Note: We are using Oracle JDK 1.8 compiled GRPC client jar When I build a docker image (Alpine Linux with zulu jdk without JCE) I get below error javax.net.ssl|ERROR|37|C7-services-1|2019-09-26 21:18:10.622 GMT|TransportContext.java:312|Fatal (HANDSHAKE_FAILURE): Couldn't kickstart handshaking ( "throwable" : { javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate) at java.base/sun.security.ssl.HandshakeContext.<init>(HandshakeContext.java:169) at java.base/sun.security.ssl.ClientHandshakeContext.<init>(ClientHandshakeContext.java:98) at java.base/sun.security.ssl.TransportContext.kickstart(TransportContext.java:216) at java.base/sun.security.ssl.SSLEngineImpl.beginHandshake(SSLEngineImpl.java:103) at io.netty.handler.ssl.JdkSslEngine.beginHandshake(JdkSslEngine.java:155) at io.netty.handler.ssl.SslHandler.handshake(SslHandler.java:1967) at io.netty.handler.ssl.SslHandler.startHandshakeProcessing(SslHandler.java:1886) at io.netty.handler.ssl.SslHandler.channelActive(SslHandler.java:2021) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:225) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:211) at io.netty.channel.AbstractChannelHandlerContext.fireChannelActive(AbstractChannelHandlerContext.java:204) at io.netty.channel.DefaultChannelPipeline$HeadContext.channelActive(DefaultChannelPipeline.java:1396) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:225) at io.netty.channel.AbstractChannelHandlerContext.invokeChannelActive(AbstractChannelHandlerContext.java:211) at io.netty.channel.DefaultChannelPipeline.fireChannelActive(DefaultChannelPipeline.java:906) at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.fulfillConnectPromise(AbstractNioChannel.java:311) at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.finishConnect(AbstractNioChannel.java:341) at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:670) at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:617) at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:534) at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:496) at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:906) at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) at java.base/java.lang.Thread.run(Thread.java:834)} ) I see that on my local below cipher suites are present * TLS_AES_128_GCM_SHA256 * TLS_AES_256_GCM_SHA384 * TLS_DHE_DSS_WITH_AES_128_CBC_SHA * TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 * TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 * TLS_DHE_DSS_WITH_AES_256_CBC_SHA * TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 * TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 * TLS_DHE_RSA_WITH_AES_128_CBC_SHA * TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 * TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 * TLS_DHE_RSA_WITH_AES_256_CBC_SHA * TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 * TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 * TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA * TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 * TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 * TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA * TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 * TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 * TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA * TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 * TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 * TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA * TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 * TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 * TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA * TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 * TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 * TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA * TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 * TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 * TLS_ECDH_RSA_WITH_AES_128_CBC_SHA * TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 * TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 * TLS_ECDH_RSA_WITH_AES_256_CBC_SHA * TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 * TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 * TLS_EMPTY_RENEGOTIATION_INFO_SCSV * TLS_RSA_WITH_AES_128_CBC_SHA * TLS_RSA_WITH_AES_128_CBC_SHA256 * TLS_RSA_WITH_AES_128_GCM_SHA256 * TLS_RSA_WITH_AES_256_CBC_SHA * TLS_RSA_WITH_AES_256_CBC_SHA256 * TLS_RSA_WITH_AES_256_GCM_SHA384 and in the image i see very few * TLS_AES_128_GCM_SHA256 * TLS_AES_256_GCM_SHA384 * TLS_DHE_DSS_WITH_AES_128_CBC_SHA * TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 * TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 * TLS_DHE_DSS_WITH_AES_256_CBC_SHA * TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 * TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 * TLS_DHE_RSA_WITH_AES_128_CBC_SHA * TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 * TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 * TLS_DHE_RSA_WITH_AES_256_CBC_SHA * TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 * TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 * TLS_EMPTY_RENEGOTIATION_INFO_SCSV * TLS_RSA_WITH_AES_128_CBC_SHA * TLS_RSA_WITH_AES_128_CBC_SHA256 * TLS_RSA_WITH_AES_128_GCM_SHA256 * TLS_RSA_WITH_AES_256_CBC_SHA * TLS_RSA_WITH_AES_256_CBC_SHA256 * TLS_RSA_WITH_AES_256_GCM_SHA384 Note: BTW on my local it is choosing TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 I downgraded my java version to Oracle JDK 1.8 and built the image also with JDK 1.8. Now i was able to resolve the issue with SSL handshake as I can see all the ciphers now available within the image. However I ended up with an issue which is very Alpine Linux. Caused by: java.lang.IllegalStateException: Could not find TLS ALPN provider; no working netty-tcnative, Conscrypt, or Jetty NPN/ALPN available at io.grpc.netty.GrpcSslContexts.defaultSslProvider(GrpcSslContexts.java:258) ~[grpc-netty-1.16.1.jar:1.16.1] at io.grpc.netty.GrpcSslContexts.configure(GrpcSslContexts.java:171) ~[grpc-netty-1.16.1.jar:1.16.1] at io.grpc.netty.GrpcSslContexts.forClient(GrpcSslContexts.java:120) ~[grpc-netty-1.16.1.jar:1.16.1] at com.samsclub.list.core.client.C7ProductCatalogProvider.createChannel(C7ProductCatalogProvider.java:104) ~[sams-list-core-0.0.10-SNAPSHOT.jar:0.0.10-SNAPSHOT] at com.samsclub.list.core.client.C7ProductCatalogProvider.init(C7ProductCatalogProvider.java:59) ~[sams-list-core-0.0.10-SNAPSHOT.jar:0.0.10-SNAPSHOT] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_212] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:1.8.0_212] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:1.8.0_212] at java.lang.reflect.Method.invoke(Method.java:498) ~[?:1.8.0_212] at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:363) ~[spring-beans-5.1.7.RELEASE.jar:5.1.7.RELEASE] at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMet see this https://github.com/grpc/grpc-java/issues/3336 I really want to be on zulu 11 and wants to call this GRPC service. Should we just get the GRPC client jar compiled with JDK 11.? My Docker Alpine image config /app # cat /etc/os-release NAME="Alpine Linux" ID=alpine VERSION_ID=3.10.0 PRETTY_NAME="Alpine Linux v3.10" HOME_URL="https://alpinelinux.org/" BUG_REPORT_URL="https://bugs.alpinelinux.org/" /app # java -version openjdk version "11.0.4" 2019-07-16 LTS OpenJDK Runtime Environment Zulu11.33+15-CA (build 11.0.4+11-LTS) OpenJDK 64-Bit Server VM Zulu11.33+15-CA (build 11.0.4+11-LTS, mixed mode) A: What do you mean by saying zulu jdk without JCE? Official zulu jdk is provided with all required crypto libraries and providers. In case of you manually exclude some of the providers or libraries you'll miss corresponding functionality. For example SunEC crypto provider is responsible for ECDSA and ECDH algorithms implementation. Excluding SunEC from the list of providers or disabling/removing jdk.crypto.ec module, you'll miss all TLS_ECDH_ECDSA_* TLS_ECDHE_ECDSA_* cipher suites. It could be a reason of your TLS handshake failure. A: Clean alpine docker image with Zulu 11 jdk shows the following: $ docker run alpn_zulu more /etc/os-release NAME="Alpine Linux" ID=alpine VERSION_ID=3.10.2 PRETTY_NAME="Alpine Linux v3.10" HOME_URL="https://alpinelinux.org/" BUG_REPORT_URL="https://bugs.alpinelinux.org/" $ docker run alpn_zulu java -version openjdk version "11.0.4" 2019-07-16 LTS OpenJDK Runtime Environment Zulu11.33+15-CA (build 11.0.4+11-LTS) OpenJDK 64-Bit Server VM Zulu11.33+15-CA (build 11.0.4+11-LTS, mixed mode) $ docker run alpn_zulu jrunscript -e "java.util.Arrays.asList(javax.net.ssl.SSLServerSocketFactory.getDefault().getSupportedCipherSuites()).stream().forEach(println)" Warning: Nashorn engine is planned to be removed from a future JDK release TLS_AES_128_GCM_SHA256 TLS_AES_256_GCM_SHA384 TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 TLS_RSA_WITH_AES_256_GCM_SHA384 TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 TLS_RSA_WITH_AES_128_GCM_SHA256 TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 TLS_RSA_WITH_AES_256_CBC_SHA256 TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA TLS_RSA_WITH_AES_256_CBC_SHA TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA TLS_ECDH_RSA_WITH_AES_256_CBC_SHA TLS_DHE_RSA_WITH_AES_256_CBC_SHA TLS_DHE_DSS_WITH_AES_256_CBC_SHA TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 TLS_RSA_WITH_AES_128_CBC_SHA256 TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA TLS_RSA_WITH_AES_128_CBC_SHA TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA TLS_ECDH_RSA_WITH_AES_128_CBC_SHA TLS_DHE_RSA_WITH_AES_128_CBC_SHA TLS_DHE_DSS_WITH_AES_128_CBC_SHA TLS_EMPTY_RENEGOTIATION_INFO_SCSV
{ "language": "en", "url": "https://stackoverflow.com/questions/58125872", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding tabs on clicking button How can I add a new tab in TabBar by clicking on a button? I tried to call 'setState' in order to add a new tab. class _MyHomeState extends State<MyHome> { final List<Tab> _tabs = [ Tab( child: Text("tab 1"), ), Tab( child: Text("tab 2"), ) ]; int _length = 2; final List<Widget> _tabBarView = [ Icon(Icons.ac_unit), Icon(Icons.access_alarm) ]; @override Widget build(BuildContext context) { return DefaultTabController( length: _length, child: Scaffold( appBar: AppBar( title: Text("New"), actions: <Widget>[ IconButton( icon: Icon(Icons.add), onPressed: () { setState(() { _tabs.add( Tab( child: Text("another"), ), ); _tabBarView.add( Icon(Icons.access_alarms), ); _length = _tabs.length; }); }, ), ], bottom: TabBar( tabs: _tabs, ), ), body: TabBarView( children: _tabBarView, ), ), ); } } By doing so, got an error message, RangeError (index): Invalid value: Not in range 0..1, inclusive: 2 A: You need minor tweaking in your code: change: bottom: TabBar( tabs: _tabs, ), ), body: TabBarView( children: _tabBarView, ), to bottom: TabBar( tabs: _tabs.toList(), // Creates a [List] containing the elements of this [Iterable]. ), ), body: TabBarView( children: _tabBarView.toList(), // Creates a [List] containing the elements of this [Iterable]. ),
{ "language": "en", "url": "https://stackoverflow.com/questions/57459037", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Premature end of POST data - Ajax with FormData is Broken on IE10 / IE11 in Some Conditions I have a JSP application. Wherein a set of data will be sent to an JSP using AJAX request. The issue is, I am getting an error when a data is sent to the JSP in Internet Explorer 11. Whereas it properly works in IE9. IllegalStateException - IOException: Premature end of POST data I couldn't find answers in google, as well as i couldn't reveal the code as its proprietary. Request Class: request EvermindHttpServletRequest response EvermindHttpServletResponse pageContext EvermindPageContext session EvermindHttpSession
{ "language": "en", "url": "https://stackoverflow.com/questions/25604906", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to create components (labels) on the fly? (or how to create facebook/hotmail-style to add contacts to message) What I want to do is to create something like that hotmail/facebook-style list of selected contacts.. with 1 little block and a "X" for removing each item. How could I achieve that in .NET? I thought of creating new labels "on the fly" and use .NET's Ajax UpdatePanel.. But, can I do it? if yes, how can i create a label on the fly, and put it just where I want? I want the items to be created in a list. (<ul>) A: Assuming you have a Panel somewhere on your site: Label myLabel = new Label(); myLabel.Text = "My Name"; myLabel.CssClass = "labelClass"; pnlItems.Controls.Add(myLabel); To have ul / li items (or something completely customisable): HtmlGenericControl ulControl = new HtmlGenericControl("ul"); pnlItems.Controls.Add(ulControl); foreach (object myThing in myItems) { HtmlGenericControl itemControl = new HtmlGenericControl("li"); itemControl.InnerHtml = myThing.GetMarkup(); ulControl.Controls.Add(itemControl); } Note this is untested - I'm fairly sure you can add controls to an Html Generic Control.
{ "language": "en", "url": "https://stackoverflow.com/questions/1862778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: draw a chart with pointer in android how I can draw a chart with a pointer that specify a point of chart and return information of that point. pointer is movable. I want to show the information of Specified point below the chart. A: Check the following libraries: https://github.com/PhilJay/MPAndroidChart https://github.com/diogobernardino/WilliamChart https://github.com/lecho/hellocharts-android They are beautiful and maybe they have what you need.
{ "language": "en", "url": "https://stackoverflow.com/questions/27210895", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Cannot list changed files using github actions I am trying to list all the changed files on file push. However my List all changed files command does not return anything even though I change the file and commit name: test on: push: branches: [ main ] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 with: fetch-depth: 0 # OR "2" -> To retrieve the preceding commit. - name: Get changed files using defaults id: changed-files uses: actions/checkout@v2 - name: List all added files run: | for file in ${{ steps.changed-files.outputs.added_files }}; do echo "$file was added" done - name: List all changed files run: | for file in ${{ steps.changed-files.outputs.modified_files }}; do echo "$file was modified" done A: Try using the one available in marketplace https://github.com/jitterbit/get-changed-files#get-all-changed-files
{ "language": "en", "url": "https://stackoverflow.com/questions/71506177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AngularJs - Dynamic Form - single selection or checkbox list I wonder how I can make a dynamic way to bring a combobox (single selection) or a checkbox list depending on what is defined in the database. [{ id:10 question: "Gender?", type: 1, //singleSelect options: [{id:1, name:"Male"}, {id:2, name:"Female"}] }, { id:11 question: "Witch videogames do you have?", type: 2, //multiSelect options: [{id:1,name:"PS4"}, {id:2, name:"XBox One"}, {id:3, name:"Wii"}, {id:4, name:"Super Nintendo"}] }] And I want to receive in controller a list of selected itens like that: [10:[1],11:[2,3]] // male and with XBox One and Wii Is is possible? A: Well, the [10:[1],11:[2,3]] is invalid JavaScript, but if you need something approximately, you can use [{"10":1,"11":[2,3]}]. You don't need AngularJS or any third party library like jQuery to build a dynamic form. You can implement by using pure JavaScript through by DOM manipulation. This is a simple demo where you can see how it works. (function() { var data = [{ "id": 10, "question": "Gender?", "type": 1, "options": [{ "id": 1, "name": "Male" }, { "id": 2, "name": "Female" }] }, { "id": 11, "question": "Witchvideogamesdoyouhave?", "type": 2, "options": [{ "id": 1, "name": "PS4" }, { "id": 2, "name": "XBoxOne" }, { "id": 3, "name": "Wii" }, { "id": 4, "name": "SuperNintendo" }] }]; function buildFields(data) { var form, count, i, j, div, label, labelOpt, field, option, content, button; form = document.getElementById("form"); count = data.length; for (i = 0; i < count; i++) { div = document.createElement("div"); // Creates a DIV. div.classList.add("question"); // Adds a css class to your new DIV. div.setAttribute("data-id", data[i].id); // Adds data-id attribute with question id in the new DIV. div.setAttribute("data-type", data[i].type); // Adds data-type attribute with question type in the new DIV. label = document.createElement("label"); // Adds a label to wrap the question content. label.innerText = data[i].id + "." + data[i].question; // Adds the question id in the label with the current question. if (data[i].type === 1) { // Check for the question type. In this case 1 is for the select tag. field = document.createElement("select"); // Creates a select tag. field.id = "field_" + data[i].id; // Adds an identifier to your select tag. field.name = "field_" + data[i].id; // Adds a name to the current select tag. if (data[i].options.length > 0) { // Checks for the options to create an option tag for every option with the current options values. option = document.createElement("option"); option.value = ""; option.text = ".:: Please select an option ::."; field.appendChild(option); for (j = 0; j < data[i].options.length; j++) { option = document.createElement("option"); option.value = data[i].options[j].id; option.text = data[i].options[j].name; field.appendChild(option); } } div.appendChild(field); } else { if (data[i].options.length > 0) { content = document.createElement("span"); for (var k = 0; k < data[i].options.length; k++) { labelOpt = document.createElement("label"); labelOpt.innerText = data[i].options[k].name; field = document.createElement("input"); field.type = "checkbox"; field.value = data[i].options[k].id; labelOpt.insertBefore(field, labelOpt.firstChild); // Inserts a field before the label. content.appendChild(labelOpt); } div.appendChild(content); } } div.insertBefore(label, div.firstChild); form.appendChild(div); } button = document.createElement("button"); button.type = "button"; button.innerText = "Send"; button.addEventListener("click", function() { var form, dataId, dataType, values, array, obj, i, result, form = document.getElementById("form"); values = []; array = []; obj = {}; for (i = 0; i < form.children.length; i++) { // Iterates for every node. if (form.children[i].tagName === "DIV") { dataId = parseInt(form.children[i].getAttribute("data-id"), 10); dataType = parseInt(form.children[i].getAttribute("data-type"), 10); if (dataType === 1) { obj[dataId] = parseInt(form.children[i].children[1].value, 10); } else { for (var j = 0; j < form.children[i].children[1].children.length; j++) { if (form.children[i].children[1].children[j].children[0].checked) { array.push(parseInt(form.children[i].children[1].children[j].children[0].value, 10)); } } obj[dataId] = array; } } } values.push(obj); result = document.getElementById("result"); result.innerText = JSON.stringify(values) + "\nTotal answers from question 11: " + values[0]["11"].length + ((values[0]["11"].length === 1) ? " answer." : " answers."); }); form.appendChild(button); } buildFields(data); })() .question { border: solid 1px #000; border-radius: 5px; padding: 5px; margin: 10px; } .question label { display: block; } #result { background-image: linear-gradient(#0CC, #fff); border-radius: 10px; padding: 10px; } <form id="form" name="form"> </form> <div id="result"> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/37735742", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Send data to a webform using MS Access VBA I am trying to send data from an Access DB to a website http://www.lee.vote/voters/check-your-registration-status/. I'm able to use similar code (below) to send data to a different website, but I can't figure out why it doesn't work for this website. The HTML from what I'm trying to fill in: <div id="FindVoterForm"> <div id="IntroText"> <h1 style="text-align: center; margin-bottom: 3px;">Voter Information in&nbsp;<span id="MainCounty">Lee</span>&nbsp;County</h1> <h2 style="text-align: center; margin-top: 3px; margin-bottom: 3px;">Sample Ballots and Voting Locations</h2> <span class="style1" style="margin-bottom: 0px;">Complete the form to see:</span><ul style="margin-top: 0px;"> <li class="style1"><b>Where to vote on election day</b></li> <li class="style1"><b>Sample ballots</b></li> <li class="style1"><b>Upcoming elections</b></li> </ul> <p class="style2" style="margin-bottom: 0px;"> You'll also be able to:</p> <ul style="margin-top: 0px;"> <li class="style2">Request a mail ballot</li> <li class="style2">Review/update your voter registration information</li> <li class="style2">Check the status of your mail ballot</li> <li class="style2">Review your voting activity for the past 12 months</li> </ul> <div id="NotRegistered" style="font-size: small;"><a href="https://www.voterfocus.com/ws/pfinder/printvapp4.php?county=lee" target="_blank">If you are not registered to vote please fill out our voter registration form</a></div><br> <i><b style="text-decoration: underline;">All items are required</b></i>. </div> <div class="voterForm"> <div class="voterFormLine"><div>1.</div><div>Voter's Last Name</div><div><input title="Please enter your last name." id="NameID" type="text" size="10" maxlength="35" value=""></div> </div><div class="voterFormLine"><div>2.</div><div>Voter's Birth Date</div><div><input title="Please enter your birth date (MM/DD/YYYY)." id="BirthDate" type="text" size="10" maxlength="10" value=""> <br>MM/DD/YYYY</div></div><div class="voterFormLine"><div>3.</div> <div><a title="House Number" href="https://www.voterfocus.com/VFVoterGlossery.php?term=House Number" target="_blank">House Number</a> of Voter's Residence Address</div> <div><input title="Please enter your house street number." id="StNumber" type="text" size="10" maxlength="10" value=""></div> </div> <div>&nbsp;</div> </div> <div><div style="text-align: center;"><h2 id="MoreVoter" style="display: none;"><b></b></h2> <button id="ButtonForm" onclick="ButtonForm_onclick()" type="button" value="Submit">Submit</button></div> </div> </div> The VBA code: 'creates a new internet explorer window Dim IE As Object Set IE = CreateObject("InternetExplorer.Application") 'opens Lee County registration check With IE .Visible = True .navigate "http://www.lee.vote/voters/check-your-registration-status/" End With 'waits until IE is loaded Do Until IE.ReadyState = 4 And Not IE.busy DoEvents Loop 'sends data to the webpage Call IE.Document.getelementbyid("NameID").setattribute("value", Last_Name) Call IE.Document.getelementbyid("BirthDate").setattribute("value", Date_of_Birth.Value) Call IE.Document.getelementbyid("StNumber").setattribute("value", Street_Number.Value) '"clicks" the button to display the results IE.Document.getelementbyid("ButtonForm").Click Any help? A: The HTML snippet you provided belongs to iframe <iframe id="dnn_ctr1579_View_VoterLookupFrame" src="https://www.electionsfl.org/VoterInfo/vflookup.html?county=lee" width="100%" height="2000" frameborder="0"></iframe>, so you should navigate to URL https://www.electionsfl.org/VoterInfo/vflookup.html?county=lee instead of http://www.lee.vote/voters/check-your-registration-status/. I navigated https://www.electionsfl.org/VoterInfo/vflookup.html?county=lee in Chrome and checked XHR logged after I submit the data via Developer Tools (F12), Network tab: Seems that is simple POST XML HTTP request with payload in JSON format, like: {'LastName':'Doe', 'BirthDate':'01/01/1980', 'StNumber':'10025', 'County':'lee', 'FirstName':'', 'challengeValue':'', 'responseValue':''} That XHR uses no cookies or any other authorization data neither in headers nor payload, so I tried to reproduce the same request using the following code: Option Explicit Sub Test_Submit_VoterInfo() Dim sLastName As String Dim sBirthDate As String Dim sStNumber As String Dim sFormData As String Dim bytFormData Dim sContent As String ' Put the necessary data here sLastName = "Doe" sBirthDate = "01/01/1980" sStNumber = "10025" ' Combine form payload sFormData = "{" & _ "'LastName':'" & sLastName & "', " & _ "'BirthDate':'" & sBirthDate & "', " & _ "'StNumber':'" & sStNumber & "', " & _ "'County':'lee', " & _ "'FirstName':'', " & _ "'challengeValue':'', " & _ "'responseValue':''" & _ "}" ' Convert string to UTF-8 binary With CreateObject("ADODB.Stream") .Open .Type = 2 ' adTypeText .Charset = "UTF-8" .WriteText sFormData .Position = 0 .Type = 1 ' adTypeBinary .Position = 3 ' skip BOM bytFormData = .Read .Close End With ' Make POST XHR With CreateObject("MSXML2.XMLHTTP") .Open "POST", "https://www.electionsfl.org/VoterInfo/asmx/service1.asmx/FindVoter", False, "u051772", "mar4fy16" .SetRequestHeader "Content-Length", LenB(bytFormData) .SetRequestHeader "Content-Type", "application/json; charset=UTF-8" .Send bytFormData sContent = .ResponseText End With ' Show response Debug.Print sContent End Sub The response for me is {"d":"[]"}, the same as in browser, but unfortunately I can't check if it processed on the server correctly, since I have no valid voter record data. A: This is the answer that I came up with after the (much needed) help determining that I was not really navigating to the right webpage for the form: 'creates a new internet explorer window Dim IE As Object Set IE = CreateObject("InternetExplorer.Application") 'opens Lee County registration check With IE .Visible = True .navigate "https://www.electionsfl.org/VoterInfo/vflookup.html?county=lee" End With 'waits until IE is loaded Do Until IE.ReadyState = 4 And Not IE.busy DoEvents Loop x = Timer + 2 Do While Timer < x DoEvents Loop 'sends data to the webpage Call IE.Document.getelementbyid("NameID").setattribute("value", Last_Name.Value) 'formats DOB to correct output Dim DOBMonth As Integer Dim DOBDay As Integer Dim DOBYear As Integer DOBMonth = Month(Date_of_Birth.Value) DOBDay = Day(Date_of_Birth.Value) DOBYear = Year(Date_of_Birth.Value) If DOBMonth < 10 Then Call IE.Document.getelementbyid("BirthDate").setattribute("value", "0" & DOBMonth & "/" & DOBDay & "/" & DOBYear) Else Call IE.Document.getelementbyid("BirthDate").setattribute("value", DOBMonth & "/" & DOBDay & "/" & DOBYear) End If Call IE.Document.getelementbyid("StNumber").setattribute("value", Street_Number.Value) '"clicks" the button to display the results IE.Document.getelementbyid("ButtonForm").Click
{ "language": "en", "url": "https://stackoverflow.com/questions/44078873", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SAPUI5 and Logon Tokens/SSO? I'm getting started with SAP's SAPUI5 framework, and I am trying to get single sign on to work with logon tokens (MYSAPSSO2), but I don't see anywhere that I can fetch a token or attach a token to an OData HTTP request. The example in the blog post I linked to above employs username/password but doesn't use a token: // Specify the SAP Gateway SalesOrder service as an OData model var salesOrderService = "https://gw.esworkplace.sap.com/sap/opu/sdata/IWFND/SALESORDER", // The SalesOrder service requires authentication // get the username/password from the SDN page. username = "[username]", password = "[password]", // SAP Gateway only supports XML, so don't use JSON asJson = false, salesOrderModel = new ODataModel(salesOrderService, asJson, username, password) Even when I look at the ODataModel.js file provided in the SDK, the constructor does not take logon tokens: /** * Constructor for a new ODataModel. * * @param {string} sServiceUrl required - base uri of the service to request data from * @param {string} [bJSON] (optional) true to request data as JSON * @param {string} [sUser] (optional) user * @param {string} [sPassword] (optional) password * * @class * Model implementation for oData format * * @extends sap.ui.model.Model * * @author SAP AG * @version 1.2.0 * * @constructor * @public */ I'm curious (though since it's new, I wouldn't be surprised if nobody had even heard of this yet) if anyone has any experience with SSO/MYSAPSSO2 logon tokens with SAPUI5. A: I am the author of the blog you refer to. Let me try and answer your question. Your comment from Mar 15 describes a proxy approach. What you should try to do is, once your proxy has received an SSO token you should pass that on to the client, using a SET-COOKIE header. So when you successfully authenticate to SAP you get an SSO token an HTTP header of the response. E.g. set-cookie: MYSAPSSO2=AjQxMDM.....BABhHAFcA%3d%3d; path=/; domain=esworkplace.sap.com Your proxy should simply pass that on to the client's browser and change the domain name to that of the proxy, otherwise the client will not use it. set-cookie: MYSAPSSO2=AjQxMDM.....BABhHAFcA%3d%3d; path=/; domain=yourproxydomain.com Next time the browser makes a request to your proxy it will automatically include this session cookie in the request header, like this: Cookie: MYSAPSSO2=AjQxMDMBABhH......%2fjmaRu5sSb28M6rEg%3d%3d Your proxy can read that cookie from the HTTP request headers and use it to make a call. I hope this helps. A: I'm responsible for SAPUI5 - although I'm not 100% sure whether I completely understand the issue, I'll try to answer. The SAPUI5 calls to read data use XMLHttpRequests and thus all certificates or cookies are sent along with the requests automatically. Futhermore, Gateway is expected to accept these (valid) certificates. So following the answer from Istak and using cookies with a proper domain, it should just work without the need of an API in UI5. Anyhow, if I missed something, please explain more in detail. Best regards Stefan A: Not Sure about SAPUI5 and oData, I have used MYSAPSSO2 token with Java EE web applications / sencha touch based apps which connect sto SAP backend systems with SSO. You simply pass the token as a cookie in the http request. There are many ways of doing this, the one I used was SimpleClientHttpRequestFactory or you could do that in UrlConnection itself.
{ "language": "en", "url": "https://stackoverflow.com/questions/9587903", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Android scene transition issue I am trying to change one scene to another scene using transition framework. MainActivity.java mSceneRoot = (ViewGroup) findViewById(R.id.root_scene); calendarScene = Scene.getSceneForLayout(mSceneRoot, R.layout.content_main_scene1,this); searchScene = Scene.getSceneForLayout(mSceneRoot, R.layout.content_main_scene2,this); searchTextView = (TextView) findViewById(R.id.searchTextEdit); searchTextView.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { TransitionManager.go(searchScene); } else { TransitionManager.go(calendarScene); } } }); content_root.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" app:layout_behavior="@string/appbar_scrolling_view_behavior" tools:showIn="@layout/activity_main" tools:context=".MainActivity"> <FrameLayout android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/root_scene"> <include layout="@layout/content_main_scene1"/> </FrameLayout> </RelativeLayout> content_main_scene2 has additional listView. Finally I got the exception: 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/InputEventReceiver: Exception dispatching input event. 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: java.lang.NullPointerException 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:2413) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.requestFocus(ViewGroup.java:2370) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:2414) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.requestFocus(ViewGroup.java:2370) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:2414) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.requestFocus(ViewGroup.java:2370) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:2414) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.requestFocus(ViewGroup.java:2370) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:2414) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.requestFocus(ViewGroup.java:2370) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:2414) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.requestFocus(ViewGroup.java:2370) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:2414) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.requestFocus(ViewGroup.java:2370) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:2414) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.requestFocus(ViewGroup.java:2373) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.View.requestFocus(View.java:6945) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.View.requestFocus(View.java:6924) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.View.rootViewRequestFocus(View.java:4746) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.removeAllViewsInLayout(ViewGroup.java:4042) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.removeAllViews(ViewGroup.java:3971) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.transition.Scene.enter(Scene.java:163) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.transition.TransitionManager.changeScene(TransitionManager.java:193) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.transition.TransitionManager.go(TransitionManager.java:342) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at com.freelance.wwtlf.info.MainActivity$2.onFocusChange(MainActivity.java:71) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.View.onFocusChanged(View.java:4836) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.widget.TextView.onFocusChanged(TextView.java:7641) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.View.handleFocusGainInternal(View.java:4617) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.View.requestFocusNoSearch(View.java:6999) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.View.requestFocus(View.java:6978) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.View.requestFocus(View.java:6945) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.View.requestFocus(View.java:6924) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.View.onTouchEvent(View.java:8653) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.widget.TextView.onTouchEvent(TextView.java:7693) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.View.dispatchTouchEvent(View.java:7706) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1959) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1959) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1959) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1959) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1959) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1959) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1959) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1959) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2216) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:1959) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:2068) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1515) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.app.Activity.dispatchTouchEvent(Activity.java:2458) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.support.v7.internal.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:60) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at android.support.v7.internal.view.WindowCallbackWrapper.dispatchTouchEvent(WindowCallbackWrapper.java:60) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/MessageQueue-JNI: at 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info D/AndroidRuntime: Shutting down VM 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa4d17b20) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/AndroidRuntime: FATAL EXCEPTION: main 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/AndroidRuntime: Process: com.freelance.wwtlf.info, PID: 5937 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/AndroidRuntime: java.lang.NullPointerException 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/AndroidRuntime: at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:2413) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/AndroidRuntime: at android.view.ViewGroup.requestFocus(ViewGroup.java:2370) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/AndroidRuntime: at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:2414) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/AndroidRuntime: at android.view.ViewGroup.requestFocus(ViewGroup.java:2370) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/AndroidRuntime: at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:2414) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/AndroidRuntime: at android.view.ViewGroup.requestFocus(ViewGroup.java:2370) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/AndroidRuntime: at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:2414) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/AndroidRuntime: at android.view.ViewGroup.requestFocus(ViewGroup.java:2370) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/AndroidRuntime: at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:2414) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/AndroidRuntime: at android.view.ViewGroup.requestFocus(ViewGroup.java:2370) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/AndroidRuntime: at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:2414) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/AndroidRuntime: at android.view.ViewGroup.requestFocus(ViewGroup.java:2370) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/AndroidRuntime: at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:2414) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/AndroidRuntime: at android.view.ViewGroup.requestFocus(ViewGroup.java:2370) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/AndroidRuntime: at android.view.ViewGroup.onRequestFocusInDescendants(ViewGroup.java:2414) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/AndroidRuntime: at android.view.ViewGroup.requestFocus(ViewGroup.java:2373) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/AndroidRuntime: at android.view.View.requestFocus(View.java:6945) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/AndroidRuntime: at android.view.View.requestFocus(View.java:6924) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/AndroidRuntime: at android.view.View.rootViewRequestFocus(View.java:4746) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/AndroidRuntime: at android.view.ViewGroup.removeAllViewsInLayout(ViewGroup.java:4042) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/AndroidRuntime: at android.view.ViewGroup.removeAllViews(ViewGroup.java:3971) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/AndroidRuntime: at android.transition.Scene.enter(Scene.java:163) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/AndroidRuntime: at android.transition.TransitionManager.changeScene(TransitionManager.java:193) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/AndroidRuntime: at android.transition.TransitionManager.go(TransitionManager.java:342) 11-06 03:14:13.848 5937-5937/com.freelance.wwtlf.info E/AndroidRuntime: at com.freelance.wwtlf.info.MainActivity$2.onFocusChange(MainActivity.java:71) ... What object is pointing to null? Update: When I have changed OnFocusChangeListener to onClickListener everything worked fine. But I still don't understand why...
{ "language": "en", "url": "https://stackoverflow.com/questions/33563807", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can I transmit a func from parent to child in reactnavigation 6? Have a nice day. Can I transmit a func from parent to child in reactnavigation 6? Maybe somethings like this: onPress={function => navigation.navigate({ name: LANGUAGES.label_people_component, params: function, merge: true, }) } Tks all. A: As mentioned here, We recommend that the params you pass are JSON-serializable. That way, you'll be able to use state persistence and your screen components will have the right contract for implementing deep linking. React Navigation parameters work like query parameters in websites in 6.x I believe, the ideal way to do this now is to use Context API where you have a single source of information. You can also use a state management library such as redux or mobx in cases where you have a large number of stores and actions to manipulate them.
{ "language": "en", "url": "https://stackoverflow.com/questions/69676101", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Error after restoring TFS database to new hardware I am using TFS 2012. I wanted to test how i can recover from server failure or any hardware failure, So i wanted to shift TFS to new PC. I followed some articles to restore it. what i did is 1)I had full backup of TFS_configuration and all other collection database.(backup taken using TFSbackup.exe) 2)In new PC i installed all the softwares(such as TFS 2012, sql server etc). 3)created all the windows user account as in old server. 4)When I checked the New PC it had default collection created which was mapped to sql server which i installed. 5)Now i deleted that default collection and restored all databases of my old TFS server(TFS_configuration and all other collection database.)(backup restored using TFSrestore.exe) 6)Now when i checked TFS administrative console it had all the collections as my old server. 7) But when i click on Administrative security, group membership etc I get error like TF30046: The instance information does not match. Team Foundation expected 368f7830-1c67-4c4c-8bc4-ba3d5b5a5543 which was not found. Please contact your Team Foundation Server administrator. In this link it was mentioned to change service host id in table. But it didn't work for me. So please help A: You mistakenly configured TFS (in fact it created a default collection). If read carefully Move Team Foundation Server from one hardware configuration to another, you have to run the AT-only Configuration Wizard after restoring the databases.
{ "language": "en", "url": "https://stackoverflow.com/questions/21621844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Routing audio output between multiple bluetooth devices with iOS using AVAudioSession Got a video conference app, implementing device selection feature of switching between Earpiece, Speaker, and connected Bluetooth devices. All seems to function appropriately apart from switching between bluetooth devices themselves. For some reason, only the last connected device gets the audio routed to it, and you can't switch back to the other ones even if they're available in availableInputs of AVAudioSession SharedInstance, using setPreferredInput with OverridePortNone I tried searching for resolutions but found the same unanswered issue from 5 years ago, I tried doing the same as changing setActive calls but was also unsuccessful. Following is the test code, which is taken from here: AVAudioSession *_audioSession = [AVAudioSession sharedInstance]; AVAudioSessionCategoryOptions _incallAudioCategoryOptionsAll = AVAudioSessionCategoryOptionMixWithOthers|AVAudioSessionCategoryOptionAllowBluetooth|AVAudioSessionCategoryOptionAllowAirPlay; [_audioSession setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:_incallAudioCategoryOptionsAll error:nil]; [_audioSession setMode:AVAudioSessionModeVoiceChat error: nil]; RCT_EXPORT_METHOD(setAudioDevice:(NSString *)device resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject) { BOOL success; NSError *error = nil; NSLog(@"[setAudioDevice] - Attempting to set audiodevice as: %@", device); if ([device isEqualToString:kDeviceTypeSpeaker]) { success = [_audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&error]; } else { AVAudioSessionPortDescription *port = nil; for (AVAudioSessionPortDescription *portDesc in _audioSession.availableInputs) { if ([portDesc.UID isEqualToString:device]) { port = portDesc; break; } } if (port != nil) { [_audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:nil]; success = [_audioSession setPreferredInput:port error:&error]; if(error != nil) { NSLog(@"setAudioDevice %@ %@", error.localizedDescription, error); } } else { success = NO; error = RCTErrorWithMessage(@"Could not find audio device"); } } if (success) { resolve(@"setAudioDevice success!"); NSLog(@"resolved success"); } else { reject(@"setAudioDevice", error != nil ? error.localizedDescription : @"", error); NSLog(@"sent reject"); } } So how can I make it that we're able to successfully change from one bluetooth device to other?
{ "language": "en", "url": "https://stackoverflow.com/questions/72348871", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Capturing a Session variable in Session_OnStart - Global.asa I'm trying to use the users session to process the code in my global.asa: Sub Session_OnStart sAdmin = Session("Admin") Application("Admin") = sAdmin The Session("Admin") is not empty, but the Application("Admin") always comes up empty when I check it. Is there a reason I'm not able to capture the users session variable in the Session_OnStart section of the global.asa? When I do this Application("Admin") doesn't come up empty, it comes up as hi Sub Session_OnStart Application("Admin") = "hi" What do I have to do to capture the users session value in the global.asa? A: It appears that you try to set "by reference" assignment so that Application("Admin") will change when Session("Admin") changes. I fear such thing is not possible in classic ASP. The only elegant way I can think of is adding helper method that will be included in all pages: Sub AssignAdminSession(value) Session("Admin") = value Application("Admin") = value End Sub Then instead of just Session("Admin") = "something" have everywhere: Call AssignAdminSession("value here")
{ "language": "en", "url": "https://stackoverflow.com/questions/16444587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to build a "defaulting map" data structure I have some configuration data that I'd like to model in code as so: Key1, Key2, Key3, Value null, null, null, 1 1, null, null, 2 9, null, null, 21 1, null, 3, 3 null, 2, 3, 4 1, 2, 3, 5 With this configuration set, I then need to do lookups on bazillion (give or take) {Key1, Key2, Key3} tuples to get the "effective" value. The effective value to use is based on a Key/Priority sum whereby in this example: Key1 - Priority 10 Key2 - Priority 7 Key3 - Priority 5 So a specifc query which has a config entry on Key1=null, Key2=match, and Key3=match beats out one that has Key1=match, Key2=null, and Key3=null since Key2+Key3 priority > Key1 priority... That make sense?! given a key of {1, 2, 3} the value should be 5. given a key of {3, 2, 3} the value should be 4. given a key of {8, 10, 11} the value should be 1. given a key of {1, 10, 11} the value should be 2. given a key of {9, 2, 3} the value should be 4. given a key of {8, 2, 3} the value should be 4. given a key of {9, 3, 3} the value should be 21. Is there an easy way to model this data structure and lookup algorithm that is generic in that the # and types of keys is variable, and the "truth table" (the ordering of the lookups) can be defined dynamically? The types being generics instead of ints would be perfect (floats, doubles, ushorts, etc), and making it easy to expand to n number of keys is important too! Estimated "config" table size: 1,000 rows, Estimated "data" being looked up: 1e14 That gives an idea about the type of performance that would be expected. I'm looking for ideas in C# or something that can translate to C# easily. A: EDIT: This code is apparently not what's required, but I'm leaving it as it's interesting anyway. It basically treats Key1 as taking priority, then Key2, then Key3 etc. I don't really understand the intended priority system yes, but when I do I'll add an answer for that. I would suggest a triple layer of Dictionaries - each layer has: Dictionary<int, NextLevel> matches; NextLevel nonMatch; So at the first level you'd look up Key1 - if that matches, that gives you the next level of lookup. Otherwise, use the next level which corresponds with "non-match". Does that make any sense? Here's some sample code (including the example you gave). I'm not entirely happy with the actual implementation, but the idea behind the data structure is sound, I think: using System; using System.Collections; using System.Collections.Generic; public class Test { static void Main() { Config config = new Config { { null, null, null, 1 }, { 1, null, null, 2 }, { 1, null, 3, 3 }, { null, 2, 3, 4 }, { 1, 2, 3, 5 } }; Console.WriteLine(config[1, 2, 3]); Console.WriteLine(config[3, 2, 3]); Console.WriteLine(config[9, 10, 11]); Console.WriteLine(config[1, 10, 11]); } } // Only implement IEnumerable to allow the collection initializer // Not really implemented yet - consider how you might want to implement :) public class Config : IEnumerable { // Aargh - death by generics :) private readonly DefaultingMap<int, DefaultingMap<int, DefaultingMap<int, int>>> map = new DefaultingMap<int, DefaultingMap<int, DefaultingMap<int, int>>>(); public int this[int key1, int key2, int key3] { get { return map[key1][key2][key3]; } } public void Add(int? key1, int? key2, int? key3, int value) { map.GetOrAddNew(key1).GetOrAddNew(key2)[key3] = value; } public IEnumerator GetEnumerator() { throw new NotSupportedException(); } } internal class DefaultingMap<TKey, TValue> where TKey : struct where TValue : new() { private readonly Dictionary<TKey, TValue> mapped = new Dictionary<TKey, TValue>(); private TValue unmapped = new TValue(); public TValue GetOrAddNew(TKey? key) { if (key == null) { return unmapped; } TValue ret; if (mapped.TryGetValue(key.Value, out ret)) { return ret; } ret = new TValue(); mapped[key.Value] = ret; return ret; } public TValue this[TKey key] { get { TValue ret; if (mapped.TryGetValue(key, out ret)) { return ret; } return unmapped; } } public TValue this[TKey? key] { set { if (key != null) { mapped[key.Value] = value; } else { unmapped = value; } } } } A: To answer your question about something which is generic in the number and type of keys - you can't make the number and type of keys dynamic and use generics - generics are all about providing compile-time information. Of course, you could use ignore static typing and make it dynamic - let me know if you want me to implement that instead. How many entries will there be, and how often do you need to look them up? You may well be best just keeping all the entries as a list and iterating through them giving a certain "score" to each match (and keeping the best match and its score as you go). Here's an implementation, including your test data - but this uses the keys having priorities (and then summing the matches), as per a previous comment... using System; using System.Collections; using System.Collections.Generic; public class Test { static void Main() { Config config = new Config(10, 7, 5) { { new int?[]{null, null, null}, 1}, { new int?[]{1, null, null}, 2}, { new int?[]{9, null, null}, 21}, { new int?[]{1, null, 3}, 3 }, { new int?[]{null, 2, 3}, 4 }, { new int?[]{1, 2, 3}, 5 } }; Console.WriteLine(config[1, 2, 3]); Console.WriteLine(config[3, 2, 3]); Console.WriteLine(config[8, 10, 11]); Console.WriteLine(config[1, 10, 11]); Console.WriteLine(config[9, 2, 3]); Console.WriteLine(config[9, 3, 3]); } } public class Config : IEnumerable { private readonly int[] priorities; private readonly List<KeyValuePair<int?[],int>> entries = new List<KeyValuePair<int?[], int>>(); public Config(params int[] priorities) { // In production code, copy the array to prevent tampering this.priorities = priorities; } public int this[params int[] keys] { get { if (keys.Length != priorities.Length) { throw new ArgumentException("Invalid entry - wrong number of keys"); } int bestValue = 0; int bestScore = -1; foreach (KeyValuePair<int?[], int> pair in entries) { int?[] key = pair.Key; int score = 0; for (int i=0; i < priorities.Length; i++) { if (key[i]==null) { continue; } if (key[i].Value == keys[i]) { score += priorities[i]; } else { score = -1; break; } } if (score > bestScore) { bestScore = score; bestValue = pair.Value; } } return bestValue; } } public void Add(int?[] keys, int value) { if (keys.Length != priorities.Length) { throw new ArgumentException("Invalid entry - wrong number of keys"); } // Again, copy the array in production code entries.Add(new KeyValuePair<int?[],int>(keys, value)); } public IEnumerator GetEnumerator() { throw new NotSupportedException(); } } The above allows a variable number of keys, but only ints (or null). To be honest the API is easier to use if you fix the number of keys... A: Yet another solution - imagine that the entries are a bit pattern of null/non-null. You have one dictionary per bit pattern (i.e. { 1, null, null } and { 9, null, null } go in the same dictionary, but { 1, 2, 3 } goes in a different one. Each dictionary effectively has a score as well - the sum of the priorities for the non-null parts of the key. You wil end up with 2^n dictionaries, where n is the number of elements in the key. You order the dictionaries in reverse score order, and then just look up the given key in each of them. Each dictionary needs to ignore the values in the key which aren't in its bit pattern, which is done easily enough with a custom IComparer<int[]>. Okay, here's the implementation: ------------ Test.cs ----------------- using System; sealed class Test { static void Main() { Config config = new Config(10, 7, 5) { { null, null, null, 1 }, {null, null, null, 1}, {1, null, null, 2}, {9, null, null, 21}, {1, null, 3, 3 }, {null, 2, 3, 4 }, {1, 2, 3, 5 } }; Console.WriteLine(config[1, 2, 3]); Console.WriteLine(config[3, 2, 3]); Console.WriteLine(config[8, 10, 11]); Console.WriteLine(config[1, 10, 11]); Console.WriteLine(config[9, 2, 3]); Console.WriteLine(config[9, 3, 3]); } } --------------- Config.cs ------------------- using System; using System.Collections; sealed class Config : IEnumerable { private readonly PartialMatchDictionary<int, int> dictionary; public Config(int priority1, int priority2, int priority3) { dictionary = new PartialMatchDictionary<int, int>(priority1, priority2, priority3); } public void Add(int? key1, int? key2, int? key3, int value) { dictionary[new[] { key1, key2, key3 }] = value; } public int this[int key1, int key2, int key3] { get { return dictionary[new[] { key1, key2, key3 }]; } } // Just a fake implementation to allow the collection initializer public IEnumerator GetEnumerator() { throw new NotSupportedException(); } } -------------- PartialMatchDictionary.cs ------------------- using System; using System.Collections.Generic; using System.Linq; public sealed class PartialMatchDictionary<TKey, TValue> where TKey : struct { private readonly List<Dictionary<TKey[], TValue>> dictionaries; private readonly int keyComponentCount; public PartialMatchDictionary(params int[] priorities) { keyComponentCount = priorities.Length; dictionaries = new List<Dictionary<TKey[], TValue>>(1 << keyComponentCount); for (int i = 0; i < 1 << keyComponentCount; i++) { PartialComparer comparer = new PartialComparer(keyComponentCount, i); dictionaries.Add(new Dictionary<TKey[], TValue>(comparer)); } dictionaries = dictionaries.OrderByDescending(dict => ((PartialComparer)dict.Comparer).Score(priorities)) .ToList(); } public TValue this[TKey[] key] { get { if (key.Length != keyComponentCount) { throw new ArgumentException("Invalid key component count"); } foreach (Dictionary<TKey[], TValue> dictionary in dictionaries) { TValue value; if (dictionary.TryGetValue(key, out value)) { return value; } } throw new KeyNotFoundException("No match for this key"); } } public TValue this[TKey?[] key] { set { if (key.Length != keyComponentCount) { throw new ArgumentException("Invalid key component count"); } // This could be optimised (a dictionary of dictionaries), but there // won't be many additions to the dictionary compared with accesses foreach (Dictionary<TKey[], TValue> dictionary in dictionaries) { PartialComparer comparer = (PartialComparer)dictionary.Comparer; if (comparer.IsValidForPartialKey(key)) { TKey[] maskedKey = key.Select(x => x ?? default(TKey)).ToArray(); dictionary[maskedKey] = value; return; } } throw new InvalidOperationException("We should never get here"); } } private sealed class PartialComparer : IEqualityComparer<TKey[]> { private readonly int keyComponentCount; private readonly bool[] usedKeyComponents; private static readonly EqualityComparer<TKey> Comparer = EqualityComparer<TKey>.Default; internal PartialComparer(int keyComponentCount, int usedComponentBits) { this.keyComponentCount = keyComponentCount; usedKeyComponents = new bool[keyComponentCount]; for (int i = 0; i < keyComponentCount; i++) { usedKeyComponents[i] = ((usedComponentBits & (1 << i)) != 0); } } internal int Score(int[] priorities) { return priorities.Where((value, index) => usedKeyComponents[index]).Sum(); } internal bool IsValidForPartialKey(TKey?[] key) { for (int i = 0; i < keyComponentCount; i++) { if ((key[i] != null) != usedKeyComponents[i]) { return false; } } return true; } public bool Equals(TKey[] x, TKey[] y) { for (int i = 0; i < keyComponentCount; i++) { if (!usedKeyComponents[i]) { continue; } if (!Comparer.Equals(x[i], y[i])) { return false; } } return true; } public int GetHashCode(TKey[] obj) { int hash = 23; for (int i = 0; i < keyComponentCount; i++) { if (!usedKeyComponents[i]) { continue; } hash = hash * 37 + Comparer.GetHashCode(obj[i]); } return hash; } } } It gives the right results for the samples that you gave. I don't know what the performance is like - it should be O(1), but it could probably be optimised a bit further. A: I'm assuming that there are few rules, and a large number of items that you're going to check against the rules. In this case, it might be worth the expense of memory and up-front time to pre-compute a structure that would help you find the object faster. The basic idea for this structure would be a tree such that at depth i, you would follow the ith element of the rule, or the null branch if it's not found in the dictionary. To build the tree, I would build it recursively. Start with the root node containing all possible rules in its pool. The process: * *Define the current value of each rule in the pool as the score of the current rule given the path taken to get to the node, or -infinity if it is impossible to take the path. For example, if the current node is at the '1' branch of the root, then the rule {null, null, null, 1} would have a score of 0, and the rule {1, null, null, 2} would have a score 10 *Define the maximal value of each rule in the pool as its current score, plus the remaining keys' score. For example, if the current node is at the '1' branch of the root, then the rule {null, 1, 2, 1} would have a score of 12 (0 + 7 + 5), and the rule {1, null, null, 2} would have a score 10 (10 + 0 + 0). *Remove the elements from the pool that have a maximal value lower than the highest current value in the pool *If there is only one rule, then make a leaf with the rule. *If there are multiple rules left in the pool, and there are no more keys then ??? (this isn't clear from the problem description. I'm assuming taking the highest one) *For each unique value of the (i+1)th key in the current pool, and null, construct a new tree from the current node using the current pool. As a final optimization check, I would check if all children of a node are leaves, and if they all contain the same rule, then make the node a leaf with that value. given the following rules: null, null, null = 1 1, null, null = 2 9, null, null = 21 1, null, 3 = 3 null, 2, 3 = 4 1, 2, 3 = 5 an example tree: key1 key2 key3 root: |----- 1 | |----- 2 = 5 | |-----null | |----- 3 = 3 | |-----null = 2 |----- 9 | |----- 2 | | |----- 3 = 4 | | |-----null = 21 | |-----null = 21 |-----null |----- 2 = 4 |-----null = 1 If you build the tree up in this fashion, starting from the highest value key first, then you can possibly prune out a lot of checks against later keys. Edit to add code: class Program { static void Main(string[] args) { Config config = new Config(10, 7, 5) { { new int?[]{null, null, null}, 1}, { new int?[]{1, null, null}, 2}, { new int?[]{9, null, null}, 21}, { new int?[]{1, null, 3}, 3 }, { new int?[]{null, 2, 3}, 4 }, { new int?[]{1, 2, 3}, 5 } }; Console.WriteLine("5 == {0}", config[1, 2, 3]); Console.WriteLine("4 == {0}", config[3, 2, 3]); Console.WriteLine("1 == {0}", config[8, 10, 11]); Console.WriteLine("2 == {0}", config[1, 10, 11]); Console.WriteLine("4 == {0}", config[9, 2, 3]); Console.WriteLine("21 == {0}", config[9, 3, 3]); Console.ReadKey(); } } public class Config : IEnumerable { private readonly int[] priorities; private readonly List<KeyValuePair<int?[], int>> rules = new List<KeyValuePair<int?[], int>>(); private DefaultMapNode rootNode = null; public Config(params int[] priorities) { // In production code, copy the array to prevent tampering this.priorities = priorities; } public int this[params int[] keys] { get { if (keys.Length != priorities.Length) { throw new ArgumentException("Invalid entry - wrong number of keys"); } if (rootNode == null) { rootNode = BuildTree(); //rootNode.PrintTree(0); } DefaultMapNode curNode = rootNode; for (int i = 0; i < keys.Length; i++) { // if we're at a leaf, then we're done if (curNode.value != null) return (int)curNode.value; if (curNode.children.ContainsKey(keys[i])) curNode = curNode.children[keys[i]]; else curNode = curNode.defaultChild; } return (int)curNode.value; } } private DefaultMapNode BuildTree() { return new DefaultMapNode(new int?[]{}, rules, priorities); } public void Add(int?[] keys, int value) { if (keys.Length != priorities.Length) { throw new ArgumentException("Invalid entry - wrong number of keys"); } // Again, copy the array in production code rules.Add(new KeyValuePair<int?[], int>(keys, value)); // reset the tree to know to regenerate it. rootNode = null; } public IEnumerator GetEnumerator() { throw new NotSupportedException(); } } public class DefaultMapNode { public Dictionary<int, DefaultMapNode> children = new Dictionary<int,DefaultMapNode>(); public DefaultMapNode defaultChild = null; // done this way to workaround dict not handling null public int? value = null; public DefaultMapNode(IList<int?> usedValues, IEnumerable<KeyValuePair<int?[], int>> pool, int[] priorities) { int bestScore = Int32.MinValue; // get best current score foreach (KeyValuePair<int?[], int> rule in pool) { int currentScore = GetCurrentScore(usedValues, priorities, rule); bestScore = Math.Max(bestScore, currentScore); } // get pruned pool List<KeyValuePair<int?[], int>> prunedPool = new List<KeyValuePair<int?[], int>>(); foreach (KeyValuePair<int?[], int> rule in pool) { int maxScore = GetCurrentScore(usedValues, priorities, rule); if (maxScore == Int32.MinValue) continue; for (int i = usedValues.Count; i < rule.Key.Length; i++) if (rule.Key[i] != null) maxScore += priorities[i]; if (maxScore >= bestScore) prunedPool.Add(rule); } // base optimization case, return leaf node // base case, always return same answer if ((prunedPool.Count == 1) || (usedValues.Count == prunedPool[0].Key.Length)) { value = prunedPool[0].Value; return; } // add null base case AddChild(usedValues, priorities, prunedPool, null); foreach (KeyValuePair<int?[], int> rule in pool) { int? branch = rule.Key[usedValues.Count]; if (branch != null && !children.ContainsKey((int)branch)) { AddChild(usedValues, priorities, prunedPool, branch); } } // if all children are the same, then make a leaf int? maybeOnlyValue = null; foreach (int v in GetAllValues()) { if (maybeOnlyValue != null && v != maybeOnlyValue) return; maybeOnlyValue = v; } if (maybeOnlyValue != null) value = maybeOnlyValue; } private static int GetCurrentScore(IList<int?> usedValues, int[] priorities, KeyValuePair<int?[], int> rule) { int currentScore = 0; for (int i = 0; i < usedValues.Count; i++) { if (rule.Key[i] != null) { if (rule.Key[i] == usedValues[i]) currentScore += priorities[i]; else return Int32.MinValue; } } return currentScore; } private void AddChild(IList<int?> usedValues, int[] priorities, List<KeyValuePair<int?[], int>> prunedPool, Nullable<int> nextValue) { List<int?> chainedValues = new List<int?>(); chainedValues.AddRange(usedValues); chainedValues.Add(nextValue); DefaultMapNode node = new DefaultMapNode(chainedValues, prunedPool, priorities); if (nextValue == null) defaultChild = node; else children[(int)nextValue] = node; } public IEnumerable<int> GetAllValues() { foreach (DefaultMapNode child in children.Values) foreach (int v in child.GetAllValues()) yield return v; if (defaultChild != null) foreach (int v in defaultChild.GetAllValues()) yield return v; if (value != null) yield return (int)value; } public void PrintTree(int depth) { if (value == null) Console.WriteLine(); else { Console.WriteLine(" = {0}", (int)value); return; } foreach (KeyValuePair<int, DefaultMapNode> child in children) { for (int i=0; i<depth; i++) Console.Write(" "); Console.Write(" {0} ", child.Key); child.Value.PrintTree(depth + 1); } for (int i = 0; i < depth; i++) Console.Write(" "); Console.Write("null"); defaultChild.PrintTree(depth + 1); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/417039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Android Picasso store files or use cache I'm using Picasso to initially download images of products to my app from a server. Since the images aren't changing nearly at all for a certain product, I save the images to the disk from the ImageView. In the app I have to display these images all over again in different sizes. To do so I'm using Picasso again, loading the saved file into an ImageView and do fit().centercrop() so I don't get any OutofMemory issues. Since Picasso is also capable of using OkHttp's cache and doing the caching by its own, I want to know: * *Are there any advantages about letting Picasso do the caching, over saving it to storage manually and handing it over again to Picasso later? *And would it be a good way to store the shrinked image (after using .fit()) as a new file so the calculation hasn't to be done all the time.
{ "language": "en", "url": "https://stackoverflow.com/questions/38878645", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: matplotlib ticklabels disabling co-ordinates from displaying, twinx/twiny functions any useful? I went through tcaswell's answer on stackoverflow for the question on looking at co-ordinate information after using xticklabels/yticklabels function: http://goo.gl/0Y5VpF that "there is no easy way to do this." I am curious if the job becomes any easier if I had twin axes. (PS: I am newbie to python :) ) e.g. I have a figure in which I have used twinx() + set_yticklabels() functions like this: bx2=bx.twinx() bx2.set_ylim(bx.get_ylim()) bx2.set_yticks(new_tick_locations) bx2.set_yticklabels(mylabellist) I no longer able to see y-position of the cursor in the interactive plot window. Kindly let me know if I could make figure window to look at co-ordinates corresponding to bx axis, so that one can readily look at y co-ordinate upon mouse over. Thanks, sahdeV
{ "language": "en", "url": "https://stackoverflow.com/questions/21268002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Any faces this kind of error in 32-bit machine? I have been using Mongo-db from one month ago i am getting the error as follows "MapViewOfFile failed /data/db/sgserver.4 errno:0 The operation completed successfully. 0". If i check in the DB path c:/data/db the size not exceeded 2GB.I am using windows2003serverR2...Anyone faced same Issue share your experience....... Advance Thanks, A: Default file sizes for MongoDB .ns => 16MB .0 => 64 MB .1 => 128 MB .2 => 256 MB .3 => 512 MB .4 => 1024 MB Add that up and you're just under 2GB. So if you've filled the .4 file, then you won't be able to allocate any more space. (the .5 file will be 2GB) If you log into Mongo and do a db.stats(), how much space are you using? That should tell you how close you are to the limit. A: What size is the /data/db? This error is most likely from Mongo trying to allocate a new database file and that new file would push the size of the db past 2GB. MongoDB allocates database files in fairly large chunks so if you are anywhere near 2GB this could be the problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/4749115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to secure Web API without individual logins? I have an api that calculates some math based on inputs and returns the result. I have multiple asp.net mvc sites that have a javascript graph which updates the graph according to user input / ajax calls from api I want the sites and graph pages to be open access. People should be able to view/update the graphs without having to login. However, I don't want people to be able to directly plug-in to my api and use it for themselves. The only time someone sees the output of the api should be through my own sites. Is this possible? I've been reading through https://identityserver4.readthedocs.io and perhaps I'm misunderstanding, but there's no way to do it without exposing the access token to javascript? I can use C#/MVC to get the access token which keeps username/password from being exposed: var tokenClient = new TokenClient(disco.TokenEndpoint, "client", "secret"); var tokenResponse = await tokenClient.RequestClientCredentialsAsync("api1"); But then for the javascript graph to make api calls, it needs to know that token. Once I've exposed the token to javascript, what's to stop someone getting that token and using it to call the api? And even if the token expires, can't they just automate grabbing a new token from my sites to use in their api calls again? If there's any benefit, I could move all the sites/api to the same server. Perhaps IP restriction could be used, but then again, couldn't someone send requests with a spoofed IP address to get around that? A: Did you checked with the [AllowAnonymous] attribute. If you put this attribute on your "Action" that you want to be open access, then anyone can access the method without login. If you want to allow access to a specific site/source, then please add this in your web.config file inside <system.webServer></system.webServer>. <httpProtocol> <customHeaders> <remove name="Access-Control-Allow-Origin" /> <add name="Access-Control-Allow-Origin" value="*" /> </customHeaders> See here * means you are allowing everyone. You can place your site address instead of * that only you want to access your api. Let me know is that what you want or anything else. A: When your site renders your page, include an encrypted json token in the page. The token will include a timestamp. When your page calls your api, include the token. Your service decrypts the token, validates the timestamp is less that NN minutes. If either of these fail, no business. This way only your site will know how to create the correct token required to call your api. Tokens can not be replayed if the timestamp age is short enough. You can get creative as to the structure/content of the token and how you encrypt, AES is a good choice.
{ "language": "en", "url": "https://stackoverflow.com/questions/42710991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Spinner won't highlight when item is selected By default, when you select an item in spinner, it highlights briefly before disappearing. I changed the color of my spinner rows to alternate color with the following code, and the highlight disappears. R.layout.textviewinside and R.layout.textview don't cause this, just the @Override for getDropDownView, because everything works if I comment out that block. How can I restore that functionality but keep the row colors? products = new ArrayAdapter<String>(this, R.layout.textview, thedata){ @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View v = super.getDropDownView(position, convertView, parent); if (position % 2 == 0) { // we're on an even row v.setBackgroundColor(0xffEBF4FA);//Color.BLUE) } else { v.setBackgroundColor(Color.WHITE); } ((TextView) v).setGravity(Gravity.CENTER); return v; } }; products.setDropDownViewResource(R.layout.textviewinside); spitem.setAdapter(products); A: Instead of using setBackgroundColor, you'll need to use setBackgroundDrawable, and use an xml state list drawable file with pressed/default states. http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList
{ "language": "en", "url": "https://stackoverflow.com/questions/17531288", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Inno Setup Compiler: add page option selected according I want to display a custom page only if the option of an earlier page is activated, for example, i have this code: [Code] var page_option : TInputOptionWizardPage; page_dir_se : TInputDirWizardPage; procedure InitializeWizard(); begin page_option := CreateInputOptionPage(1,'Select','','',False,True); page_option.Add('Option 1'); page_option.Add('Option 2'); page_dir_se :=CreateInputDirPage(page_option.ID,'Select', '','',False, ''); page_dir_se.Add('Select A'); page_dir_se.Add('Select B'); page_dir_se.Add('Select C'); end; In the ​​example only if page_option.Values[0] is TRUE page_dir_se should show me, and if page_option.Values​​[1] is TRUE then should show me another page. I use Inno Setup Compiler Thankz for help. Regards xD A: You can skip any page in the ShouldSkipPage event: [Setup] AppName=My Program AppVersion=1.5 DefaultDirName={pf}\My Program [Code] var DirPage: TInputDirWizardPage; OptionPage: TInputOptionWizardPage; procedure InitializeWizard; begin OptionPage := CreateInputOptionPage(wpWelcome, 'Caption', 'Description', 'SubCaption', False, True); OptionPage.Add('Option 1'); OptionPage.Add('Option 2'); DirPage := CreateInputDirPage(OptionPage.ID, 'Caption', 'Description', 'SubCaption', False, ''); DirPage.Add('Select A'); DirPage.Add('Select B'); DirPage.Add('Select C'); end; function ShouldSkipPage(PageID: Integer): Boolean; begin // skip the page if your custom dir page is about to show and // the option is not checked Result := (PageID = DirPage.ID) and not OptionPage.Values[0]; end;
{ "language": "en", "url": "https://stackoverflow.com/questions/25558501", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Flyway changes performed in previous migration script are not visible to next migrations scripts In a spring-based project, I'm using flyway as a database migration tool. I encounter very strange behavior. Suppose that I have 1 to n migration scripts to execute (mix between JDBC and SQL-based scripts). Flyway performs successfully a sequence of scripts but it stuck suddenly on script n-3 because it is not able to see changes performed in previous scripts. Strangely when I restarted my JAR and continue the migration process, the previous changes become visible to the stuck script and the error disappear. Noting that I use Spring Data to implement my java based migration scripts.
{ "language": "en", "url": "https://stackoverflow.com/questions/75614322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: open two new windows/tabs (different external sites) from a single button press in c# Is there a way I can open two pages, both in external websites, from a single button press in c# (or jquery/javascript, having set the parameters via c#)? The context is I am trying to allow users to share content to both twitter and facebook with a single click. When my user performs an action on my site, they generate (in the c# code-behind) a custom url. this needs to be passed to twitter and the fb share dialog via c#. I'm able to build the 2 urls I need using String.Format to pass my custom url and other information, but at the moment the user needs to press one button for FB, and one for Twitter - I'd love to get that down to a single button press. A: On the button press event can you just load both? ScriptManager.RegisterStartupScript(Page, Page.GetType(), "popup", "window.open('" + url1+ "','_blank')", true); ScriptManager.RegisterStartupScript(Page, Page.GetType(), "popup", "window.open('" + url2+ "','_blank')", true);
{ "language": "en", "url": "https://stackoverflow.com/questions/34731697", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Drag and Drop Javascript - better way I have created a little application where there is a dragzone and within it two elements. I should have possibility to drag and drop these two paragraphs within this area. Code below works pretty well, but when i drop one element at the other element or at the edge of the dropzone or sometimes randomly this element move to the top left corner instead of right place. This is really annoying! Is there a way to go around this issue? Or is there a better way to write this app? var section = document.querySelector("#dragzone"); var currentLabel function moveStart(e) { e.dataTransfer.setData('text/plain', null); myX = e.offsetX === undefined ? e.layerX : e.offsetX; myY = e.offsetY === undefined ? e.layerY : e.offsetY; currentLabel = e.target; } function moveDragOver(e) { e.preventDefault(); e.dataTransfer.dropEffect = "move"; } function moveDrop(e) { e.preventDefault(); currentLabel.style.left = e.offsetX - myX + 'px'; currentLabel.style.top = e.offsetY - myY - 10 + 'px'; } section.addEventListener('dragstart', moveStart, false); section.addEventListener('dragover', moveDragOver, false); section.addEventListener('drop', moveDrop, false); #dragzone { position: relative; width: 300px; height: 300px; border: 2px solid black; } p { position: absolute; top: 20px; left: 20px; } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>My site</title> </head> <body> <div id="dragzone"> <p draggable="true">DraggableElement1</p> <p draggable="true">DraggableElement2</p> </div> </body> </html>
{ "language": "en", "url": "https://stackoverflow.com/questions/41986628", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: dojo: Show or hide divs based on selection in a list Is there a simple way to accomplish this using dojo (jQuery would be easier for me but I have to use dojo): I have a simple unordered list. I don't want dojo to style the list (as it might if I used some widget). When I click a link on the list I want to show a div associated with the link. Then if I click another link in the list the first div hides and that one shows. <div id="content"> <h2>Header</h2> <ul> <li><a href="#sub_content1">Link 1</a></li> <li><a href="#sub_content2">Link 2</a></li> <li><a href="#sub_content3">Link 3</a></li> </ul> <div id="sub_content1" style="display:none;"> <h3>Sub Content Header 1</h3> <p>Lorem ipsum veritas britas conflictum civa</p> </div> <div id="sub_content2" style="display:none;"> <h3>Sub Content Header 2</h3> <p>Lorem ipsum mobius ceti</p> </div> <div id="sub_content3" style="display:none;"> <h3>Sub Content Header 3</h3> <p>Lorem ipsum citrus pecto</p> <ul> <li>Lemons</li> <li>Limes</li> </ul> </div> </div><!-- end of #content --> A: So in fact you're creating your own tabcontainer? If you really want to do it yourself you should probably need something like this: require(["dojo/ready", "dojo/on", "dojo/dom-attr", "dojo/dom-style", "dojo/query", "dojo/NodeList-dom"], function(ready, on, domAttr, domStyle, query) { ready(function() { query("ul li a").forEach(function(node) { query(domAttr.get(node, "href")).forEach(function(node) { domStyle.set(node, "display", "none"); }); on(node, "click", function(e) { query("ul li a").forEach(function(node) { if (node == e.target) { query(domAttr.get(node, "href")).forEach(function(node) { domStyle.set(node, "display", "block"); }); } else { query(domAttr.get(node, "href")).forEach(function(node) { domStyle.set(node, "display", "none"); }); } }); }); }); }); }); I'm not sure how familiar you are with Dojo, but it uses a query that will loop all links in lists (with the dojo/query and dojo/NodeList-dom modules) (you should provide a classname or something like that to make it easier). Then it will, for each link, retrieve the div corresponding to it and hide it, it will also connect a click event handler to it (with the dojo/on module). When someone clicks the link, it will (again) loop all the links, but this time it's doing that to determine which node is the target one and which isn't (so it can hide/show the corresponding div). I made a JSFiddle to show you this. If something is still not clear you should first try to look at the reference guide of Dojo since it really demonstrates the most common uses of most modules. But since this behavior is quite similar to a TabContainer, I would recommend you to look at the TabContainer reference guide.
{ "language": "en", "url": "https://stackoverflow.com/questions/15906685", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: CSS3 :target on named tag not working I am having a hard time getting :target to work on a named tag. The fiddle is here: https://jsfiddle.net/vgcLartp/1 Any ideas why this is not working? A: You need to use target on the sections that you want to show not the links section:target {...} See updated jsfiddle nav { height: 60px; border-bottom: 1px solid #eaeaea; } .nav-item { display: block; float: left; margin-right: 20px; height: 60px; font-size: 26px; line-height: 60px; text-align: center; overflow: hidden; color: #666; text-decoration: none; border-bottom: 3px solid transparent; outline: none; } .nav-item:last-child { margin-right: 0; } .nav-item:hover { color: #333; } .nav-item.active, .nav-item.active:hover { color: #333; border-bottom-color: #b39095; } section:target { visibility: visible; opacity: 1; } /* -------------------------------- SECTIONS -------------------------------- */ #sections { float: left; width: 1200px; height: 400px; } section { position: fixed; width: 630px; height: 400px; float: left; opacity: 0; visibility: hidden; transition: opacity 0.5s linear; } section p { padding-top: 5px; line-height: 1.6em; } section a { color: #b39095; text-decoration: none; } section a:hover { color: #7b618a; } /* --------------------------------- OPTIONS -------------------------------- */ fieldset { margin: 26px 0 15px 0; border: 1px solid #ccc; border-radius: 3px; padding: 10px; } input { padding-left: 2px; } #oxford-app-id { width: 80px; } #oxford-app-key { width: 290px; } label { padding-left: 5px; } <div id="container"> <header> <nav> <a id="options" class="nav-item active" href="#section-options">options<br>saved</a> <a id="about" class="nav-item" href="#section-about">about</a> </nav> </header> <div id="sections"> <section id="section-options"> <p> Options </p> </section> <section id="section-about"> <p> About </p> </section> </div> </div> A: try this :target { visibility: visible; opacity: 1; } A: From w3school: URLs with an # followed by an anchor name link to a certain element within a document. The element being linked to is the target element. The :target selector can be used to style the current active target element. :target selector is useful when within an URL is specified (using an anchor for example) an element in your HTML. In your case you can use: :target { visibility: visible; opacity: 1; }
{ "language": "en", "url": "https://stackoverflow.com/questions/44947386", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android AVD install chrome and firefox I created few AVD's using the AVD Manager. I want to know how can I install chrome/firefox on these AVD's? A: Chrome's .apk Firefox's .apk Download both .apk files and install to your AVD using adb install apk_name A: To install something onto a device, you need to already have the device running. So first, start the device using the emulator command. Then, in a different terminal/command window, use the adb command to install the package. In my case, I've copied the apk file to the platform-tools folder: ./adb install Firefox_17.0.apk Like the rest of the emulator, the installation is slow, so be patient. Of course, this just installs the packages. Getting them to run successfully is another matter entirely. So far, I cannot get the Chrome or Firefox packages to run. Chrome says "Not supported on this version of Android. Version 4.0 is minimal supported version." I am running 4.3 in the emulator. And Firefox starts but then immediately terminates with a "Unfortunately, Firefox has stopped" message. A: Get the apk files and install them through adb (adb install .apk.
{ "language": "en", "url": "https://stackoverflow.com/questions/10139733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: How to remove "continue;"? I have this c++ program that tries to remove vowels from a char array. This works, but I want to do this without continue;. #include <iostream> #include <string.h> using namespace std; int main() { char s[21],afterElimination[19],vowels[] = "aeiou"; cin.get(s,20); int i, n = strlen(s),VowelPos = -1,h = 0; for (i = 0; i < n; i++) { if (strchr(vowels,s[i])) { if(VowelPos == -1) { VowelPos = i; continue; } VowelPos = i - 1; } afterElimination[h++] = s[i]; } afterElimination[h] = NULL; strcpy(afterElimination + VowelPos, afterElimination + VowelPos + 1); cout<<afterElimination; return 0; } A: It's pretty easy to remove continue from the loop. What you need is two indexes in your loop. One for the position in the source array and one for the position in the array to copy to. Then you put the copy operation inside the if statement so if there is no copy you do nothing to go to the next iteration. That would make you loop look like for (int source_index = 0, copy_index = 0; source_index < n; ++source_index) { // increment source_index always if (!strchr(vowels,s[i])) { // this isn't a vowel so copy and increment copy_index afterElimination[copy_index++] = s[i]; } // now this is the continue but we don't need to say it } A: This is a typical approach to filtering letters from a given string. #include <string.h> char s[20] = "something"; char no_vowels[20] = {0}; int i = 0; int j = 0; const char *vowels = "aeiou"; while (s[i]) { if (!strchr(vowels, s[i])) { no_vowels[j] = s[i]; j++; } i++; } Here's a working example.
{ "language": "en", "url": "https://stackoverflow.com/questions/54261350", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: I can't make this JavaScript count working I want to make a button (out of divs) and a paragraph (or any text field) below the divs that counts the clicks. $(document).ready(function() { $('#butt').mousedown(function() { $("#butt").hide(); }); $("#pushed").mouseup(function() { $("#butt").show(); }); $("#butt").click(function() { button_click(); }); }); var clicks = 0; function button_click() { clicks = parseInt(clicks) + parseInt(1); var divData = document.getElementById("showCount"); divData.innerHTML = "Clicks:" + clicks; } <!-- <link type="text/css" rel="stylesheet" href="CSS.css"/> --> <form name="ButtonForm"> <div id="container"> <div id="pushed"></div> <div id="butt"></div> </div> <div id="showCount"></div> <script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script> <!--<script src="Untitled-1.js" type="text/javascript"></script>--> </form> A: Your div elements are empty and there is no CSS to give them any explicit size, so they will never be visible for you to click on them. Also, the mousedown event handler can and should be combined with the click handler for butt and the mouseup event handler should just be a click event as well. Additionally, you only need to update the number of clicks, not the word "Clicks", so make a separate placeholder for the number with a span element and then you can hard-code the word "Clicks" into the div. Lastly, to increment a number by one, you can just use the pre or post-increment operator (++). $(document).ready(function() { var clicks = 0; var divData = $("#clickCount"); $("#pushed").on("click", function() { $("#butt").show(); }); $("#butt").on("click", function() { $("#butt").hide(); clicks++; // increment the counter by one divData.html(clicks); }); }); #pushed, #butt {height:50px; width:150px; background-color:green; margin:5px;} <body> <form name="ButtonForm"> <div id="container"> <div id="pushed"></div> <div id="butt"></div> </div> <div id="showCount">Clicks <span id="clickCount"></span></div> <script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script> </form> </body> A: First of all, you should simplify your code. Hiding and showing the button is not necessary to produce the result you are looking for. Second, change the #butt element to an actual button so that you have something to see and click. Third, make sure your script is loading after jquery is included. <script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script> <button id="butt">I'm a button</button> <div id="showCount"></div> <script> $(document).ready(function() { $("#butt").click(function() { button_click(); }); var clicks = 0; function button_click() { clicks = parseInt(clicks) + parseInt(1); var divData = document.getElementById("showCount"); divData.innerHTML = "Clicks:" + clicks; } }); </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/41249981", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Proxy for MSGraph APIs I am trying to create an adapter (WEB API that will act as a pass through) for invoking the MS Graph APIs for managing my Active Directory. AD objects like application and users will be customized to meet our application needs (removing some attributes, adding some extension attributes etc.) and a transformation from our application specific object to AD object would happen in our adapter layer before and after calling MS Graph APIs. MS Graph APIs currently supports OData queries. Applications and users would be read as page-wise. If I have to provide the same OData options in my pass thru Web API layer, how can I do that? i.e. * *API A supports OData queries. *API B calls the methods that support OData queries in API A. *API B is exposed to the client. When the client calls the method from API B with OData $Filter, the result has to be returned. How can I support the OData options in API B? Thanks in advance. A: Well, I'm not sure I get your question correctly but, from what I understand, you just want to proxy the API calls to MS Graph and make some changes on the fly to the response. OData queries are just simple query parameters (see the OData tutorial). So, basically, you just have to get those query parameters in your proxy and forward them to the MS Graph. The response you'll get will then be compliant with the original query. However, depending on how you mangle the data, you may end up not being compliant with the user query. For example: * *The user made a $select(Id) query, but your logic add a custom property Foo. The user just wanted Id but you added Foo anyway. *The user made an $orderby Name asc query, but your logic modify the property Name. It may not be ordered after your logic. *The user wants to make $filter query on the Foo property. MS Graph will complain because it doesn't know the Foo property. *Etc. If you want to handle that cases, well, you'll have to parse the different OData queries and adapt your logic accordingly. $orderby, $top/$skip, $count, $expand and $select should be pretty straight-forward ; $filter and $search would require a bit more work. A: Thanks. I was looking for a solution to this. https://community.apigee.com/questions/8642/how-do-we-fetch-the-query-parameters-odata-standar.html Instead of parsing the URL to get the OData query parameters, i wanted to understand the standard method to process the OData requests. Now I am doing the below to extract the OData query parameters and passing them to MSGraph API. string strODataQuery = String.Join("&", HttpContext.Request.Query.Where(kvp => kvp.Key.StartsWith("$")) .Select(kvp => String.Format("{0}={1}", kvp.Key, Uri.EscapeDataString(kvp.Value)))); And I am performing the conversions after retrieving the results. Regards
{ "language": "en", "url": "https://stackoverflow.com/questions/51611623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Hibernate - Updating an ID of a parent in a child without updating parent? I couldn't find the answer or didn't phrase this question properly. If you guys know... let me know :-) I have a parent which has children.... on the child, I have regular vars that map to column names However, one is mapped as many-to-one. The child basically contains the ID for the parent. Except in the child I obviously contain the entity of the parent, not the id. ie: (QUICK simple example....) @ManyToOne(fetch= FetchType.EAGER) @JoinColumn(name="bcId",referencedColumnName="id") private ParentEntityClass theParentClass; How, can I set the the parent object in this hibernate entity so it ONLY uses the parent entity for the ID and doesn't try to save the parent. Should I use Cascade.refresh so it refreshes but doesn't update the parent? Thanks :)
{ "language": "en", "url": "https://stackoverflow.com/questions/21609497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why are these MongoDB sums not adding up? Lets say I have 2 documents: { "_id" : "8tvgUTKt2U", "answers" : [ [ NumberInt(-1) ] ] }, { "_id" : "BDTESUEIlm", "answers" : [ [ NumberInt(1) ], [ NumberInt(-1) ] ] } I would like to total the values of the array items. But when I $unwind 'answers' and $sum them in $group pipeline I get this: { "_id" : "BDTESUEIlm", "answerTotal" : NumberInt(0) } { "_id" : "8tvgUTKt2U", "answerTotal" : NumberInt(0) } What am I doing wrong? A: It’s because when you $unwind a two dimensional array once you end up with just an array and $sum gives correct results when applied to numerical values in $group pipeline stage otherwise it will default to 0 if all operands are non-numeric. To remedy this, you can use the $sum in a $project pipeline without the need to $unwind as $sum traverses into the array to operate on the numerical elements of the array to return a single value if the expression resolves to an array. Consider running the following pipeline to get the correct results: db.collection.aggregate([ { '$project': { 'answerTotal': { '$sum': { '$map': { 'input': '$answers', 'as': 'ans', 'in': { '$sum': '$$ans' } } } } } } ])
{ "language": "en", "url": "https://stackoverflow.com/questions/52265362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SQL update query not cooperating I am adding a save/update button to the bottom of my editing form on my admin panel. For some reason, whenever I make a change to the form and click save it just reloads the page with no changes made. I also noticed that ONLY when I try to run the code from the pages.php file(runnning from index then clicking pages is fine) it says: Undefined variable: dbc in C:\Users\Jake\Desktop\Xampp\htdocs\jakefordsite\admin\content\pages.php on line 12 Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\Users\Jake\Desktop\Xampp\htdocs\jakefordsite\admin\content\pages.php on line 12 I can get rid of this error by declaring a new $dbc(databaseconnection) variable in pages.php, but I still have the same problem updating my form data. PAGES.PHP: <?php ## Page Manager ?> <h2>Page Manager</h2> <div class="col sidebar"> <ul> <?php $q = "SELECT * FROM pages ORDER BY name ASC"; $r = mysqli_query($dbc, $q); if ($r) { while ($link = mysqli_fetch_assoc($r)) { echo '<li><a href="?page=pages&id='.$link['id'].'">'.$link['name'].'</a></li>'; } } ?> </ul> </div> <div class="col editor"> <?php if (isset($_POST['submitted']) == 1) { $q = "UPDATE pages SET title='$_POST[title]', name='$_POST[name]', body='$_POST[body]', WHERE id = '$_POST[id]'"; $r = mysqli_query($dbc, $q); } if (isset($_GET['id'])) { $q = "SELECT * FROM pages WHERE id = '$_GET[id]' LIMIT 1"; ; $r = mysqli_query($dbc, $q); $opened = mysqli_fetch_assoc($r); ?> <form action="?page=pages&id=<?php echo $opened['id'] ?>" method="post"> <p><label>Page title: </label><input type="text" size="30" name="title" value="<?php echo $opened['title']?>"></p> <p><label>Page name:</label> <input type="text" size="30" name="name" value="<?php echo $opened['name']?>"></p> <label>Page body: </label><br> <textarea name="body" cols="30" rows="8"><?php echo $opened['body'] ?></textarea> <input type="hidden" name="submitted" value="1"/> <input type="hidden" name="id" value="<?php echo $opened['id'] ?>"/> <p><input type="submit" name="submit" value="Save Changes"/></p> </form> <?php } ?> </div> INDEX.PHP: <?php // Setup document: include('config/setup.php'); ?> <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title><?php //echo $page_title; ?>JakeForDesign - Admin Panel</title> <link rel="stylesheet" type="text/css" href="css/styles.css"> </head> <body> <div class="wrap_overall"> <div class="header"> <?php head(); ?> </div> <div class="nav_main"> <?php nav_main(); ?> </div> <div class="content"> <?php include('content/'.$pg.'.php'); ?> </div> <div class="footer"> <?php footer(); ?> </div> </div> </body> </html> SETUP.PHP <?php ## Setup Document // host(or location of the database), username, //password, database name $dbc = @mysqli_connect('127.0.0.1', 'root', 'password', 'main') OR die ('Could not connect to the database because: '. mysqli_connect_error() ); include('Functions/sandbox.php'); include('Functions/template.php'); if (isset($_GET['page']) == '') { $pg = 'home'; } else { $pg = $_GET['page']; } $page_title = get_page_title($dbc, $pg); ?> A: on Pages.php you have $r = mysqli_query($dbc, $q); $q is fine but you have not mentioned $dbc on your setup page, create a class for connection, declareing a connection method and then, on PAGES.PHP: $db_obj = new setup(); /* create object for setup class */ $dbc = $db_obj -> connect_db();/* call connection method */
{ "language": "en", "url": "https://stackoverflow.com/questions/20089603", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: c++ how to create a std::vector of functors class A { public: int x; //create a vector of functors in B and C here }; class B { public: struct bFunctor { void operator()() const { //some code } }; }; class C { public: struct cFunctor { void operator()() const { //some code } }; }; void main() { A obj; //iterate through the vector in A and call the functors in B and C } My question is what should be the format of the vector in class A for calling functors in B and C? Or is the only way this is possible to have a base functor in A and make the functors in B and C derive from it? Or is there a better approach? A: There are essentially two ways to approach this (that I can think of ATM): Note: I would rename cFunctor and bFunctor to simply Functor in both cases. They are nested inside respective classes and thus such prefix makes little sense. Type erased Example of type erasure is std::function. class A { public: int x; std::vector<std::function<void(void)>> functors; A() : functors { B::bFunctor(), C::cFunctor() } { } }; If you need the functors to have more advanced behaviour, Boost.TypeErasure any might help. Polymorphic * *Create an abstract functor type. *Make B::bFunctor and C::cFunctor inherit from it. *Store vector of that abstract functor type smart pointers. struct AbstractFunctor { virtual void operator()() const = 0; }; class B { public: struct Functor : public AbstractFunctor { void operator()() const { //some code } }; }; class A { public: int x; std::vector<std::unique_ptr<AbstractFunctor>> functors; A() { // this could most probably be shortened with make_unique functors.emplace_back(std::unique_ptr<AbstractFunctor>(new B::Functor())); functors.emplace_back(std::unique_ptr<AbstractFunctor>(new C::Functor())); } };
{ "language": "en", "url": "https://stackoverflow.com/questions/17864064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Cannot validate, with novalidate option Hi I was inserting some date do my table. For some reasons I had to disable my constraint. The constraint was associated with index. I. ve used this line of code: ALTER TABLE my_table DISABLE CONSTRAINT "my_constraint" drop index And my_constraint is in disable state. No I' d like to enable this constraint, but after calling this line: ALTER TABLE my_table ENABLE NOVALIDATE CONSTRAINT "my_constraint";\ I recive an error: ORA-02299: cannot validate (USER.my_constraint) - - duplicate keys found A: You cannot have non-unique values with a unique index. But you can have non-unique values with a unique constraint that is enforced by a non-unique index. Even if you initially created a non-unique index, the drop index and enable syntax will try to recreate a unique index unless you provide more details in the using index section. For example: SQL> create table my_table(my_column number, 2 constraint my_constraint unique (my_column)); Table created. SQL> alter table my_table disable constraint my_constraint drop index; Table altered. SQL> insert into my_table select 1 from dual union all select 1 from dual; 2 rows created. SQL> alter table my_table enable novalidate constraint my_constraint; alter table my_table enable novalidate constraint my_constraint * ERROR at line 1: ORA-02299: cannot validate (USER.MY_CONSTRAINT) - duplicate keys found SQL> alter table my_table enable novalidate constraint my_constraint 2 using index (create index my_index on my_table(my_column)); Table altered. SQL> --The constraint is enforced, even though other rows violate it. SQL> insert into my_table values(1); insert into my_table values(1) * ERROR at line 1: ORA-00001: unique constraint (USER.MY_CONSTRAINT) violated A: When you inserted the rows into your table you violated the constraint, looks like it is a unique constraint based on the error message "duplicate keys found" check what columns the constraint is based on, and then do a quick query like the following to see if you have any rows with duplicates (columna and columnb are the columns in your unique constraint) SELECT columna, columnb COUNT() FROM mytable HAVING COUNT() > 1 You won't be able to enable the unique constraint until all the rows in the table meet the rules of the constraint.
{ "language": "en", "url": "https://stackoverflow.com/questions/7981221", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Handling the Windows.UI.Xaml.Application.Suspending event I try to resolve the dreaded .WindowsPhone.exe!{<ID>}_Quiesce_Hang hang issue of my WinRT (Windows Phone 8.1) app. At the moment I have the following handling of the Windows.UI.Xaml.Application.Suspending event: private void App_Suspending(object iSender, SuspendingEventArgs iArgs) { SuspendingDeferral clsDeferral = null; object objLock = new object(); try { clsDeferral = iArgs.SuspendingOperation.GetDeferral(); DateTimeOffset clsDeadline = iArgs.SuspendingOperation.Deadline; //This task is to ensure that the clsDeferral.Complete() //is called before the deadline. System.Threading.Tasks.Task.Run( async delegate { //Reducing the timeout by 1 second just in case. TimeSpan clsTimeout = clsDeadline.Subtract(DateTime.UtcNow).Subtract(TimeSpan.FromSeconds(1)); if (clsTimeout.TotalMilliseconds > 100) { await System.Threading.Tasks.Task.Delay(clsTimeout); } DeferrerComplete(objLock, ref clsDeferral); }); //Here I execute the suspending code i.e. I serializing the app //state and save it in files. This may take more than clsTimeout //on some devices. ... //I do not call the Complete method here because the above //suspending code is old-fashoin asynchronous i.e. not async but //returns before the job is done. //DeferrerComplete(objLock, ref clsDeferral); } catch { DeferrerComplete(objLock, ref clsDeferral); } } private static void DeferrerComplete(object iLock, ref SuspendingDeferral ioDeferral) { lock (iLock) { if (ioDeferral != null) { try { ioDeferral.Complete(); } catch { } ioDeferral = null; } } } I have read the answer about the _Quiesce_Hang problem. I get the idea that it might be related to app storage activity. So my question is: what am I missing? Does my handling of the Suspending event look OK?
{ "language": "en", "url": "https://stackoverflow.com/questions/37298079", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unity 2 and Enterprise library configuration tool Can someone show me how to use Enterprise library configuration tool with Unity2 Whatever I did, when I open the Enterprise library configuration tool, I could not have it working with a Unity config file. When I click on the menu to add a new block, there is no Unity configuration block What am I doing wrong? Thank you for your help A: Unity 2.0 and documentation is available as a separate download as of today. http://msdn.microsoft.com/unity http://blogs.msdn.com/agile/archive/2010/04/20/microsoft-enterprise-library-5-0-released.aspx Unfortunately the limited support for the Unity configuration in the Configuration Tool that you may have seen in one of the EntLib 5.0 betas didn't make it into the final release due to time constraints. However, we have made the Unity configuration XML significantly easier to author with things like assembly and namespace aliasing to save having to repeatedly specify fully qualified types. A: We have released Unity 2.0 standalone, Unity 2.0 for Silverlight as well as Enterprise Library 5.0 full documentation set today. A: Unity 2 is not yet finalized (still in Beta 2). I guess we have to wait. Besides, Unity 2 config file is much easier to be typed manually, compared to the 1.x versions. A: If interested in Unity config tool, which was part of the beta but didn't make it to the final EntLib5.0 release, you can find it here
{ "language": "en", "url": "https://stackoverflow.com/questions/2763420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Testing android app. Trying to mock getSystemService. Have been struggling with this for quite some time now, enough to make a user here on stack overflow actually. We're developing an android application, and I want to test a method inside an activity class. I have done some unit testing before, but never for an android project, and I've never tried mocking before. The method I'm trying to test: public boolean isGPSEnabled() { LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); GPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); return GPSEnabled; } This method checks if the android device got the GPS enabled and returns true if it is, false if not. I'm trying to mock the LocationManager and the Context, and this is what I have so far: @RunWith(MockitoJUnitRunner.class) public class IsGPSEnabledTest { @Mock LocationManager locationManagerMock = mock(LocationManager.class); MockContext contextMock = mock(MockContext.class); @Test public void testGPSEnabledTrue() throws Exception { when(contextMock.getSystemService(Context.LOCATION_SERVICE)).thenReturn(locationManagerMock); when(locationManagerMock.isProviderEnabled(LocationManager.GPS_PROVIDER)).thenReturn(true); MapsActivity activity = new MapsActivity(); assertEquals(true, activity.isGPSEnabled()); } } When I run this test I get this error: "java.lang.RuntimeException: Method getSystemService in android.app.Activity not mocked." Any help on this would be appreciated. A: Pass the mocked context to your method in activity. @Test public void isGpsOn() { final Context context = mock(Context.class); final LocationManager manager = mock(LocationManager.class); Mockito.when(context.getSystemService(Context.LOCATION_SERVICE)).thenReturn(manager); Mockito.when(manager.isProviderEnabled(LocationManager.GPS_PROVIDER)).thenReturn(true); assertTrue(activity.isGpsEnabled(context)); }
{ "language": "en", "url": "https://stackoverflow.com/questions/49007114", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: double returning only one precision in java in my code i am performing division on numbers and storing it in a double variable. but the variable is returning with only one precision. i want to increase the precision how could i do that. double x; for ( int i =0 ; i<10000 ; i++) { x= w[i] / l[i]; System.out.println(x); } in the above code w and l are integer arrays; i am getting output like 3.0 0.0 1.0 0.0 i want to increase the precision upto 4 atleast. A: Use x = ((double) w[i]) / l[i]; As it is, you're dividing two integers using integer division, and assigning the resulting int to a double. Casting one of the operands to a double makes it do a double division instead. A: If you divide an int by another int you get an int not a double. Try x = (double) w[i] / l[i]; A: System.out.printf("%10.4f", x); Mind, only BigDecimal has precise precision. Doubles are approximations.
{ "language": "en", "url": "https://stackoverflow.com/questions/13903457", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can the models.py file created by Django be used by another python file to fill in a database? I have followed the tutorial (parts 1 and 2) on the Django site (https://docs.djangoproject.com/en/1.4/intro/tutorial01/) and have managed to create a couple folders and to connect to my website. My app is called 'app', so my folder structure looks a bit like: * *mainFolder *---__init__.py *---test.py *---djangoSite (created by Django) *------ manage.py *------ djangosite *--------- other .py files *------ app *----------__init__.py *--------- models.py *--------- other .py files I changed the models.py file to be something like: class Result(models.Model): options = models.CharField(max_length = 1000, unique = False) reverse = models.DecimalField(decimal_places = 6, max_digits = 12) test.py currently runs a couple tests on some other classes. What I want is for my test.py class to run these tests and save the results in a database (in columns and reverse). I was hoping to do something like this in my test.py class: import models.py if __name__ == "__main__": optionResult = someTestsThatRuns reverseResult = someOtherTestThatRuns models.Result c; c.options = optionResult c.reverse = reverseResult I'd like for the last two lines to save the result in the database. Is this possible? How would I import the models.py from the app folder? Thank you EDIT: When I say someTestsThatRuns, these aren't unit tests. They are practically a function that returns a list and some strings with either 'PASS' or 'FAIL'. Sorry for the confusion A: Create an empty __init__.py file in the app folder so Python treats the directory as a package. Then do: from app.models import Result optionResult = someTestsThatRuns reverseResult = someOtherTestThatRuns c = Result() c.options = optionResult c.reverse = reverseResult c.save() That will save 'c' to the database. Note that Django's test suite can create its own test database, which runs tests on a separate database. You can read more about Django testing here. https://docs.djangoproject.com/en/dev/topics/testing/?from=olddocs A: FIXED As David mentioned in the comments, the environment variable was indeed not set. Since I was in Windows, what I had to do was Start -> Computer -> Properties -> advanced System Settings -> Environment Variables -> add Environment Variable. There I added 'DJANGO_SETTINGS_MODULE' and its location as 'C:\path\to\your\settings.py' Afterwards, in command prompt, I had to do the following: enter python >import sys >import os >sys.path.append(r"C:\location\to\settings.py") >from django.core.management import setup_environ >setup_environ(settings) >sys.path.append(os.getcwd() + '\\from\\current\\to\\models.py' >from models import Result This is all explained at http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/ , though I did find it somewhat difficult to understand. Another problem I had with importing my models is that there were TWO folders named exactly the same (djangoSite), so when importing, the computer had some issues trying to figure out which one. I had to rename, remove, reset environment variable and recheck all of the paths I have throughout my files =/ I am sorry if my explanations aren't the best, I barely understood what I did, but I do hope this will help other in the future
{ "language": "en", "url": "https://stackoverflow.com/questions/11335327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Integration class Hey everybody here is my code: package Chapter5; import java.util.Scanner; public class MainMenu extends Integration { static Scanner s = new Scanner(System.in); static int c; static double lower, upper; static double Curves; static double sum = 0; public static void main(String[] args) { while(true) { System.out.println("Please choose one of the options"); System.out.println("1: Calculate the area between two curves"); System.out.println("2: Calculate the volume when two curves are revolved about a disk"); System.out.println("3: Calculate the volume when a single curve is revolved about a shell"); System.out.println("4: Quit"); c = s.nextInt(); if(c == 1) { System.out.println("Area between two curves"); System.out.println("Please enter the lower limit"); lower = s.nextInt(); System.out.println("Please enter the upper limit"); upper = s.nextInt(); System.out.print("Lower limit: " + lower); System.out.println(" Upper limit: " + upper); System.out.println("The area under the f curve: " + sumf); System.out.println("The area under the g curve: " + sumg); sum = sumf - sumg; System.out.println("Area between the two curves = " + sum); } if(c == 2) { System.out.println("Working"); } if(c == 3) { System.out.println("Working"); } if(c == 4) { break; } } } Here is my Integration class: package Chapter5; /*Author: Cory Zander * Purpose: Find the area and volume between two curves */ public class Integration { static double x; static double dx; static double f, g; static double sumg = 0; static double sumf = 0; public static double f(double x) { f = x * Math.exp(x); return x; } public static double g(double x) { g = Math.pow(x, 2); return x; } public static double Areaf(double lower, double upper) { int i; x = lower; dx = (upper - lower)/2000; for(i = 0; i <= 2000; i++) { if(i == 0 || i == 2000) { sumf += f; } else { sumf += 2 * f; } x += dx; } sumf *= dx/2; return sumf; } public static double Areag(double lower, double upper) { int i; x = lower; dx = (upper - lower)/2000; for(i = 0; i <= 2000; i++) { if(i == 0 || i == 2000) { sumg += g; } else { sumg += 2 * g; } x += dx; } sumg *= dx/2; return sumg; } Okay I just edited this and fixed the areaf and areag issue, but for some reason when I get the area under the f curve I still get 0. Why is it not taking the sumf from the Integration class A: public static void main(String[] args){ if (c == 1){ //... double area1 = Integration.Areaf(lower, upper); double area2 = Integration.Areag(lower, upper); sum = area1 - area2;//sum and minus used? System.out.println("Area between the two curves = " + sum); } } Also you used inheritance incorrectly cause all your methods in base class (Integration) are static. You can simply delete extends clause from sub class or adjust it in correct way.
{ "language": "en", "url": "https://stackoverflow.com/questions/13713585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: create value to a model from another model's method I'm trying to create a new table (Payslip model) that will contain the computed salary on an employee in a cutoff. I want Payslip.salary to get value from Employee.compute_pay() Given the example in the url link above, what should my views.py look like? Is this the best approach to this kind of process? or Is there any library that can help with what I want to do here? https://imgur.com/a/wVG5qrd model.py class Employee(models.Model): name = models.CharField(max_length=20) rate = models.IntegerField() absent = models.IntegerField() def __str__(self): return self.name def compute_pay(self): daily = rate / 20 return rate - (daily*absent) class Payslip(models.Model): name = models.CharField(max_length=20) salary = models.IntegerField() def __str__(self): return self.name views.py def compute(request): if request.method == "POST": return render(request,'payroll/compute/compute.html') A: I do not think there is a need for another model Payslip, also you have no ForeignKey connections between the two models for it to work. Considering your requirement, property decorator should work. Read up on how @property works. Basically, it acts as a pseudo model field, keep in mind the value of this field is not stored anywhere in the database, but it is tailor-made for situations like this where the field changes based on other fields and is needed for read-only. Try this class Employee(models.Model): name = models.CharField(max_length=20) rate = models.IntegerField() absent = models.IntegerField() def __str__(self): return self.name @property def compute_pay(self): daily = self.rate / 20 return (self.rate - (daily*self.absent)) you can get the employee's salary by Employee.compute_pay just like any other model field
{ "language": "en", "url": "https://stackoverflow.com/questions/54926789", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to query classes with edges in orient Db? My problem is, how can I query β€œChat” table to retrieve person’s details in Profile Table. ParticipatinIn edge started from Person to chat. HasProfile Edge came started person to Profile. Please Help me to solve this.. Thank You A: I have used this structure You can use a query like this : select name, person.name, person.out("hasProfile").name as profile from (select name, in('ParticipatinIn') as person from Chat unwind person) unwind profile If you use traverse, if a person is a part of two different Chat, you got that person only one time. Hope it helps. A: With this schema: Try this: select name, in('HasProfile').name as Person, in('HasProfile').out('ParticipatingIn').name as Chat from Profile This is the output: If you don't like see the bracket you can use the unwind command: select name, in('HasProfile').name as Person, in('HasProfile').out('ParticipatingIn').name as Chat from Profile unwind Person,Chat This is the output: UPDATE select name, in('ParticipatingIn').name as Person, in('ParticipatingIn').out('HasProfile').name as Profile from Chat UPDATE 2 traverse * from Chat Hope it helps Regards.
{ "language": "en", "url": "https://stackoverflow.com/questions/37585048", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Split Strtotime('now') to seconds and minutes I am developing a browser game where the player gets hospitalized for 30 minutes when his health becomes 0. I am using strtotime to check how much time is left until he gets out of the hospital. <?php $current_time = strtotime('now') + 1800; // This variable goes to the database // The player gets hospitalized for 30 minutes, that's 1800 seconds. // Updating the database ... $sql = "UPDATE playerstats SET hospitalized='1', hospitaltimer=$current_time WHERE id = $id"; ?> Now let's say the player is in the page where it says he has to wait ?? minutes ?? seconds until he gets out of the hospital. <?php // Getting the timer from the database ... global $db; $sql = "SELECT * FROM playerstats WHERE id=$id"; $stmt = $db->query($sql); $result = $stmt->fetchAll(); $timer = $result[0]['hospitaltimer']; // substracting strtotime('now') from the timer to see how many seconds are left // until the player is released from the hospital $timer = $timer - strtotime('now'); // Lets just say that 2 minutes have passed, the $timer should now be with a result // like 1680 or something, ?> My question is, how to split that timer to minutes and seconds? I want to split the 1680 seconds that remain to minutes and seconds. Thanks anyways. A: Since you're storing hospitaltimer as seconds from the unix epoch, substracting both strtotime figures would then be converted to a date that's, for example, 1680 seconds after the unix epoch. Not what you're looking for. I'd suggest approaching this by storing the "exit time" in yyyy-mm-dd format a.- You'd need to alter your table and convert hospitaltimer to a DATETIME field. that's pretty straight-forward b.- change your code to store the hospitaltimer value as a yyyy-mm-dd hh:mm:ss like this: $current_time = date('Y-m-d H:i:s', strtotime('now') + 1800); // This variable goes to the database and then change the logic to show the remaining time: $timer = date_create($result[0]['hospitaltimer']); // the "exit time" you inserted $now = date_create(date('Y-m-d H:i:s')); $diff = date_diff($timer,$now)->format('%r%i minutes %s seconds'); if ($diff < 0) { echo "out"; } else { echo $diff." before being able to leave"; } Alternatively, substracting the output of different strtotime() operations would be a non-standard way to calculate dates which you could work around by: $timer = $timer - strtotime('now'); // now the timer reads 1680 per your example $seconds = $timer % 60; // use modulo 60 to calculate seconds remaining after dividing seconds by 60 and retrieving the integer part of the result $minutes = ($timer - $seconds) / 60; // from full timer, substract the seconds and the remaining amount, divided by 60 is converted to minutes Both of these alternatives would work, but the benefit of storing the hospitaltimer as a timestamp is that at any given point you could easily query the table to find out how many users are still hospitalized (for example) by simply using a where hospitaltimer > now()
{ "language": "en", "url": "https://stackoverflow.com/questions/55130258", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Quarkus and JDBI integration: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default] I'm trying to use Quarkus and JDBI β€” not so many examples on this out there I would say :/ The Gradle script has these dependencies: dependencies { implementation(enforcedPlatform("io.quarkus:quarkus-universe-bom:2.1.3.Final")) implementation(enforcedPlatform("org.jdbi:jdbi3-bom:3.21.0")) implementation("org.jdbi:jdbi3-core") implementation("org.jdbi:jdbi3-sqlobject") runtimeOnly("io.quarkus:quarkus-config-yaml") runtimeOnly("io.quarkus:quarkus-flyway") runtimeOnly("io.quarkus:quarkus-jdbc-h2") ... } I have a class to configure (and integrate) JDBI: @ApplicationScoped public class PersistenceConfig { @Inject DataSource dataSource; @Singleton public Jdbi jdbi() { return Jdbi.create(dataSource) .installPlugin(new SqlObjectPlugin()); } @Produces public ActorRepository actorRepository(final Jdbi jdbi) { return jdbi.onDemand(ActorRepository.class); } } And I think the problem is somehow within that one (and the datasource), because I'm currently getting this error when starting the application: 2021-08-27 11:31:32,852 ERROR [io.qua.dep.dev.IsolatedDevModeMain] (main) Failed to start quarkus: java.lang.RuntimeException: io.quarkus.builder.BuildException: Build failure: Build failed due to errors [error]: Build step io.quarkus.arc.deployment.ArcProcessor#validate threw an exception: javax.enterprise.inject.spi.DeploymentException: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default] - java member: org.acme.config.PersistenceConfig#dataSource - declared on CLASS bean [types=[java.lang.Object, org.acme.config.PersistenceConfig], qualifiers=[@Default, @Any], target=org.acme.config.PersistenceConfig] at io.quarkus.arc.processor.BeanDeployment.processErrors(BeanDeployment.java:1094) at io.quarkus.arc.processor.BeanDeployment.init(BeanDeployment.java:259) at io.quarkus.arc.processor.BeanProcessor.initialize(BeanProcessor.java:129) at io.quarkus.arc.deployment.ArcProcessor.validate(ArcProcessor.java:418) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at io.quarkus.deployment.ExtensionLoader$2.execute(ExtensionLoader.java:820) at io.quarkus.builder.BuildContext.run(BuildContext.java:277) at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18) at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449) at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478) at java.base/java.lang.Thread.run(Thread.java:829) at org.jboss.threads.JBossThread.run(JBossThread.java:501) Caused by: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default] Caused by: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default] - java member: org.acme.config.PersistenceConfig#dataSource - declared on CLASS bean [types=[java.lang.Object, org.acme.config.PersistenceConfig], qualifiers=[@Default, @Any], target=org.acme.config.PersistenceConfig] at io.quarkus.arc.processor.Beans.resolveInjectionPoint(Beans.java:492) at io.quarkus.arc.processor.BeanInfo.init(BeanInfo.java:463) at io.quarkus.arc.processor.BeanDeployment.init(BeanDeployment.java:247) ... 13 more at io.quarkus.runner.bootstrap.AugmentActionImpl.runAugment(AugmentActionImpl.java:415) at io.quarkus.runner.bootstrap.AugmentActionImpl.createInitialRuntimeApplication(AugmentActionImpl.java:275) at io.quarkus.runner.bootstrap.AugmentActionImpl.createInitialRuntimeApplication(AugmentActionImpl.java:66) at io.quarkus.deployment.dev.IsolatedDevModeMain.firstStart(IsolatedDevModeMain.java:91) at io.quarkus.deployment.dev.IsolatedDevModeMain.accept(IsolatedDevModeMain.java:424) at io.quarkus.deployment.dev.IsolatedDevModeMain.accept(IsolatedDevModeMain.java:64) at io.quarkus.bootstrap.app.CuratedApplication.runInCl(CuratedApplication.java:136) at io.quarkus.bootstrap.app.CuratedApplication.runInAugmentClassLoader(CuratedApplication.java:93) at io.quarkus.deployment.dev.DevModeMain.start(DevModeMain.java:145) at io.quarkus.deployment.dev.DevModeMain.main(DevModeMain.java:63) Caused by: io.quarkus.builder.BuildException: Build failure: Build failed due to errors Caused by: io.quarkus.builder.BuildException: Build failure: Build failed due to errors [error]: Build step io.quarkus.arc.deployment.ArcProcessor#validate threw an exception: javax.enterprise.inject.spi.DeploymentException: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default] - java member: org.acme.config.PersistenceConfig#dataSource - declared on CLASS bean [types=[java.lang.Object, org.acme.config.PersistenceConfig], qualifiers=[@Default, @Any], target=org.acme.config.PersistenceConfig] at io.quarkus.arc.processor.BeanDeployment.processErrors(BeanDeployment.java:1094) at io.quarkus.arc.processor.BeanDeployment.init(BeanDeployment.java:259) at io.quarkus.arc.processor.BeanProcessor.initialize(BeanProcessor.java:129) at io.quarkus.arc.deployment.ArcProcessor.validate(ArcProcessor.java:418) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at io.quarkus.deployment.ExtensionLoader$2.execute(ExtensionLoader.java:820) at io.quarkus.builder.BuildContext.run(BuildContext.java:277) at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18) at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449) at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478) at java.base/java.lang.Thread.run(Thread.java:829) at org.jboss.threads.JBossThread.run(JBossThread.java:501) Caused by: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default] Caused by: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default] - java member: org.acme.config.PersistenceConfig#dataSource - declared on CLASS bean [types=[java.lang.Object, org.acme.config.PersistenceConfig], qualifiers=[@Default, @Any], target=org.acme.config.PersistenceConfig] at io.quarkus.arc.processor.Beans.resolveInjectionPoint(Beans.java:492) at io.quarkus.arc.processor.BeanInfo.init(BeanInfo.java:463) at io.quarkus.arc.processor.BeanDeployment.init(BeanDeployment.java:247) ... 13 more at io.quarkus.builder.Execution.run(Execution.java:116) at io.quarkus.builder.BuildExecutionBuilder.execute(BuildExecutionBuilder.java:79) at io.quarkus.deployment.QuarkusAugmentor.run(QuarkusAugmentor.java:151) at io.quarkus.runner.bootstrap.AugmentActionImpl.runAugment(AugmentActionImpl.java:413) ... 9 more Caused by: javax.enterprise.inject.spi.DeploymentException: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default] Caused by: javax.enterprise.inject.spi.DeploymentException: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default] - java member: org.acme.config.PersistenceConfig#dataSource - declared on CLASS bean [types=[java.lang.Object, org.acme.config.PersistenceConfig], qualifiers=[@Default, @Any], target=org.acme.config.PersistenceConfig] at io.quarkus.arc.processor.BeanDeployment.processErrors(BeanDeployment.java:1094) at io.quarkus.arc.processor.BeanDeployment.init(BeanDeployment.java:259) at io.quarkus.arc.processor.BeanProcessor.initialize(BeanProcessor.java:129) at io.quarkus.arc.deployment.ArcProcessor.validate(ArcProcessor.java:418) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at io.quarkus.deployment.ExtensionLoader$2.execute(ExtensionLoader.java:820) at io.quarkus.builder.BuildContext.run(BuildContext.java:277) at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18) at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449) at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478) at java.base/java.lang.Thread.run(Thread.java:829) at org.jboss.threads.JBossThread.run(JBossThread.java:501) Caused by: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default] Caused by: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default] - java member: org.acme.config.PersistenceConfig#dataSource - declared on CLASS bean [types=[java.lang.Object, org.acme.config.PersistenceConfig], qualifiers=[@Default, @Any], target=org.acme.config.PersistenceConfig] at io.quarkus.arc.processor.Beans.resolveInjectionPoint(Beans.java:492) at io.quarkus.arc.processor.BeanInfo.init(BeanInfo.java:463) at io.quarkus.arc.processor.BeanDeployment.init(BeanDeployment.java:247) ... 13 more I can't fully comprehend why the datasource cannot be injected since I already have it configured in the YAML file: quarkus: datasource: db-kind: "h2" jdbc: url: "jdbc:h2:mem:java_quarkus_graphql;DB_CLOSE_DELAY=-1;MODE=PostgreSQL" username: "sa" flyway: clean-disabled: true locations: "classpath:database/migration" migrate-at-start: true validate-on-migrate: true I read the guide around this subject and it should be available as AgroalDataSource β€” or just DataSource. UPDATE #1 By the way, this setup/configuration works if I use an older version (1.13.4.Final) of Quarkus: > Task :quarkusDev Listening for transport dt_socket at address: 5005 __ ____ __ _____ ___ __ ____ ______ --/ __ \/ / / / _ | / _ \/ //_/ / / / __/ -/ /_/ / /_/ / __ |/ , _/ ,< / /_/ /\ \ --\___\_\____/_/ |_/_/|_/_/|_|\____/___/ 2021-08-27 12:55:39,840 |- INFO in io.quarkus:88 [Quarkus Main Thread] - java-quarkus-graphql 0.1.2-SNAPSHOT on JVM (powered by Quarkus 1.13.4.Final) started in 0.770s. Listening on: http://localhost:8080 2021-08-27 12:55:39,843 |- INFO in io.quarkus:91 [Quarkus Main Thread] - Profile dev activated. Live Coding activated. 2021-08-27 12:55:39,843 |- INFO in io.quarkus:92 [Quarkus Main Thread] - Installed features: [agroal, cdi, config-yaml, flyway, hibernate-validator, jdbc-h2, mutiny, narayana-jta, smallrye-context-propagation, smallrye-graphql] UPDATE #2 Version 2.2.1.Final doesn't have the issue when starting the application, but somehow it fails when running the test cases: @Stereotype @QuarkusTest @Transactional @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface QuarkusTransactionalTest { // ... } @QuarkusTransactionalTest final class ActorRepositoryTest { @Inject ActorRepository repository; @Test void findById_WhenActorDoesNotExist() { Assertions.assertThat(repository.findById(UUID.fromString("c6b1d415-77ee-49c2-b912-fbd00e07702b"))).isNotPresent(); } @Test void findById_WhenActorExist() { Assertions.assertThat(repository.findById(UUID.fromString("3bea7318-bb7a-4232-9343-59579dd5b2a2"))) .contains(ActorFactory.penelopeGuiness()); } } ActorRepositoryTest > findById_WhenActorExist() FAILED java.lang.RuntimeException: java.lang.RuntimeException: io.quarkus.builder.BuildException: Build failure: Build failed due to errors [error]: Build step io.quarkus.arc.deployment.ArcProcessor#validate threw an exception: javax.enterprise.inject.spi.DeploymentException: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default] - java member: org.acme.config.PersistenceConfig#dataSource - declared on CLASS bean [types=[java.lang.Object, org.acme.config.PersistenceConfig], qualifiers=[@Default, @Any], target=org.acme.config.PersistenceConfig] at io.quarkus.arc.processor.BeanDeployment.processErrors(BeanDeployment.java:1100) at io.quarkus.arc.processor.BeanDeployment.init(BeanDeployment.java:265) at io.quarkus.arc.processor.BeanProcessor.initialize(BeanProcessor.java:129) at io.quarkus.arc.deployment.ArcProcessor.validate(ArcProcessor.java:418) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at io.quarkus.deployment.ExtensionLoader$2.execute(ExtensionLoader.java:820) at io.quarkus.builder.BuildContext.run(BuildContext.java:277) at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18) at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449) at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478) at java.base/java.lang.Thread.run(Thread.java:829) at org.jboss.threads.JBossThread.run(JBossThread.java:501) Caused by: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type javax.sql.DataSource and qualifiers [@Default] - java member: org.acme.config.PersistenceConfig#dataSource - declared on CLASS bean [types=[java.lang.Object, org.acme.config.PersistenceConfig], qualifiers=[@Default, @Any], target=org.acme.config.PersistenceConfig] at io.quarkus.arc.processor.Beans.resolveInjectionPoint(Beans.java:492) at io.quarkus.arc.processor.BeanInfo.init(BeanInfo.java:471) at io.quarkus.arc.processor.BeanDeployment.init(BeanDeployment.java:253) ... 13 more A: yes , it works with AgroalDataSource A: Fixed with latest (2.2.3.Final) version.
{ "language": "en", "url": "https://stackoverflow.com/questions/68952783", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }