text
stringlengths
15
59.8k
meta
dict
Q: Plus Minus Toggle on Clicking a Link I have a link with a plus symbol (More Details[+]) ... when the user clicks the link, I want the link to change to a minus (More Details[-]), and show the content below it. I can show/hide the content, but the +/- toggle doesn't work. Note: I'm new to javascript, so please be patient with my lack of knowledge... Note: There are a few posts about +/- toggles. I need help with the code that I wrote below. Below is the javascript... // Plus/Minus Toggle function toggle_plus(id) { var f = document.getElementById(id); if (f.classList.contains("showplus")) { f.removeClass("showplus"); f.addClass("showminus"); } else { f.removeClass("showminus"); f.addClass("showplus"); } } // Toggle to show and hide content below the link function toggle_visibility(id) { var e = document.getElementById(id); if(e.style.display == 'block') { e.style.display = 'none'; } else { e.style.display = 'block'; } } And below is the html for the content..... <div class="teamdetail"> <a href="javascript:void(0)" onclick="toggle_visibility('team4'); toggle_plus('team4Plus');">More Details [<span id="team4Plus" class="showplus"></span>]</a> </div> <div id="team4" class="teamtxt"> Text Goes Here </div> And the CSS for the showplus and showminus .showminus:before { content: '-'; } .showplus:before { content: '+'; } A: .removeClass and .addClass are jQuery functions. You need to use .classList.add and .classList.remove // Plus/Minus Toggle function toggle_plus(id) { var f = document.getElementById(id); if (f.classList.contains("showplus")) { f.classList.remove("showplus"); f.classList.add("showminus"); } else { f.classList.remove("showminus"); f.classList.add("showplus"); } } // Toggle to show and hide content below the link function toggle_visibility(id) { var e = document.getElementById(id); if(e.style.display == 'block') { e.style.display = 'none'; } else { e.style.display = 'block'; } } .showminus:before { content: '-'; } .showplus:before { content: '+'; } <div class="teamdetail"> <a href="javascript:void(0)" onclick="toggle_visibility('team4'); toggle_plus('team4Plus');">More Details [<span id="team4Plus" class="showplus"></span>]</a> </div> <div id="team4" class="teamtxt"> Text Goes Here </div> A: In addition to Dave's answer (I don't have enough rep to comment :/), toggle is your friend. // Plus/Minus Toggle function toggle_plus(id) { var f = document.getElementById(id); f.classList.toggle("showplus"); f.classList.toggle("showminus"); } Will do the same. Also, the Chrome inspector console is your friend - it would've been throwing up errors to you. https://developers.google.com/web/tools/chrome-devtools/console/
{ "language": "en", "url": "https://stackoverflow.com/questions/49910174", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to change a Char in a String in a TStringList After writing the content of the text file to the TStringList object, I try to change one character in the line and then write the entire content of the object back to the file. In the saved file, the changed line character was not saved as expected and is still unchanged. To write the change of character to the file I need to use the String object. void __fastcall TForm1::Button1Click(TObject *Sender) {  TStringList *Lista = new TStringList;  if(OpenDialog1->Execute())     Lista->LoadFromFile(OpenDialog1->FileName); Lista->Strings[0][1] = '0'; // this does not work // Only this way work String A = Lista->Strings[0]; A[1] = '0'; Lista->Strings[0] = A; } I don't understand why the sign change directly in the TStringList object doesn't happen, or if it does, why isn't it written to the file. A: The TStringList::Strings[] property getter DOES NOT return a reference to a String object, like you are expecting. It returns a String object by value instead, which means a copy is returned as a temporary object. Strings[0][1] = ... has no effect because you are modifying that temporary object and not assigning it anywhere afterwards, so it just goes out of scope immediately. That is why you need to save that temporary object to a local variable first, and then assign that variable back to the Strings[] property after modifying the variable's data.
{ "language": "en", "url": "https://stackoverflow.com/questions/75339236", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Setting up a library in Eclipse CDT I am creating a project which needs to use the libnoise headers. However I am having difficulty compiling. I have put the headers into my src/ directory of my project, so I am able to include them with #include "noise/noise.h" #include "noise/noisegen.h" #include "noiseutils.h" But when I try and create a Perlin module noise::module::Perlin perlinModule;, I get the following compilation error: PROJECTDIR\bin/../src/libnoise_wrapper.cpp:66: undefined reference to `noise::module::Perlin::Perlin()' ./src/libnoise_wrapper.o: In function `~Perlin': PROJECTDIR\bin/../src/noise/module/perlin.h:160: undefined reference to `vtable for noise::module::Perlin' PROJECTDIR\bin/../src/noise/module/perlin.h:160: undefined reference to `noise::module::Module::~Module()' PROJECTDIR\bin/../src/noise/module/perlin.h:160: undefined reference to `vtable for noise::module::Perlin' PROJECTDIR\bin/../src/noise/module/perlin.h:160: undefined reference to `noise::module::Module::~Module() I have created a Project Include reference to the /src/noise folder as well as noiseutils.h file (which is in the src/ directory itself). Are there any other configurations I am missing? A: "I have put the headers into my src/ directory of my project, so I am able to include them with " That's not the usual way to do! You should have an installation of this library in your environment (there are some instructions how to do this for your particular case available in this tutorial from the libnoise online documentation), and add the additional include paths to search using the Project Properties->C/C++ Build->Settings-><actual C++ Compiler>->Includes->Include paths (-I) settings. "Are there any other configurations I am missing?" Check the Project Properties->C/C++ Build->Settings-><actual toolchain linker>->Libraries properties page. You'll need to provide noise in the Libraries list there, and eventually an additional Library search path pointing to the actual libs installation. The latter depends on how and where you have the libnoise installed in your environment.
{ "language": "en", "url": "https://stackoverflow.com/questions/24713869", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jQuery datepicker - Set display position of the calendar when displayed as an overlay Is there any way to specify where will the calendar be displayed when the related input gets the focus? I didn't find a way of doing this in the doc. Thanks! A: Ok, so one solution a coleague gave me for this was to comment out the jquery lines that position the calendar when it is displayed.
{ "language": "en", "url": "https://stackoverflow.com/questions/2790848", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: When I do Flask run, it shows error : ModuleNotFoundError: No module named 'werkzeug.contrib'. Can anyone help me with this? the exact error I get is : flask.cli.NoAppException: While importing "application", an ImportError was raised:Traceback (most recent call last): File "/home/harshit/.local/lib/python3.6/site-packages/flask/cli.py", line 240, in locate_app __import__(module_name) File "/home/harshit/Documents/project1/application.py", line 18, in <module> Session(app) File "/home/harshit/.local/lib/python3.6/site-packages/flask_session/__init__.py", line 54, in __init__ self.init_app(app) File "/home/harshit/.local/lib/python3.6/site-packages/flask_session/__init__.py", line 61, in init_app app.session_interface = self._get_interface(app) File "/home/harshit/.local/lib/python3.6/site-packages/flask_session/__init__.py", line 93, in _get_interface config['SESSION_USE_SIGNER'], config['SESSION_PERMANENT']) File "/home/harshit/.local/lib/python3.6/site-packages/flask_session/sessions.py", line 313, in __init__ from werkzeug.contrib.cache import FileSystemCache ModuleNotFoundError: No module named 'werkzeug.contrib' I am trying to import sessions from Flask A: You will need to downgrade werkzeug version from 1.0.0 to 0.16.0 This solved the problem for me. Just run the following commands in your project: python3 -m pip uninstall werkzeug and then python3 -m pip install werkzeug==0.16.0 A: Either downgrade the version to 0.16.0 or replace werkzeug.contrib.cache with cachelib. I can highly recommend upgrading the package. The deprecated module werkzeug.contrib is very easy to replace! Install cachelib and replace all imports from: from werkzeug.contrib.cache import FileSystemCache to from cachelib import FileSystemCache A: Werkzeug 1.0.0 has removed deprecated code, including all of werkzeug.contrib. You should use alternative libraries for new projects. werkzeug.contrib.session was extracted to secure-cookie. If an existing project you're using needs something from contrib, you'll need to downgrade to Werkzeug<1: pip3 install Werkzeug<1 A: If you still need deprecated code from werkzeug.contrib, you can downgrade Werkzeug version to less than 1. pip install Werkzeug<1 A: For Python 3.8 python3 -m pip uninstall werkzeug python3 -m pip install werkzeug python3 -m pip install flask-session A: After downgrading werkzeug: pip install werkzeug==0.16.0 If you get the following: flask 2.0.2 requires Werkzeug>=2.0, but you have werkzeug 0.16.0 which is incompatible Consider doing:pip install flask==1.1.1 A: For my upgrade (0.15.5 -> 2.2.3) Everything is moved or removed from contrib to other modules. I recomend going to the documentation for your specific version of werkzeug and searching the library you are trying to import. I found mine! from werkzeug.middleware.profiler import ProfilerMiddleware app = ProfilerMiddleware(app)
{ "language": "en", "url": "https://stackoverflow.com/questions/60624139", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Smooth slideup/down after creating DOM elements I have a larga amount of xml data in $(db). When a certain element is clicked, a function traverses through $(db) and creates new DOM elements inside a hidden div. How can I then smoothly slide down the div? $('li').live('click', function(){ // many $('div.content').append(.... $('div.content').slideDown(); }); In the above example the div.content becomes visible, however without the slide effect. If I, instead of creating DOM elements load an html document with the vary same content, the slide effect works properly. I think that when creating a lot of new DOM elements the browser jams, and then cannot perform a smooth animation. How could I sort this problem out? Would it be possible to create all the DOM elements inside a variable, and then display it as it would happen when you use .load()? A: If you can select the newly created element from the DOM, this method will work nicely (needs jQuery). You will simply show the elements you created and then scroll the browser into view. function scrollTo(element){ $("html, body").animate({ scrollTop: $(element).position().top }); }
{ "language": "en", "url": "https://stackoverflow.com/questions/10195758", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: android2.3 DownloadManager I use DownloadManager, which in available since Android 2.3, to download FTP. But it does not work. I do not know how to make it work? I did not find proper examples. Does DownloadManager support FTP? A: Unfortunatelly, FTP won't work. DownloadManager supports HTTP. And HTTPS is supported since ICS. If you try downloading from FTP you receive one of these exceptions: java.lang.IllegalArgumentException: Can only download HTTP URIs or java.lang.IllegalArgumentException: Can only download HTTP/HTTPS URIs
{ "language": "en", "url": "https://stackoverflow.com/questions/14212339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: python dynamic multiple inheritance __init__ I am trying to write a plugin environment where I need to do multiple inheritances on an unknown number of classes. Therefore, I have opted to use the type class creation: class A(object): def __init__(self,s): self.a="a" def testA(self,x): print(x) class B(object): def __init__(self,s): self.b="b" def testA(self,x): print(x) C = type('C', (A,B), {}) x= C("test") print x.b When I run the above code, I get the error: AttributeError: 'C' object has no attribute 'b' This is because only the init for class A is being run when the instance for class C is initialized. My question is how can I get the class C to have both the init for class A as well as the init for class B to run when an instance of class C is initialized. I do realize that if I had class C like the following it would work: class C(A,B): def __init__(self,s): A.__init__(self,s) B.__init__(self,s) However, given that I need to have a dynamic list of classes inherited this will not work. A: It seems you're using python 2 so I'm using this old python 2 super() syntax where you have to specify the class and the instance, although it would work in python 3 as well. In python 3 you could also use the shorter super() form without parameters. For multiple inheritance to work is important that the grandparent class __init__ signature matches the signature of all siblings for that method. To do that, define a common parent class (MyParent in this example) whose __init__ has the same parameter list as all the childs. It will take care of calling the object's __init__ that doesn't take any parameter, for us. from __future__ import print_function class MyParent(object): def __init__(self, s): super(MyParent, self).__init__() class A(MyParent): def __init__(self, s): self.a = "a" super(A, self).__init__(s) def testA(self, x): print(x) class B(MyParent): def __init__(self, s): self.b = "b" super(B, self).__init__(s) def testA(self,x): print(x) C = type('C', (A, B), {}) x = C("test") print(x.b) You can define as many children to MyParent as you want, and then all __init__ methods will be called, provided you used super() correctly.
{ "language": "en", "url": "https://stackoverflow.com/questions/49946616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android context & OSGi Bundle I'm actually working on OSGi on Android, and I'm close to reach my goal, but there's one little problem. The framework (Apache Felix) is running successfully. The problem comes from Bundles that want to get Context of the Application. I just can't try to use them, because at runtime, I've got a beautiful "Could not find classe Android.content.Context", refrenced from [...]. (And then come a NoClassDefFoundError when trying to get the ServiceReference) I linked the Android.jar to the Bundle, but it doesn't seems to be enough (even if compilation is ok). Maybe it's the way I'm creating the bundle that's wrong, I juste export it as a .jar when finished. So if you've got some tips about how to solve this problem, they're welcome ;) Thanks ! A: Ok, I'm finally done with it. I am a fool, really. In the Manifest.mf, section "Import-Package", don't forgot to add android.content It now works perfectly ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/5188652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: EntityManager inside Entity Bean how-to How to use (inject) entityManager to Entity Bean? Inside my Entity bean I have some validations that need to do query on other (unrelated) Entity, some kind of List-Of-Values Entity. What is the right way to do this? To put EntityManager to a constructor of Entity Bean? Or what? A: Entity beans do not (in general) support injection of any kind because they are not created by the container. This general topic was recently discussed on the JSR-338 (JPA 2.1) mailing list and reasons were given why it is generally considered a bad idea for entities to reference entity managers.
{ "language": "en", "url": "https://stackoverflow.com/questions/10532256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Cast to derived class in base class constructor Python I have a base class and a derived class. I want to be able to cast the base class to derived class in the constructor of base class, using one of the arguments passed. Elucidated below: Class A(object): def ___init___(self, arg1, arg2 ..., shouldBeDerivedClass): if shouldBeDerivedClass: #Cast this object to Derived Class B and Call constructor of derived class else: #Continue constructing base class object Class B(A): __init__(self, some args): #Should reach here How can I achieve this? Thank you.
{ "language": "en", "url": "https://stackoverflow.com/questions/45108643", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: prevent user to login from other device or other browser at same time prevent user to login from other device or other browser at same time If user is logged in from one pc/device then that perticular user can not log in using same id and password from another pc/device or another browser. using php and mysql A: You can have a separate column in your db table e.g. is_logged and when a user is logged for first time it will be updated to true so every other attempt will fail. SELECT * FROM my_table WHERE username = 'username' AND password = 'password' AND is_logged != 1; UPDATE (based on your update) You can have another column such as last_action (timestamp) and set in your application logic a particular time that if a user hasn't interact with the website (e.g. 3600 seconds) then he will be considered as automatically logged out during his next login attempt. SELECT * FROM my_table WHERE username = 'username' AND password = 'password' AND TIME_TO_SEC(TIMEDIFF(NOW(), last_action)) > 3600; A: you can add a column in your login table( besides where you have stored password and username) and set it to one whenever a user logs in. Check that column every time with password and username. If it is not one. Grant login. else error message. Set it to zero when a user logs out.
{ "language": "en", "url": "https://stackoverflow.com/questions/33202383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-5" }
Q: Add a health check in Startup.Configure We want to standardize health checks across our .NET Core APIs, and we thought an easy way would be to install a NuGet package which contains something we could add in the Startup file like so. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseHealthCheck(env.EnvironmentName, env.ApplicationName, "/myHealthCheckUrl"); // And all the rest of the app.UseSomethings. } And now if someone hits myapp.com/myHealthCheckUrl, they will get back a message saying something like myAppName is alive in myEnvironmentName. I don't even know the right terms to use to Google for an answer. How would we go about doing this? Swashbuckle does something similar with UseSwaggerUi, but that calls app.UseFileServer and delivers a modified HTML page. Would this be the way to handle it, or is there a more lightweight option available? Again, we want this to have minimal impact in the rest of each API, so we're trying to avoid controller actions in the app itself. A: As indicated in the comments on the question, what we were looking for was to provide a Middleware. The far simplest way to do this is by adding this piece of code into the Configure method, and that is what we decided to go with. app.Map("/HealthCheck", a => { a.Run(async context => { await context.Response.WriteAsync($"{env.ApplicationName} is alive in {env.EnvironmentName}"); }); }); Since that specifically does NOT answer the question of creating a way to do this in a NuGet package, here is how you would do it in an extensions class. public static class ApplicationBuilderExtensions { /// <summary> /// Gives a happy little response when someone makes a request to healthCheckUrl /// </summary> public static IApplicationBuilder UseHealthCheck(this IApplicationBuilder app, string environmentName, string applicationName, string healthCheckUrl) { app.Map(healthCheckUrl, a => { a.Run(async context => { await context.Response.WriteAsync($"{applicationName} is alive in environmentName"); }); }); return app; } } And then call it with app.UseHealthCheck(env.EnvironmentName, env.ApplicationName, "/myHealthCheckUrl"); in the Startup.Configure method.
{ "language": "en", "url": "https://stackoverflow.com/questions/44709327", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ValueError: The model is not configured to compute accuracy. You should pass `metrics=["accuracy"]` to the `model.compile()` method I am very new in Deep Learning: I am doing a deep learning course on Udemy. once I execute my code, it says: ValueError: The model is not configured to compute accuracy. You should pass metrics=["accuracy"] to the model.compile() method. I tried to change 'accuracy' into 'acc', It gives me no more error, but the code is super fast, it shows me only 10 epochs instead of 100. besides I was expecting accuracy around 83% but I am having something like 79%. can someone please help me? '''' import keras from keras.wrappers.scikit_learn import KerasClassifier from sklearn.model_selection import cross_val_score from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense def build_classifier(): classifier = Sequential() classifier.add(Dense(6, kernel_initializer='uniform', activation='relu', input_dim= 11)) classifier.add(Dense(6, kernel_initializer='uniform', activation='relu')) classifier.add(Dense(1, kernel_initializer='uniform', activation='sigmoid')) classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) return classifier classifier = KerasClassifier(build_fn= build_classifier, batch_size=10 , nb_epoch=100) accuracies = cross_val_score(estimator = classifier, X = x_train, y = y_train, cv=10, n_jobs=-1) '''' This is my fulltraceback: '''' accuracies = cross_val_score(estimator = classifier, X = x_train, y = y_train, cv=10, n_jobs=-1, verbose=0) Traceback (most recent call last): File "<ipython-input-138-36c63e93365e>", line 1, in <module> accuracies = cross_val_score(estimator = classifier, X = x_train, y = y_train, cv=10, n_jobs=-1, verbose=0) File "C:\ProgramData\Anaconda3\envs\deeplearning\lib\site-packages\sklearn\model_selection\_validation.py", line 389, in cross_val_score error_score=error_score) File "C:\ProgramData\Anaconda3\envs\deeplearning\lib\site-packages\sklearn\model_selection\_validation.py", line 235, in cross_validate for train, test in cv.split(X, y, groups)) File "C:\ProgramData\Anaconda3\envs\deeplearning\lib\site-packages\joblib\parallel.py", line 1017, in __call__ self.retrieve() File "C:\ProgramData\Anaconda3\envs\deeplearning\lib\site-packages\joblib\parallel.py", line 909, in retrieve self._output.extend(job.get(timeout=self.timeout)) File "C:\ProgramData\Anaconda3\envs\deeplearning\lib\site-packages\joblib\_parallel_backends.py", line 562, in wrap_future_result return future.result(timeout=timeout) File "C:\ProgramData\Anaconda3\envs\deeplearning\lib\concurrent\futures\_base.py", line 435, in result return self.__get_result() File "C:\ProgramData\Anaconda3\envs\deeplearning\lib\concurrent\futures\_base.py", line 384, in __get_result raise self._exception ValueError: The model is not configured to compute accuracy. You should pass `metrics=["accuracy"]` to the `model.compile()` method. '''' I also tried this: ' try: accuracies = cross_val_score(estimator = classifier, X = x_train, y = y_train, cv=10, n_jobs=-1, verbose=0) except ValueError as e: print ("ValueError:", e) ValueError: The model is not configured to compute accuracy. You should pass `metrics=["accuracy"]` to the `model.compile()` method. ' A: In your imports you are mixing imports between the keras and tf.keras packages, that is actually not supported, you should choose one and make all imports from the selected package.
{ "language": "en", "url": "https://stackoverflow.com/questions/59556100", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Make image height auto adjust to text height Given this HTML <div class="flex"> <div> <img src="https://via.placeholder.com/300x300" alt=""> </div> <div> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis facilisis nisi elit, vitae interdum nisi porttitor a. Maecenas porta mollis venenatis. Proin suscipit, est et malesuada ultricies, nisi elit aliquam arcu, et luctus felis dolor euismod ante. Praesent nec malesuada arcu. Nunc rutrum erat risus, id elementum leo dignissim eu. Fusce feugiat, massa vestibulum venenatis ullamcorper, nisl justo aliquam purus, nec pellentesque tellus magna non quam. Pellentesque luctus quam in justo congue tempor. Cras placerat sit amet nulla id pretium. Nulla facilisi. Phasellus dictum neque sed lacus congue, vel dapibus enim efficitur. </div> </div> how can I make the image height scale automatically with the text div, according to browser width and font size of the text? * *https://jsfiddle.net/msuL6pvx/ In this case the image has to be scaled down to have the same height as the text *https://jsfiddle.net/msuL6pvx/1/ In this case the image has to be enlarged to its max size (300x300) and not exceed those dimensions A: I dont' think this is possible with pure CSS. The only think I could think of is using position: absolute for <img> to take it out of the flow in combination with max-height; then adjusting the margin of the text with javascript. https://jsfiddle.net/zphb0fLd/ Hope it's useful. A: Well as far as my knowledge, the image size can be increased with relative to text size, but its opposite case is not possible. Here is my code. I use the flexbox to increase the height of the image as per text size. Let me know if it meets your requirements. <div class="flex"> <div class="image-container"> <img src="https://via.placeholder.com/300x300" alt=""> </div> <div class="text-container"> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis facilisis nisi elit, vitae interdum nisi porttitor a. Maecenas porta mollis venenatis. Proin suscipit, est et malesuada ultricies, nisi elit aliquam arcu, et luctus felis dolor euismod ante. Praesent nec malesuada arcu. Nunc rutrum erat risus, id elementum leo dignissim eu. Fusce feugiat, massa vestibulum venenatis ullamcorper, nisl justo aliquam purus, nec pellentesque tellus magna non quam. Pellentesque luctus quam in justo congue tempor. Cras placerat sit amet nulla id pretium. Nulla facilisi. Phasellus dictum neque sed lacus congue, vel dapibus enim efficitur. </p> </div> </div> .flex{ display:flex; flex-wrap:wrap; } .image-container{ flex:1; } .text-container{ flex:3; } .text-container p{ font-size:2em; padding:10px; } .image-container img{ width:100%; height:100%; object-fit:cover; } Live example link: https://codepen.io/pranaysharma995/pen/JjdQWyQ
{ "language": "en", "url": "https://stackoverflow.com/questions/61037163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Button OnClick in string variable pass another method This code is not working. cellDeleteButton.innerHTML = "<input type='button' value='Sil' id='btnSil'; class='btn btn-danger' onclick='DeleteRow("+table_id+","+lastRow+")'/>"; This is code output : <input type="button" value="Sil" id="btnSil" ; class="btn btn-danger" onclick="DeleteRow(tblEklenecekListe,1)"> I want this to be the output : <input type="button" value="Sil" id="btnSil" ; class="btn btn-danger" onclick=DeleteRow('tblEklenecekListe',1)"> Please help me A: onclick='DeleteRow("+table_id+","+lastRow+")'/>"; it's wrong, and not a good way to do that. try this const input = Document.createElement('input'); input.type = "button"; input.value = "Sil"; input.id = "btnSil"; input.class = "btn btn-danger"; input.addEventListener('click', ()=> deleteRow(tableId, lastRow)); cellDeleteButton.appendChild(input); let me know if that works. updated:
{ "language": "en", "url": "https://stackoverflow.com/questions/68781778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: FluentNHibernate and persistence of tree structure I have an application storing a tree structure and is able to generate the database fine, but when inserting I get an exception. I simplified the code to narrow down the problem. The class to be saved: public class Node { public virtual int NodeId { get; set; } public virtual string Name { get; set; } public virtual Node Parent { get; set; } public virtual IList<Node> Children { get; set; } } This is the mapper code: public sealed class NodeMap : ClassMap<Node> { public NodeMap() { Id(n => n.NodeId).GeneratedBy.Identity(); Map(n => n.Name); References(n => n.Parent).LazyLoad().Nullable(); HasMany(n => n.Children).LazyLoad().KeyColumn("ParentId"); } } When I do an insert like dataClient.Insert(new Node { Name = "Test" }); I get an exception saying: NHibernate.Exceptions.GenericADOException: could not insert: [Model.Node][SQL: INSERT INTO [Node] (Name, NodeId) VALUES (?, ?); select SCOPE_IDENTITY()] And the inner exception says: System.Data.SqlClient.SqlException: Cannot insert explicit value for identity column in table 'Node' when IDENTITY_INSERT is set to OFF. Which is actually perfectly understandable, but I just wonder why it is trying to set an explicit value for NodeId. When I remove the References part, the insert goes through, so it must be related to that somehow. The version of FluentNHibernate is 1.2.0.712 and the version of NHibernate is 3.1.0.4000. A: it is because the default column is typename + id for the reference which happens to be the same name as the id column. Explicitly state it in the reference. References(n => n.Parent, "ParentId").LazyLoad().Nullable(); Update: as convention public class ReferenceColumnConvention : IReferenceConvention { public void Apply(IManyToOneInstance instance) { // uncomment if needed //if (instance.EntityType == instance.Property.PropertyType) instance.Column(instance.Name + "id"); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/9551456", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: "common_google_play_services_install_title" error I am trying to export my application which uses google play services library. But there is a lint warning which prevents me to export the app even though I've cleaned the project. But its running fine in the emulator.Here is the warning it shows: "common_google_play_services_install_title" is translated here but not found in default locale Issue: Checks for translations that appear to be unused (no default language string) Id: ExtraTranslation If a string appears in a specific language translation file, but there is no corresponding string in the default locale, then this string is probably unused. (It's technically possible that your application is only intended to run in a specific locale, but it's still a good idea to provide a fallback.). Note that these strings can lead to crashes if the string is looked up on any locale not providing a translation, so it's important to clean them up.[] Can someone help me out with this?? I'm stuck up here very badly.. A: Go to Window in Eclipse and then to Preferences. Click on the arrow beside Android and you will find Lint Error Checking. Uncheck the second checkbox which says "Run full error check when exporting the app and abort if fatal errors are found." And you are good to go.
{ "language": "en", "url": "https://stackoverflow.com/questions/16791119", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Kohana Exception not clear I'm using Kohana and when running index.php page, I've got following error: Kohana_Exception [ 0 ]: Directory a:0:{} must be writable a:0:{} what is it? Everything is writeable: I'm working under linux debian squeeze and ls-l done on every folder and subfolder remove every doubt.. I've checked pages involved and indicated: MODPATH/pajas/init.php SYSPATH/classes/kohana/core.php [ 562 ] » require_once() DOCROOT/index.php [ 96 ] » require(arguments) but everything seems to be ok.. that Directory a:0:{} is completely dark for me and I'll hope someone could help me looking for solution in the right way Thanks a lot everyone :) A: Did you recently add a module name pajas? Based on the error messages you posted, core.php appears to be failing on the init script of a "pajas" module. Assuming this is the "pajas" module you are using, a quick look at the init script shows it attempts to locate a path from the configuration name 'user_content.dir', and if the path is not writeable it raises an exception with the message 'Directory :dir must be writable' (source). Check your configs for a file named user_content.php which should have a key name dir. By default, it should be in {MODPATH}/{pajas_directory}/config/user_content.php (default example here), but you should also check if it is overriden somewhere (usually in APPPATH/config/. Next, make sure that the default path APPPATH/user_content (or whatever your overriden path is) exists.
{ "language": "en", "url": "https://stackoverflow.com/questions/20418231", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Assistance with CVLine/CVPoint In a text file, npoints3, I have coordinates of the form 1 242 2 242 3 242 ... 900 242, which is a straight line across my image;however, the following code prints a straight line plus an additional line segment. I am not sure what I am doing wrong. Can someone assist me with why I am getting the extra line segment? Thanks in advance! IplImage* InputImg = cvLoadImage("image.jpg", CV_LOAD_IMAGE_GRAYSCALE); CVPoint * points = (CvPoint*)malloc(length*sizeof(CvPoint*)); FILE *fp; fp = fopen("npoints3", "r"); for(i=1; i <= length; i++) { fscanf(fp, "%d", &(points[i].x)); fscanf(fp, "%d", &(points[i].y)); printf("%d %d\n",points[i].x, points[i].y); } for(i=1; i < length; i++) cvLine(InputImg, points[i], points[i+1], red, 3, 1); Thanks for your reply. In order to make sure I understood you clearly, I have posted your suggestion edits. Is the following loops what you suggested? Thanks in advance. IplImage* InputImg = cvLoadImage("image.jpg", CV_LOAD_IMAGE_GRAYSCALE); if (!InputImg) { printf("Could not load Input Image"); exit(0); } points1 = (CvPoint*)malloc(length*sizeof(CvPoint*)); points2 = (CvPoint*)malloc(length*sizeof(CvPoint*)); points = (CvPoint*)malloc(length*sizeof(CvPoint*)); fp = fopen("points", "r"); for(i=0; i < length; i++) { fscanf(fp, "%d", &(points[i].x)); fscanf(fp, "%d", &(points[i].y)); } for(i=0; i < length; i++) { points1[i].x = points[i].x; points1[i].y = points[i].y; points2[i].x = points[i+1].x; points2[i].y = points[i+1].y; // cvLine(InputImg, points1[i], points2[i], red, 3, 1); } cvSnakeImage(InputImg, points, length, alpha, beta, gamma, CV_VALUE, winni, criteria, calcGradient); for (i = 0; i <length-1; i++) { points1[i].x = points[i].x; points1[i].y = points[i].y; points2[i].x = points[i+1].x; points2[i].y = points[i+1].y; cvLine(InputImg, points1[i], points2[i], red, 3, 1); } A: Looks to me like it might be an off-by-one error. When you call malloc, you are allocating enough space for an array of length elements. Arrays are 0-indexed -- that is, points[0] to points[length-1] are valid memory addresses, while points[length] is not. At the end of your first loop, the last point you set is one element past the end of the array, and it's possible that the value gets overwritten by something by the time you try to draw the last line segment. Try changing your first loop to be: for(i=0; i < length; i++) { // scanf stuff here } and your second loop to: for(i=0; i < length-1; i++) // cvLine stuff here
{ "language": "en", "url": "https://stackoverflow.com/questions/14913944", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android use CFB I'm trying to encode my String with AES and CFB. If im doing this Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding"); , it works fine. But if i'm using "AES/CFB/NoPadding" instead of "AES", then the same String with the same password is different. Here is my Code: SecretKeySpec key = new SecretKeySpec(cryptPassword.getBytes(), "AES"); byte[] cryptByte = cryptString.getBytes("UTF8"); Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] hans = cipher.doFinal(cryptByte); cryptString = Base64.encodeToString(hans,Base64.DEFAULT); Can someone help me? Thanks a lot!!! A: Assuming that the question is about the difference of Cipher.getInstance("AES") and Cipher.getInstance("AES/CFB/NoPadding"): For Oracle JDK the default mode/padding when you do not specify them in the transformation string is "ECB/PKCS5Padding", meaning that Cipher.getInstance("AES") is the same as Cipher.getInstance("AES/ECB/PKCS5Padding"). The result of encoding some data with AES/ECB/PKCS5Padding is predictably different from encoding the same data with AES/CFB/NoPadding. To minimize the confusion you should always specify the full transformation with explicit mode and padding values.
{ "language": "en", "url": "https://stackoverflow.com/questions/23087482", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Oracle Merge - constraint violation on unique key I have this table in oracle 11g. TABLE: ORDER_LOCK Name Null Type ---------------------- -------- ---------- ORDER_ID NOT NULL NUMBER(10) [PRIMARY KEY] ORDER_REF_ID NUMBER(10) [UNIQUE KEY] ORDER_MSG_SENT NUMBER(1) merge into ORDER_LOCK al using ( select ? ORDER_REF_ID, ? ORDER_MSG_SENT from dual ) t on (al.ORDER_REF_ID = t.ORDER_REF_ID) when not matched then insert (ORDER_ID, ORDER_REF_ID, ORDER_MSG_SENT) values (ORDER_LOCK_SEQ.nextval, t.ORDER_REF_ID, t.ORDER_MSG_SENT) I am using the above Merge from my applications (Java). The merge call happens from multiple threads. The code has been working fine but yesterday we got a constraint violation (ORA-00001) on the unique key 'ORDER_REF_ID'. Is there a problem with the Merge statement? or, Is there any specific scenario when the above Merge statement may result in a constraint violation? Thanks Pushkar A: This will happen if you have two sessions (in your case, Java threads) that try to insert the same ORDER_REF_ID. Consider the following scenario: 1) Session 1 executes this MERGE statement (without committing it): merge into ORDER_LOCK al using ( select 1 ORDER_REF_ID, sysdate ORDER_MSG_SENT from dual ) t on (al.ORDER_REF_ID = t.ORDER_REF_ID) when not matched then insert (ORDER_ID, ORDER_REF_ID, ORDER_MSG_SENT) values (ORDER_LOCK_SEQ.nextval, t.ORDER_REF_ID, t.ORDER_MSG_SENT); 2) Session 2 starts the same MERGE statement: merge into ORDER_LOCK al using ( select 1 ORDER_REF_ID, sysdate ORDER_MSG_SENT from dual ) t on (al.ORDER_REF_ID = t.ORDER_REF_ID) when not matched then insert (ORDER_ID, ORDER_REF_ID, ORDER_MSG_SENT) values (ORDER_LOCK_SEQ.nextval, t.ORDER_REF_ID, t.ORDER_MSG_SENT); (this will try to insert the row, since Session 2 doesn't "see" the uncommitted changes from Session 1. Session 2 will block, since it is waiting for the lock held by Session 1): 3) Session 1 commits => Session 2 now tries to perform the insert, which will raise an ORA-00001: UNIQUE CONSTRAINT VIOLATION since the ORDER_REF_ID 1 already exists UPDATE To fix this problem, I'd suggest you modify your application and introduce some kind of affinity between Java threads and ORDER_REF_IDs - each ORDER_REF_ID should "belong" to exactly one thread, and that thread should exclusively insert / update data for its ORDER_REF_ID.
{ "language": "en", "url": "https://stackoverflow.com/questions/21904005", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How can I add progress bar to my github action I am writing some GitHub actions for my project and I would like to have the orange progress bar to track the progress of my action. A: The progress bar is shown on jobs that define the attribute environment Here's an example of how to use it: jobs: deploy: runs-on: ubuntu-latest environment: Production steps: - run: ./deploy.sh --env prod A: This is workflow reuse, you can read more in the documentation here This progress bar shows jobs running in another workflow, which is probably not a good practice, but if you want this progress bar, you need to create various workflows and a centralized workflow that "reuses" all. Github Actions show jobs running and done, you can track this why, no need for a progress bar. If you really want a progress bar directly for track jobs, you need to ask Github for this feature.
{ "language": "en", "url": "https://stackoverflow.com/questions/72912540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Display even numbers from a range in the tkinter Spinbox I'm trying to display the even numbers from a range between 0 and 1000 in a spinbox. Below is the following code : Spinbox(root, from_ = 0, to = 1000, textvariable = year).pack() How can I modify such that only the even numbers between 0 and 1000 is displayed in the spinbox? A: Spinbox will accept an explicit list of values: Spinbox(values=(1, 10, 100, 1000)) Of course, you don't want to enumerate all the evens from 0 to 1000, use range, starting at 0 and with a step of 2: Spinbox(values=list(range(0, 1000+1, 2))).pack()
{ "language": "en", "url": "https://stackoverflow.com/questions/44065733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Strange copy/paste behavior in custom itemEditor component used in a Datagrid I'm turning to you folks for answers because this really blows my mind... Let me explain: I'm using a slightly modified spark NumericStepper as an item editor in a datagrid. I had to modify the original because for some reason it's values only went up to 10. So i extended NumericStepper like so: <?xml version="1.0" encoding="utf-8"?> <mx:NumericStepper xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" xmlns:mx="library://ns.adobe.com/flex/mx" maximum="100000000"> <fx:Declarations> <!-- Place non-visual elements (e.g., services, value objects) here --> </fx:Declarations> </mx:NumericStepper> And used it like this in my Datagrid column declaration: <mx:DataGridColumn dataField="cost" itemEditor="package.to.custom.NumericStepper" editorDataField="value"/> Up to here, everything normal. Valeus are perfectly updated and all. Now when I was filling the datagrid and using ctrl+v to paste values in the editor, the values get doubled (pasting '123' yields '123123'). When pasting through the right-click menu item "Paste" (It's an AIR app), though, everything works perfectly (pasting '123' shows '123'). I'm puzzled by this behavior. Have I done something wrong in the declaration of the component? or in the way it is used in the datagrid? And why do both paste methods give different results? I'd appreciate any light shed on this matter. A: If anyone is still having this problem, which exists on all mx NumericSteppers, here is what Adobe had to say: https://bugs.adobe.com/jira/browse/SDK-18278
{ "language": "en", "url": "https://stackoverflow.com/questions/4960481", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Rename all files in a folder I'm on a linux, and a download a lot of funny pictures. Unfortunately, I'm left with a bunch of duplicate names like download (1) and image.jpeg. I would like to change them all to something a bit more helpful. Is there a way to (preferably using bash) to rename all files to sequential 4 digit numbers with leading zeroes? Eg: 0001 0002 0003 0004 .... A: The code snippet provided in the previous answer, is an elegant way of doing it but a typo or a shell incompatibility may cause it not to function properly. please try the code below instead. It does the same thing but every shortcut has been explicitly written with debugging echo commands in the loop. counter=1 cd /my/image/directory for f in $(ls -1) do new_filename=$(printf "%04d" ${counter}) echo "renaming ${f} ..to.. ${new_filename}" mv ${f} ${new_filename} (( counter=${counter}+1 )) done the screen output will be a little chatty. if you have too many files, you might want to add | tee screen.out to the end of the line with done command. So that you can go back and see what happened to which file recorded in the screen.out. A: I created my own tool to do this. It also maintains file extensions, which I did not mention, but should probably be included. Here is the code: #!/bin/sh dir=$1 cd $dir echo "Renaming all files in $dir." COUNTER=1 for i in `ls -1` do extension=${i##*.} mv "$i" "$COUNTER.$extension" echo "$i ==> $COUNTER.$extension" COUNTER=$(expr $COUNTER + 1 ) done It does not (at the time of writing) include the leading zeroes, but it gets the job done. A: As long as you don't care which file is renamed to what, it's easy :) counter=1 for f in *; do mv "$f" "$( printf "%04d" $((counter++)) )" done A: Trying to rename all files with suffix .bash to suffix .sh in a folder is easily done with rename .bash .sh *.bash
{ "language": "en", "url": "https://stackoverflow.com/questions/16306877", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: runtime error for leetcode problem 154 : reorder list https://leetcode.com/problems/reorder-list/ this is my codes logic 1) taking care of edge cases when 0,1,2 elements in list 2) storing node addresses in vector addr 3) inserting last nodes after 1st nodes one by one i.e 1-2-3 should become 1-3-2 /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ #define Node ListNode class Solution { public: void reorderList(ListNode* head) { if(head == nullptr || head->next == nullptr || head->next->next == nullptr) { return; } // copy to vector vector <Node*> addr; Node *temp = head; while(temp != nullptr) { addr.push_back(temp); temp = temp->next; } int n = addr.size(); Node *ins = addr[--n]; temp = head; while(temp != ins) { // insert after temp ins->next = temp->next; temp->next = ins; if((--n) != 0) ins = addr[n]; temp = temp->next->next; } temp->next = nullptr; } }; this is my output Line 924: Char 34: runtime error: addition of unsigned offset to 0x603000000010 overflowed to 0x603000000008 (stl_vector.h) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior /usr/bin/../lib/gcc/x86_64-linux-gnu/8/../../../../include/c++/8/bits/stl_vector.h:933:34 random edits made and code worked altho i still dunno why the above code is not working! class Solution { public: void reorderList(Node* head) { if(head == nullptr || head->next == nullptr || head->next->next == nullptr) { return; } // copy to vector vector <Node*> addr; Node *temp = head; while(temp != nullptr) { addr.push_back(temp); temp = temp->next; } int n = addr.size(); Node *ins = addr[--n]; temp = head; while(temp != ins && temp->next != ins) { // insert after temp ins->next = temp->next; temp->next = ins; ins = addr[--n]; temp = temp->next->next; } if(temp->next == ins) { ins->next = nullptr; } else { temp->next = nullptr; } } };
{ "language": "en", "url": "https://stackoverflow.com/questions/62167014", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I'm trying to upload an array of images using Alamofire but getting error I'm trying to upload an array of images to the server using Alamofire 4.8.2 Here is the function: func uploadMultiplePhotos(centreId: Int, imagesArray: [UIImage]) { let parameters = ["ec_id": centreId, "uploaded_image": imagesArray] as [String : Any] Alamofire.upload(multipartFormData: { (multipartFormData : MultipartFormData) in let count = imagesArray.count for i in 0..<count{ multipartFormData.append(imagesArray[i], withName: "photo[\(i)]", fileName: "photo\(i).jpeg", mimeType: "image/jpeg") } for (key, value) in parameters { multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key) } print(multipartFormData) }, to: storeCentreImageURL) { (result) in switch result { case .success(let upload, _ , _): upload.uploadProgress(closure: { (progress) in print("uploding: \(progress.fractionCompleted)") }) upload.responseJSON { response in print(response.result.value!) } case .failure(let encodingError): print("failed") print(encodingError) } } } getting error in the line below: multipartFormData.append(imagesArray[i], withName: "photo[\(i)]", fileName: "photo\(i).jpeg", mimeType: "image/jpeg") Cannot invoke 'append' with an argument list of type '(UIImage, withName: String, fileName: String, mimeType: String)' A: You need to convert the image to data imagesArray.indices.forEach { multipartFormData.append(imagesArray[$0].jpegData(compressionQuality:0.8)!, withName: "photo[\($0)]", fileName: "photo\($0).jpeg", mimeType: "image/jpeg") }
{ "language": "en", "url": "https://stackoverflow.com/questions/56683594", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Renaming input file before uploading with jquery and laravel I want to rename input file to be uploaded before sending to laravel. Basically, i found an another way to rename the file in laravel but in this question I want to rename the file before sending to laravel. In my case, I'm using jquery upload file, and now I want the input file to be renamed before uploading it. I want to get the new file name that I used to insert in the hidden input text. Is there any solution to solve this kind of matter? By the way, thank you in advance! ^_^ A: Did you check this: File Docs as per this doc you can do this as follow: $request->file('photo')->move($destinationPath, $fileName); where $fileName is an optional parameter that renames the file. so you can use this like: $fileName = str_random(30); // any random string then pass this as above.
{ "language": "en", "url": "https://stackoverflow.com/questions/46557825", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: joomla 2.5 module retrieve data from database i want to retrieve data from database in my module page.for that my helloworld.php put the code // Get a database object $db = JFactory::getDbo(); $query = $db->getQuery(true); $query->select('id, description'); $query->from('#__banners'); // sets up a database query for later execution $db->setQuery($query); // fetch result as an object list $result = $db->loadObjectList(); now i want to show the results in default.php. but when echo $result in default.php it dose not show anything. how to i show the result? how to i get data from #__banners table? A: $db->loadObjectList() returns an array which you can't echo. You can create a foreach loop like so: foreach ( $result as $row ) { echo $row->description; } A: You have to load the results from the model method in view.html.php. In view.html.php function display($tpl = null) { $model = JModelLegacy::getInstance('ModelName', 'FrontendModel'); //(or BackendModel) $variable = $model->getNameOfModelMethod(); $this->assignRef('variable', $variable); } And in default.php just call $this->variable.
{ "language": "en", "url": "https://stackoverflow.com/questions/20244411", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to cache stored procedure results to retrieve the results faster? I have a stored procedure which takes a lot of time (around 5 minutes) to execute. This stored procedure fills up a table. Now I am retrieving the data from that table. I have created a job to execute this stored procedure every 15 minutes. But while the stored procedure is in execution, my table is empty and the front end shows no results at that time. My requirement is to show data at the front end side all the time. Is there a way to cache the stored procedure results and use that result while the stored procedure executes? Here is my stored procedure, BEGIN declare @day datetime declare @maxdate datetime set @maxdate = getdate() set @day = Convert(Varchar(10),DATEADD(week, DATEDIFF(day, 0, getdate())/7, 0),110) truncate table tblOpenTicketsPerDay while @day <= @maxdate begin insert into tblOpenTicketsPerDay select convert(varchar(20),datename(dw,@day)) day_name, count(*) Open_Tickets from (select [status], createdate, closedate FROM OPENROWSET('MSDASQL','DSN=SQLite','Select * from tickets') AS a where createdate <= @day except select [status], createdate, closedate FROM OPENROWSET('MSDASQL','DSN=SQLite','Select * from tickets') AS a where closedate <= @day and [status] = 'closed') x set @day = @day + 1 end END Any ideas will be helpful. Thanks. A: If I have understood correct then your main concern is: your stored procedure empties the table and then fills it up and since it takes time, your application have no data show. In that case, you can have a secondary/auxiliary clone table; say tblOpenTicketsPerDay_clone and have your stored procedure fill that table instead like insert into tblOpenTicketsPerDay_clone select convert(varchar(20),datename(dw,@day)) day_name, count(*) Open_Tickets from That way your application will always have data to display since main table has the data. Once, the clone table is done filling up then transfer the same data to main table saying delete from tblOpenTicketsPerDay; insert into tblOpenTicketsPerDay select * from tblOpenTicketsPerDay_clone; A: No, but the problem is not caching, it isa totally bad approach to generate the data. Generate new data into a temporary table, then MERGE The results (using the merge keyword) into the original table. No sense in deleting the data first. That is a terrible design approach.
{ "language": "en", "url": "https://stackoverflow.com/questions/27177600", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: If the GCM server receives a message to be sent to an Android phone, is the message going to survive on the server until it reaches the client? I mean, once the message has reached the server, can I rely on GCM for that message to arrive to the phone whenever the phone is online? Can the message be lost in the middle of the way to the phone? Is there a confirmation (message arrvied) between server and phone? I read in the documentation that "GCM makes no guarantees about delivery or the order of messages" but I don't understand if this means that the message can be lost while trying to reach the phone or that if the phone is off the message will never arrive to the phone. A: If the phone is off and you turn it on you will then get the GCM message, its the same as you would an email that you got if you had your phone off. When it says there is no guarantee you will receive the message that means there is no guarantee the server will send it out. I remember reading there is a time to live on the message but its not one that expires for a while
{ "language": "en", "url": "https://stackoverflow.com/questions/11780507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Custom Context Menu on everything except "input" in jQuery I want to add custom context menu with jQuery for the whole body of the page, except the textfields. How can I do that? I have tried that code: $('body:not(input)').bind('contextmenu', function(){ /*code*/ }); A: Check the srcElement before plugin executions. If it's not an input element, do trigger the contextmenu plugin: $(document).on("contextmenu", function(e) { if (!$(e.srcElement).is(":input")) { // if it's not an input element... $(this).triggerTheContextMenuPlugin(); } }); A: Use an event listener on the document and check if it was initiated by an input element. $(document).on("contextmenu", function (e) { if (e.target.tagName.toUpperCase() === "INPUT") { console.log("context menu triggered"); } }); Demo here A: Inspired by Salman's solution. You can stop the event propagation in all input elements, with the e.stopPropagation() function. In doing so, you keep the default behavior of the inputs elements: $(function() { $(document).on("contextmenu", function(e) { alert("Context menu triggered, preventing default"); e.preventDefault(); }); $("input").on("contextmenu", function(e) { e.stopPropagation(); }); }); JSFiddle Demo
{ "language": "en", "url": "https://stackoverflow.com/questions/21047264", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use Purchase Status API I'm developing an app which has several non-consumable inApp products in it and i need to get the purchase status of those by directly sending requests to Google server and receiving the result. As i understood "Purchase Status API" gives that possibility but it's not working for me. I made all the needed settings in "Google API Console": Switched on "Google Play Android Developer API". Created a client ID for my App. I tried to use the methods described over here: http://developer.android.com/google/play-services/auth.html But the methods GoogleAuthUtil.getToken(); and GoogleAuthUtil.getTokenWithNotification(); are throwing me an "Unknown exception". However i managed to get the access token by using this code: AccountManager acountM=AccountManager.get(Utils.curentActivity); Account[] acount=acountM.getAccountsByType("com.google"); String AUTH_TOKEN_TYPE = "oauth2:https://www.googleapis.com/auth/androidpublisher"; AccountManagerFuture<Bundle> future=acountM.getAuthToken(acount[0], AUTH_TOKEN_TYPE, null, Utils.curentActivity, null, null); try{ String token=future.getResult().getString(AccountManager.KEY_AUTHTOKEN); }catch(Exception e){e.printStackTrace();} But after this, i have no idea what to do with this token. If i try to Authenticate like this: URL url=new URL("https://www.googleapis.com/oauth2/v1/userinfo?access_token="+token); URLConnection conection=url.openConnection(); conection.setDoInput(true); conection.connect(); InputStream is=conection.getInputStream(); It throws me a "File not found exception". If i try to get the purchase status of a product: String packageName=MainActivity.this.getPackageName(); String productId="SKU_KEY_1"; HttpClient client=new DefaultHttpClient(); HttpGet get=new HttpGet("https://www.googleapis.com/androidpublisher/v1.1/applications/"+packageName+"/inapp/"+productId+"/purchases/"+token); HttpResponse response=client.execute(get); InputStream is=response.getEntity().getContent(); String result=Utils.readInputStream(is); is.close(); The result is a JSON which looks like this: { "error": { "errors": [ { "domain": "global", "reason": "required", "message": "Login Required", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Login Required" } } I'm desperately looking for a solution for several days. I'll will be glad if somebody will provide me a solution or an up to date documentation on this point. A: So looking over your code and information I would try a couple things, first verifying your access token. I have used this as a reference. Using a browser and a simple html page (see below) I am able to acquire the token and verify it. You will need to need to fill out the values as specified on that page. Make sure that your token is correct first. I did this by using that userinfo address in a browser. Next you inapp purchase html location needs ?access_token={access_token} at the end after the If you notice the section "Accessing the API" in the above page about authorization, you need to add this. Here is the webpage that I have used to help get the token for testing. NOTE that this is for testing and will not work as final solution because the authorization token is only good for a short time. You will need to make sure that the code that gets that access token functions correctly. In addition again refer to the page above to fill this out for your product. The only thing that is dynamic in this is the "code" value which comes from the instructions on that page. Hope some of this can help you... <form action=" https://accounts.google.com/o/oauth2/token" method="post"> <input name="grant_type" type="hidden" value="authorization_code" /> <input name="code" type="hidden" value="the code from the previous step"/> <input name="client_id" type="hidden" value="the client ID token created in the APIs Console"/> <input name="client_secret" type="hidden" value="the client secret corresponding to the client ID"/> <input name="redirect_uri" type="hidden" value="the URI registered with the client ID"/> <input type="submit" /> </form>
{ "language": "en", "url": "https://stackoverflow.com/questions/19230320", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Ansible string concatenation into config file I have a list of variables ("/dev/sda", "/dev/sdb") which I would like to to dynamically update a config file. The config file is finally expected to look like filter = [ "a|/dev/sda[145]|", "a|/dev/sdb[145]|", "a|/dev/mapper/3500.*part1|", "r|.*|" ] Currently, the config file looks like this. filter = [ "a|/dev/mapper/3500.*part1|", "r|.*|" ] A: I have the answer to my own question. I am not sure if this is the "jinja" way of doing things. {% set ldsk = [] %} {% for disk in ldisks %} {{ ldsk.append( "\"|a"+ disk +"[145]|\"") }} {% endfor %} filter = [ {{ ldsk | join(", ") }}, "a|/dev/mapper/3500.*part1|", "r|.*|" ]
{ "language": "en", "url": "https://stackoverflow.com/questions/57451002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: docker postfix - missing logs I created docker container like this: FROM debian RUN export DEBIAN_FRONTEND=noninteractive RUN apt-get update RUN apt-get install -y syslog-ng syslog-ng-core RUN apt-get install -y postfix vim \ && rm -rf /var/lib/apt/lists/* CMD /etc/init.d/postfix start && /bin/bash And start it like this: docker run --name testmailsrv -p 25:25 -p 143:143 -p 993:993 -v mailsrvpostfixetc:/etc/postfix -v mailsrvdovecotetc:/etc/dovecot -it mailsrv/mailsrv-0.6:latest My postrix is not working properly, but I can't find any logs to diagnose it. No file /var/log/mail.log, no output from journalclt, nothing interesting from "docker logs" command. How can I see any log from postfix in docker? A: This image suggests: # Use syslog-ng to get Postfix logs (rsyslog uses upstart which does not seem # to run within Docker). run apt-get install -q -y syslog-ng expose 25 cmd ["sh", "-c", "service syslog-ng start ; service postfix start ; tail -F /var/log/mail.log"] That might be easier in order to produce and see those logs (as output of the main thread) Also, satnhak suggests in the comments (in 2021): You probably also need this: syslog-ng/syslog-ng issue 2407 That refers to syslog-ng/syslog-ng PR 2408: "system-source: check if /proc/kmsg can be opened". Or you would need in your configuration: source s_local { system( exclude-kmsg(yes) ); internal(); }; satnhak adds: adding this to the Dockerfile does the trick: RUN sed -i 's/system()/system(exclude-kmsg(yes))/g' \ /etc/syslog-ng/syslog-ng.conf A: * *Install rsyslog apt-get install ryslog *Start rsyslog service rsyslog start *Restart postfix service postfix restart *You will find /var/log/mail.log
{ "language": "en", "url": "https://stackoverflow.com/questions/46998673", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I design a data warehouse model that allows me to dynamically query for total action count, unique user count, and a count of total users Currently facing a problem where I am trying to create a login utilization report for a web application. To describe the report a bit, users in our system are tagged with different metadata about the user. For example, I could be tagged with "New York City" and "Software Engineer", while other users may be tagged with different locations and job titles. The utilization report is essentially the following: * *Time period (quarterly) *Total number of logins *Unique logins *Total users *"Engagement percentage" (Unique logins / Total users) The catch is, the report needs to be a bit dynamic. I need to be able to be apply any combination of job titles and locations and have each of the numbers reflect the applied metadata. The time period also needs to be able to be easily adjusted to support weekly, monthly, and yearly as well. Ideally, I can create a view in Redshift that allows our BI software users to run this report whenever they see fit. My question is, what is an ideal strategy to design a data model to support this report? I currently have an atomic fact table that contains all logins with this schema: * *User ID *Login ID *Login Timestamp *Job Title Group ID (MD5 hash of job titles to support multi valued) *Location Group ID (MD5 hash of locations to support multi valued) The fact table allows me to easily write a query to aggregate on total (count of login id) and unique (distinct count of user id). How can I supplement the data I have to include a count of total users? Is what I currently have the best approach? A: Hierarchical, fixed-depth many-to-one (M:1) relationships between attributes are typically denormalized or collapsed into a flattened dimension table. If you’ve spent most of your career designing entity-relationship models for transaction processing systems, you’ll need to resist your instinctive tendency to normalize or snowflake a M:1 relationship into smaller subdimensions; dimension denormalization is the name of the game in dimensional modeling. It is relatively common to have multiple M:1 relationships represented in a single dimension table. One-to-one relationships, like a unique product description associated with a product code, are also handled in a dimension table. Occasionally many-to-one relationships are resolved in the fact table, such as the case when the detailed dimension table has millions of rows and its roll-up attributes are frequently changing. However, using the fact table to resolve M:1 relationships should be done sparingly. In your case I recommend you to have this following design as a solution :
{ "language": "en", "url": "https://stackoverflow.com/questions/66342700", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to find number of specific column in csv using pandas? This is my csv file. Iam uploading this data to db using python pandas.How to find the number of fee columns are there(fee_1,fee_2,fee_3)?. Because the start,end,fee columns are dynamic. I need to upload based on the number of fee columns. If number of fee columns is 2 means i need to upload this, "slot_fee":[{"start": i['Start_1'],"end": i['End_1'],"fee": i['Fee_1']},{"start": i['Start_2'],"end": i['End_2'],"fee": i['Fee_2']}] If it is 3 means i need to upload this,and so on. "slot_fee":[{"start": i['Start_1'],"end": i['End_1'],"fee": i['Fee_1']},{"start": i['Start_2'],"end": i['End_2'],"fee": i['Fee_2']},{"start": i['Start_3'],"end": i['End_3']] Can anyone help me with the python pandas code for this? A: If I understand your question correctly this might help : df.columns[df.columns.str.startswith('Fee_')] it gives you the list of columns that start with Fee_, if you want the last one you can add df.columns[df.columns.str.startswith('Fee_')][-1]
{ "language": "en", "url": "https://stackoverflow.com/questions/73944940", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: shift operation in linked list name played games score Deep 5 540 (head) Peter 34 455 Avijit 2 430 Pekka 4 310 (tail) For the above linked list of player list, I want to sort list in ascending order when Avijit gets higher score than Peter. So its a shift operation in linked list. Can anyone help me to find out the problem in code below to do this operation. And any solution? Thanks. void Player::update_statistics(int last_game_point) { player_ptr currPtr = head; // Moving pointer player_ptr prevPtr = NULL; // Pointer to node before *currPtr //player_ptr head; // class variable in Player class //player_ptr selected_player; // class variable in Player class //player_ptr previous_player; // class variable in Player class // update selected player's data cout<<++(selected_player->played_games); // increase by 1 for last game selected_player->total_point=(selected_player->total_point)+last_game_point; if ((selected_player!=head) && (previous_player->total_point < selected_player->total_point)){ previous_player->link = selected_player->link; // search for appropriate position while (currPtr->total_point > selected_player->total_point){ prevPtr = currPtr; currPtr = currPtr->link; } if (currPtr==head) selected_player->link=head; head=selected_player->link; } else { previous_player->link=selected_player; selected_player->link=currPtr; } } A: I think you want else { previous_player->link=selected_player; selected_player->link=currPtr; } to be else { prevPtr->link=selected_player; selected_player->link=currPtr; } A: If this is not a homework and you are not trying to learn the intrinsics of algorithms on a linked list then you should * *use the standard library *avoid using pointers when you don't need pointers That said, to answer your question: struct record { std::string name; int games_played; int score; }; bool lower_score(const record& a, const record& b) { return a.score < b.score; } // ... std::vector<record> records = the_records(); std::sort(records.begin(), records.end(), lower_score); I'm not sure why you want to use a list; if you have no specific concrete reason then you should probably use a vector. Otherwise, std::list has a sort() member: std::list<record> records = no_no_i_meant_those_records(); records.sort(lower_score);
{ "language": "en", "url": "https://stackoverflow.com/questions/5918955", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Special characters in Request URL in SoapUI I use SoapUI to send HTTP and SOAP requests. There is an URL like this: https://mydomain/response? , where a HTTP request should be posted. URL in raw request view it appears without question mark. I tried to provide it in URL encoded(%3F) form too, but it is not resolved, it points to a different URL. A: This is an example of a GET string. Anything after the "?" will be the parameters. You don't have anything after the "?". Thus no parameters. For some reason, this makes soapui remove it. But it really should be without any consequence. Both https://mydomain/response? and https://mydomain/response will reach the same endpoint with no parameters.
{ "language": "en", "url": "https://stackoverflow.com/questions/53062929", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Open folder vs create new project from existing files, located under shared network drive in PhpStorm It's not clear to my why I should use the option in PhpStorm to create a new project from existing files instead of just opening a folder and declaring the project directory. I have a web server installed and I can access it's root by a shared network drive. Now I can just open the a folder in PhpStorm and declare it's root. It will generate a PhpStorm project at the given directory. But there is also an option to open a new project from existing files (located under shared network drive). My best guess is that this option is the way to go. Is this true and if so, why? Or if it doesn't matter, why doesn't it? There will be several people using the same shared drive to work in different projects in the webroot. A: You can, of course, create a project on mounted network drive via File/Open, but note that this is not officially supported. All IDE functionality is based on the index of the project files which PHPStorm builds when the project is loaded and updates on the fly as you edit your code. To provide efficient coding assistance, PHPStorm needs to re-index code fast, which requires fast access to project files and caches storage. The latter can be ensured only for local files, that is, files that are stored on you hard disk and are accessible through the file system. Sure, mounts are typically in the fast network, but one day some hiccup happen and a user sends a stacktrace and all we see in it is blocking I/O call. So, the suggested approach is downloading files to your local drive and use deployment configuiration to synchronize local files with remote. See https://confluence.jetbrains.com/display/PhpStorm/Sync+changes+and+automatic+upload+to+a+deployment+server+in+PhpStorm
{ "language": "en", "url": "https://stackoverflow.com/questions/36935776", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Adding scrolling programmatically when needed I have a screen set up in my app with all the constraints and everything, and so don't want to set up a scroll view for this view in the interface builder if it means that I will lose the constraints. The content size varies, so I only want to make the view scrollable if it goes off the screen. Is there a way to make this view scrollable without the constraints being deleted? (If it can be done in the interface builder without changing constraints, then please say) A: 1- Drag a scrollView behind it and hook it's leading , trailing , top and bottom to superView 2- Copy that view you want to make it scroll-bale , paste it inside the scrollview with L,T,T,B constraints to the scrollView and Equal width to top outer view BTW: You can also use embed from Editor -> EmbedIn -> scrollView Note: this won't break inner constraints of the view , but you will lose only the constraints of the view itself
{ "language": "en", "url": "https://stackoverflow.com/questions/52165239", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: IPN not receiving from paypal sandbox I had developed a website with online transaction using paypal as payment option. Checkout and the shopping cart calculations on paypal side are working, but i'm not receiving any IPN messages from paypal sandbox. <form name="paypal_form" action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post"> <input type="hidden" name="rm" value="2" /> <input type="hidden" name="cmd" value="_cart" /> <input type="hidden" name="upload" value="1" /> <input type="hidden" name="invoice" value="1234" /> <input type="hidden" name="business" value="merchant@domain.com" /> <input type="hidden" name="return" value="http://domain.com/success" /> <input type="hidden" name="cancel_return" value="http://domain.com/cancel" /> <input type="hidden" name="notify_url" value="http://domain.com/notify"> <input type="hidden" name="item_name_1" value="First item"/> <input type="hidden" name="amount_1" value="6.00"/> <input type="hidden" name="quantity_1" value="1"/> <input type="hidden" name="shipping_1" value="5.00"/> <input type="hidden" name="currency_code" value="EUR"/> </form> The overview page in merchant paypal account shows the transactions are completed. When i click on transaction details it shows error 3004 . Also the IPN history page does not displaying any IPN records. It says "no records found in last 24 hours" . How can i solve this? Thanks & Regards. A: It can be PayPal error - see: https://www.x.com/developers/paypal/forums/instant-payment-notifications-ipn-payment-data-transfer-pdt/ipn-failing-hasn-t-been-changed?page=0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C0%2C1 The most iportant messages from the link above are PayPal responses: July 18: "I have found that the problem you are experiencing with IPN in the Sandbox is being caused by some technical issues with the PayPal system. Our engineers are currently working diligently on a solution to this problem." and July 19: "We are aware of this issue and our engineers are currently working on a solution. Unfortunately, i can't give you an exact timeframe when this will be done, however this should be resolved within the next days." A: Make sure that your ipn is actually world-accessible (and not under localhost or a private network) A: If you are trying this on localhost, it wont work. IPN just works on live. And you are saying you are not getting message from paypal sandbox ? If you are working on sandbox, why are you keeping the action url for actual paypal form ?
{ "language": "en", "url": "https://stackoverflow.com/questions/11625285", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: CSS based 50% Transparent border without using transparent image I need to make the border of fancy box transparent after i have made some modifications to it. For some reason i cant make it work with transparent. I have create a sample example which is somewhat & i want to make the borders of the inner DIV transparent. i tried few thing but did not work. I would appreciate a pure CSS solution without using any transparent images Example: JSFiddle Is their a way we can add Opacity to border A: Just use color as transparent like this for making it fully transparent border:10px solid transparent; My fiddle And if you want to add opacity, than this approach of your's is correct, it does make the border opaque border-color:rgba(17,17,17,0.7); You can use this too border-color:rgba(244,244,244,0.4); My fiddle
{ "language": "en", "url": "https://stackoverflow.com/questions/12793041", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: for loop/list-comprehensions to apply zip_longest for list of lists combinations to get (l1[0]:l2[0]) without getting l1[0]:l2[1]) I have been working on combining lists of lists...testing answers to various questions on zip, zip_longest, lists, list comprehensions, iteration through lists of unequal lengths lists of lists, but I have been unable to find one that fixes my issue. I am now defeated. This may very well be a result of my inexperience, but I've run out of places to look. I have two lists of lists with the internal lists having various lengths. I want to zip_longest each internal list with the following type of result: [('1', '1. A method'), ('2', '2. The method'), ('Description', '3.Description'), etc.] The attempts shown below get me results I like but the code generats cross combining of list_1[0] with list_2[1]. I want only combining of lists at the same index (list_1[0] with list_2[0]) then 1:1, 2:2. from itertools import zip_longest claim_text = [['1. A method', '2. The method', '3. Description'], ['1. A method', '2. The method', '3. The method', '5. The method']]; claim_num = [['1', '2'], ['1', '2', '3']] combined = [] for i in claim_text: for x in claim_num: combined.append(list(itertools.zip_longest(x,i, fillvalue='Description'))) print(combined) another approach: [(list(itertools.zip_longest(a,b, fillvalue='Description'))) for a in claim_num for b in claim_text] Any help is appreciated. A: Do you want to zip_longest the first num with the first text, second null with second text, etc.? Then start by combining the sublists of the two inputs with zip: [list(zip_longest(a, b, fillvalue='Description')) for a, b in zip(claim_num, claim_text)] Output: [[('1', '1. A method'), ('2', '2. The method'), ('Description', '3. Description')], [('1', '1. A method'), ('2', '2. The method'), ('3', '3. The method'), ('Description', '5. The method')]]
{ "language": "en", "url": "https://stackoverflow.com/questions/74047967", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Merging a decrypted search of items within a LINQ query I have the following search query: IQueryable<File> files = GetFiles(f => f.Clients.Any(fc => fc.Contacts.Any(c => c.Companies.Any(x => x.Name.Contains(searchText))))); Unfortunately the search for Companies.Name will never work because the Name is encrypted. So I have the following list of decrypted Companies. It's a Stored Procedure and it uses SQL CLR to decrypt the Name field: List<Company> companies = GetSearchCompanies(searchText).Query.ToList(); This list is working fine, it returns a list of companies based on the searchText. My question is whether I can replace the original files list of companies in order to be able to search against decrypted Company names as well as the other searches against Contacts, Clients, etc. Any help would be appreciated and thanks in advance. A: How about something like: var newFiles = from f in files join c in companies on f.CompanyId equals c.CompanyId select new File { prop1 = f.prop1, //Assign all your other properties Company = c };
{ "language": "en", "url": "https://stackoverflow.com/questions/16703863", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create an association class in draw.io? I've started using the website draw.io, I want to create a class diagram but I couldn't find how to create an association class, any help would be useful. Thanks. A: draw.io is a drawing tool, not a UML tool. As such you can simply draw two class shapes, connect them with an association shape, then draw a third class as you association class and then use an association shape to connect you association class to the association. Then go into the properties of the last association shape and change the line style to dashed. Now it looks like a valid UML Association class, but I think you should really opt for a real UML tool instead of a drawing tool when you want to do anything with UML. Using this tool is similar to writing Java with MS Word. A: The accepted answer is far to be perfect. In Draw.io (now called Diagrams.net), you can connect two shapes (here classes) with a connector but you cannot connect two connectors together. Consequently, with the given solution, it will look like an association class but the dashes will not be really adjusted : And really worste, if you need to re-arrange your diagram, the association link will not move and you will have to re-adjust it manually : So, as it is sadly not possible to have a 100% satisfying solution for an association class, another solution is to turn the association class as a regular class. Here in the example, the OrderLine class is associated with both Order and Product classes. It is worth to note the migration of the multiplicities. Refactoring a class association as such an association will ALWAYS lead to have a 1 multiplicity for the non-association classes (here Order and Product), and the original multiplicities will be moved to the association class (here OrderLine).
{ "language": "en", "url": "https://stackoverflow.com/questions/47158665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Proper way to handle Query Cursor in Google Firestore? (Vue/Nuxt.js) I run a chat application with Firebase Firestore and it works all super well, however I'm running into the following issue: For paginating my conversations & chats I use query cursors for my listeners. I save these query cursors into my state (vuex) so I can access them later when needed. That works and I can paginate my chat messages and conversations. I create query cursors like so: const query = await ref.get() const cursor = query.docs[query.docs.length - 1] commit('SET_CONVERSATIONS_QUERY_CURSOR', cursor) And later use them in the next query like so: .startAfter(state.conversations.queryCursor) Everything actually works perfect. My issue now is that that cursor saved in my state seem to be updated regularly (...why Firebase?) & especially directly. This gives me the following error messages when using vuex strict-mode (-> not allowed to access the state directly): app.js:506 Error: [vuex] Do not mutate vuex store state outside mutation handlers. Now I of course want to use strict mode to avoid mutation state directly, but I can't due to the query cursors in my state. I tried to clone the cursor before saving in to the store, but shallow clones did no good and deep clones did not work because of Converting circular structure to JSON. So... * *Is there a recommended way on how to store query cursors for later use? *Are there options to just store the id of a document and later "recreate" a query cursor? Thanks! A: You can prevent javascript object from getting modified by using Object.freeze(obj). So in your case it should be const cursor = Object.freeze(query.docs[query.docs.length - 1])
{ "language": "en", "url": "https://stackoverflow.com/questions/53243866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Converting enums to symbols in Julia I have a definition of an enum as below. I would like to map each instance of the enum into the corresponding symbol. I can do this by manually constructing an array symbols and indexing into it. Is there a way of accomplishing this without specifying the array of symbols by hand? @enum MyEnum A=1 B=2 C=3 symbols = [:A, :B, :C] function enumToSymbol(x::MyEnum) :: Symbol return symbols[Int(x)] end @assert enumToSymbol(A) == :A A: Just use Symbol: julia> @enum MyEnum A=1 B=2 C=3 julia> Symbol(A) :A julia> x = A A::MyEnum = 1 julia> Symbol(x) :A as it is defined as follows: Base.Symbol(x::Enum) = namemap(typeof(x))[Integer(x)]::Symbol in particular you have an un-exported: julia> Base.Enums.namemap(typeof(x)) Dict{Int32,Symbol} with 3 entries: 2 => :B 3 => :C 1 => :A
{ "language": "en", "url": "https://stackoverflow.com/questions/64619215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: HTML,PHP issues I am creating a website at school for a pretend client. At this stage it is a mobile repair/shop with services and products. My aim is to get all the products on my edit page so that if an item was out of stock my (client) could login as an admin and edit the page without having to go through the database and manually do it, or change the code. I am getting this error every time and I am out of ideas on why this might not be working. I am totally new to this. Parse error: syntax error, unexpected end of file in /Applications/XAMPP/xamppfiles/htdocs/matthew/edit.php on line 108 Here is my code: <?php // Start the session session_start(); ?> <!DOCTYPE html> <title>Matts Mobile</title> <link rel="stylesheet" href="css/style.css"> <body> <header> <div class="col span_1_of_3"> <div class="logo"> <a href="index.php"><img src="images/logo.png" style=width:150px;height:150px;></a> </div> </div> <div class="col span_2_of_3"> <div class="z"> <img src="images/m3.jpg" style=width:70%;> </div> <div class="topnav"> <!-- ... --> </div> </div> <?php $pagenum=$_GET["pagenum"]; include 'setup.php'; if(isset($_SESSION['username'])){ if($_SESSION["username"] ==$user) {$message= "Welcome admin"; } } else { header('Location: login.php'); } //---// $sql = "SELECT * FROM pages where pagenum = $pagenum"; $result = $conn->query($sql); $row = mysqli_fetch_all($result,MYSQLI_ASSOC) ; #print_r($row); if(!$row){echo "0 results";} else { $pagenum = $row[0]["pagenum"]; $pagetitle = $row[0]["pagetitle"]; $pagetext = $row[0]["pagetext"]; //print "$pagetext";} //---// $sql = "SELECT * FROM pages where product_id = $product_id"; $result = $conn->query($sql); $row = mysqli_fetch_all($result,MYSQLI_ASSOC) ; #print_r($row); if(!$row){echo "0 results";} else { $product_id = $row[0]["product_id"]; $name = $row[0]["name"]; $price = $row[0]["price"]; $image = $row[0]["image"]; //print "$name";} //---// $conn->close(); ?> </header> <main> <div class="main_container"> <form action="update.php" method="post"> Page Number: <input type="text" name="pagenum" value="<?php echo $pagenum; ?>" ><br> Page Title: <input type="text" name="pagetitle" value="<?php echo $pagetitle; ?>" ><br> Products: 1<input type="checkbox" name="stock" value="<?php echo $product_id=1; ?>" > 2<input type="checkbox" name="stock" value="<?php echo $product_id=2; ?>" > <textarea name="pagetext" rows="5" cols="40"><?php echo $pagetext;?></textarea> <input type="submit"> </form> </div> </main> </body> A: The last lines of your PHP code are if (...) { ... } else { ... Note that there is no closing brace for the else. That's what it's upset about.
{ "language": "en", "url": "https://stackoverflow.com/questions/54602299", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Python dictionary, how can I create a key with a string and the actual key combined? I hope this is a quite easy question, but for me without a lot of python background I can't find an answer. df = pd.DataFrame( {'Messung': ['10bar','10bar','10bar','20bar','20bar'], 'Zahl': [1, 2, 3, 4, 5], 'Buchstabe': ['a','b','c','d','e']}) There is a DataFrame (made a simplier Test DF for this post) where I loop through one column and compare the first 2 numbers of a string. The whole column has in the end like 20 Keys. Everytime the key is found, append the whole row to this key. d={} for row, item in enumerate(df['Messung']): key=item[0:2] if key not in d: d[key] = [] d[key].append(df.iloc[row]) This code works, but my first attempt to this was different. I wanted to have dictionaries where I have keys named as 'RP_10', 'RP_20'. d={} for row, item in enumerate(df['Messung']): key=item[0:2] if key not in d: d['RP_'+key] = [] d['RP_'+key].append(df.iloc[row]) Can someone explain to me, why this doesn't work and how could I write the code so that I get 'RP_10', 'RP_20' and so on? A: Can you please try below code. You do small mistake in if condition. d={} for row, item in enumerate(df['Messung']): key=item[0:2] key = "RP_"+key if key not in d: d[key] = [] d[key].append(df.iloc[row]) ALso you can use setdefault() of python.Then your code looks like as below: d={} for row, item in enumerate(df['Messung']): key=item[0:2] key = "RP_"+key d.setdefault(key, []).append(df.iloc[row]) A: While trying your solution I noticed, I can even delete the line with key=item[0:2] and directly build my key with 'RP_' and the item[0:2] d={} for row, item in enumerate(df['Messung']): key = "RP_"+item[0:2] d.setdefault(key, []).append(df.iloc[row])
{ "language": "en", "url": "https://stackoverflow.com/questions/66886187", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: android sort integers from database from big to small I made an quiz android app where the user get score every time he finish the quiz and after that the score will be saved in the database and after that the user can display the saved score. and my question is how I can display or sort these score on the page score from the biggest score to the smallest. this is my code where I get the score and name of the user and set it on a textview: TextView tv1 = (TextView) findViewById(R.id.TextView1); DbHelper info = new DbHelper(this); userInfo.open(); String data = userInfo.getData(); userInfo.close(); tv1.setText(data); my getData method: // TODO Auto-generated method stub String[] columns = new String[] { KEY_ID2, KEY_NAME, KEY_SCORE}; Cursor c = ourDbase.query(MyTABLE, columns , null, null, null, null, null); String result =""; int TheRow = c.getColumnIndex(KEY_ID); int TheName = c.getColumnIndex(KEY_NAME); int TheScore = c.getColumnIndex(KEY_SCORE); for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){ result = result + c.getString(TheRow ) + " " + c.getString(TheName ) + " " + c.getString(TheScore ) + "\n"; } return result; } A: You can set ascending or descending in the last argument of your query. In your case, your getData() method can return your string with the KEY_SCORE column in descending order by changing the query line to this: Cursor c = ourDbase.query(MyTABLE, columns , null, null, null, null, KEY_SCORE + " DESC"); Good Luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/26679665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Parse SGML using beautiful soup Below is the sample content :- <WKEXT-META-ATTRS> <WKEXT-META-ATTR NAME="uri" VALUE="http://sample.com/ceres/wk-us/Concept/i8148" DATA-TYPE="OTHER"></WKEXT-META-ATTR></WKEXT-META-ATTRS></WKEXT-META-OBJECT> <WKEXT-META-OBJECT NAME="UNIONREPINFO" ID="ext-met-0005" PUBLISHER-URI="http://wk-us.com/meta/publishers/#CCH"> <WKEXT-META-ATTRS> <WKEXT-META-ATTR NAME="UnionRep" VALUE="Jim Gookins" DATA-TYPE="OTHER"></WKEXT-META-ATTR></WKEXT-META-ATTRS></WKEXT-META-OBJECT> <WKEXT-META-OBJECT NAME="TOPICALSUBJECTINFO" ID="ext-met-0006" PUBLISHER-URI="http://sample.com/meta/publishers/#CCH"> <WKEXT-META-ATTRS> <WKEXT-META-ATTR NAME="uri" VALUE="http://sample.com/ceres/sample/Concept/i8173" DATA-TYPE="OTHER"></WKEXT-META-ATTR></WKEXT-META-ATTRS></WKEXT-META-OBJECT> <WKEXT-META-OBJECT NAME="TOPICALSUBJECTINFO" ID="ext-met-0007" PUBLISHER-URI="http:/sample/meta/publishers/#CCH"> I want to extract the VALUE of uri -- "http://sample.com/ceres/wk-us/Concept/i8141 I am currently trying out with below code:- with open ("sample.sgm","r")as f: contents =f.read() soup = BeautifulSoup(contents, 'lxml') s = soup.find('wkext-meta-attr').attrs #for a in s: # t = a.attrs # for key,value in t.items(): # alias_text.append(t['normval']) #print(alias_text) #df = DataFrame(alias_text, columns=['arbitratorname']) #s_topic=soup.find('WKEXT-META-ATTRS'= print(s) I am not able to figure out how to obtain the exact value . Any help will be much appreciated!!! A: If you want to retrieve the value of each wkext-meta-attr, You can use the`.findAll() method and then loop through each element. Check whether the below code fulfills your task: from bs4 import BeautifulSoup with open ("sample.sgm","r")as f: contents =f.read() soup = BeautifulSoup(contents, 'html.parser') meta_attrs = soup.findAll('wkext-meta-attr') for meta_attr in meta_attrs: print(meta_attr['value'])
{ "language": "en", "url": "https://stackoverflow.com/questions/64966365", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Netty doesn't complain if port is already used Following problem: I expect an exception if a port is already used. So I tried to start my server twice in a thread public void start() { new Thread(new Runnable() { @Override public void run() { EventLoopGroup bossGroup = new EpollEventLoopGroup(); EventLoopGroup workerGroup = new EpollEventLoopGroup(); ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(final SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast("decoder", new Decoder(Server.this)); socketChannel.pipeline().addLast("encoder", new Encoder(Server.this)); } }); serverBootstrap.bind(port).channel().closeFuture().syncUninterruptibly(); } }).start(); } But got no exception. I also tried to add an channel handler and catch a exception there, no luck :/ Surrounding the line with bind(port) to catch an exception has also no effect. But I noticed when I added a ChannelListener to the ChannelFuture, that one of the started instances never reached that point. Anyone an idea? A: After binding you are directly taking the channel from the future, but it probably hasn’t finished at that point. Try to wait for your bind to complete with bind(port).sync(). See for reference https://www.baeldung.com/netty#6-server-bootstrap and https://netty.io/4.1/api/io/netty/channel/ChannelFuture.html
{ "language": "en", "url": "https://stackoverflow.com/questions/72352246", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to write CLLocation's GPS information into UIImage using PHPhotoKit? Is there any method to write GPS info into one image? for example, I want to develop a camera app that can take photos with location information. Can I use PhotoKit related methods or some other methods such as ImageIO? Thanks. A: You can add location information to your image like this let locationCordinate = CLLocationCoordinate2DMake(lat, long) let currentDate = NSDate() let imageLocation = CLLocation(coordinate: locationCordinate, altitude: 0.0, horizontalAccuracy: 0.0, verticalAccuracy: 0.0, timestamp: currentDate) After this you can add this location to your image like this PHPhotoLibrary.sharedPhotoLibrary().performChanges({ let assetLocationChangeRequest = PHAssetChangeRequest(forAsset: lastImageAsset) assetLocationChangeRequest.location = imageLocation }, completionHandler: { (success:Bool, error:NSError?) -> Void in if (success) { print("Succesfully saved location to image") } else { print("Failed to save with Error : \(error!)") } })
{ "language": "en", "url": "https://stackoverflow.com/questions/40777333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: merge sort merge run time anaylsis I have some confusion of the run time analysis of the merge function in merge sort. Merg(A,p,q,r) 1 n1=q-p+1 2 n2=r-q 3 let L[1..n1+1] and R[1..n2+1] be new arrays 4 for i=1 to n1 5 L[i] = A[p+i-1] 6 for j =1 to n2 7 R[j] = A[q+j] 8 L[n1+1] = infinity 9 R[n2+1] = infinity 10 i =0 11 j=0 12 for k=p to r 13 if L[i]<=R[j] 14 A[k]=L[i] 15 i=i+1 16 else A[k] = R[j] 17 j=j+1 In my book it says the following: to see that the merge procedure runs in O(n) time, where n=r-p+1, observe that each of lines 1-3 and 8-11 takes constant time, the for loops of lines 4-7 take O(n1+n2) = O(n)time, and there are n iterations of the for oop of lines 12-17, each of which takes constant time My question is why do lines 12-17 take constant time per iteration and not affect the run time but lines 4-7 don't take constant time. to me, it seems like both loops are doing the same thing. can someone help clarify this for me? Thanks! A: Lines 1 through 9 are just splitting the input (A) into two pieces (L and R). Lines 10 and 11 are doing a bit of initializing to get ready for merging. The merge itself is from lines 12-17. IOW, everything before line 12 (or arguably 10, not that it really matters) is irrelevant to analyzing the merge because none of it is really part of the merge at all. Edit: Ultimately, however, a single iteration from 1 to 27 is linear: in lines 4-7, you walk exactly once through the input array, assigning each input exactly once to either L or R. In lines 12-27, you then walk through those two pieces, and copy them back to the original input. Ignoring a few other minor details like initializing i and j, the total number of operations is exactly 2N. For big-O notation, constant factors are ignored, so it's O(N). A: It's confusingly written. Both loops (4-7 and 12-17) have the same length (n) and the inside of both loops are constant time (no nested loops). So they're each O(n), for a total of O(n) for the whole routine. Regarding Jerry's answer, lines 4-7 matter because they're still O(n). If you could magically remove lines 12-17 you'd still have an O(n) routine.
{ "language": "en", "url": "https://stackoverflow.com/questions/7668392", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Create multi-page document from a single page template using doc4j I am planning to use doc4j for search and replace in a template. I'do like to create the page for each member in the list. Basically, I need to replicate the same page from the template. I have done simple search and replace. However, this little complex one for which I need some sample examples. Here is my requirement: * *I have a docx template which has the content with place holders. *There is a table with 3 columns in it and I need to replace with different values for each column like first name, last name and etc. The number of rows may vary anywhere from one to 200. So technically this may go beyond one page. If it exceeds more than one page, then I need the table header to repeat in the next page too. *I want to copy the same template on every page and replace the place holder. Basically create a single document with multiple pages each page for one member. Please provide me with the example. Appreciate the help. Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/36226178", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: search the product by tag or category not working I am working on a search. I am trying to search the product by tag or category. I tried the below code but it's not working. I am getting Nothing Found Also, the Below code is working only with title and content. Would you help me out with this? <?php /** * The template for displaying search results pages * * @link https://developer.wordpress.org/themes/basics/template-hierarchy/#search-result * * @package CoolPickings */ get_header(); ?> <section id="primary" class="content-area mainSearch"> <main id="main" class="site-main"> <div class="equalPadding"> <div class="cp-seeWrapper"> <?php if ( have_posts() ) : ?> <div class="row"> <?php while (have_posts()){the_post();?> <div class="col-xl-4 col-lg-4 col-md-4 col-sm-12 col-xs-12 "> <div class="cp-shadow cp-seeSinglePostWrapper"> <?php the_post_thumbnail();?> <div class="bg-white single-post-box"> <div class="d-flex cp-CategoryList"> <div class="seeDate"><?php echo get_the_date('F j, Y'); ?></div> <div class="cp_cat_list"> <?php $cat = get_the_category(); ?> <a href="<?php echo esc_url( get_category_link( $cat[0]->term_id ) );?>"><?php echo $cat[0]->cat_name?></a><?php //the_category(''); ?> </div> </div> <div class="cp-b-content"><h2><a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( the_title_attribute( 'echo=0' ) ); ?>"><?php echo wp_trim_words(get_the_title(), 12, '...'); ?></a></h2></div> <p><?php echo wp_trim_words(get_the_excerpt(), 25, '...'); ?></p> </div> </div> </div> <?php } ?> <?php //endwhile; //the_posts_navigation(); else : get_template_part( 'template-parts/content', 'none' ); endif; ?> </div> </div> </div> </main><!-- #main --> </section><!-- #primary --> <?php get_sidebar(); get_footer(); A: Try the following code below. The only difference is using terms as an array. $getSearch=get_search_query(); $args = array( 'tax_query' => array( 'relation' => 'OR', array( 'taxonomy' => 'product_tag', 'field' => 'slug', 'terms' => array($getSearch) // Using the terms as an array ), array( 'taxonomy' => 'product_cat', 'field' => 'slug', 'terms' => array($getSearch) // Using the terms as an array ) ), 'post_type' => 'product' ); $the_query = new WP_Query( $args ); // ... functions.php add_action( 'pre_get_posts', 'my_search_exclude' ); function my_search_exclude( $query ) { if ( ! $query->is_admin && $query->is_search && $query->is_main_query() ) { $query->set( 's', '' ); } } You can find more info here: https://developer.wordpress.org/reference/classes/wp_query/#taxonomy-parameters
{ "language": "en", "url": "https://stackoverflow.com/questions/59300576", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unable to load dataset from "" using class com.github.springtestdbunit.dataset.FlatXmlDataSetLoader I wrote a demo of Spring Boot + JPA, and here I met a question that confused me couple of days when I try to do some tests on repository. The error is **java.lang.IllegalArgumentException: Unable to load dataset from"dbunit/studentTestSample" using class com.github.springtestdbunit.dataset.FlatXmlDataSetLoaderava.lang.IllegalArgumentException: Unable to load dataset from "/data/dbunit/studentTestSample.xml" using class com.github.springtestdbunit.dataset.FlatXmlDataSetLoader at org.springframework.util.Assert.notNull(Assert.java:201) ~[spring-core-5.3.12.jar:5.3.12] at com.github.springtestdbunit.DbUnitRunner.loadDataset(DbUnitRunner.java:211) ~[spring-test-dbunit-1.3.0.jar:na] at com.github.springtestdbunit.DbUnitRunner.loadDataSets(DbUnitRunner.java:192) ~[spring-test-dbunit-1.3.0.jar:na] at com.github.springtestdbunit.DbUnitRunner.setupOrTeardown(DbUnitRunner.java:173) ~[spring-test-dbunit-1.3.0.jar:na] at com.github.springtestdbunit.DbUnitRunner.beforeTestMethod(DbUnitRunner.java:75) ~[spring-test-dbunit-1.3.0.jar:na] at com.github.springtestdbunit.DbUnitTestExecutionListener.beforeTestMethod(DbUnitTestExecutionListener.java:185) ~[spring-test-dbunit-1.3.0.jar:na]** * *Firstly, here is my test file package com.meds.infrastructure.student; import com.github.springtestdbunit.TransactionDbUnitTestExecutionListener; import com.github.springtestdbunit.annotation.DatabaseSetup; import com.meds.domain.student.entity.StudentInfoDo; import com.meds.infrastructure.repository.StudentRepository; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.test.context.support.DirtiesContextTestExecutionListener; import org.springframework.transaction.annotation.Transactional; @AutoConfigureMockMvc @SpringBootTest @ContextConfiguration @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class, TransactionDbUnitTestExecutionListener.class, MockitoTestExecutionListener.class }) public class StudentRepositoryTest { @Autowired private StudentRepository studentRepository; @Test @Transactional @DatabaseSetup("dbunit/studentTestSample") public void should_get_student_info_id() { StudentInfoDo studentInfoDo = studentRepository.findStudentById(1l); assertThat(studentInfoDo.getId()).isEqualTo(1l); assertThat(studentInfoDo.getStudentId()).isEqualTo("studentId"); assertThat(studentInfoDo.getName()).isEqualTo("studentName1"); assertThat(studentInfoDo.getGender()).isEqualTo("MALE"); } } and here is my gradle.build dependencies { implementation 'junit:junit:4.13.1' annotationProcessor 'org.mapstruct:mapstruct-processor:1.2.0.Final' annotationProcessor 'org.projectlombok:lombok:1.18.10' compileOnly 'org.projectlombok:lombok:1.18.10' compileOnly 'org.mapstruct:mapstruct-processor:1.2.0.Final' implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.hibernate:hibernate-core' implementation 'javax.xml.bind:jaxb-api:2.3.0' implementation 'javax.xml.soap:saaj-api:1.3.5' implementation 'jakarta.validation:jakarta.validation-api:2.0.2' implementation 'org.flywaydb:flyway-core' implementation 'org.mapstruct:mapstruct-jdk8:1.2.0.Final' implementation 'org.mapstruct:mapstruct:1.3.1.Final' implementation 'io.springfox:springfox-swagger2:2.8.0' implementation 'io.springfox:springfox-swagger-ui:2.8.0' implementation 'org.springframework.boot:spring-boot-starter-security' runtimeOnly 'mysql:mysql-connector-java' testImplementation("org.dbunit:dbunit:2.5.2") testImplementation("com.github.springtestdbunit:spring-test-dbunit:1.3.0") testImplementation 'org.springframework.boot:spring-boot-starter-test' } Here is my studentTestSample.xml <?xml version="1.0" encoding="UTF-8"?> <dataset> <student_info id="1" student_id="studentId1" student_name="studentName1" gender="MALE" grouped="0" /> </dataset> *What I have tried * *add classpath at @DatabaseSetup *add "" at XML file *add version at XML file *remove jupiter and use junit.Test *Check the location of XML I guess the reason is cannot find the XML file(because I change the file name randomly it still has this error), maybe it's about my Spring Boot version and JUnit version does not support DbUnit? A: Try something like this @DatabaseSetup("/data/.../studentTestSample.xml") Careful with your file path will help you resolve problem. Reference document https://springtestdbunit.github.io/spring-test-dbunit/apidocs/com/github/springtestdbunit/annotation/DatabaseSetup.html section parameter value. A: I finally found the issue. It was because the format of xml was not right! Here is my xml name: studentTestSample It should be written like is: studentTestSample.xml I do remember I wrote "studentTestSample.xml" when I created this file. It looks like I have to emphasize the type of my xml file. Finally, make sure you can jump to the location of file when you are typing command+B.
{ "language": "en", "url": "https://stackoverflow.com/questions/70060569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Uri Segment When Using Ajax In my codeigniter application i want to display the uri segments.Iam using ajax to call controller. This is my html code function add_store(){ var path="<?php echo base_url()?>images/loader.gif"; $("#add_store").html("<div align='center' style='margin-top:200px;'><img src="+path+" style='width:25px;' /></div>").show(); $.ajax({ type: "POST", url: "<?php echo base_url();?>index.php/Admin/add_store/", success: function(msg){ $("#add_store").html(''); $("#add_store").html(msg).show(); } }); } This is my controller code public function add_store() { echo $this->uri->segment(3); } nothing will be displayed.How can i get uri segments? If i use echo $this->uri->segment(1); Then it displays Admin but after 1 nothing will be displayed. A: Looks like your controller 'Admin' is calling a method 'add_store', but there are no further segments, that's why your 3rd one isn't passed. 1st segment: "Admin" 2nd segment: "add_store" I don't know what you want to achieve, but if you have an url like: admin/add_store/someparam/someotherparam you would just do public function add_store($param1, $param2) { echo $param1; // 'someparam' echo $param2; // 'someotherparam' } without the need to call directly the uri segment.
{ "language": "en", "url": "https://stackoverflow.com/questions/8413433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Counting number of records in database: Django I'm trying to output the count of the number of "subscribers" in my database in Django, I've found count in my view and then I think I'm using it correctly in the html, but it always just outputs "there are subscribers" without the number, when I use "|length" in the html it always outputs 0, so I'm not sure what my error is. views.py def list_todo_items(request): context = {'todo_list' : Todo.objects.all()} count = Todo.objects.count() context2 = {'count': count} # context = {'count': Todo.objects.count()} # count = Todo.objects.count() return render(request, 'index.html',context,context2) def insert_todo_item(request: HttpRequest): todo = Todo(content=request.POST['content']) try: todo.full_clean() except ValidationError: # pymsgbox.alert('ValidationError! Phone number must be entered in the format: +999999999. Up to 15 digits allowed.', 'Title') return redirect('/main/list/') todo.save() return redirect('/main/list/') def delete_todo_item(request,todo_id): todo_to_delete = Todo.objects.get(id=todo_id) todo_to_delete.delete() return redirect('/main/list/') index.html {% for todo in todo_list %} <li class="list-group-item"> {{todo.content}} <form action="{% url 'delete_todo_item' todo.id %}" method="post" class="float-right d-inline"> {% csrf_token %} {{form.as_p}} <button type="submit" class="btn"> <i class="far fa-trash-alt fa-lg text-danger float-right"></i> </button> </form> </li> <li class="list-group-item"> <span class="font-italic">There are {{ count }} subscribers.</span> </li> {% empty %} <li class="list-group-item"> <span class="font-italic">No current subscribers.</span> </li> {% endfor %} A: You can pass multiple items to the same context. A dictionary allows to add multiple key-value pairs (as long as the keys are hashable, and unique): def list_todo_items(request): context = { 'todo_list': Todo.objects.all(), 'count': Todo.objects.count() } return render(request, 'index.html', context)
{ "language": "en", "url": "https://stackoverflow.com/questions/61350232", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to bind a String to a TexBlock Property ? WPF c# I have this : TextBlock MyText = new TextBlock(); String SomeWords; I want to bind those two properties but I dont know how to do it with a string : Binding binding = new Binding(); binding.Path = new PropertyPath(MyText.Text); BindingOperations.SetBinding(SomeWords, ???????, binding); What am I suppose to put at the emplacement of the question marks ? Ty !!! A: TextBlock MyText = new TextBlock(); Binding binding = new Binding(); binding.Path = new PropertyPath("Name"); //Name of the property in Datacontext BindingOperations.SetBinding(MyText,TextBlock.TextProperty , binding); If you want to bind to property of some other object you will need to set binding.Source to that object. A: The other answers are technically more correct to this particular question given you are trying to create the binding in code, but usually people perform these simple bindings through xaml. Xaml View: <TextBox Text="{Binding MyTextPropertyFromViewModel}" /> C# ViewModel: public String MyTextPropertyFromViewModel { get; set; } A: That should be the target property of the binding, ie your TextBlock.TextProperty See: http://msdn.microsoft.com/en-us/library/system.windows.data.bindingoperations.setbinding.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/18632617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Create an Angular 2 app inside no Angular project I've created an Angular 2 app inside a normal javascript project and I need to use some files (.CSS, .JS, etc) outside the Angular app, but if I use the CLI with command ng serve it creates the app in the http://localhost:4200/, and the app works, but these files outside the angular app they won't be loaded. So I have to deploy the app with ng build --prod to get these files and see the real result. But I think this is not the best way as I have to deploy the app for every change in the code. So, is there any way to manage this situation? Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/42391211", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Python Decorator for printing every line executed by a function I want to, for debugging purposes, print out something pertaining to each and every line executed in a python method. For example if there was some assignment in the line, i want to print what value was assigned for that variable, and if there was a function call, i want to print out the value returned by the function, etc. So, for example if i were to use a decorator, applied on function/method such as : @some_decorator def testing() : a = 10 b = 20 c = a + b e = test_function() the function testing when called, should print the following : a = 10 b = 20 c = 30 e = some_value Is there some way to achieve this? More fundamentally, i want to know whether i can write a code that can go through some other code line by line, check what type of an instruction it is, etc. Or maybe like we can get a dictionary for finding out all the variables in a class, can i get a dictionary like datastructure for getting every instruction in a function, which is as good a metaprogram can get. Hence, I am particularly looking a solution using decorators, as I am curious if one can have a decorator that can go through an entire function line by line, and decorate it line by line, but any and all solutions are welcome. Thanks in advance. A: How about something like this? Would this work for you? Debug Context: import sys class debug_context(): """ Debug context to trace any function calls inside the context """ def __init__(self, name): self.name = name def __enter__(self): print('Entering Debug Decorated func') # Set the trace function to the trace_calls function # So all events are now traced sys.settrace(self.trace_calls) def __exit__(self, *args, **kwargs): # Stop tracing all events sys.settrace = None def trace_calls(self, frame, event, arg): # We want to only trace our call to the decorated function if event != 'call': return elif frame.f_code.co_name != self.name: return # return the trace function to use when you go into that # function call return self.trace_lines def trace_lines(self, frame, event, arg): # If you want to print local variables each line # keep the check for the event 'line' # If you want to print local variables only on return # check only for the 'return' event if event not in ['line', 'return']: return co = frame.f_code func_name = co.co_name line_no = frame.f_lineno filename = co.co_filename local_vars = frame.f_locals print (' {0} {1} {2} locals: {3}'.format(func_name, event, line_no, local_vars)) Debug Decorator: def debug_decorator(func): """ Debug decorator to call the function within the debug context """ def decorated_func(*args, **kwargs): with debug_context(func.__name__): return_value = func(*args, **kwargs) return return_value return decorated_func Usage @debug_decorator def testing() : a = 10 b = 20 c = a + b testing() Output ########################################################### #output: # Entering Debug Decorated func # testing line 44 locals: {} # testing line 45 locals: {'a': 10} # testing line 46 locals: {'a': 10, 'b': 20} # testing return 46 locals: {'a': 10, 'b': 20, 'c': 30} ###########################################################
{ "language": "en", "url": "https://stackoverflow.com/questions/32163436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: IF-statement depending on notebook.page.label (gtk#) I am realtively new to C# and am trying to have an action in my toolbar that will act depending on which page in a notebook that I am currently "viewing". Here is what I am trying to do: protected void OnRefreshActionActivated (object sender, EventArgs e) { if (mynotebook.CurrentPage.Equals == pgMyNotebookPage) { lblMsg.Text = "You are viewing the first page"; } else { lblMsg.Text = "You are viewing the second page"; } } However I can't seem to get this to work. Any pointers? Regards, Christian A: I solved this by creating a messagedialog that showed me the output of mynotebook.CurrentPage. It turned out that each page was assigned a number starting with 0. This is the working code: protected void OnRefreshActionActivated (object sender, EventArgs e) { if (nbMain.CurrentPage == 0) { lblMsg.Text = "You are viewing the first page."; } else { lblMsg.Text = "You are viewing the first page."; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/43331758", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WebKit gradient from an image Does anyone know if there is a tool that will take an image (.png, .gif, etc) and output the gradient that the image contains? I really want to recreate this image in css. Looks like a mix of linear and radial gradients and is beyond my css skills A: Getting the gradient from a random image is going to be tough for any image processor. You would probably have better luck by getting the pixel data for the image, finding the top and bottom pixel, pulling the color data out of them, then using these values to create your gradient. A: Get started with this tool http://gradients.glrzad.com/ and then read about radial gradients here to make it radial http://hacks.mozilla.org/2009/11/css-gradients-firefox-36/ You can get this far with that tool: -webkit-gradient( linear, left bottom, left top, color-stop(0, rgb(68,214,254)), color-stop(0.49, rgb(53,150,230)), color-stop(0.51, rgb(123,180,236)), color-stop(1, rgb(255,255,255)) ) -moz-linear-gradient( center bottom, rgb(68,214,254) 0%, rgb(53,150,230) 49%, rgb(123,180,236) 51%, rgb(255,255,255) 100% ) Then make it radial, mozilla only here -moz-radial-gradient(right bottom, ellipse, #44D6FE 0%, #3596E6 49%, #7BB4EC 51%, #FFFFFF 100%) repeat scroll 0 0 transparent and here is an image of what it looks like A: Your example is an overlap of two radial gradients. There is a white to mid-blue stop to opaque radial gradient centered above the button with a mid-opacity; on top of simple blue to white radial gradient centered to the bottom right.
{ "language": "en", "url": "https://stackoverflow.com/questions/3847188", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Replace input field error message text based on input field label name So I have this account creation form for a company. Here's what it looks like: I am going to explain first how a feature in this system works. * *After company creation, a table will be shown, listing all the companies I created. *In the Action column of this table, there's an action button that once I click it, I will be logged in into a specific company I chose, acting as the user logged inside that company. *Inside, there's more like the same layout and I can create a sub-company called "Operator". *So there's a "Create Operator" button and once clicked, I will be redirected to the same form layout above (except that the "Company Name" label is changed to "Operator Name"). *Alright, so I am using Yii2 php framework and basically, each input field is an attribute in a db table and in my model, there's a function called public function attributeLabels() where each of these attributes are assigned to a specific label. *For example, first input field's db table attribute name is company_name so inside this function it is assigned as company_name => "Company Name" and this label is passed to the view which is this form. So whenever there are error messages, this label is used. *Regardless if I am creating a company or operator, the error message is always "Company Name should not be blank". What I need to accomplish is when I create an operator, the error message should be "Operator Name should not be blank." I hope you get my problem. So I tweaked some javascript/jQuery but I am still having problems. // For changing Operator Name error message var operatorNameLabel = $('.field-company-company_name label').attr('for','company-company_name').text(); var companyNameErrorDiv = $(".field-company-company_name p"); var operatorNameMsg = 'Operator Name should not be blank.'; $('#submit-button').click(function() { // Change Operator Name error message if (operatorNameLabel == "Operator Name") { companyNameErrorDiv.html("<p class='help-block help-block-error'>Operator Name should not be blank</p>"); //companyNameErrorDiv.text(operatorNameMsg); } }); $('#content-offset').click(function () { if (operatorNameLabel == "Operator Name") { companyNameErrorDiv.html("<p class='help-block help-block-error'>Operator Name should not be blank</p>"); //companyNameErrorDiv.text(operatorNameMsg); } }); My problem in my current code is that : * *when I leave the operator name input field blank then click into a blank space outside the input field, the error message is still "Company Name should not be blank." *but then when I click back to the input field, that's the time the error message changes to "Operator Name should not be blank." *What really happens is that when I click at the operator name input field, then single click outside or at any other input fields, the error message remains "Company Name should not be blank.", *but when I do a second click, the the error message changes. *There's a problem when I click back to the operator name input field for it keeps on getting back to the "Company Name should not be blank" error message, when clicked. I hope you get my problem. EDIT: Yii2 generated html looks like this: <div class="form-group field-company-company_name required has-error"> <label class="col-lg-2 control-label name-label" for="company-company_name" data-name="Operator Name">Operator Name</label> <div class="col-lg-3"> <input type="text" id="company-company_name" class="form-control" name="Company[company_name]" required="required"> </div> <div class="col-lg-7"> <p class="help-block help-block-error">Company Name cannot be blank.</p> </div> </div> A: Try adding required attribute to input element, data-* at label element; css :invalid, :after pseudo element, content property of label to display message when input is invalid. input:invalid + label:after { content: " " attr(data-name) " should not be blank"; color: red; } <input type="text" name="company_name" required /><label data-name="Company Name"></label><br> <input type="text" name="login_name" required /><label data-name="Login Name"></label><br> <input type="email" name="email" required /><label data-name="Email"></label><br> <input type="password" name="password" required /><label data-name="Password"></label><br> <input type="password" name="password_confirm" required /><label data-name="Password Confirm"></label>
{ "language": "en", "url": "https://stackoverflow.com/questions/36299287", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Python - Create a Bar Chart of Average Estimated Salary by c_rating, but do a facet_wrap by gender My data set is Churn_Modeling: RowNumber CustomerId Surname CreditScore Geography Gender Age Tenure Balance NumOfProducts HasCrCard IsActiveMember EstimatedSalary Exited 1 15634602 Hargrave 619 France Female 42 2 0 1 1 1 101348.88 1 2 15647311 Hill 608 Spain Female 41 1 83807.86 1 0 1 112542.58 0 3 15619304 Onio 502 France Female 42 8 159660.8 3 1 0 113931.57 1 4 15701354 Boni 699 France Female 39 1 0 2 0 0 93826.63 0 5 15737888 Mitchell 850 Spain Female 43 2 125510.82 1 1 1 79084.1 0 6 15574012 Chu 645 Spain Male 44 8 113755.78 2 1 0 149756.71 1 I created a column called c_rating with the following ranges: (<500 -="very poor", 500-600="poor", 601-660="fair", 661-780="good", and >= 780 – "excellent") with code: from plotnine import * from dfply import * import numpy as np import pandas as pd from sklearn.linear_model import LinearRegression import datetime as dt a_churn = pd.read_csv("Churn_Modeling.csv") a_churn['c_rating'] = pd.cut(a_churn['CreditScore'], bins=[0,500,600,660,780,1000],labels = ['very poor', 'poor', 'fair', 'good', 'excellent']) a_churn I am trying to create a Bar Chart of Average Estimated Salary by c_rating, but do a facet_wrap by gender. (a_churn >> group_by(X.c_rating) >> summarise(avg_est_salary = X.EstimatedSalary.mean()) >> ggplot(mapping=aes(x=avg_est_salary,y = 'c_rating')) +geom_bar(stat = "identity")) However I get the error c_rating is not defined. A: Is this what you are trying to do? from plotnine import ggplot, aes, geom_bar, facet_wrap import pandas as pd a_churn = pd.read_csv('Churn_Modeling.csv') a_churn['c_rating'] = pd.cut(a_churn['CreditScore'], bins=[0,500,600,660,780,1000],labels = ['very poor', 'poor', 'fair', 'good', 'excellent']) p = ggplot(a_churn) + aes(x='c_rating', y='EstimatedSalary') + geom_bar(stat='identity', alpha=0.8) + facet_wrap('Gender') print(p)
{ "language": "en", "url": "https://stackoverflow.com/questions/65270025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Twig impossible to invoke a method on a string variable After updating "twig/twig" to "v2.4.4" I have an error when calling macro function. Impossible to invoke a method ("widget_prototype") on a string variable (":ERP/timesheets:_form_part.html.twig"). My macro: {% macro widget_prototype(widget, remove_text) %} {% if widget.vars.prototype is defined %} {% set form = widget.vars.prototype %} {% set name = widget.vars.prototype.vars.name %} {% else %} {% set form = widget %} {% set name = widget.vars.full_name %} {% endif %} Calling macro part: {% include ':ERP/timesheets:_data_content_supply_from_widget.html.twig' with {form:form, name:name} %} {% endmacro %} <div id="post_supplies" data-prototype="{{ _self.widget_prototype(form.supplies, 'remove'|trans({}, 'common'))|escape }}" style="margin-bottom: 5px"> {% for widget in form.supplies.children %} {{ _self.widget_prototype(widget, 'remove'|trans({}, 'common')) }} {% endfor %} </div> How to correctly call macro? Tried calling without _self and I have the error: Unknown "widget_prototype" function. A: DarkBee's answer is good, but if your macro is in the same twig file that's calling it then you will still need to import it like so: {% import _self as my_macros %} {{ my_macros.widget_prototype(...) }} Seems a bit counter-intuitive but that's how it is. A: You need to import the macro, not include it {% import "my_macro.twig" as my_macro %} {{ my_macro.function(arg1) }}
{ "language": "en", "url": "https://stackoverflow.com/questions/47013982", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Specifying matplotlib scatter size in plot units I would like to specify my scatter dot size not using points or pixels but rather using plot units. Take for instance the following: import matplotlib.pyplot as plt x = [0] y = [0] plt.scatter(x,y) plt.show() This produces a plot as follows: What if, say, I wanted my marker to have a radius of exactly 0.002 plot units? I understand the s parameter indicates the area of the marker size in points. Is there a way to directly provide it in plot units? If not what is the best way to convert from plot units to points so I can pass it into the s parameter? I have also seen some other questions which propose using a PatchCollection and simply plotting a circle with a specified radius. I would prefer not to use this approach. I'd like to avoid extensively rewriting existing code and instead use the s parameter along with plt.scatter. Edit I tried using the code from this question which apparently allows you to control the marker size based on plot units. However I couldn't really get it to work for my basic case: import matplotlib.pyplot as plt import numpy as np class scatter(): def __init__(self,x,y,ax,size=1,**kwargs): self.n = len(x) self.ax = ax self.ax.figure.canvas.draw() self.size_data=size self.size = size self.sc = ax.scatter(x,y,s=self.size,**kwargs) self._resize() self.cid = ax.figure.canvas.mpl_connect('draw_event', self._resize) def _resize(self,event=None): ppd=72./self.ax.figure.dpi trans = self.ax.transData.transform s = ((trans((1,self.size_data))-trans((0,0)))*ppd)[1] if s != self.size: self.sc.set_sizes(s**2*np.ones(self.n)) self.size = s self._redraw_later() def _redraw_later(self): self.timer = self.ax.figure.canvas.new_timer(interval=10) self.timer.single_shot = True self.timer.add_callback(lambda : self.ax.figure.canvas.draw_idle()) self.timer.start() x = [0] y = [0] fig = plt.figure() ax = fig.gca() size = 3.14*0.002**2 scatter(x, y, ax, size = 0.002, edgecolors = 'black') ax.set_ylim(-0.004, 0.004) ax.set_xlim(-0.004, 0.004) ax.scatter(x,y) ax.grid() plt.show() The above outputs the following figure: Which does not look like it has a size of 0.002 as I indicated in scatter(x, y, ax, size = 0.002, edgecolors = 'black'). I'm not sure what I'm doing wrong here.
{ "language": "en", "url": "https://stackoverflow.com/questions/57543182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Details of socket using socket ID This question may sound basic one . Are there any functions in c or Java where I can get the socket details like , port , address , buffer size using only socket identifier ? A: Some minimal information available with me is posted below. I don't know much of Java. But as far as 'C' is concerned, you can use the getsockopt function to get the buffer sizes (send buffer and recv buffer) of the socket. It appears getsockname helps you in getting the ip & port to which the socket is bound to. A: In c in the function accept: csock = accept(sock, (struct sockaddr*)&csin, &recsize); * *sock is the socket server(int) *csock is the socket client (int) *recsize is the size *csin is a struct with client's details * *csin.sin_addr is the client's address *csin.sin_port is the client's port From a socket ID try this: #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> f() { int s; struct sockaddr_in sa; int sa_len; . . . /* We must put the length in a variable. */ sa_len = sizeof(sa); /* Ask getsockname to fill in this socket's local */ /* address. */ if (getsockname(s, &sa, &sa_len) == -1) { perror("getsockname() failed"); return -1; } /* Print it. The IP address is often zero beacuase */ /* sockets are seldom bound to a specific local */ /* interface. */ printf("Local IP address is: %s\n", inet_ntoa(sa.sin_add r)); printf("Local port is: %d\n", (int) ntohs(sa.sin_port)); . . . }
{ "language": "en", "url": "https://stackoverflow.com/questions/10851515", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I add additional columns during BULK INSERT without modifying source file I have a BULK INSERT into a table but I need to add data that is not in my csv for the last column in each row of the table. For example, if my csv file contains 10 columns but the database table contains 11 columns, how can I add data for the last column? Modifying the csv file itself is not an option Is this possible with BULK INSERT? Here is my script: BULK INSERT [Data_GPS].[dbo].[Data_z] FROM 'C:\TEMP\SQL\Bulk insert\dane.csv' WITH ( FIRSTROW = 2, FIELDTERMINATOR = ';', ROWTERMINATOR = '\n', ERRORFILE = 'C:\TEMP\SQL\Bulk insert\errors.txt', TABLOCK ) A: Sure. Just use OPENROWSET(BULK ...) instead of BULK INSERT and you can add whatever extra columns you want. EG select * from openrowset(bulk 'C:\TEMP\dane.csv', format='CSV')
{ "language": "en", "url": "https://stackoverflow.com/questions/67004594", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get string between two sets of characters in shell I pipe the following string "version": "1.0.0", to sed and I'm trying to get 1.0.0 out of it. I want to get it by the rule: get string between : " and ",. I've been trying the following: sed -e '/:\ \"/,/\ ",/p' sed -e 's/:\ \"\(.*\)\",/\1/' The first one does nothing and the last one returns "version"1.0.0, which is close, but no cigar. What am I missing? A: You need to match complete input by using .* on either side of your search pattern to be able to replace full line with just the captured group's back-reference. This sed should work: s='"version": "1.0.0",' sed 's/.*: "\([^"]*\)",.*/\1/' <<< "$s" 1.0.0 Or even this one: sed 's/.*: "\(.*\)",.*/\1/' <<< "$s" 1.0.0 A: Another approach, using grep with lookahead/lookbehind: $ grep -oP '(?<=: ")[^"]*(?=")' <<< '"version": "1.0.0",' 1.0.0 or shorter, using \K to exclude : " from the matched string: $ grep -oP ': "\K[^"]+' <<< '"version": "1.0.0",' 1.0.0
{ "language": "en", "url": "https://stackoverflow.com/questions/44161285", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Storing Documents on Azure with custom metadata i am trying to find the best way to implement a small site allowing the user to upload a file and then search on it. i used azure search with blob storage. the file is stored on the blob storage and is then gets indexed by azure search indexer - so far so good. the problem is that i would like to add to each document some custom data like file id and other business data, this data is not part of the document. is there a way to achieve this? some one, suggested i use cosmos db, though i am not sure its the best way to go when it comes to documents. Thanks A: If you would like to keep using blob storage, you can store metadata with the blobs - just add custom metadata to your blobs, add corresponding fields to the search index, and the blob indexer will pick up the metadata.
{ "language": "en", "url": "https://stackoverflow.com/questions/48628574", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to enable SSL usage when using local XML autodiscover file? I use the Redemption library and I encountered a problem I can not solve by myself. In my project, I use a local XML file to login to the Exchange server (Autodiscover service is disabled on the server and can not be enabled). For this purpose, I create an Outlook Autodiscover "PreferLocalXml" registry key value and a domain name value defining the path to the local XML file. Redemption works correctly, but for some reason it does not use SSL when sending requests to the server. Is it possible to force SSL usage in this case? However, using Autodiscover (without local XML file) works fine (SSL is used). Thank you in advance for your help. I tried setting RDOSession.ConnectEncryptData to true, but it did not work. A: But PreferLocalXml is supposed to point to a local file, not a web server, so SSL would not apply - the file is accesses using the file API.
{ "language": "en", "url": "https://stackoverflow.com/questions/75056646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Trigger to run TeamCity based on file existence I want to run TeamCity processes based on file existance. I have two TeamCity processes (Dev and Prod): * *Dev should be run if there is DevParam file in repo (or in specified location). *Prod should be run if there is ProdParam file. I want to run exactly one process after each push to repository. This files will be added and removed like: * *[0] Repository has DevParam file *[1] Pushed, there is still DevParam file -> Dev process should be run *[2] Pushed, removed DevParam file and added ProdParam -> Prod process should be run *[3] Pushed, there is still ProdParam -> Prod should be run I tried to create Trigger with rules, but I failed (rule like +:DevParam run also on file removal). Git recognizes addind and removing this files as Moving with Rename, so it may be relevant. A: file management is not a normal process. I strongly advise you to use the branch flow. For your example, use develop branch(DevParam) for an all your developers and master branch for a prod Try to use the follows advice. The developers are coding in the dev branch. Each developer working only this branch. You should create the build configuration with the trigger to your dev branch. After each new commit, the configuration will be triggered. If you decided that the code in the dev branch is ready to production, you just merged all to the master. And now you can also trigger the same configuration only for a master branch. For more information about gitflow-workflow read this
{ "language": "en", "url": "https://stackoverflow.com/questions/54690386", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Intel Compiler /QxCORE-AVX2 switch and compatibility with AMD Excavator/RyZen For some unknown reason Intel decided to does not support AVX2 via typical /arch: option. /arch: recognizes only following instructions IA32,SSE,SSE2,SSE3,AVX. So if you want to compile for AVX2 you are basically forced to activate /QxCORE-AVX2 switch. The problem with this option is that it injects check code. That code at runtime checks if your cpu is compatible with selected intructions. If CPU is not compatible then this message pops-up. Please verify that both the operating system and the processor support Intel(R) MOVBE, F16C, FMA, BMI, LZCNT and AVX2 instructions. Now I'm worried that the same message may pop-up on AMD Excavator and RyZen CPU due to not being GenuineIntel. Unfortunately I do not have access to any AMD cpu so I can't check that on real cpu. To make your life easier I've compiled this simple code with activated /QxCORE-AVX2 option. #include "stdafx.h" int _tmain(int argc, _TCHAR* argv[]) { double a, b, c; a = 3.0; b = 2.0; c = 1.0; a = a*b + c; printf("a=%1.1f",a); return 0; } and here is decompiled asm code: http://codepad.org/KL4Vq978 My question to people who understand asm code is do you see anything what may block execution of this code on latest AMD cpus? If yes will this http://www.softpedia.com/get/Programming/Patchers/Intel-Compiler-Patcher.shtml help? A: It turns out that /arch:CORE-AVX2 is recognized and compiled executable contains FMA instructions! I really do not understand why this option is not listed in Visual Studio and in ICL /help ?!? Dropbox menu in Visual Studio (NO AVX2!) http://i.cubeupload.com/c1xidV.png ICL /help http://i.cubeupload.com/y2Cre6.png A: The Ryzen supports these instruction sets, but the code will not run on AMD processors because it checks if the processor is "GenuineIntel". There has been a long discussion and legal battle about this issue. See http://www.agner.org/optimize/blog/read.php?i=49
{ "language": "en", "url": "https://stackoverflow.com/questions/41550108", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is there a jQuery event that fires when all effects are done running The title explains the question, otherwise is there way to call a function when all the effects on a page are done running? A: You could nest your animations like this $('#Div1').slideDown('fast', function(){ $('#Div2').slideUp('fast'); }); And do them sequentially... You could also do something like this: var animations = 0; checkAnimation(1); $('#Div1').slideDown('fast', function(){ checkAnimation(-1); }); checkAnimation(count){ animations += count; if(count == 0) //animations complete } else { //still animating } } Hope this helps. A: You might be able to make use of .queue to get the functionality you are after. If the length of the queue was 0 you would know that all animations on the object are finished. Documentation
{ "language": "en", "url": "https://stackoverflow.com/questions/462778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Angular + TypeScript + AMD = duplication? I've been developing in Angular for a few months and am now investigating whether it's worth moving to TypeScript for my development. One of the issues I'm having is the duplication when using external modules and injecting services. For example I have this (simplified) code: ///<reference path="../../../../typings/tsd.d.ts" /> // imports for strong typing import audioModel = require('app/plugins/audio/audio.model'); export class AudioController { public model: audioModel; static $inject = ['$scope', '$q', 'AudioModel']; constructor(protected $scope, protected $q, protected AudioModel:audioModel) { this.model = new AudioModel(); } } The AudioModel is an Angular factory defined in the external module 'audio.model.ts', so it seems to me that I'm injecting it twice - once using Angular, and again using the TypeScript import to get strong typing. Is there a better way to both use Angular dependency injection and strong typing in an AMD project? A: Is there a better way to both use Angular dependency injection and strong typing in an AMD project This was an issue with angular 1.x dependency injection. The Angular module system was independent of the traditional Browser module systems in existance (e.g. AMD). So you do need to import it twice. Once the Type, next the DI.
{ "language": "en", "url": "https://stackoverflow.com/questions/32627930", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to integrate a maven project with parent pom as module? I'd like to use a parent maven project/aggregator to build my project and a dependency which I have in my source root as git submodule, e.g. aggregator pom.xml - dependency pom.xml - project pom.xml I naively adapted this layout from GNU C/C++ projects, like coreutils which simply checkout dependencies as submodules and updated them to a compatible commit together with the project state/commit. The thing with maven is that there's a parent directive in pom.xml of the dependency and removing it would definitely require to modify the dependency which is not the intention of this setup. So, the same question asked a very different way is: Is a parent directive in a pom definitely preventing a project from being used as a maven module?. Can the warning Some problems were encountered while building the effective model or [dependency] 'parent.relativePath' of POM [dependency] points at [aggreator] instead of org.sonatype.oss:oss-parent, please verify your project structure be ignored? I'm aware about the fact that this isn't the intended workflow of maven (with the local cache in mind) and that it could be easily achieved by making dependency not a maven module, but just a git submodule and write a two-line build script invoking mvn in the source root and the dependency subdirectory. I tried using the reactor plugin, but it simply doesn't build anything which isn't included in module declaration (both the make and the make-dependents target) (error Couldn't find project [dependency] in reactor; make sure you specified the correct group:artifactId). I'm using maven 3.3.1. A: Is a parent directive in a pom definitely preventing a project from being used as a maven module No. In the end a parent is simply used to inherit stuff and it can refer to any parent. In a multimodule project parents and children point to each other (child refers to a parent, parent defines child as a module). On the other hand: you might wonder why it is a problem that any project is used as a module. The writer of the aggregator pom probably had a reason for it. Can the warning Some problems were encountered while building the effective model or [dependency] 'parent.relativePath' of POM [dependency] points at [aggreator] instead of org.sonatype.oss:oss-parent, please verify your project structure be ignored? It shouldn't be ignored, it must be set correctly, i.e. use <relativePath></relativePath> (empty String) in the parent.
{ "language": "en", "url": "https://stackoverflow.com/questions/31770982", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: SQL Server queries xls file worked yesterday(I swear), now refuses to. 0.o Hey all, the following select statement used to correctly query an Excel spreadsheet on a 64bit SQL Server 2008 R2, and now provides me with an error. SELECT MPNCode, Supplier, Stock , Price, Manufacturer, [Description] FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0 Xml;Database=C:\inetpub\wwwroot\nCompass\Products\Import\SupplierProducts.xls;HDR=YES', 'SELECT * FROM [Sheet1$]') WHERE MPNCode IS NOT NULL The error I get is. OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" returned message "Unspecified error". Msg 7303, Level 16, State 1, Line 1 Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)". I've tried restarting everything and googled the thing to death - somehow something has happened that is preventing this from working. The file-path/file-name is correct because when I change the path I get a different error message. Ad-hoc connections are enabled from the surface manager - after this I'm stumped at what the issue could be. Any help will be very much appreciated. A: Is the linked spreadsheet opened on the desktop? What happens if you create a new sheet in the same folder and try to open it instead? A: I think SQL Server needs to access to TEMP folders to copy or create some files. If the folder does not exist or ther SQL Service account does not have enough permission to access the folders, you'll get the exception. Run Procmon.exe on the server and execute the query again. You can see what's happening and where the SQL Server wants to access.
{ "language": "en", "url": "https://stackoverflow.com/questions/4656500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: package ‘RMySQL’ is available as a source package but not as a binary I am receiving the above error when I try to install this package. Reading this question install RMySQL for Mac I read the install guide. Here's what is said: During installation, RMySQL looks for the MySQL headers and libraries in the system directories. If these are not installed in system-wide directories (or if you want to use an alternate MySQL distribution), you may specify which MySQL directory(ies) to use through one of the following: 1. The shell variables PKG_CPPFLAGS and PKG_LIBS (using Bourne shell) export PKG_CPPFLAGS="-I<include-dir>" export PKG_LIBS="-L<library-dir> -lmysqlclient" For instance, on some 64 systems (e.g., Linux) you may need to set export PKG_CPPFALGS="-I/usr/include/mysql" export PKG_LIBS="-L/usr/lib64/mysql -lmysqlclient" I have browsed my computer, I don't believe that those directories exist. I have installed XAMPP previously on my Mac and wondered if the directories needed are in there somewhere since XAMPP uses MySQL? Can I just download the directories somewhere? How can I find if they are already on my computer? export PKG_CPPFALGS="-I/usr/include/mysql" export PKG_LIBS="-L/usr/lib64/mysql -lmysqlclient" I'm at a loss for what to do next? A: If you don't mind installing another MySQL server via Homebrew, I have posted the complete solution in another thread: Installing RMySQL in mavericks But in your case, I do find those directories in XAMPP that contain the same necessary MySQL header and library files as those installed via Homebrew. So you can set the environment variables and build in the Terminal way: % export PKG_CPPFALGS="-I/Applications/XAMPP/xamppfiles/include" % export PKG_LIBS="-L/Applications/XAMPP/xamppfiles/lib -lmysqlclient" ## RMySQL_x.x-x.tar is the source package you have manually downloaded % R CMD INSTALL RMySQL_x.x-x.tar or in the RStudio way: > Sys.setenv(PKG_CPPFLAGS = "-I/Applications/XAMPP/xamppfiles/include") > Sys.setenv(PKG_LIBS = "-L/Applications/XAMPP/xamppfiles/lib -lmysqlclient") ## It will automatically download the source package in the remote repo > install.packages("RMySQL", type = "source")
{ "language": "en", "url": "https://stackoverflow.com/questions/24229696", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to chain api calls with AngularJS I'm new to angualrJS and web development in general. I have a controller named FavoritesCtrl that makes an api call and returns an object. My controller looks like this: controllers.controller('FavoritesCtrl', function($scope, $http) { $http.jsonp('https://api...=JSON_CALLBACK').then(function (scooby){ $scope.list=scooby.data; }); }); I access the returned data in my html with this: <div ng-controller="FavoritesCtrl"> <li ng-repeat="favorite in list.favorites"> <div>product_id: {{ favorite.product_id }} </div> I need to send that {{ favorite.product.id }} back as a parameter in another api call so I can generate an affiliate link, but I don't know the most angular way to do it. Should I attempt to send the second call in the FavoritesCtrl or would it make sense to put it in a new controller? I can get the proper affiliate link back with something like this: controllers.controller('FavoritesCtrl', function($scope, $http) { $http.jsonp('https://api...=JSON_CALLBACK').then(function (scooby){ $scope.list=scooby.data; var length = scooby.data.favorites.length; var i; for (i=0;i<length;i+=1){ var getProductId = scooby.data.favorites[i].product_id; $http.jsonp('https://api...+getProductId+'&callback=JSON_CALLBACK').then(function (fred){ console.log(fred.data.link); }); }); }); But I can't figure out a good way to display this on my page with the associated item. Any suggestions will be greatly appreciated. Thank You! A: You're on the right track. I think in your for loop in the controller, just put $scope.list.favorites[i].affiliateLink = [whatever the returned value of the specific affiliate link should be]; Then in the HTML, it would just interpolate as {{favorite.affiliateLink}} A: You probably want to use ng-click and this will call another method in your controller: <li><a ng-click="doSomething(favorite.product_id)" href="">{{favorite.product_id}}</a></li> in your controller : $scope.doSomething = function (prodId) { // Do whatever you want here }; A: You can accomplish this in a more elegant way using a tool that you already have - promises. Promises are there to help you chain events like this. A simple example would be: get('story.json').then(function(response) { return JSON.parse(response); }).then(function(response) { console.log("Yey JSON!", response); }); A very good introduction to promises can be found here [1]. [1] http://www.html5rocks.com/en/tutorials/es6/promises/
{ "language": "en", "url": "https://stackoverflow.com/questions/21035855", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Log with Python logging in Robot Framework I use robot framework 3.0 under Python 2.7.8. Robot framework's documentation (http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#programmatic-logging-apis) states that In addition to the new public logging API, Robot Framework offers a built-in support to Python's standard logging module. This works so that all messages that are received by the root logger of the module are automatically propagated to Robot Framework's log file. I made a short library file to test this: from logging import debug, error, info, warn def try_logging(): info("This is merely a humble info message.") debug("Most users never saw me.") warn("I warn you about something.") error("Something bad happened.") My test case is: *** Test Cases *** Logtest Try logging When I run it it is a PASSED case, but nothing logged into the HTML log. The test execution log has the suit and the case and the keyword as it should but when I expand them nothing is logged but the "Start / End / Elapsed" line. How could I forward the Python logger messages to Robot? As you can see the so called automatic propagation is not working automatically. My goal is to write a library that can be run with or without Robot Fw. Ty for your help in advance. A: After hours of code digging I managed to find the answer. I think it is worth sharing as it may be help you if you have some similar issue. In my case I had some unused libraries imported. One of them was a class that was instantiated when Robot Framework imported the library file. This object had some logger settings that messed up the defaults, that is why I got no result in the robot log. Without it I got the expected results and automatic propagation worked fine.
{ "language": "en", "url": "https://stackoverflow.com/questions/36739964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to detect if a JS variable is undefined? // mystring contains dynamic text. Sometimes can be // null var a = mystring.split(" "); var proc = a[0] + " " + a[1]; If a does not contain text, after split proc is undefined. If I try to assing its value to a textbox the result is "undefined": mytextbox.val(proc); So I need a way to make that proc has always a value, at least an empty string. A: You can just use (mystring || " ") which will evaluate to mystring if it is not null, or " " if it is. Or, you can just put an if statement around the whole thing: if (mystring != null) { // stuff } else { var proc = ""; } A: var proc = ""; if (mystring !== null) { // omit this if you're sure it's a string var a = mystring.split(" "); if (a.length > 1) { proc = a[0] + " " + a[1]; } } I'm quite sure your proc is not undefined, but the string " undefined".
{ "language": "en", "url": "https://stackoverflow.com/questions/13630926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: .NET application closes without error on using library methods I have a C++ DLL Library. I'm testing the DLL with a C# Project with NET Framework 4.0. In the C++ DLL I'm using some libraries, like POCO, Boost, ODBC, SQLite, SOCI... It was doing great until I decided to replace the SOCI interface with the POCO one to reduce the number of libraries loaded in the library. I compiled the PocoData, PocoDataODBC and added them, together with the headers, into the project. The project compiles OK, creates the DLL, and the DLL passes the Dependency Walker tests. But something strange happens when using the DLL from the .NET Project. The app just closes when executing the DLL methods that contains the Poco::Data part to connect with the database. There is no exception or error thrown. Not even "application just crashed" from windows. It just stop running and the Visual Studio returns to normal just like if it ended correctly. I isolated the error and it's enought with any use or call inside the PocoData library to do this error. I can use the library until it tries to use a method that has any call to this. For example: Session session("ODBC", conn); Or even this alone: Poco::Data::RecordSet rs(); So every time the C# calls a method that contains anything from the Poco::Data in the DLL it fails. Any idea what can be happening? Windows events log something when the app makes the error, I don't know if it's relevant. It raises two events, the first one is a system hour change between same value (strange), type: Kernel-General. The second one (about 10 seconds later) is Service Control Manager level Information: Service Windows Error Reporting Service entered in running state.
{ "language": "en", "url": "https://stackoverflow.com/questions/23114511", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Code executes differently on Windows and Android I'm coding a simple game called Jotto. A player tries to guess a secret five letter word; each letter is unique. After each 5-letter guess word you're told how many letters in the guess are also in the secret word. It's my first attempt at cross-platform development with Delphi. I've developed Windows apps in Delphi, and a little bit for Android with Flutter. All the code executes as expected on Windows (32 bit), but not on Android (64 bit, SDK 25.2.5). No exceptions are raised, but the calculated number of correct guesses each turn are incorrect and unpredictable (i.e., the calculated result of total below is what's off). Running the code through the debugger shows local variables are incorrect sometimes, too. Here are the relevant functions: function TJotto.OccurrencesOfChar(const aWord, aChar: string): integer; var i: integer; begin result := 0; for i := 1 to Length(aWord) do if aWord[i] = aChar then inc(result); end; and function TJotto.MakeGuess(aGuessWord: string): string; var i: integer; total: integer; wordToDisplay: string; begin total := 0; // number of matches wordToDisplay := aGuessWord; // save copy of guess before deleting duplicate letters // because guess will be displayed // did user solve puzzle? if aGuessWord = FSecretWord then Exit('You did it! The word was ' + aGuessWord); // make sure all letters in aGuessWord are different // otherwise a guess like 'vexed' will say an E is present in FSecretWord twice for i := 5 downto 1 do if OccurrencesOfChar(aGuessWord, aGuessWord[i]) > 1 then Delete(aGuessWord, i, 1); // go through each letter in aGuessWord to see if it's in FSecretWord // keep a running total number of matches for i := 1 to Length(aGuessWord) do total := total + OccurrencesOfChar(FSecretWord, aGuessWord[i]); result := wordToDisplay + #9 + total.ToString; end; A: Note: Previous to Delphi 10.4 the mobile compilers used by default 0-based indexing for strings. See Zero-based strings. Use the Low() and High() intrinsic functions to iterate strings. The irregularities you are seeing is because of indexing outside of the boundries of the string. When debugging, use overflow and range checking on to detect these kind of errors. Your code will look like this: function TJotto.OccurrencesOfChar(const aWord, aChar: string): integer; var i: integer; begin result := 0; for i := Low(aWord) to High(aWord) do if aWord[i] = aChar then inc(result); end; and function TJotto.MakeGuess(aGuessWord: string): string; var i: integer; total: integer; wordToDisplay: string; begin total := 0; // number of matches wordToDisplay := aGuessWord; // save copy of guess before deleting duplicate letters // because guess will be displayed // did user solve puzzle? if aGuessWord = FSecretWord then Exit('You did it! The word was ' + aGuessWord); // make sure all letters in aGuessWord are different // otherwise a guess like 'vexed' will say an E is present in FSecretWord twice for i := High(aGuessWord) downto Low(aGuessWord) do if OccurrencesOfChar(aGuessWord, aGuessWord[i]) > 1 then Delete(aGuessWord, i+1-Low(aGuessWord), 1); // Delete uses one-based array indexing even in platforms where the strings are zero-based. // go through each letter in aGuessWord to see if it's in FSecretWord // keep a running total number of matches for i := Low(aGuessWord) to High(aGuessWord) do total := total + OccurrencesOfChar(FSecretWord, aGuessWord[i]); result := wordToDisplay + #9 + total.ToString; end;
{ "language": "en", "url": "https://stackoverflow.com/questions/66649475", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Knockout.js How should I add computed value to observaleArray? I need to add to observableArray computed values, my current code is look like this: self.prices = ko.observableArray(); ..... var pax = $("select#ticketsnumber option:selected").val(); var irt; if ($("input[name='isrt']").is(":checked")) { irt = 1; } else { irt = 0; } $.each(self.prices(), function (price) { price.FinalPrice = ko.computed(function() { return prices.Price * irt * parseInt(pax); }); }); But I do not have any idea how should I call binding of this computed value (currently this way - <span name="totalprice" data-bind="text: ko.utils.unwrapObservable($data.FinalPrice)">) as well as this just seemed like computed value has not been added - binding result show 0. Data model: public class PriceItem { ... public string Price { get; set; } ... public int FinalPrice { get; set; } } This is the way how I retrieve data to self.prices: self.getprices = function () { var destinationtypefrom = $("select#optionsfrom option:selected").attr("name"); var destinationtypeto = $("select#optionsto option:selected").attr("name"); var fromcode = $("select#optionsfrom").val(); var tocode = $("select#optionsto").val(); var json = { desttypefrom: destinationtypefrom, desttypeto: destinationtypeto, codefrom: fromcode, codeto: tocode, 'DepartureDate': $("#departure").val(), 'ReturnDate': $("#return").val() }; $.ajax({ url: "/Home/GetFlights", data: json, type: "post", cache: false, success: function (result) { if (result.Error == null) { self.prices(result); ko.mapping.fromJS(result, {}, self.prices); } else { $("#modalerror").on("show.bs.modal", function () { var modal = $(this); modal.find("#errormsg").text(result.Error); }); } }, error: function (xhr) { var err = eval("(" + xhr.responseText + ")"); alert(err.Message); } }); } A: The main problem is that your $.each is wrong by assuming the first argument to be the actual element in the prices array. In fact, the first argument is the index, the second argument is the actual price you want to augment. Also, you seem to have a typo in the computed function calculation, it's price.Price instead of prices.Price. Try this: $.each(self.prices(), function (index, price) { price.FinalPrice = ko.computed(function() { return price.Price * irt * parseInt(pax); }); }); And in your HTML, something like: <div data-bind="foreach: prices"> <span name="totalprice" data-bind="text: FinalPrice"></span> </div> See Fiddle
{ "language": "en", "url": "https://stackoverflow.com/questions/28690366", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Swift code that will print a string of all the characters of a new word typed in a UITextView as they are being typed I need help with swift code or function that will run in the body of UITextView function textViewDidChange that will print a string of all the letters of a new Word as they are being typed in a UITextView control. So if I have a UITextView control on my user interface named txtTextView and it has no text in it when the application starts running if I then type letter "o" then letter "o" will be printed in the console out put screen. After I have typed "or" then "or" will be printed. After I have typed "orange" then "orange" will be printed. If after typing orange I press space bar and start typing "ma" then "ma" will be printed and after I have typed "orange mango" then "mango" will be printed. Hope I have conveyed the idea. Basically I would like the code to print all the letters of every new word as they are being typed in the UITextView. Many thanks for your help. func textViewDidChange( textView: UITextView ) { // code for this place } A: Just create an outlet to your textField, add the UITextViewDelegate and set the delegate. After that just override the textViewDidChange method. Code example below @IBOutlet weak var textView: UITextView! override func viewDidLoad() { super.viewDidLoad() textView.delegate = self } @IBAction func textField_EditingChanged(sender: UITextField) { // Will print out each letter that is typed print(sender.text!.characters.last!) // Will print out the word print(sender.text!) } func textViewDidChange(textView: UITextView) { // Will print out each letter that is typed print(textView.text!.characters.last!) // Will print out the word print(textView.text!) }
{ "language": "en", "url": "https://stackoverflow.com/questions/35947054", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: AS3 Assign Class to XML Loaded element I need to load a set of images with from XML and assign Interactivity to them first I load the XML import flash.display.Loader; import flash.net.URLRequest; var loader:Loader = new URLLoader(); var request:URLRequest = new URLRequest("myXML.xml"); loader.load(request); loader.addEventListener(Event.Complete, proessFile); function processFile(e:Event):void { var loadedXML:XML = (e.target.data); } //load set of images from XML file for (var i:uint = 0; i < loadedXML.image.length(); i++) { var imgLoader:Loader = new Loader(); var imgRequest:URLRequest = new URLRequest (loadedXML.img[i].attribute("filepath")); imgLoader.load(imgRequest); addChild(imgLoader); } here I need to make every single image draggable. Is it possible to change it into another data type, b/c I can't work with Loader? I've tried assign them .name property, but I was unable to call them later. I don't know If I'm clear enough, but essentially I need to work with every single loaded image as new object. Is it possible to assign variable to every single image? Any suggestion for thework flow here would be much appreciated. A: Because you add them to the stage, you could try naming them and then calling them via the stage's getChildByName method. Or you could build an array of loaders or, better yet, movieClips. Something like: import flash.display.Loader; import flash.net.URLRequest; var loader:Loader = new URLLoader(); var request:URLRequest = new URLRequest("myXML.xml"); loader.load(request); var images:Array = new Array(); loader.addEventListener(Event.Complete, proessFile); function processFile(e:Event):void { var loadedXML:XML = (e.target.data); } //load set of images from XML file for (var i:uint = 0; i < loadedXML.image.length(); i++) { // create a new movie clip var tmpMovieClip:MovieClip = new MovieClip(); var imgLoader:Loader = new Loader(); var imgRequest:URLRequest = new URLRequest (loadedXML.img[i].attribute("filepath")); imgLoader.load(imgRequest); // add the loader to the movie clip's display list tmpMovieClip.addChild(imgLoader); // add the movieclip to the previously declared array images.push(tmpMovieClip); } This way, you can call and use any element of the Array when you need them. If you don't need the MoviClips, you could just add the Loader instances into the Array. A: I'm afraid I am having trouble understanding some your questions. Is it possible to change it into another data type, b/c I can't work with Loader? First, what data type would you like to change it to. Second, why can't you work with Loader? I've tried assign them .name property, but I was unable to call them later. Why did you want to call them and how did you try to? I need to work with every single loaded image as new object. Each loader object encapsulates a single image object. The image is actually inside the Loader (on the .content property). evilpenguin describes how you can store references to the loader objects inside an array so that you can access them later. That is the correct basic approach. The real question is: "What exactly are you trying to do?" You say: here I need to make every single image draggable. If it is that simple, then add events directly to the loader (which encapsulates the image). for each(var image:XML in loadedXML.image) { var imgLoader:Loader = new Loader(); var imgRequest:URLRequest = new URLRequest(image.@filepath); imgLoader.load(imgRequest); addChild(imgLoader); // NOTE: you may want to wait until it is done loading // before you add drag and drop behaviour although // that isn't strictly necessary makeDraggable(imgLoader); } function makeDraggable(loader:Loader):void { loader.addEventListener(MouseEvent.MOUSE_DOWN, startDrag); loader.addEventListener(MouseEvent.MOUSE_UP, stopDrag); // NOTE: I'll leave it up to you to decide // how you want to implement drag and drop } Note: I've also changed your loop to use E4X which is a much nice way of dealing with XML in Actionscript. A: To create a 'copy' of your images simply do the following. private function contentLoaderInfo_completeHandler(event:Event):void { var loaderInfo:LoaderInfo = event.target as LoaderInfo; var originalBitmap:Bitmap = loaderInfo.content as Bitmap; var newBitmap:Bitmap = new Bitmap(originalBitmap.bitmapData.clone()); images.push(addChild(newBitmap)); } This way you are completely detached from the loader object and can dispose of them completely. Obviously as evilpenguin suggested you could then instead add them to Sprites or MovieClips and then add these to the stage (the Bitmap class is not a DisplayObjectContainer and so you can not add extra children to them).
{ "language": "en", "url": "https://stackoverflow.com/questions/1265361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Formatting CDATA string shows unexpected character I have this string entry: <string name="title_label">[<![CDATA[<b>Title</b>]]> %s</string> and I format it this way: String titleLabel = getString(R.string.title_label); Spanned title = Html.fromHtml(String.format(titleLabel, "My Title")); However, it shows: [Title My Title instead of: Title My Title Why is it showing the '[' character in the beginning? A: Try changing it to : <string name="title_label"><![CDATA[<b>Title</b>]]> %s</string> A: Dude, you have 3 opening and 2 closing square brackets there in your XML :) Happens to the best of us :)
{ "language": "en", "url": "https://stackoverflow.com/questions/38716119", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Stop Camera from rotating around a rotating parent I have a rolling marble and would like my camera to follow it. My problem is that my camera is also rotating around my object as it is rotating. Here's my code. -(void) setupCameraOnMarble:(SCNNode*)marble { [cameraNode removeFromParentNode]; [marble addChildNode:cameraNode]; SCNLookAtConstraint *marbleStare = [SCNLookAtConstraint lookAtConstraintWithTarget:marble]; marbleStare.gimbalLockEnabled = YES; cameraNode.constraints = @[marbleStare]; } I'm thinking that a transform constraint should work but I don't understand how it works. A: Are you sure you need to make cameraNode a child of marble? Because according to SKNode docs: when a node’s coordinate system is scaled or rotated, this transformation is applied both to the node’s own content and to that of its descendants see SKNode So i assume you need to un-child camera from marble. And to achive that followint the object behavior from camera, you may update camera coordinates somewhere in the code, that moves the marble A: I have un-childed my camera to my sphere and made my class a SCNSceneRendererDelegate protocol and added this to the rendering loop: -(void) renderer:(id)renderer updateAtTime:(NSTimeInterval)time { [cameraNode setPosition: SCNVector3Make(marbleNode.presentationNode.position.x, marbleNode.presentationNode.position.y + 5, marbleNode.presentationNode.position.z + 10)]; } If I log the coordinates of the marble.presentationNode they are changing but my camera still doesn't move!
{ "language": "en", "url": "https://stackoverflow.com/questions/45701159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Stripe multiple subscriptions at checkout best method? I am using Stripe and have a site (node, express, react) where customers purchase subscriptions. They can purchase multiple subscriptions at a time and those subscriptions can have varying intervals. So, each subscription is created separately on the back end during checkout. Basically, the back end receives an array of subscription criteria for the customer's cart and sets up each one as its own subscription, returning an array of subscription objects. Here is the possible issue I am realizing. Let's say there are 5 subscriptions in a customer's cart it is possible that 3 subscriptions are created successfully and that 2 fail due to insufficient funds, or other reasons. Now you have a partially completed checkout, the card has already been charged for 3 subscriptions and you need new payment details for the remaining 2 subscriptions. Plus, you have to handle letting the user know and altering the cart to reflect that only some of the cart has been purchased which I'm not sure what the expected UI/UX for something like that is. Anyone have any ideas on how to handle this better with Stripe to charge all or none or something similar.
{ "language": "en", "url": "https://stackoverflow.com/questions/66974896", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to use json response in wpf application My wpf application is communicating with php web api. First I post some data to web api and recieved json resonse. At server side php script just prepared an array and json_encode(arrayName)is sent to client. At my client side I am using following code using (WebResponse jsonResponse = request.GetResponse()) { // Do something with response StreamReader streamReader = new StreamReader(jsonResponse.GetResponseStream()); String responseData = streamReader.ReadToEnd(); MessageBox.Show(responseData); } in the message box I am able to see all the data sent by server. Now I don't have any idea how to assign this data to local variables? Kindly guide me. http://i.imgur.com/1Qzds8G.png EDIT Response shown in message box is :- [{"response":"true","user_id":"250","username":"sapan108"}]' After Googling I created following class :- public class UserData { public string response { get; set; } public string error { get; set; } public int user_id { get; set; } public string username { get; set; } } Now How to assign json response to these variables. Note: Due to less reputation unable to post image directly. Sorry for inconvenience. A: 1) You should create class to represent json data (http://json2csharp.com/) public class RootObject { public string response { get; set; } public string user_id { get; set; } public string username { get; set; } public string current_balance { get; set; } public string message { get; set; } public string outh_token { get; set; } public List<string> lastFiveSpinNumbers { get; set; } } 2) You should deserialize json data into class (the easiest way is to using Json.NET library - http://www.newtonsoft.com/json) using (WebResponse jsonResponse = request.GetResponse()) { // Do something with response StreamReader streamReader = new StreamReader(jsonResponse.GetResponseStream()); String responseData = streamReader.ReadToEnd(); var myData = JsonConvert.DeserializeObject<List<RootObject>>(responseData); // process your data foreach (var rootObject in myData) { string response = rootObject.response; // ... } }
{ "language": "en", "url": "https://stackoverflow.com/questions/29191934", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to pass custom props to drawer screens in React Navigation 5? Here's my Drawer Navigation config: return ( <NavigationContainer theme={navigationTheme}> <Drawer.Navigator drawerContent={(props) => ( <DrawerContent {...props} /> )} > <Drawer.Screen name="Home" component={HomeScreen} /> <Drawer.Screen name="About" component={AboutScreen} /> </Drawer.Navigator> </NavigationContainer> ); and in my DrawerContent component: export default function DrawerContent({ state, navigation, ...props }) { return ( <DrawerContentScrollView {...props}> <Drawer.Section> {state.routes.map((route) => ( <DrawerItem key={route.key} label={route.name} onPress={() => navigation.navigate(route.name)} /> ))} </Drawer.Section> </View> </DrawerContentScrollView> ); } I want to add an icon prop to my DrawerItem component inside the DrawerContent component. I tried doing this: <Drawer.Screen name="Home" icon="home" component={HomeScreen} /> and in my DrawerContent {state.routes.map((route) => ( <DrawerItem key={route.key} icon={({ color, size }) => ( <MaterialCommunityIcons name="home" icon={route.icon} color={color} size={size} /> )} label={route.name} onPress={() => navigation.navigate(route.name)} /> ))} But the route.icon property is undefined. Any idea on this? A: Fixed it using options prop on Screen. In my Drawer Navigator: <Drawer.Navigator> <Drawer.Screen name="Home" component={HomeScreen} options={{ icon: 'home' }} /> </Drawer.Navigator> and to access it in the custom DrawerContent component: export default function DrawerContent({ state, navigation, ...props }) { const getIcon = (key) => props.descriptors[key].options.icon; return ( <DrawerContentScrollView {...props}> <Drawer.Section> {state.routes.map((route) => ( <DrawerItem key={route.key} label={route.name} icon={({ color, size }) => ( <MaterialCommunityIcons name={getIcon(route.key)} color={color} size={size} /> )} onPress={() => navigation.navigate(route.name)} /> ))} </Drawer.Section> </View> </DrawerContentScrollView> ); }
{ "language": "en", "url": "https://stackoverflow.com/questions/62275750", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: setTimeout(fn,0) triggering before styles have been applied When I want to yield execution of my javascript and allow the browser to apply styles etc. before I continue, I tend to use the common technique of setTimeout with a delay of 0 to have a callback queued at the end of the event loop. However, I came across a situation where this doesn't seem to be working reliably. In the snippet below, I have an active class that applies a transition to the chaser element. When I hover over a target div, I want to remove the active class from the chaser element, move the chaser to a new location, then reapply the active class. The effect should be that the o should immediately vanish, and then fade in its new location. Instead, both the opacity and top have the transition applied, so the o slides from position to position, most of the time. If I increase the inner timeout's delay to 10, it starts to behave as I originally intended. If I set it to 5, then it sometimes does and sometimes doesn't. I would have expected any setTimeout to have queued my callback until after the style updates have been applied, but there's a clear race condition here. Am I missing something? Is there a way to guarantee the order of updates? I'm on Chrome 56 on macOS and Windows, haven't tested other browsers yet. (I know I can achieve this in other ways such as applying the transition to only the opacity property - please consider this a contrived example to demonstrate the particular question about ordering style updates). var targets = document.querySelectorAll('.target'); var chaser = document.querySelector('#chaser'); for (var i = 0; i < targets.length; i++) { targets[i].addEventListener('mouseenter', function(event) { chaser.className = ''; setTimeout(function() { // at this point, I'm expecting no transition // to be active on the element chaser.style.top = event.target.offsetTop + "px"; setTimeout(function() { // at this point, I'm expecting the element to // have finished moving to its new position chaser.className = 'active'; }, 0); }, 0); }); } #chaser { position: absolute; opacity: 0; } #chaser.active { transition: all 1s; opacity: 1; } .target { height: 30px; width: 30px; margin: 10px; background: #ddd; } <div id="chaser">o</div> <div class="target">x</div> <div class="target">x</div> <div class="target">x</div> <div class="target">x</div> <div class="target">x</div> A: What you need to listen for is transitionend event before doing anything else. You can read up on MDN about transitionend event. Btw, setTimeout should never be used to guarantee timing. EDIT: This is for reference after clarification from OP. Whenever a style change occurs to an element, there is either a reflow and/or repaint. You can read more about them here. If the second setTimeout is ran before the first reflow, then you get the sliding effect. The reason why 10ms will lead to the desired effect is because .active class is added after the offsetTop property has been adjusted (leading to transition property applied after the element has changed it's offsetTop). Usually, there are 60fps (i.e: ~16ms per frame) which means that you have a 16 ms window to do anything before the new styles are applied. This is why a small delay of 5ms will sometimes lead different results. TL:DR - The browser asks JS and CSS every 16ms for any updates, and calculates what to draw. If you miss the 16ms window, you can have completely different results. A: You are calling a setTimeout() timing method inside another setTimeout() timing method. My thought is, why not call the both setTimeout() method separately like so: The first setTimeout() method should execute first, then at end of execution, it should call the second setTimeout() method. A: Here is a working script for moving the chaser: function _( id ) { return document.getElementById( id ); } window.addEventListener( 'load', function() { var targets = document.querySelectorAll('.target'); var chaser = document.querySelector('#chaser'); setTopPosition( targets ); function setTopPosition( targets ) { for (var i = 0; i < targets.length; i++) { targets[i].addEventListener('mouseenter', function(event) { chaser.className = ''; _( 'status' ).innerText = chaser.className; // to inspect the active class setTimeout(function() { /* at this point, I'm expecting no transition // to be active on the element */ chaser.style.top = event.target.offsetTop + "px"; }, 0); // check if charser.className == '' if ( chaser.className == '') { setClassName(); } else { alert( 0 ); } }); // addEventListener } // for } //function setTopPosition( targets ) function setClassName() { setTimeout(function() { /* at this point, I'm expecting the element to have finished moving to its new position */ chaser.className = 'active'; _( 'status' ).innerText = chaser.className; }, 0); } // function setClassName() }); HTML: <div id="chaser">o</div> <div class="target">x</div> <div class="target">x</div> <div class="target">x</div> <div class="target">x</div> <div class="target">x</div> <div id="status">status</div> CSS: #chaser { position: absolute; opacity: 0; } #chaser.active { transition: all 1s; opacity: 1; } .target { height: 30px; width: 30px; margin: 10px; background: #ddd; }
{ "language": "en", "url": "https://stackoverflow.com/questions/42229156", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How do I send data from a Component to another Component in Angular? I'm very new to Angular, and I'm really struggling to find a concise answer to this problem. I have a Form Component Here: (I'm excluding the directives and imports as they're not really relevant) export class JournalFormComponent implements OnInit { public entries: EntriesService; constructor(entries: EntriesService) { this.entries = entries; } ngOnInit(): void { } } The EntriesService service just stores an array of entries: export class Entry { constructor ( public num: number, public name: string, public description: string, public text: string ) { } } The Form Component template renders a <h2> and a <app-input> Component for each entry in the EntriesService, which works. That looks like this: <div *ngFor="let entry of entries.entries"> <h2> {{ entry.num }}. {{ entry.name }} </h2> <app-input id="{{entry.num}}"></app-input> </div> Here's the <app-input> Input Component: @Component({ selector: 'app-input', template: ` <textarea #box (keyup.enter)="update(box.value)" (blur)="update(box.value)"> </textarea> ` }) export class InputComponent { private value = ''; update(value: string) { this.value = value; } getValue () { return this.value; } } The InputComponent stores the user's text perfectly, but I don't know how to pass that data to the Form Component's EntriesService to update the Entry in order to Export it or Save it later. How is this done? I think I'm phrasing this question well, but I'm not sure. If you need clarification I'll provide it. Not sure if it matters, but I'm using Angular 9.1.11 A: There are many ways to update the data from one component to another. * *component to component using service or subjects *parent~child component data exchange using Input() and Output() decorators. Or by using @ViweChild() interactions. and many more But please do check the angular docs https://angular.io/guide/component-interaction . Use the below simple code, u might need to include modules like FormsModule. and import Input(), Output etc @Component({ selector: 'app-journal-form', template: ` <div *ngFor="let entry of entries.entries; let i=index"> <h2> {{ entry.num }}. {{ entry.name }} </h2> <app-input id="{{entry.num}}" [entry]="entry" [arrayIndex]="i" (updateEntry)="updateEntry($event)" ></app-input> </div>` }) export class JournalFormComponent implements OnInit { constructor(private entries: EntriesService) { this.entries = entries; } ngOnInit(): void { } updateEntry(event){ console.log(event); this.entries[event.arrayIndex] = event.entry; } } @Component({ selector: 'app-input', template: ` <textarea [(ngModel)]="name" (keyup.enter)="update()" (blur)="update()"> </textarea> ` }) export class InputComponent { @Input() entry: any; @Input() arrayIndex: number; @Output() updateEntry: EventEmitter<any> = new EventEmitter(); name:string; constructor() { console.log(entry); this.name = entry.name; } update(){ this.entry.name = this.name; this.updateEntry.emit({entry: this.entry, arrayIndex}); } } A: Output event will help in this situation. <div *ngFor="let entry of entries.entries"> <h2> {{ entry.num }}. {{ entry.name }} </h2> <app-input id="{{entry.num}}" (entryChange) = "entry.text = $event"></app-input> </div> app-input component export class InputComponent { private value = ''; @Output() entryChange = new EventEmitter<string>(); update(value: string) { this.value = value; this.entryChange.emit(value); } } Instead of entry.text = $event you can also pass it to any save function, like saveEntry($event);
{ "language": "en", "url": "https://stackoverflow.com/questions/63443573", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is selected option selected if attribute is in DOM or not To create a Dual Listbox like Bootstraps I needed to remove the default gray color of selected option. The only way to remove this gray color was to change the selected state of the element to false. No other trick worked to remove the gray background color of selected option. Now if I do so, the attribute selected still remains in DOM but seems to be false. I thought if we have an element like: <option value="1" selected>1: Lorem ipsum</option> if selected is there it means always option selected true as it is the same as: <option value="1" selected="selected">1: Lorem ipsum</option> or <option value="1" selected="true">1: Lorem ipsum</option> but this seems not to be like so. Could anyone shed some light on this for me? I've created a fiddle https://jsfiddle.net/npm6tn0m/ trying to demonstrate the scenario. Where the css option[selected] { background-color: orange; } only works for the selected option which is set to false but still has the selected attribute in DOM. Cause this may vary across different browsers here is an image from what I see in OSX Chrome browser: All code like in the fiddle also here on SO: var elements = document.querySelectorAll('.special option'); for(var i=0; i < elements.length; i++) { elements[i].selected = false; } setTimeout(function(){ var elements = document.querySelectorAll('option'); for(var i=0; i < elements.length; i++) { console.log('Value = ' + elements[i].value + ' selected: '+ elements[i].selected); } }, 1000); option[selected] { background-color: orange; } <select class="special" multiple> <option value="1" selected>1: Lorem ipsum</option> <option value="2" >2: dolor sit amet</option> </select> <select multiple> <option value="3" selected>3: Lorem ipsum</option> <option value="4" >4: dolor sit amet</option> </select> A: I thought if we have an element like: <option value="1" selected>1: Lorem ipsum</option> if selected is there it means always option selected true as it is the same as: <option value="1" selected="selected">1: Lorem ipsum</option> ... but this seems not to be like so. Could anyone shed some light on this for me? You're correct about how boolean attributes work, just not about what the selected boolean attribute represents. :-) The selected attribute represents the default selected state, not the current selected state. It's like an input's value attribute in that way; the default (used in case of form reset, for instance), not the current value. Just as the current value of an input is not represented in the DOM, similarly the current value of a option's selectedness is not represented in the DOM. A: Different browser may treat this attribute differently. According to the MSDN documentation (for Internet Explorer): To select an item in HTML, it is not necessary to set the value of the SELECTED attribute to true. The mere presence of the SELECTED attribute set its value to true. In firefox and Safari this does work: <option selected='false' /> From what I can tell by looking at the official WC3 standard for HTML5, the supported case is only: <option selected='selected' /> You will either need to selectively emit the attribute, or use selected='false' or use javascript to control which item is initially selected.
{ "language": "en", "url": "https://stackoverflow.com/questions/40482300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Generate only continuous combinations of a list of numbers I have a list in python [1, 2, 3, 4, 5, 6]. I want to generate all possible combinations of length 2, 3, 4 and 5. I have used itertools.combinations to generate the combinations but it doesn't generate continuous combinations only. For example, length 2 combinations should be only [1, 2], [2, 3], [3, 4], [4, 5], [5, 6]. Is there any faster way to generate than the following code? for start, end in combinations(range(len(lst)), 2): if end - start <= 4 and end-start >= 1: print(lst[start:end+1]) A: You don't need combinations at all. What you want looks more like a sliding window. for i in range(2, 6): for j in range(len(lst) - i + 1): print(lst[j:j + i]) A: You can loop over the list as following: a = [1,2,3,4,5,6] for i in range(2, len(a)): for j in range(len(a)-i + 1): print(a[j:j+i]) print() The trick here is that a[j:j+i] returns the list from j, up until j+i. Putting this into a function form: def continuous(lst, length): slices = [] for j in range(len(lst)-length + 1): slices.append(a[j:j+length]) return slices A: You can loop through the list in the following method lst = [1, 2, 3, 4, 5 ,6] def continuous(lst, length): result = [] for i in range (0, len(lst)-length): entry = [] for j in range (0, length): entry.append(lst[i+j]) result.append(entry) return result print(continuous(lst, 2)) or if you are just looking to print it line by line def continuous(lst, length): for i in range (0, len(lst)-length): entry = [] for j in range (0, length): entry.append(lst[i+j]) print(entry)
{ "language": "en", "url": "https://stackoverflow.com/questions/53186152", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to turn a Rails app with Devise into an OAuth provider? I have a Rails application with admin accounts using Devise for authentication. I am creating a second application and would like to authenticate using the first application instead of duplicating admin accounts in the second application. So my idea is to turn the first application into an OAuth provider so that the second app can simply act as an OAuth client using something like OmniAuth. Have you done this before? Is there a plugin which adds the ability to Devise to be able to act as an OAuth provider? What do I need to change/add in order to turn the app into an OAuth provider? A: Use Doorkeeper gem. Its easy to introduce OAuth 2 provider functionality to your application. It can be also integrated with Devise. Doorkeeper also provides a configuration option to auto-approve and skip the authorization step. This is useful when working with a set of trusted applications, so that you don't confuse your users by requiring them to "authorize" your company's trusted app. # in config/initializers/doorkeeper.rb Doorkeeper.configure do # ...other config options... skip_authorization do true end end
{ "language": "en", "url": "https://stackoverflow.com/questions/25878009", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }